From alan.gauld at btinternet.com Fri Aug 1 00:16:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Jul 2008 23:16:40 +0100 Subject: [Tutor] Mixing in and Mixing out classes in python References: <176387.51878.qm@web32803.mail.mud.yahoo.com> Message-ID: "Tomaz Bevec" wrote > I am using the following function to mixin in classes > into specific object instances ... > Is there an analogous way to "Mixout" classes from an instance at > runtime? I'm sure it is possible but... Are you just asking out of interest? Or do you have a real world need for this? Using multiple inheritence is a non trivial aspect of OOP (albeit powerful) that is fraught with difficulty and potential side effects. Adding a mixin at run time is difficult enough, removing one would bend my brain way too far I suspect. (Many coding standards insist on limiting MI to two classes or even banning it outright as being too bug prone.) Dynamic mixins add a whole new complexity (it's somewhat akin to the FAQ here about dynamically naming variables) all you generic code has to take account of the new method introduced and any potential side-effects that may not be handled in your code. Unless your mixin classes are ultra clean and stateless in their implementation you run a risk of breaking things in ways that are almost impossible to debug. I've never come across a need for dynamic mixin additions and I'm interested in how you think you might use this. (CLOS is the only other place I've even seen this discussed and it's possible there with some under the covers work but I've never seen it used!) Curious, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 1 00:31:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Jul 2008 23:31:06 +0100 Subject: [Tutor] Memory error - how to manage large data sets? References: <20080731.062222.812.1@SELINAPNOTE> Message-ID: "Kepala Pening" wrote > However, to have limit = 2, perhaps I should do > while b <= limit. > > Thanks Alan for pointing it out. No probs, forgetting to test both ends of the range is a common mistake. In fact good testing practice says that for any range of values you should test - the lowest legal value - correct result - one lower than the lowest - fails gracefully - much lower than lowest - fails gracefully - a mid range value - correct result - the highest legal value - correct value (Of course testing the "highest possible value" would be tricky in your case! :-) - one higher than the highest - fails gracefully - much higher than the legal limit - fails gracefully - an invalid value - fails gracefully (eg in your case limit = 'four') So that's at least 8 tests for every range parameter/variable in your code. Automated testing is "A Good Thing" :-) Alan G. > > ----- Original Message ----- > From: "Alan Gauld" > To: tutor at python.org > Date: Thu, 31 Jul 2008 06:39:32 +0100 > Subject: Re: [Tutor] Memory error - how to manage large data sets? > >> >> "Kepala Pening" wrote >> >> > def sumEvenFibonacci( limit ): >> > a, b = 1, 1 # don't waste with a = 0 >> > sum = 0 >> > while b < limit: >> > if b%2 == 0: sum += b >> > a, b = b, a + b >> > return sum >> > >> > print sumEvenFibonacci( 2000000 ) >> >> Does it work for limit = 2? >> >> Alan G. >> >> >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tomazbevec at yahoo.com Fri Aug 1 02:09:51 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Thu, 31 Jul 2008 17:09:51 -0700 (PDT) Subject: [Tutor] Mixing in and Mixing out classes in python In-Reply-To: Message-ID: <160626.42794.qm@web32807.mail.mud.yahoo.com> Thanks for your reply Alan, I am partially asking out of interest, but I also have a potential application. I'm working on a simulation of cellular growth patterns (basically cell instances interacting stochastically on a lattice). Anyway, there are many different cell "behaviors" that I have to simulate, and cells can potentially gain and lose these "behaviors" over the course of the simulation. It would be too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing it in (and initializing it) when necessary or when biological function is gained by the cells. In addition some of the behaviors would be too big (as in lines of code) if they were implemented in one function so splitting functionality up in my mixin class makes it conceptually easier for me. Also the behaviors sometimes need access to the internals of the cell class. After I mixin a class every method that starts with the word 'behavior.*' in that class is called when I update the simulation. All of my mixins inherit from "object" only. So far my approach is working well, but I don't have a clean way for cells to lose functionality. Hence my question about mixin out. I tried to just delete the 'behavior.*' functions with the del operator (like for an attribute) but it didn't work. I have however thought of a number of ways to work around this, and per your suggestion I think I'll just try something else, but if you have any idea on how to dynamically mix out I'd be glad to here it. Thanks, Tomaz --- On Thu, 7/31/08, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] Mixing in and Mixing out classes in python > To: tutor at python.org > Date: Thursday, July 31, 2008, 3:16 PM > "Tomaz Bevec" wrote > > > I am using the following function to mixin in classes > > into specific object instances ... > > > Is there an analogous way to "Mixout" > classes from an instance at > > runtime? > > I'm sure it is possible but... > > Are you just asking out of interest? > Or do you have a real world need for this? > > Using multiple inheritence is a non trivial aspect of OOP > (albeit > powerful) > that is fraught with difficulty and potential side effects. > Adding a > mixin at > run time is difficult enough, removing one would bend my > brain way too > far I suspect. (Many coding standards insist on limiting MI > to two > classes > or even banning it outright as being too bug prone.) > > Dynamic mixins add a whole new complexity (it's > somewhat akin to > the FAQ here about dynamically naming variables) all you > generic > code has to take account of the new method introduced and > any > potential side-effects that may not be handled in your > code. Unless > your mixin classes are ultra clean and stateless in their > implementation > you run a risk of breaking things in ways that are almost > impossible > to debug. > > I've never come across a need for dynamic mixin > additions and > I'm interested in how you think you might use this. > (CLOS is the only > other place I've even seen this discussed and it's > possible there > with some under the covers work but I've never seen it > used!) > > Curious, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Aug 1 02:29:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 Jul 2008 20:29:12 -0400 Subject: [Tutor] Mixing in and Mixing out classes in python In-Reply-To: <160626.42794.qm@web32807.mail.mud.yahoo.com> References: <160626.42794.qm@web32807.mail.mud.yahoo.com> Message-ID: <1c2a2c590807311729m6966b118q3b31b937eda94732@mail.gmail.com> On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec wrote: > Thanks for your reply Alan, > > I am partially asking out of interest, but I also have a potential application. > > I'm working on a simulation of cellular growth patterns (basically cell instances interacting stochastically on a lattice). Anyway, there are many different cell "behaviors" that I have to simulate, and cells can potentially gain and lose these "behaviors" over the course of the simulation. It would be too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing it in (and initializing it) when necessary or when biological function is gained by the cells. Perhaps you could keep the behaviors in a dictionary? You could override __getattr__() in the cell class to look up attributes whose names start with 'behavior' in the dict. Kent From cfuller084 at thinkingplanet.net Fri Aug 1 04:57:43 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 31 Jul 2008 21:57:43 -0500 Subject: [Tutor] key/value order in dictionaries In-Reply-To: References: <489178D0.4000304@timgolden.me.uk> Message-ID: <200807312157.43501.cfuller084@thinkingplanet.net> On Thursday 31 July 2008 05:33, Monika Jisswel wrote: > Python dictionaries are not ordered & the order you will get when you print > a dictionary is the order that the python virtual machines thinks optimal > for that dictionary for its own internal procedures. If you need an ordered dictionary, such things exist. The implementation I use is at http://www.voidspace.org.uk/python/modules.shtml, but there may be one or two other popular ones out there. You probably shouldn't use them unless you have a specific need to. They will be a lot slower, and extra dependencies always complicates distribution. Cheers From angelayian at yahoo.com Fri Aug 1 05:16:54 2008 From: angelayian at yahoo.com (Angela Yang) Date: Thu, 31 Jul 2008 20:16:54 -0700 (PDT) Subject: [Tutor] how do I create a lists of values associated with a key? Message-ID: <279879.31091.qm@web50107.mail.re2.yahoo.com> Hi, I have a list of values for one key.? How do I specify this data structure? First tried, collection = [] collection['abby'].append('apprentice1') collection['abby'].append('apprentice2') That did not work because list index is not numeric. But for dictionaries, it is key - value pairs.? But I need key -> multiple values. Do you have some example how to specify this? Angela -------------- next part -------------- An HTML attachment was scrubbed... URL: From federo at email.si Fri Aug 1 09:39:39 2008 From: federo at email.si (Federo) Date: Fri, 01 Aug 2008 09:39:39 +0200 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? Message-ID: <20080801073939.974DC8CEF6@www1.email.si> Hi .. I have to admit that Python is really surprising me. It was lucky day a few weeks ago I firts time start using Python. Lot's of things realy can be done with short learning curve. Your user guieds was best place to start! Below is problem I am unable to solve. I would appreciate your advice or even better code sample. The problem is URL authorisation. I try to approaches but no luck so far. Two problems: 1.) Being able to logon using Python code 2.) Being able to send data to a form and get back server reply ad 1.) The Two pages I try to open: Login: https://investor.firstrade.com/firstrade/login.do Main page after login: https://investor.firstrade.com/firstrade/mainmenu.do I have tried bellow code (with currect user name and password of course): >>> import urllib2 >>> password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() >>> protocol = 'https://' >>> username = 'user' >>> password = 'pass' >>> top_level_url = "investor.firstrade.com/firstrade/login.do" >>> password_mgr.add_password(None, top_level_url, username, password) >>> handler = urllib2.HTTPBasicAuthHandler(password_mgr) >>> opener = urllib2.build_opener(handler) >>> a_url = "https://investor.firstrade.com/firstrade/login.do" >>> f = opener.open(a_url) >>> a = f.read() >>> print (a) but it replied login page after login. It looks like they are using cookie. Bellow line can be find in header Set-Cookie: JSESSIONID=351CE048D9FEAD01E21604129D38725C; Path=/; Secure On the web I found user guide explaining coookie login. However I do not understand how to combine now password and cookie login if this will solve the problem at first place... http://www.voidspace.org.uk/python/articles/cookielib.shtml#fetching-webpages CODE SAMPLE to be able to solve the problem very appreciated.. There is by pass solution using Web Recorder Macro. However it will be much better to BE ABLE TO handle entire process with Python.. ad 2.) Filling data to form / getting beck server values. I need server reply from the same web side we are discussing in point 1. Here is Code sample: import urllib import urllib2 url = 'https://investor.firstrade.com/firstrade/mainmenu.do' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'symbol' : 'xsnx'} data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() a.) I do not understand where can I find currect fields names for values in the above code sample (in our case "Symbol" is written before Text box (look attached print screen. HTML code of main side is attached file Firstrade_MainSideHTML.rtf) where you can write stock ticker and than press a button. Server replied real time stock data which I would like to read)? b.) Probably code will be more complex as sample code above as code has to take care also for proper authorisation.. Sorry for taking your time. Your help would be very useful as I stacked with this. Being able to handle URL requests is very important now days... Cheers, Fedo ____________________ http://www.email.si/ ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: Firstrade_MainSide.jpg Type: image/pjpeg Size: 45800 bytes Desc: Firstrade_MainSide.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Firstrade_MainSideHTML.rtf Type: application/msword Size: 41489 bytes Desc: Firstrade_MainSideHTML.rtf URL: From alan.gauld at btinternet.com Fri Aug 1 12:21:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Aug 2008 11:21:43 +0100 Subject: [Tutor] Mixing in and Mixing out classes in python References: <160626.42794.qm@web32807.mail.mud.yahoo.com> Message-ID: "Tomaz Bevec" wrote > I'm working on a simulation of cellular growth patterns ...and cells > can potentially gain and lose these "behaviors" over the course > of the simulation. OK, That might be a valid scenario. But personally I'd probably implement that as an attribute of the cell - a list of behaviours and build a Behaviour class with subclasses. The methods of which take a Cell class as their argument. It is then trivial to add remove behaviours. And simply call them in a loop for b in self.behavious: b.doit(self) Or maybe have a dictionary of behaviours if you even want to call specific ones. eg def myMeth(self): # do sometjing try: self.behaviours['behaviourMyMeth'](self) except KeyError: pass # do the rest > I have however thought of a number of ways to work around this, > and per your suggestion I think I'll just try something else, I'd come back to the old OOP adage, inheritance is for Is-A relationships. Is you Cell a behaviour or does it Have-A behaviour? With mixins that adage tends to get bent since mixins are often functional in nature but if the function is not intrinsic to the class I tend to use delegation. > any idea on how to dynamically mix out I'd be glad to here it. I don't know but I'm sure its possible if you understand the class internals well enough. Regards, Alan G. From marc.tompkins at gmail.com Fri Aug 1 12:20:43 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 1 Aug 2008 03:20:43 -0700 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <279879.31091.qm@web50107.mail.re2.yahoo.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang wrote: > Hi, > > I have a list of values for one key. How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple > values. > > Do you have some example how to specify this? > > Angela > Each "value" can, itself, be a container - a tuple, a list, or another dictionary. dictTuple = {"a":(1,2,3), "b":(4,5,6)} dictList = {"a":[1,2,3], "b":[4,5,6]} dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}} Retrieving values: valValue = dictTuple["a"][0] # 1 valValue = dictTuple["b"][2] # 6 Lists work just the same: valValue = dictList["a"][0] # 1 valValue = dictList["b"][2] # 6 Dictionaries are, well, like dictionaries: valValue = dictDict["a"]["c"] # 1 valValue = dictDict["b"]["h"] # 6 Hope that helps.... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 1 12:25:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Aug 2008 11:25:53 +0100 Subject: [Tutor] how do I create a lists of values associated with a key? References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: "Angela Yang" wrote > But for dictionaries, it is key - value pairs. But I need key -> > multiple values. But a value can be a list. d = {} d['odd'] = [1,3,5,7] d['even'] = [2,4,6,8] print d['odd'][2] # = 5 See the Raw Materials top[ic in my tutorial for another example using a dictionary to store address data: >>> addressBook = { ... 'Fred' : ['Fred', '9 Some St',' Anytown', '0123456789'], ... 'Rose' : ['Rose', '11 Nother St', 'SomePlace', '0987654321'] ... }>>> print addressBook['Rose'] ['Rose', '11 Nother St', 'SomePlace', '0987654321'] >>> print addressBook['Fred'][3] 0123456789 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tomazbevec at yahoo.com Fri Aug 1 12:25:26 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Fri, 1 Aug 2008 03:25:26 -0700 (PDT) Subject: [Tutor] __getattribute__ instead of Mixing in and Mixing out classes in python In-Reply-To: <1c2a2c590807311729m6966b118q3b31b937eda94732@mail.gmail.com> Message-ID: <131953.81675.qm@web32807.mail.mud.yahoo.com> Thanks for your suggestion, Kent. I've looked into it a little bit and I think its probably the right way to go. --- On Thu, 7/31/08, Kent Johnson wrote: > From: Kent Johnson > Subject: Re: [Tutor] Mixing in and Mixing out classes in python > To: tomazbevec at yahoo.com > Cc: "Tutor Python" > Date: Thursday, July 31, 2008, 5:29 PM > On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec > wrote: > > Thanks for your reply Alan, > > > > I am partially asking out of interest, but I also have > a potential application. > > > > I'm working on a simulation of cellular growth > patterns (basically cell instances interacting > stochastically on a lattice). Anyway, there are many > different cell "behaviors" that I have to > simulate, and cells can potentially gain and lose these > "behaviors" over the course of the simulation. It > would be too much to put every behavior function in the cell > class, so I'm writing each behavior as a mixin and > mixing it in (and initializing it) when necessary or when > biological function is gained by the cells. > > Perhaps you could keep the behaviors in a dictionary? You > could > override __getattr__() in the cell class to look up > attributes whose > names start with 'behavior' in the dict. > > Kent From benoit.thiell at cern.ch Fri Aug 1 12:29:01 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Fri, 1 Aug 2008 12:29:01 +0200 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> Message-ID: Dear Angela, in order to do this, the setdefault function of the dictionaries is very useful. For example: mydict = {} mylist = mydict.setdefault(mykey, []) mylist.append(myvalue) "setdefault" either returns the already existing list or sets a new list for the key and returns it. Regards, Benoit Thiell. On Fri, 1 Aug 2008, Marc Tompkins wrote: > > > On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang wrote: > Hi, > > I have a list of values for one key.? How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs.? But I need key -> multiple values. > > Do you have some example how to specify this? > > Angela > > > Each "value" can, itself, be a container - a tuple, a list, or another dictionary. > > dictTuple = {"a":(1,2,3), "b":(4,5,6)} > dictList = {"a":[1,2,3], "b":[4,5,6]} > dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}} > > Retrieving values: > valValue = dictTuple["a"][0]? # 1 > valValue = dictTuple["b"][2]? # 6 > > Lists work just the same: > valValue = dictList["a"][0]? # 1 > valValue = dictList["b"][2]? # 6 > > Dictionaries are, well, like dictionaries: > valValue = dictDict["a"]["c"]? # 1 > valValue = dictDict["b"]["h"]? # 6 > > > Hope that helps.... > > -- > www.fsrtechnologies.com > > From kent37 at tds.net Fri Aug 1 12:41:59 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 06:41:59 -0400 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> On Fri, Aug 1, 2008 at 3:39 AM, Federo wrote: > Hi .. > > I have to admit that Python is really surprising me. It was lucky day a few > weeks ago I firts time start using Python. Lot's of things realy can be done > with short learning curve. Your user guieds was best place to start! > > Below is problem I am unable to solve. I would appreciate your advice or > even better code sample. The problem is URL authorisation. I have a writeup on form-based authentication here: http://personalpages.tds.net/~kent37/kk/00010.html#e10form-based-authentication Kent From kent37 at tds.net Fri Aug 1 12:45:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 06:45:53 -0400 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <279879.31091.qm@web50107.mail.re2.yahoo.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: <1c2a2c590808010345o560fbeccwdb5a788acd57251f@mail.gmail.com> On Thu, Jul 31, 2008 at 11:16 PM, Angela Yang wrote: > Hi, > > I have a list of values for one key. How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple > values. A dict or defaultdict with list values would work well here. The defaultdict has the advantage of not requiring any user code to handle missing keys: In [7]: from collections import defaultdict In [8]: c=defaultdict(list) In [9]: c['abby'].append('apprentice1') In [10]: c['abby'].append('apprentice2') In [11]: c Out[11]: defaultdict(, {'abby': ['apprentice1', 'apprentice2']}) Kent From monjissvel at googlemail.com Fri Aug 1 12:49:00 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 10:49:00 +0000 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: 2008/8/1 Angela Yang > > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple values. > > Do you have some example how to specify this? > You already know this : Collection1 = [] Collection2 = [] Collection1.append('apprentice1') Collection1.append('apprentice2') if you add a MainCollection to the picture which can be coded like this: MainCollection = {'Collection1':[], 'Collection2':[]} Adding elements to a Collection is as simple as this interactive session demonstrates : Python 2.4.4 (#2, Apr 15 2008, 23:43:20) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> MainCollection = {'Collection1':[], 'Collection2':[]} >>> type(MainCollection) >>> MainCollection['Collection1'] [] >>> MainCollection['Collection1'].append('aa') >>> MainCollection['Collection1'] ['aa'] >>> MainCollection['Collection1'].append('bb') >>> MainCollection['Collection1'] ['aa', 'bb'] From monjissvel at googlemail.com Fri Aug 1 13:04:48 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:04:48 +0000 Subject: [Tutor] Unzipping a list In-Reply-To: <20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com> References: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com> <20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com> Message-ID: > > >>> answers= ['ask','tell','repeat','sell'] > >>> > >>> > >>> a = '/usr/program/bin -o '+ ' '.join(answers) > >>> print a > /usr/program/bin -o ask tell repeat sell > 2008/7/8 Faheem : > Hey all, > > If anyone is interested I found this while googling > > answers= ['ask'.'tell','repeat','sell'] > > def unzip(answers): > unzipped = "".join(answers) # if all items are strings > unzipped = ", ".join(map(str, answers)) > unzipped = " ".join(str(v) for v in answers if v > 0) > return unzipped > > will give the following > > ask tell repeat sell > > :) > >> hey all, >> How can i pass the elements of a list in the follwoing manner? >> >> L =['ask'.'tell','repeat','sell'] >> >> To illustrate my question: >> how can i pass the above list as follows >> >> "/some/program/run -o ask tell repeat sell" >> >> thanks in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From monjissvel at googlemail.com Fri Aug 1 13:13:09 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:13:09 +0000 Subject: [Tutor] Newbie In-Reply-To: <562071.37071.qm@web59516.mail.ac4.yahoo.com> References: <562071.37071.qm@web59516.mail.ac4.yahoo.com> Message-ID: if you remove the comma after the print i for i in range(10) : print i print "Goodbye World!" your problem will be solved, the comma in a print statement means ' ' or space. THREADING is a word that means something else than having two strings on the same line. 2008/7/23 Sam Last Name > Hey guys, I'm wanting to learn Python and eventually how to program with > it. I'm 16 and very eager to learn. I already have a question. > > Heres my script: > print "Hello World!" > print "Here are the ten numbers from 0 to 9" > for i in range(10) : > print i, > print "Goodbye World!" > > Result of my script : > Hello World! > Here are the ten numbers from 0 to 9 > 0 Goodbye World! > 1 Goodbye World! > 2 Goodbye World! > 3 Goodbye World! > 4 Goodbye World! > 5 Goodbye World! > 6 Goodbye World! > 7 Goodbye World! > 8 Goodbye World! > 9 Goodbye World! > > > I don't Understand. I have an idea it something like Goodbye world is > threading together with the numbers? Feedback is Thanked :) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From monjissvel at googlemail.com Fri Aug 1 13:15:54 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:15:54 +0000 Subject: [Tutor] Tutor Newbie In-Reply-To: <138002.84298.qm@web59507.mail.ac4.yahoo.com> References: <138002.84298.qm@web59507.mail.ac4.yahoo.com> Message-ID: it would take learning to use some of the modules that help create GUIs. they are : wx and Tkinter 2008/7/25 Sam Last Name > Hey guys, need some info on "programs" :) > > > Heres a Very simple Script that works with basically any numbers. > > > width = input("What is the Width?") > length = input("What is the Length?") > area = width*length > print area > # my question is what would it take (programs, extra stuff in script, > ect..) to make this a nice looking usable desktop program? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From monjissvel at googlemail.com Fri Aug 1 13:37:16 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:37:16 +0000 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: Here is some code, it will help you manage cookies, & stay logged in to the website for further queries. import os, sys, time, urllib, urllib2, cookielib, re > > cj=cookielib.LWPCookieJar() > headers={'User-Agent' : user_agent} > opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > get_login=urllib2.urlopen('https://www.website.com/login_page.html') > > recieved_login_page = get_login.readlines() > > for line in recieved_login_page: > #you've got to parse each line in the page > #and extract information from it & assign it to variables > > #those variables you just extracted you've got to put them in this > dictionary > values={'username':'xxxxxxxxx', 'pass':'xxxxxxxxx', 'submit' : 'submit', > 'anothervar':'xxxx'} > data=urllib.urlencode(values) > > req=urllib2.Request('https://www.website.com/form_action.php', data, > headers) #I think "https://investor.firstrade.com/firstrade/login.do" > response=urllib2.urlopen(req) > ofcourse this is just example code and you should replace some variables with your own, but it should work for your case if you know where the form submits its data & what data it submits (you put this data in the values dict & then encode it & use it to authenticate and the opener (urllib2.install_opener(opener)) should keep you logged in to the page because it keeps track of cookies for you. 2008/8/1 Federo > Hi .. > > I have to admit that Python is really surprising me. It was lucky day a few > weeks ago I firts time start using Python. Lot's of things realy can be > done > with short learning curve. Your user guieds was best place to start! > > Below is problem I am unable to solve. I would appreciate your advice or > even better code sample. The problem is URL authorisation. I try to > approaches > but no luck so far. Two problems: > > 1.) Being able to logon using Python code > 2.) Being able to send data to a form and get back server reply > > ad 1.) > The Two pages I try to open: > > Login: > https://investor.firstrade.com/firstrade/login.do > Main page after login: > https://investor.firstrade.com/firstrade/mainmenu.do > > I have tried bellow code (with currect user name and password of course): > >>> import urllib2 > >>> password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() > >>> protocol = 'https://' > >>> username = 'user' > >>> password = 'pass' > >>> top_level_url = "investor.firstrade.com/firstrade/login.do" > >>> password_mgr.add_password(None, top_level_url, username, password) > >>> handler = urllib2.HTTPBasicAuthHandler(password_mgr) > >>> opener = urllib2.build_opener(handler) > >>> a_url = "https://investor.firstrade.com/firstrade/login.do" > >>> f = opener.open(a_url) > >>> a = f.read() > >>> print (a) > > but it replied login page after login. It looks like they are using cookie. > Bellow line can be find in header > Set-Cookie: JSESSIONID=351CE048D9FEAD01E21604129D38725C; Path=/; Secure > > On the web I found user guide explaining coookie login. However I do not > understand how to combine now password and cookie login if this will solve > the > problem at first place... > > http://www.voidspace.org.uk/python/articles/cookielib.shtml#fetching-webpages > > CODE SAMPLE to be able to solve the problem very appreciated.. > > There is by pass solution using Web Recorder Macro. However it will be much > better to BE ABLE TO handle entire process with Python.. > > ad 2.) Filling data to form / getting beck server values. I need server > reply > from the same web side we are discussing in point 1. > > Here is Code sample: > import urllib > import urllib2 > > url = 'https://investor.firstrade.com/firstrade/mainmenu.do' > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values = {'symbol' : 'xsnx'} > > data = urllib.urlencode(values) > req = urllib2.Request(url, data) > response = urllib2.urlopen(req) > the_page = response.read() > > a.) I do not understand where can I find currect fields names for values > in the above code sample (in our case "Symbol" is written before Text box > (look > attached print screen. HTML code of main side is attached file > Firstrade_MainSideHTML.rtf) > where you can write stock ticker and than press a button. Server replied > real > time stock data which I would like to read)? > b.) Probably code will be more complex as sample code above as code has to > take > care also for proper authorisation.. > > Sorry for taking your time. Your help would be very useful as I stacked > with > this. Being able to handle URL requests is very important now days... > > Cheers, Fedo > > ____________________ > http://www.email.si/ > > ____________________ > http://www.email.si/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From agent.krycek at gmail.com Fri Aug 1 20:47:52 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Fri, 1 Aug 2008 12:47:52 -0600 Subject: [Tutor] Logging In To Forum Message-ID: Hello, I would like to have my script log in to a vBulletin forum. My script does seem to do this (as I can check my control panel, etc.). But although I can get access to my account, the forum fails to update the date when I last visited. That date updates just fine when I do it manually through a browser. I was wondering if I was maybe messing something up with cookies. Any suggestions would be appreciated. Thanks! #!/usr/bin/python # forumlogin.py # Logs into vBulletin forum import urllib2, time import cgitb; cgitb.enable() def main(): print "Content-type: text/html\n" url = "http://forums.x10hosting.com/login.php?do=login" queryString = "..." opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) response = opener.open(url, queryString) logfile() response.close() def logfile(): fileIn = open("../logfile.txt", "a") fileIn.write("\n") fileIn.write(time.ctime()) fileIn.close() *if* __name__ == "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Aug 1 21:20:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 15:20:41 -0400 Subject: [Tutor] Logging In To Forum In-Reply-To: References: Message-ID: <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> On Fri, Aug 1, 2008 at 2:47 PM, Alex Krycek wrote: > Hello, > > I would like to have my script log in to a vBulletin forum. My script does > seem to do this (as I can check my control panel, etc.). But although I can > get access to my account, the forum fails to update the date when I last > visited. That date updates just fine when I do it manually through a > browser. I was wondering if I was maybe messing something up with cookies. > Any suggestions would be appreciated. Thanks! You might try actually reading the response data with response.read(). Otherwise you should look closely at the interaction with the browser; you need to mimic that. Firebug and other browser tools can help. Kent From agent.krycek at gmail.com Fri Aug 1 21:25:46 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Fri, 1 Aug 2008 13:25:46 -0600 Subject: [Tutor] Logging In To Forum In-Reply-To: <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> References: <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> Message-ID: Kent, I tried reading several pages with the read() function. Unfortunately nothing changed. I'll take a look at Firebug. Thanks. On Fri, Aug 1, 2008 at 1:20 PM, Kent Johnson wrote: > On Fri, Aug 1, 2008 at 2:47 PM, Alex Krycek > wrote: > > Hello, > > > > I would like to have my script log in to a vBulletin forum. My script > does > > seem to do this (as I can check my control panel, etc.). But although I > can > > get access to my account, the forum fails to update the date when I last > > visited. That date updates just fine when I do it manually through a > > browser. I was wondering if I was maybe messing something up with > cookies. > > Any suggestions would be appreciated. Thanks! > > You might try actually reading the response data with response.read(). > Otherwise you should look closely at the interaction with the browser; > you need to mimic that. Firebug and other browser tools can help. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredp101 at mac.com Sat Aug 2 07:41:06 2008 From: fredp101 at mac.com (Fred @ Mac) Date: Fri, 01 Aug 2008 22:41:06 -0700 Subject: [Tutor] Scan Directory for files Message-ID: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Hello, new to python, so please go easy on me! I am using for f in os.listdir(watch_dir): tree = ET.parse(f) for shot in tree.findall('Shot'): ..do stuff.. to scan a directory for specific files (xml files specifically). But my script fails if, for example, a directory also exists in "watch_dir" How can i restructure this so it only returns a list of the .xml files in that directory, ignores other files and or directories in "watch_dir" Thanks! From jeff at drinktomi.com Sat Aug 2 08:26:22 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 1 Aug 2008 23:26:22 -0700 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: <4F80CB79-A34E-41BA-8A52-2B7D2B3CF86E@drinktomi.com> On Aug 1, 2008, at 12:39 AM, Federo wrote: > > Below is problem I am unable to solve. I would appreciate your > advice or > even better code sample. The problem is URL authorisation. I try to > approaches > but no luck so far. Two problems: > > 1.) Being able to logon using Python code > 2.) Being able to send data to a form and get back server reply While it's possible to cobble together something using urllib and htmlparser, you're much better off using mechanize. It's basically an entire browser in a library. It handles http authentication, cookies, form processing, etc. For more details check out the project's page at: http://wwwsearch.sourceforge.net/mechanize/ - Jeff Younker - jeff at drinktomi.com - From steve.poe at gmail.com Sat Aug 2 09:00:23 2008 From: steve.poe at gmail.com (Steve Poe) Date: Sat, 2 Aug 2008 00:00:23 -0700 Subject: [Tutor] Scan Directory for files In-Reply-To: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: <87E0D850-D657-4D3C-A5C1-27904B0BCB37@gmail.com> Fred, What is/are the exact error message(s)? You may want to look at the module glob. Steve Ar e you typing this in the python interpreter or On Aug 1, 2008, at 10:41 PM, Fred @ Mac wrote: > Hello, > > new to python, so please go easy on me! > > I am using > > for f in os.listdir(watch_dir): > tree = ET.parse(f) > for shot in tree.findall('Shot'): > ..do stuff.. > > to scan a directory for specific files (xml files specifically). > > But my script fails if, for example, a directory also exists in > "watch_dir" > > How can i restructure this so it only returns a list of the .xml > files in that directory, ignores other files and or directories in > "watch_dir" > > Thanks! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Aug 2 10:07:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 09:07:11 +0100 Subject: [Tutor] Scan Directory for files References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: "Fred @ Mac" wrote > for f in os.listdir(watch_dir): > tree = ET.parse(f) > for shot in tree.findall('Shot'): > ..do stuff.. > > But my script fails if, for example, a directory also exists in > "watch_dir" Take a look at os.walk which allows recursive traversal of a directory structure. There is a short discussion in the OS topic on my web tutor. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sat Aug 2 12:07:43 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 03:07:43 -0700 Subject: [Tutor] I can't believe this needs to be this complex Message-ID: <20080802100759.4A97D1E4003@bag.python.org> I'm pretty new to Python's dictionaries, but I had a need for a function that would find the values in a dict that have more than one key each. It took me several hours to write. See . Seems to do the job, both with the example shown, and with the dict of colors at . But I can't believe the function needs to be so complex. And also, I suppose I've reinvented the wheel (again). Please instruct me. My apologies in advance to Kent for not using a single list comprehension. Thanks, Dick Moores From andreengels at gmail.com Sat Aug 2 12:27:34 2008 From: andreengels at gmail.com (Andre Engels) Date: Sat, 2 Aug 2008 11:27:34 +0100 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802100759.4A97D1E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> Message-ID: <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> On Sat, Aug 2, 2008 at 11:07 AM, Dick Moores wrote: > I'm pretty new to Python's dictionaries, but I had a need for a function > that would find the values in a dict that have more than one key each. It > took me several hours to write. See > . Seems to do the job, both with > the example shown, and with the dict of colors at > . > > But I can't believe the function needs to be so complex. And also, I suppose > I've reinvented the wheel (again). Please instruct me. > > My apologies in advance to Kent for not using a single list comprehension. Well, list comprehension does indeed seem the solution to your problem, although a single list comprehension would not be necessary. I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is untested, I have no Python on the computer I am working on now), or http://py77.python.pastebin.com/f76ba5002 to indeed just use a single list comprehension (or rather, two nested list comprehensions, again untested for the above reason). -- Andr? Engels, andreengels at gmail.com From rdm at rcblue.com Sat Aug 2 12:49:08 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 03:49:08 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> Message-ID: <20080802104920.B10F21E4003@bag.python.org> At 03:27 AM 8/2/2008, Andre Engels wrote: >Content-Transfer-Encoding: >base64Content-Disposition: inlineOn Sat, Aug 2, >2008 at 11:07 AM, Dick Moores wrote: > > I'm pretty new to Python's dictionaries, but I had a need for a function > > that would find the values in a dict that have more than one key each. It > > took me several hours to write. See > > > shown, and with the dict of colors at> > . > > >?]H?[???[Y at ve the function needs to be so complex. And also, I suppose > > I've reinvented the wheel (again). Please instruct me. > > >^H\???Y\?[?Y?[??H??[??????\?[??H?@ngle list comprehension. > >Well, list comprehension does indeed seem the solution to your >problem, although a single list comprehension would not be necessary. >I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is >untested, I have no Python on the computer I am working on now), or >http://py77.python.pastebin.com/f76ba5002 to indeed just use a single >list comprehension (or rather, two nested list comprehensions, again >untested for the above reason). You genius! How could you answer so quickly and accurately (20 minutes!) without access to Python? Both of your scripts work, after I corrected one typo. See . Thanks! Dick Moores From rdm at rcblue.com Sat Aug 2 13:18:09 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 04:18:09 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802104920.B10F21E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> <20080802104920.B10F21E4003@bag.python.org> Message-ID: <20080802111945.A6E0C1E4003@bag.python.org> At 03:49 AM 8/2/2008, Dick Moores wrote: >At 03:27 AM 8/2/2008, Andre Engels wrote: >>Content-Transfer-Encoding: >>base64Content-Disposition: inlineOn Sat, Aug 2, >>2008 at 11:07 AM, Dick Moores wrote: >> > I'm pretty new to Python's dictionaries, but I had a need for a function >> > that would find the values in a dict that have more than one key each. It >> > took me several hours to write. See >> > >> > shown, and with the dict of colors at> >> . >> > >>?]H?[???[Y at ve the function needs to be so complex. And also, I suppose >> > I've reinvented the wheel (again). Please instruct me. >> > >>^H\???Y\?[?Y?[??H??[??????\?[??H?@ngle list comprehension. >> >>Well, list comprehension does indeed seem the solution to your >>problem, although a single list comprehension would not be necessary. >>I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is >>untested, I have no Python on the computer I am working on now), or >>http://py77.python.pastebin.com/f76ba5002 to indeed just use a single >>list comprehension (or rather, two nested list comprehensions, again >>untested for the above reason). > >You genius! How could you answer so quickly and >accurately (20 minutes!) without access to Python? > >Both of your scripts work, after I corrected one >typo. See . And here's your one-liner () at work on the dict of colors at . Dick From kent37 at tds.net Sat Aug 2 13:49:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 07:49:51 -0400 Subject: [Tutor] Scan Directory for files In-Reply-To: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: <1c2a2c590808020449h5499f2ebw4aabb691e9c30675@mail.gmail.com> On Sat, Aug 2, 2008 at 1:41 AM, Fred @ Mac wrote: > Hello, > > new to python, so please go easy on me! > > I am using > > for f in os.listdir(watch_dir): > tree = ET.parse(f) Should be ET.parse(os.path.join(watch_dir, f)) I think... > for shot in tree.findall('Shot'): > ..do stuff.. > > to scan a directory for specific files (xml files specifically). > > But my script fails if, for example, a directory also exists in "watch_dir" > > How can i restructure this so it only returns a list of the .xml files in > that directory, ignores other files and or directories in "watch_dir" The glob module can filter file names based on patterns. os.path.isfile() will tell you if something is a file. So for example: pattern = os.path.join(watch_dir, "*.xml") for f in glob.glob(pattern): if not os.path.isfile(f): #already did the join in the pattern continue tree = ET.parse(f) Jason Orendorff's path module is useful for this also though the doc site seems to be down: http://pypi.python.org/pypi/path.py/2.2 Kent From kent37 at tds.net Sat Aug 2 14:02:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 08:02:17 -0400 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802100759.4A97D1E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> Message-ID: <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores wrote: > I'm pretty new to Python's dictionaries, but I had a need for a function > that would find the values in a dict that have more than one key each. >From your sample output it appears that you want not just the values, but a list of (value, keys) pairs for which there are more than one key. It is easy to just build a reverse dict and filter its items: In [15]: from collections import defaultdict In [16]: rev=defaultdict(list) In [18]: for k, v in d.iteritems(): rev[v].append(k) In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ] Out[20]: [[1, ['a', 'e', 'g']], [2, ['b', 'f', 'i', 'h']], [4, ['d', 'j']], ['U.S. Senator', ['John McCain', 'Barack Obama']], [56, [45, 55]]] This also has the advantage of making only two passes over the data so its performance should be O(n). Your solution and Andre's make one or more passes over the data for each data element so they will have O(n*n) performance meaning for a large dict they could be very slow. Kent From rdm at rcblue.com Sat Aug 2 15:27:21 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 06:27:21 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> Message-ID: <20080802132734.A50001E4016@bag.python.org> At 05:02 AM 8/2/2008, Kent Johnson wrote: >On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores wrote: > > I'm pretty new to Python's dictionaries, but I had a need for a function > > that would find the values in a dict that have more than one key each. > > From your sample output it appears that you want not just the values, >but a list of (value, keys) pairs for which there are more than one >key. It is easy to just build a reverse dict and filter its items: > >In [15]: from collections import defaultdict >In [16]: rev=defaultdict(list) >In [18]: for k, v in d.iteritems(): > rev[v].append(k) > >In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ] > >Out[20]: >[[1, ['a', 'e', 'g']], > [2, ['b', 'f', 'i', 'h']], > [4, ['d', 'j']], > ['U.S. Senator', ['John McCain', 'Barack Obama']], > [56, [45, 55]]] > >This also has the advantage of making only two passes over the data so >its performance should be O(n). Your solution and Andre's make one or >more passes over the data for each data element so they will have >O(n*n) performance meaning for a large dict they could be very slow. Wow, the genius' genius appears! You're using some Python tools I didn't know about. More study! I made a function of your code and time tested it against mine, using as d that dict of colors at . Yours is 73 times faster! In [12]: run -t -N10 fcn_values_dupe_keys.py Time was 0.297 seconds Time was 0.328 seconds Time was 0.344 seconds Time was 0.328 seconds Time was 0.313 seconds Time was 0.344 seconds Time was 0.39 seconds Time was 0.297 seconds Time was 0.312 seconds Time was 0.297 seconds IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 3.3092253345 s, 0.33092253345 s. System: 0.0 s, 0.0 s. In [13]: run -t -N10 kent1.py Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0.015 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 0.044969961266 s, 0.0044969961266 s. System: 0.0 s, 0.0 s. BTW Kent, I'm going to take this opportunity to ask you about "System" in the IPython timing results. It's always zero for the code I time. What's an example of code that would have System be greater than zero? And what's the distinction between User and System? (I'm using Win XP, if that's relevant.) Thanks, Dick From jtp at nc.rr.com Sat Aug 2 16:34:48 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 10:34:48 -0400 Subject: [Tutor] Classes in separate files Message-ID: All, I've started tinkering (just a little) with classes, primarily because I have to. (I've never been a huge fan of OOP, but can tolerate it when used properly). I'll be the first to admit that I don't know much about how to program "correctly" when dealing with objects, however, so any thoughts in the matter would be greatly appreciated. I have a few files that I use as "libraries" which contain dozens of functions that I use across a wide array of programs. This works fine when I want to invoke a function, pass in a few parameters, and then get something back. I'm now trying to put a few classes which I know I will be using repeatedly in a separate file, as well. The issue is, however, that I'm not sure the "best" way to pass things into classes, and the "best" way to get something back. I have a main file, main.py. It's going to create several instances that are defined by a class in class1.py. *However*, I also need to instantiate numerous other classes defined in class2.py. class1.py has a few classes, such as - ticket (represents a ticket opened to fix bugs in a program) - ticketAnalyzer (an object who looks at all the tickets opened/available) class2.py has a few classes, as well, such as: - codemonkey (defines a person that is going to take tickets and fix them) - codereviewer (defines a person who will double check a codemonkey's work) main.py has the "main" function, and will what is actually invoked at the command line. In main.py I can instantiate an object of type ticket, an object of type ticketAnalyzer, and then instantiate code{monkey,reviewer} classes. However, how do I get codemonkey and codereviewer to call methods on the ticket and ticketAnalyzer classes? The only solution I can think of here is having the main function (in main.py) which instantiates all these objects actually *pass in* to the codemonkey and reviewer the reference to the specific objects ticketAnalyzer and ticket. Is this the best way to do it? Should I handle that behavior in the __init__ of code{monkey,reviewer}? Should I instead create a method inside of the codemonkey and reviewer classes that accepts the object pointer to the ticket objects and then interact between ticket/code* objects as such? I image it would be much easier to have everything in one file, but that goes against my grain. ;) Thoughts appreciated! -j From desm at hotmail.co.uk Sat Aug 2 16:40:14 2008 From: desm at hotmail.co.uk (desmond mansfield) Date: Sat, 2 Aug 2008 14:40:14 +0000 Subject: [Tutor] Why use lambda? In-Reply-To: References: Message-ID: I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? What can lambda do that normal function definitions cannot? Is it quicker to execute/less memory intensive? Or is it just quicker to type and easier to think about? Any answers would be appreciated. thanks, _________________________________________________________________ Make a mini you on Windows Live Messenger! http://clk.atdmt.com/UKM/go/107571437/direct/01/ From jtp at nc.rr.com Sat Aug 2 16:51:03 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 10:51:03 -0400 Subject: [Tutor] Classes in separate files In-Reply-To: References: Message-ID: Another question on classes in separate files... main.py instantiates a class called 'testClass' inside of a file temp.py. In main.py: t = temp.testClass() So now I can access some of the variables inside of 't'. For example, let's say that in main.py, I do the following: # get a variable from the t class (I know, this is not the cleanest way to do this ;)) tempVariable = t.tempVar So here's a question...how does the object *t* (defined in the temp.py file) access a global (or even local) variable in main.py? Is it possible? What if I want the object t to write to a global variable inside of main.py...is that possible? Thanks! -j On Sat, Aug 2, 2008 at 10:34 AM, James wrote: > All, > > I've started tinkering (just a little) with classes, primarily because > I have to. (I've never been a huge fan of OOP, but can tolerate it > when used properly). > > I'll be the first to admit that I don't know much about how to program > "correctly" when dealing with objects, however, so any thoughts in the > matter would be greatly appreciated. > > I have a few files that I use as "libraries" which contain dozens of > functions that I use across a wide array of programs. This works fine > when I want to invoke a function, pass in a few parameters, and then > get something back. I'm now trying to put a few classes which I know I > will be using repeatedly in a separate file, as well. > > The issue is, however, that I'm not sure the "best" way to pass things > into classes, and the "best" way to get something back. > > I have a main file, main.py. It's going to create several instances > that are defined by a class in class1.py. *However*, I also need to > instantiate numerous other classes defined in class2.py. > > class1.py has a few classes, such as > - ticket (represents a ticket opened to fix bugs in a program) > - ticketAnalyzer (an object who looks at all the tickets opened/available) > > class2.py has a few classes, as well, such as: > - codemonkey (defines a person that is going to take tickets and fix them) > - codereviewer (defines a person who will double check a codemonkey's work) > > main.py has the "main" function, and will what is actually invoked at > the command line. In main.py I can instantiate an object of type > ticket, an object of type ticketAnalyzer, and then instantiate > code{monkey,reviewer} classes. However, how do I get codemonkey and > codereviewer to call methods on the ticket and ticketAnalyzer classes? > > The only solution I can think of here is having the main function (in > main.py) which instantiates all these objects actually *pass in* to > the codemonkey and reviewer the reference to the specific objects > ticketAnalyzer and ticket. Is this the best way to do it? Should I > handle that behavior in the __init__ of code{monkey,reviewer}? Should > I instead create a method inside of the codemonkey and reviewer > classes that accepts the object pointer to the ticket objects and then > interact between ticket/code* objects as such? > > I image it would be much easier to have everything in one file, but > that goes against my grain. ;) > > Thoughts appreciated! > -j > From technorapture at gmail.com Sat Aug 2 17:42:10 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Sat, 2 Aug 2008 11:42:10 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: References: Message-ID: <376fbdcf0808020842q2c1efa0cw57443bfd45ab8d52@mail.gmail.com> >From what I've seen, Lambda is most useful if you're passing functions as arguments to other functions. You could use lambda to create a function on-the-fly, as you've said, and that will save you the trouble of having to write it separately. Try looking for examples on functional programming in Python to find more examples. On Sat, Aug 2, 2008 at 10:40 AM, desmond mansfield wrote: > > I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". > But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? > > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? > > Any answers would be appreciated. thanks, > _________________________________________________________________ > Make a mini you on Windows Live Messenger! > http://clk.atdmt.com/UKM/go/107571437/direct/01/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- The ByteBaker : http://www.bytebaker.com From dineshbvadhia at hotmail.com Sat Aug 2 17:51:55 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 2 Aug 2008 08:51:55 -0700 Subject: [Tutor] removing whole numbers from text Message-ID: I want to remove whole numbers from text but retain numbers attached to words. All whole numbers to be removed have a leading and trailing space. For example, in "the cow jumped-20 feet high30er than the lazy 20 timing fox who couldn't keep up the 865 meter race." remove the whole numbers 20 and 865 but keep the 20 in jumped-20 and the 30 in high30er. What is the best to do this using re? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at cs.wpi.edu Sat Aug 2 18:26:00 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Sat, 2 Aug 2008 12:26:00 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: References: Message-ID: > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? Notational convenience. Think about how, in arithmetic expressions, how we're not forced to give explicit names to all the subexpressions: ######################### def hypotenuse(a, b): return ((a * a) + (b * b))**0.5 ######################### Imagine a world where we have to give explicit names to all of the subexpressions: ################### def hypotenuse(a, b): tmp1 = a * a tmp2 = b * b tmp3 = tmp1 + tmp2 tmp4 = tmp3**0.5 return tmp4 #################### Does this look funny to you? Why? Sometimes we don't care what something is named: we just want to use the value. lambda's use is motivated by the same idea: sometimes, we want to use a function value without having to give a name. Here's a toy example. #################################### def deepmap(f, datum): """Deeply applies f across the datum.""" if type(datum) == list: return [deepmap(f, x) for x in datum] else: return f(datum) #################################### If we wanted to apply a squaring on all the numbers in the nested list (while still maintaining the nested structure): [42, 43, [44, [45]]] then we can use deepmap by feeding in a square function to it. ############################## def square(x): return x * x deepmap(square, [42, 43, [44, [45]]]) ############################### An alternative way to express the above is: deepmap(lambda x: x *x, [42, 43, [44, [45]]]) Here, we avoid having to first give a name to the function value we're passing to deepmap. From alan.gauld at btinternet.com Sat Aug 2 18:50:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 17:50:12 +0100 Subject: [Tutor] Classes in separate files References: Message-ID: "James" wrote > The issue is, however, that I'm not sure the "best" way to pass > things > into classes, and the "best" way to get something back. In an OOP syustem you don;t normally have to pass a lot into a method since most of the data should be internal to the object Often a single object parameter is all thats required - if any. > I have a main file, main.py. It's going to create several instances > that are defined by a class in class1.py. *However*, I also need to > instantiate numerous other classes defined in class2.py. The files issue is largely irrelevant and no different for OOP than for procedural coding. Keep related classes in a single module. Put unrelated classes in another module to ease reuse. > class1.py has a few classes, such as > - ticket (represents a ticket opened to fix bugs in a program) > - ticketAnalyzer (an object who looks at all the tickets > opened/available) Its convention to make class names start with an upperc ase letter. Attributes/methods/instances start with lowercase. As to TicketAnalyzer - why doesn't the ticket analyze itself? > class2.py has a few classes, as well, such as: > - codemonkey (defines a person that is going to take tickets and fix > them) So has a method called fix(aTicket)? > - codereviewer (defines a person who will double check a > codemonkey's work) So has a method called check(aTicket)? These two classes sound like subclasses of a common superclass - called Person maybe? > main.py has the "main" function, and will be what is actually > invoked at > the command line. In main.py I can instantiate an object of type > ticket, an object of type ticketAnalyzer, and then instantiate > code{monkey,reviewer} classes. However, how do I get codemonkey and > codereviewer to call methods on the ticket and ticketAnalyzer > classes? in the CodeMonkey.fix(aTicket) method the code can reference aTicket. as in: def fix(self, aTicket): faultType = aTicket.analyze() # do whatever you do to fix it?! aTicket.status = aTicket.analyze() # check if its fixed return aTicket.status > The only solution I can think of here is having the main function > (in > main.py) which instantiates all these objects actually *pass in* to > the codemonkey and reviewer the reference to the specific objects > ticketAnalyzer and ticket. Is this the best way to do it? Its one approach. Without knowing a lot more about the problem it seems a reasonable way forward > handle that behavior in the __init__ of code{monkey,reviewer}? Almost certainly not. the monkey and reviewer will presumably work on more than one ticket so you want to feed the work in progressively rather than create new instances for each ticket - I assume, maybe not! You don't say much about what the system does, which is pretty fundamental to OOD since it is driven by the behaviour required. I'm guessing that you want to be able to create multiple tickets and assign them to a group of monkeys and reviewers? The system then manages the progress of the tickets? > I instead create a method inside of the codemonkey and reviewer > classes that accepts the object pointer to the ticket objects and > then > interact between ticket/code* objects as such? That's the way I'd go. OOP programs are all about objects interacting. Think of the main function as being the global controller kicking off the initial scenarios which then run as semi-autonomous threads. > I image it would be much easier to have everything in one file, but > that goes against my grain. ;) As I said earlier the physical location of the code makes no difference to the logical design of the system. A few import startements will deal with that. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 2 19:00:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:00:30 +0100 Subject: [Tutor] Why use lambda? References: Message-ID: "desmond mansfield" wrote > But what I don't understand, and cannot seem to find an > answer to, is why I'd actually want to use it ? Its a matter of taste. There is nothing you can do with lambda that you cannot do with a function definition. But you might need an awful lot of functions which can make your code cluttered. > What can lambda do that normal function definitions cannot? Exist without a name. > Is it quicker to execute/less memory intensive? No. > Or is it just quicker to type and easier to think about? Quicker to type but most folks don't find them easier to think about! The exception to that is people trained in Lambda calculus where lambdas are a fundamental part of the theory. Using lambdas then becomes the natural way to express a solution. Lambda calculus is what the Functional Programming style is based upon. Python supports FP so it has lambdas. You don't have to use them. Some other languages provide much stronger support for lambdas than does Python. The python community tends to be split into those who would like to see lanmdas made much more powerful and those who woyuld like to see them removed entirely! The current syntactic sugar version pleases nobody very much. :-) >From a pure FP theory point of view a function is a named lambda. In some dialects of Lisp you define a function by creating a lambda, like this: (defun f (lambda (expr))) In Python we can say that def f : return (expr) is identical to f = lambda: (expr) Ruby and Smalltalk both offer "code blocks" which perform the same function but with more flexibility. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 2 19:04:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:04:00 +0100 Subject: [Tutor] removing whole numbers from text References: Message-ID: "Dinesh B Vadhia" wrote > I want to remove whole numbers from text but retain numbers > attached to words. Is this a homework? If so we can only offer suggestions to direction but not give solutions. > What is the best to do this using re? Yes, use re to define a pattern then use sub() to replace with an empty string Alan G. -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Aug 2 19:08:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:08:44 +0100 Subject: [Tutor] I can't believe this needs to be this complex References: <20080802100759.4A97D1E4003@bag.python.org><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> Message-ID: "Dick Moores" wrote > BTW Kent, I'm going to take this opportunity to ask you about > "System" in the IPython timing results. It's always zero for the > code I time. What's an example of code that would have System be > greater than zero? And what's the distinction between User and > System? (I'm using Win XP, if that's relevant.) In timing user time is time that the CPU spends executing user code - your program. System time is time the CPU spends doing OS things. If your code had a blocking call that waited for input on a port say, then the OS might be doing other stuff in the background while your code waited. This would show as system time. In some OR even time spent reading files from disk is counted as system time because your code is executing low level OS functions. Try timing a function that does nothing but read a large file. See if there is any system time showing up. Or time a GUI app that waits for user input... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From noufal at nibrahim.net.in Sat Aug 2 20:02:50 2008 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sat, 02 Aug 2008 23:32:50 +0530 Subject: [Tutor] removing whole numbers from text In-Reply-To: References: Message-ID: <4894A14A.8060306@nibrahim.net.in> Alan Gauld wrote: > > "Dinesh B Vadhia" wrote > >> I want to remove whole numbers from text but retain numbers >> attached to words. > > Is this a homework? > If so we can only offer suggestions to direction but not give solutions. > >> What is the best to do this using re? > > Yes, use re to define a pattern then use sub() to replace with > an empty string If you're having trouble with writing regular expressions, you can either use http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs re-builder mode for some interactive training. -- ~noufal http://nibrahim.net.in/ From jtp at nc.rr.com Sat Aug 2 20:36:00 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 14:36:00 -0400 Subject: [Tutor] locks and threads Message-ID: All, I'm trying to write a class that will acquire a lock before entering a critical section, and then release it. Does this look like the right way to go about accomplishing my goal? try: grabLock = self.lock.acquire( 0 ) if grabLock: print 'acquired lock successfully' else: print "did *not* obtain lock" < ** what do I put here? ** > finally: if grabLock is True: self.lock.release() print 'released lock' What should I be doing in the else: statement? If I can't grab the lock, should I simply try again? Maybe a while loop that keeps trying until I grab the lock? (I'm not really sure how I'm going to integrate the 'try' statement with the while loop, though, to solve the problem of not grabbing the lock) Thoughts? -j From benoit.thiell at cern.ch Sat Aug 2 21:01:26 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Sat, 2 Aug 2008 21:01:26 +0200 Subject: [Tutor] removing whole numbers from text In-Reply-To: <4894A14A.8060306@nibrahim.net.in> References: <4894A14A.8060306@nibrahim.net.in> Message-ID: Dear Dinesh, if you're using the regular expression only once, I would recommend: without_numbers = " ".join(re.split(" [0-9]+ ", phrase)) If not, compile the regular expression first and use the compiled version. Regards, Benoit Thiell. On Sat, 2 Aug 2008, Noufal Ibrahim wrote: > Alan Gauld wrote: >> >> "Dinesh B Vadhia" wrote >> >>> I want to remove whole numbers from text but retain numbers >>> attached to words. >> >> Is this a homework? >> If so we can only offer suggestions to direction but not give solutions. >> >>> What is the best to do this using re? >> >> Yes, use re to define a pattern then use sub() to replace with >> an empty string > > > If you're having trouble with writing regular expressions, you can either use > http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs re-builder mode for > some interactive training. > > > -- > ~noufal > http://nibrahim.net.in/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sat Aug 2 22:17:51 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 02 Aug 2008 16:17:51 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: References: Message-ID: <4894C0EF.7000604@gmail.com> desmond mansfield wrote: > I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". > But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? > > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? In my Python Pipelines program for the Count stage I have: opts = { 'characters' : lambda rec, tot: tot + len(rec), 'words' : lambda rec, tot: tot + len(rec.split()), 'lines' : lambda rec, tot: tot + 1, 'minline' : lambda rec, tot: min(len(rec), tot), 'maxline' : lambda rec, tot: max(len(rec), tot), } Consider how many more lines of code it would take if I had to use defs. Consider how readable it is to have the expressions all in one place. -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sun Aug 3 01:28:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 00:28:11 +0100 Subject: [Tutor] Why use lambda? References: <4894C0EF.7000604@gmail.com> Message-ID: "bob gailer" wrote > In my Python Pipelines program for the Count stage I have: > > opts = { > 'characters' : lambda rec, tot: tot + len(rec), > 'words' : lambda rec, tot: tot + len(rec.split()), > 'lines' : lambda rec, tot: tot + 1, > 'minline' : lambda rec, tot: min(len(rec), tot), > 'maxline' : lambda rec, tot: max(len(rec), tot), > } def characters(rec,tot): return tot + len(rec) def words(rec,tot): return tot + len(rec.split()) etc... Not many more characters than using lambda and avoids the need for the dictionary lookup: instead of w = opts['words'](r,c) just use: w = words(r,c) If you need the dictionary for dynamic lookup then just insert the functions intop the dict: opts = { 'characters' : characters, 'worsds' : words, etc... } > Consider how many more lines of code it would take if I had to use > defs. More or less by definition a Python lambda expression can be replaced with a one-liner function. > Consider how readable it is to have the expressions all in one > place. In this case I'm not sure the gain is huge, its largely a matter of personal preference. Alan G. From alan.gauld at btinternet.com Sun Aug 3 01:35:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 00:35:20 +0100 Subject: [Tutor] Classes in separate files References: Message-ID: "James" wrote > Another question on classes in separate files... It could just as well be about functions. The issue is about visibility of names not classes. > main.py instantiates a class called 'testClass' inside of a file > temp.py. > > In main.py: > t = temp.testClass() > ... > So here's a question...how does the object *t* (defined in the > temp.py > file) access a global (or even local) variable in main.py? Is it > possible? You would need to import main into temp.py. But thats OK since your code has to know about main to want to access one of its variables! But it destroys yuour classes reuse capability since they are now bound to main... Otherwise make it a parameter to the method and pass it in from where it is called in main. > What if I want the object t to write to a global variable > inside of main.py...is that possible? Same as above import the module. Or make the method returm the value and explicitly set the value. All of which emphasises why global variables are a bad design idea. And why class methods should work with their own internal data as much as possible. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From david at abbottdavid.com Sun Aug 3 04:14:27 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 22:14:27 -0400 Subject: [Tutor] Output never stops Message-ID: <48951483.6020501@abbottdavid.com> Very new to python and never programed before. Can not figure out why the output never stops when I run this in a terminal #!/usr/bin/python choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") while choice != '-1': person = {'Lary': 43,'Joan': 24} if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print 'Bad Code' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From david at abbottdavid.com Sun Aug 3 04:21:33 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 22:21:33 -0400 Subject: [Tutor] Output never stops In-Reply-To: <48951483.6020501@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> Message-ID: <4895162D.5010803@abbottdavid.com> David wrote: > Very new to python and never programed before. Can not figure out why > the output never stops when I run this in a terminal > > > #!/usr/bin/python > > > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print 'Bad Code' > should have been like this; #!/usr/bin/python choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") while choice != '-1': person = {'Lary': 43,'Joan': 24} if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print 'Bad Code' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From vsant at hcs.harvard.edu Sun Aug 3 04:50:22 2008 From: vsant at hcs.harvard.edu (Vivek Sant) Date: Sat, 2 Aug 2008 22:50:22 -0400 Subject: [Tutor] Output never stops In-Reply-To: <4895162D.5010803@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> Message-ID: <6B8E91B8-CBD1-46FC-A1A7-C511501BDEB4@hcs.harvard.edu> Hi David, Simple explanation - you should use if instead of while. A while statement executes whatever is in that block again and again until the condition becomes false. So your code, the way you have it, first checks if the user's input is not -1. If you have typed Lary, it goes on to print Lary, hits the end of the while block, and starts back at the top, since choice still is not -1. If you change while to if, the statement will only be executed once. Here's a scenario you might want to use a while loop (which might be what you were trying to do): suppose you want to keep on asking for input if the input is not a quit code, or valid input. To do this, you could just put the choice = raw_input line inside the while block, and perhaps make sure to initialize choice to '' (an empty string or something). Vivek On Aug 2, 2008, at 10:21 PM, David wrote: > David wrote: >> Very new to python and never programed before. Can not figure out >> why the output never stops when I run this in a terminal >> >> >> #!/usr/bin/python >> >> >> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") >> while choice != '-1': person = {'Lary': 43,'Joan': 24} >> if choice == 'Lary': >> print "Lary's age is:", person.get('Lary') >> >> elif choice == 'Joan': >> print "Joan's age is:", person.get('Joan') >> >> else: >> print 'Bad Code' >> > should have been like this; > > #!/usr/bin/python > > > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print 'Bad Code' > > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From federo at email.si Sat Aug 2 16:39:53 2008 From: federo at email.si (Federo) Date: Sat, 02 Aug 2008 16:39:53 +0200 Subject: [Tutor] Developing Macro: Is it possible in Python? Message-ID: <20080802143954.3159C8D183@www1.email.si> Hi Is it possible to do macro with Python? Macro should be able to click on given x,y screen location (one click, double click), drag scroll bar up / down etc.. Macro should be also able to extract data from predefined screen x,y location. I would use this to control desktop windows based program. The program is written from external provider - not Microsoft or me (it runs on xp environment).. Above actions can be easily performed using Macro Scheduler. I am looking for possibility to do the same with Python? Is there any other way beside macro to control windows based application? The best will be to be able to control application from background (the same time mouse and screen would be free for other work. No flashing on screen. In ideal program would be ran as beck - hiden process..) Cheers, Fedo ____________________ http://www.email.si/ From federo at email.si Sat Aug 2 17:17:48 2008 From: federo at email.si (Federo) Date: Sat, 02 Aug 2008 17:17:48 +0200 Subject: [Tutor] Firstrade URL Authentication? In-Reply-To: <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> References: <20080801073939.974DC8CEF6@www1.email.si> <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> Message-ID: <20080802151749.D7F6B8DEA1@www1.email.si> Hi Kent Thanks for your reply. According to your instruction I have tried in Python interactive window the following (in my test I have used real username and password): >>> import urllib2 >>> import urllib >>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) >>> urllib2.install_opener(opener) >>> params = urllib.urlencode(dict(username='user', password='pass')) >>> f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) >>> data = f.read() >>> f.close() >>> f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do') >>> data = f.read() >>> print(data) It printed out login page which means I wasn't able to login to the main page. There must be some sofisticated trick to login to www.Firstrade.com. Any Idea what else can I try? Cheers, Fedo On Fri, 1 Aug 2008 at 12:45:47, Kent Johnson wrote: > On Fri, Aug 1, 2008 at 3:39 AM, Federo wrote: > > Hi .. > > > > I have to admit that Python is really surprising me. It was lucky day a > few > > weeks ago I firts time start using Python. Lot's of things realy can be > done > > with short learning curve. Your user guieds was best place to start! > > > > Below is problem I am unable to solve. I would appreciate your advice or > > even better code sample. The problem is URL authorisation. > > I have a writeup on form-based authentication here: > http://personalpages.tds.net/~kent37/kk/00010.html#e10form-based-authenticati > on > > Kent ____________________ http://www.email.si/ From kent37 at tds.net Sun Aug 3 05:32:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 23:32:09 -0400 Subject: [Tutor] Firstrade URL Authentication? In-Reply-To: <20080802151749.D7F6B8DEA1@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> <20080802151749.D7F6B8DEA1@www1.email.si> Message-ID: <1c2a2c590808022032v5c4ef486r4084f215273fa4e4@mail.gmail.com> On Sat, Aug 2, 2008 at 11:17 AM, Federo wrote: > There must be some sofisticated trick to login to www.Firstrade.com. Any Idea > what else can I try? You have to find out what it does in the browser using Firebug or other tools that will let you see the headers and data. Perhaps there is another cookie (Django authentication sends a cookie with the login form). Perhaps there is some other header that must be set. Look for other cookies and try setting the User-Agent header to match what the browser sends, or just match all the headers. Kent From kent37 at tds.net Sun Aug 3 05:38:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 23:38:50 -0400 Subject: [Tutor] locks and threads In-Reply-To: References: Message-ID: <1c2a2c590808022038u7f3d568v7e913840d2a6dd23@mail.gmail.com> On Sat, Aug 2, 2008 at 2:36 PM, James wrote: > All, > > I'm trying to write a class that will acquire a lock before entering a > critical section, and then release it. Does this look like the right > way to go about accomplishing my goal? > > try: > grabLock = self.lock.acquire( 0 ) > if grabLock: > print 'acquired lock successfully' > else: > print "did *not* obtain lock" > < ** what do I put here? ** > > finally: > if grabLock is True: > > > self.lock.release() > print 'released lock' > > What should I be doing in the else: statement? If I can't grab the > lock, should I simply try again? Maybe a while loop that keeps trying > until I grab the lock? (I'm not really sure how I'm going to integrate > the 'try' statement with the while loop, though, to solve the problem > of not grabbing the lock) What are you using for the lock. A threading.Lock will block if you try to acquire it and it is not available. Why do you need the try? You could put the acquire in a while loop. You probably want to sleep in the loop, so you don't chew up too much CPU. Kent From rdm at rcblue.com Sun Aug 3 06:11:41 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 21:11:41 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> Message-ID: <20080803041156.34ED71E4006@bag.python.org> At 10:08 AM 8/2/2008, Alan Gauld wrote: >"Dick Moores" wrote > >>BTW Kent, I'm going to take this opportunity to ask you about >>"System" in the IPython timing results. It's always zero for the >>code I time. What's an example of code that would have System be >>greater than zero? And what's the distinction between User and >>System? (I'm using Win XP, if that's relevant.) > >In timing user time is time that the CPU spends executing user >code - your program. System time is time the CPU spends doing >OS things. > >If your code had a blocking call that waited for input on a port say, >then the OS might be doing other stuff in the background while >your code waited. This would show as system time. >In some OR even time spent reading files from disk is >counted as system time because your code is executing >low level OS functions. > >Try timing a function that does nothing but read a large file. >See if there is any system time showing up. Well, here's one that reads in the text of Dickens' _Little Dorrit_ and returns the word count: In [11]: run -t -N10 timing_test_little_dorrit.py 339832 339832 339832 339832 339832 339832 339832 339832 339832 339832 IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 5.94446752311 s, 0.594446752311 s. System: 0.0 s, 0.0 s. >Or time a GUI >app that waits for user input... This one is a Gui that has an Exit button. I called it and then hit the button: In [4]: run -t ToolkitV15.py IPython CPU timings (estimated): User : 10.5294301371 s. System: 0.0 s. So no non-zero System time yet. But thanks for your explanation. Dick From alan.gauld at btinternet.com Sun Aug 3 10:00:29 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:00:29 +0100 Subject: [Tutor] I can't believe this needs to be this complex References: <20080802100759.4A97D1E4003@bag.python.org><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m><20080802132734.A50001E4016@bag.python.org> <20080803041156.34ED71E4006@bag.python.org> Message-ID: "Dick Moores" wrote >>>code I time. What's an example of code that would have System be >>>greater than zero? And what's the distinction between User and >>>System? (I'm using Win XP, if that's relevant.) It may be that XP doesn't report System time. > Well, here's one that reads in the text of Dickens' _Little Dorrit_ > and returns the word count: > > IPython CPU timings (estimated): > Total runs performed: 10 > Times : Total Per run > User : 5.94446752311 s, 0.594446752311 s. > System: 0.0 s, 0.0 s. I would definitely have expected some system time there. > This one is a Gui that has an Exit button. I called it and then hit > the button: > > IPython CPU timings (estimated): > User : 10.5294301371 s. > System: 0.0 s. That suggests that it is counting elapsed time as user time in which case I'm not sure how it counts system time. It may be an XP issue. Anyone got different results under Linux/MacOS? Alan G. From alan.gauld at btinternet.com Sun Aug 3 10:06:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:06:52 +0100 Subject: [Tutor] Developing Macro: Is it possible in Python? References: <20080802143954.3159C8D183@www1.email.si> Message-ID: "Federo" wrote > Is it possible to do macro with Python? Macro means different things in different context. > Macro should be able to click on given x,y screen > location (one click, double click), drag scroll bar up / down etc.. It seems that you are referring to simulating user actions. The answer then is yes its possible but not trivial. You can use the low level Windows API to send messages to windows simulating mouse clicks etc. But it will usually require monitoring the messages first using a program like Windows Spy. The result is extremely fragile in that any change in the windows environment can render your code useless. > Is there any other way beside macro to control windows > based application? If it supports COM then you can use COM objects to manipulate things directly. The winall package has support for COM or you can use the API directly via ctypes. I confess I tend to use VBScript for this kind of thing, IMHO it plays with Windows much more simply than Python. Alan G. From alan.gauld at btinternet.com Sun Aug 3 10:12:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:12:35 +0100 Subject: [Tutor] Output never stops References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> Message-ID: "David" wrote >> the output never stops when I run this in a terminal >> > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': > person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > else: > print 'Bad Code' You set choice outside the while loop then never change it so the while test will always be true and loop forever. You need to copy the raw_input line into the body of the while loop to reset choice. Also for good style you should move the person = {} line outside the loop since you only want to set up the dictionary once, not every time you execute the loop. The dictionary never changes so recreating it every time is wasteful. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sun Aug 3 13:19:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 04:19:35 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> <20080803041156.34ED71E4006@bag.python.org> Message-ID: <20080803111950.2BA9A1E4002@bag.python.org> At 01:00 AM 8/3/2008, Alan Gauld wrote: >"Dick Moores" wrote > >>>>code I time. What's an example of code that would have System be >>>>greater than zero? And what's the distinction between User and >>>>System? (I'm using Win XP, if that's relevant.) > >It may be that XP doesn't report System time. > >>Well, here's one that reads in the text of Dickens' _Little Dorrit_ >>and returns the word count: >> >>IPython CPU timings (estimated): >>Total runs performed: 10 >> Times : Total Per run >> User : 5.94446752311 s, 0.594446752311 s. >> System: 0.0 s, 0.0 s. > >I would definitely have expected some system time there. > >>This one is a Gui that has an Exit button. I called it and then hit >>the button: >> >>IPython CPU timings (estimated): >> User : 10.5294301371 s. >> System: 0.0 s. > >That suggests that it is counting elapsed time as user time >in which case I'm not sure how it counts system time. >It may be an XP issue. > >Anyone got different results under Linux/MacOS? _Little Dorrit_ is available in us-ascii at ; _War and Peace_ at . Dick From kent37 at tds.net Sun Aug 3 14:15:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 08:15:01 -0400 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <20080803041156.34ED71E4006@bag.python.org> Message-ID: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld wrote: > "Dick Moores" wrote > >>>> code I time. What's an example of code that would have System be greater >>>> than zero? And what's the distinction between User and System? (I'm using >>>> Win XP, if that's relevant.) > > It may be that XP doesn't report System time. >From the IPython help for 'run': -t: print timing information at the end of the run. IPython will give you an estimated CPU time consumption for your script, which under Unix uses the resource module to avoid the wraparound problems of time.clock(). Under Unix, an estimate of time spent on system tasks is also given (for Windows platforms this is reported as 0.0). Kent From cniall at icedcerulean.com Sun Aug 3 16:04:09 2008 From: cniall at icedcerulean.com (CNiall) Date: Sun, 03 Aug 2008 15:04:09 +0100 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) Message-ID: <4895BAD9.5010004@icedcerulean.com> I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.2 0.20000000000000001 >>> 0.33 0.33000000000000002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20000000000000001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ From rdm at rcblue.com Sun Aug 3 17:30:42 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 08:30:42 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <20080803041156.34ED71E4006@bag.python.org> <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> Message-ID: <20080803153054.705E81E4002@bag.python.org> At 05:15 AM 8/3/2008, Kent Johnson wrote: >On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld wrote: > > "Dick Moores" wrote > > > >>>> code I time. What's an example of code that would have System be greater > >>>> than zero? And what's the distinction between User and System? > (I'm using > >>>> Win XP, if that's relevant.) > > > > It may be that XP doesn't report System time. > > From the IPython help for 'run': > > -t: print timing information at the end of the run. IPython will >give you an estimated CPU time consumption for your script, which >under Unix uses the resource module to avoid the wraparound >problems of time.clock(). Under Unix, an estimate of time spent on >system tasks is also given Thanks, Kent. RTFM! >(for Windows platforms this is reported >as 0.0). I wonder why it is reported for Windows at all? Dick From rdm at rcblue.com Sun Aug 3 17:30:42 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 08:30:42 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <20080803041156.34ED71E4006@bag.python.org> <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> Message-ID: <20080803153054.73F471E4003@bag.python.org> At 05:15 AM 8/3/2008, Kent Johnson wrote: >On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld wrote: > > "Dick Moores" wrote > > > >>>> code I time. What's an example of code that would have System be greater > >>>> than zero? And what's the distinction between User and System? > (I'm using > >>>> Win XP, if that's relevant.) > > > > It may be that XP doesn't report System time. > > From the IPython help for 'run': > > -t: print timing information at the end of the run. IPython will >give you an estimated CPU time consumption for your script, which >under Unix uses the resource module to avoid the wraparound >problems of time.clock(). Under Unix, an estimate of time spent on >system tasks is also given Thanks, Kent. RTFM! >(for Windows platforms this is reported >as 0.0). I wonder why it is reported for Windows at all? Dick From thomas.pani at gmail.com Sun Aug 3 17:32:27 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Sun, 03 Aug 2008 17:32:27 +0200 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> References: <4895BAD9.5010004@icedcerulean.com> Message-ID: <4895CF8B.3050203@gmail.com> CNiall wrote: > I want to make a simple script that calculates the n-th root of a given > number (e.g. 4th root of 625--obviously five, but it's just an example > :P), and because there is no nth-root function in Python I will do this > with something like x**(1/n). > Side note: of course there are python built-in ways to do that. You just named one yourself: In [6]: 625**(1.0/4) Out[6]: 5.0 also: In [9]: pow(625, 1.0/4) Out[9]: 5.0 > However, with some, but not all, decimals, they do not seem to 'equal > themselves'. > > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the decimal > does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 > and not 0.20000000000000001? > You just can't store 0.1 as a binary floating point. You might want to read: http://www.network-theory.co.uk/docs/pytut/FloatingPointArithmeticIssuesandLimitations.html http://www.network-theory.co.uk/docs/pytut/RepresentationError.html The decimal module provides decimal floating point arithmetic: http://docs.python.org/lib/module-decimal.html like in: In [1]: 0.2 * 2 Out[1]: 0.40000000000000002 In [2]: from decimal import Decimal In [3]: Decimal('0.2') * 2 Out[3]: Decimal("0.4") thomas From david at abbottdavid.com Sun Aug 3 17:33:15 2008 From: david at abbottdavid.com (David) Date: Sun, 03 Aug 2008 11:33:15 -0400 Subject: [Tutor] Output never stops In-Reply-To: References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> Message-ID: <4895CFBB.1070601@abbottdavid.com> Alan Gauld wrote: > > "David" wrote >>> the output never stops when I run this in a terminal >>> >> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") >> while choice != '-1': person = {'Lary': 43,'Joan': 24} >> if choice == 'Lary': >> print "Lary's age is:", person.get('Lary') >> elif choice == 'Joan': >> print "Joan's age is:", person.get('Joan') >> else: >> print 'Bad Code' > > You set choice outside the while loop then never change it so the > while test will always be true and loop forever. > You need to copy the raw_input line into the body of the while loop to > reset choice. > > Also for good style you should move the person = {} line outside the > loop since you only want to set up the dictionary once, not every time > you execute the loop. The dictionary never changes so recreating it > every time is wasteful. > > HTH, > Thanks Alan, also your tutorial/book is a big help. I think I got it :) #!/usr/bin/python person = {'Lary':43,'Joan':24} choice = 0 while choice != '-1': if choice == '': print "You must enter Lary or Joan to continue! (-1 to quit): " choice = raw_input( "Who's age do want to know, Lary or Joan? (-1 to quit): ") if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print "Goodbye!" -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From kent37 at tds.net Sun Aug 3 17:35:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 11:35:49 -0400 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> References: <4895BAD9.5010004@icedcerulean.com> Message-ID: <1c2a2c590808030835r1dd8f52bq2d32f57e6dc6edc2@mail.gmail.com> On Sun, Aug 3, 2008 at 10:04 AM, CNiall wrote: > I want to make a simple script that calculates the n-th root of a given > number (e.g. 4th root of 625--obviously five, but it's just an example :P), > and because there is no nth-root function in Python I will do this with > something like x**(1/n). > > However, with some, but not all, decimals, they do not seem to 'equal > themselves'. This is probably a bad way of expressing what I mean, so I'll > give an example: > 0.125 >>>> 0.2 > 0.20000000000000001 >>>> 0.33 > 0.33000000000000002 > > As you can see, the last two decimals are very slightly inaccurate. However, > it appears that when n in 1/n is a power of two, the decimal does not get > 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not > 0.20000000000000001? This is a limitation of floaating point numbers. A discussion is here: http://docs.python.org/tut/node16.html Your root calculator can only find answers that are as accurate as the representation allows. Kent From alan.gauld at btinternet.com Sun Aug 3 17:44:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 16:44:46 +0100 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals0.200000001) References: <4895BAD9.5010004@icedcerulean.com> Message-ID: "CNiall" wrote > However, with some, but not all, decimals, they do not seem to > 'equal themselves'. This is probably a bad way of expressing what I > mean, so I'll give an example: > >>> 0.5 > 0.5 > >>> 0.2 > 0.20000000000000001 > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the > decimal does not get 'thrown off'. And that is the clue. Computers represent data as binary, ie powers of two. If a number cannot be expressed exactly as a power of two then a computer (any binary computer!) cannot represent the number exactly. It is the same in "natural" arithmetic where we use base 10. We cannot exactly represent numbers like 1/3 as a decimal number we have to approximate to 0.33333333.... Likewise with 1/7 etc. In most cases the approximation is "good enough" and we just live with it. (But its not a good idea to use floating point numbers to represent money!). If you do need exact numbers you can use the decimal module which will do what you want but at the expense of adding complexity. > How might I make Python recognise 0.2 as 0.2 and not > 0.20000000000000001? Mostl;y it won;t matter, what you will want is to be able to print it as 0.2. You can do this in a number of ways but the most flexible is to use a format string: >>> x = 0.2 >>> print "%6f" % x 0.2000 The percent inside the string is a marker which is substituted by the value after the percent outside the string (ie x in this case) The number following the first % is the length of representation - 6 chars in this case. There are several other numbers and symbols you can use to coerce the representation to be as you wish - left/roight aligned, leading zeros, scientific notation etc Search the Python docs for "format" and you should find the details... The other thing to watch is when comparing float values. >>> y = 1 - 0.8 >>> y == x False >>> e = 0.0000000001 >>> x-e < y < x+e True You can find out more about format stringsin the Simple Sequences topic of my tutorial. You can find out a little bit more about floating point numbers in the Raw Data topic of my tutorial under the heading Real Numbers. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ptmcg at austin.rr.com Sun Aug 3 17:41:30 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 3 Aug 2008 10:41:30 -0500 Subject: [Tutor] Developing Macro: Is it possible in Python? In-Reply-To: References: Message-ID: <72D8C9397E8345E0A71D28B66C16EFDD@AWA2> I have used pywinauto for such tasks in the past. http://pywinauto.openqa.org/ In my case, I used pywinauto to automate mouse clicks on a browser in order to auto-play a Flash game running in the browser. I had to use PIL to take screenshots and then process images to "read" the screen. -- Paul From emile at fenx.com Sun Aug 3 18:20:23 2008 From: emile at fenx.com (Emile van Sebille) Date: Sun, 03 Aug 2008 09:20:23 -0700 Subject: [Tutor] Developing Macro: Is it possible in Python? In-Reply-To: <20080802143954.3159C8D183@www1.email.si> References: <20080802143954.3159C8D183@www1.email.si> Message-ID: Federo wrote: > Above actions can be easily performed using Macro Scheduler. I am looking for > possibility to do the same with Python? Hi Federo, I regularly combine Macro Scheduler with python by having my python code write mSched scripts. I find the combination of the two particularly adept at controlling legacy windows apps on current windows platforms. The main function accepts a command list and name, writes a .scp msched script file and invokes the mSched command with os.system. When I first considered how to approach this in about 2002, I looked at Mark Hammonds extensions and tried that, but it seemed to me at the time that the older apps simply didn't play nice and I fought harder to implement a pure python solution than the problem deserved. Now, it's easy to review the python created msched scripts and 'follow along' to catch the odd bug. mSched's capabilities have grown over that time as well and added some commands that make timing issues more predictable. Although, I admit I'm never actually in the mSched environment so I may well be doing things with python that are entirely doable in mSched. But, with python as glue I can control and coordinate as many disparate environments as the solution requires and it's mostly quick and easy. Emile From kent37 at tds.net Sun Aug 3 23:04:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 17:04:39 -0400 Subject: [Tutor] Firstrade Authentication ... In-Reply-To: <20080803164558.A7EB4981F4@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> Message-ID: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> On Sun, Aug 3, 2008 at 12:45 PM, Federo wrote: > Jeff, Kent Hi! > > If possible I would most appreciate to use mechanize approach Jeff suggested. > Python plagin: http://wwwsearch.sourceforge.net/mechanize/ This seems to get to the "Thank you for applying for a Firstrade account." page: import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet500', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() print(data) Differences from your code: - Does a GET on the login page - the session cookie is set here, not on the POST - Includes all the form parameters Kent PS Please respond to the list, not to me personally. From zack_holden at hotmail.com Mon Aug 4 00:16:13 2008 From: zack_holden at hotmail.com (zack holden) Date: Sun, 3 Aug 2008 22:16:13 +0000 Subject: [Tutor] newbie: write ArcGIS lists to file? Message-ID: Dear List, This is my first time on the list, and my first run at Python, please forgive my ignorance. I'm trying to use Python to access ArcGIS modules in order to perform the same task on multiple files in a folder. I'm able to access a set of files via: import arcgisscripting, string gp = arcgisscripting.create() gp.Workspace = "E:/data" rasterSelect = [] rasterList = gp.ListRasters("", "tif") raster = rasterList.Next() while raster: if raster.endswith("_dt.tif"): print raster rasterSelect.append(raster) raster = rasterList.Next() This produces a list of all the files I have in my folder. I need to begin producing .csv files of this list that I can access using other programs. Would someone be willing to post a few lines of code showing me how to write the list the code above creates to an external file? Gratefully, Zack From python-list at puzzled.xs4all.nl Mon Aug 4 00:24:37 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Mon, 04 Aug 2008 00:24:37 +0200 Subject: [Tutor] Firstrade Authentication ... In-Reply-To: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> Message-ID: <48963025.6020709@puzzled.xs4all.nl> Kent Johnson wrote: [snip] > params = dict(username='janezfedero', password='kmet500', destination='') I hope this is a fake username & password.... Regards, Patrick From alan.gauld at freenet.co.uk Mon Aug 4 00:55:09 2008 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 3 Aug 2008 23:55:09 +0100 Subject: [Tutor] Any Italian speakers? Message-ID: <8635291937C04629B8D8AB50677E206E@xp> I received this message which Google tells me is Italian but then only gives a partial translation... Can anyone help? ------------------- voglio chiderti solo 1 cosa ... ma secondo te qualle e il miglior programma X programmare??? grazie ... da Cristian ----------------- Alan G. From alan.gauld at btinternet.com Mon Aug 4 01:08:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:08:35 +0100 Subject: [Tutor] Output never stops References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> <4895CFBB.1070601@abbottdavid.com> Message-ID: "David" wrote > Thanks Alan, also your tutorial/book is a big help. I think I got it > :) Close but not quite there yet. > choice = 0 > while choice != '-1': > if choice == '': > print "You must enter Lary or Joan to continue! (-1 to quit): > " > choice = raw_input( > "Who's age do want to know, Lary or Joan? (-1 to quit): > ") > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > else: > print "Goodbye!" Consider what happens if I enter a blank name. You print Goodbye but then go round the loop again prompting for another choice. You probably want the Goodbye to only be printed if choice == '-1'? And the test for the empty string should ptrobably be after you ask for the input? Also the normal way to access a dictionary value is to use square brackets: person['Lary'] get() does have the advantage that you can add a default value that is returned if the key doesn't exist. But that's not relevant in this case. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carlos.laviola at gmail.com Mon Aug 4 01:12:52 2008 From: carlos.laviola at gmail.com (Carlos Laviola) Date: Sun, 03 Aug 2008 20:12:52 -0300 Subject: [Tutor] List elements as indices to another list Message-ID: <48963B74.9000009@gmail.com> Hi, I have a simple "matrix" (nested list) defined as such: M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] I'm trying to come up with a different way of getting its, well, "reverse antidiagonal", since the actual antidiagonal of M goes from M[0, N] to M[N, 0] according to http://planetmath.org/encyclopedia/AntiDiagonalMatrix.html: j = 0 for i in range(len(M)-1, -1, -1): print M[i][j] j += 1 This works fine, but I was looking for a different solution, just for kicks, and came across something interesting. I can do: >>> i, j = range(len(M)), range(len(M)-1, -1, -1) >>> i [0, 1, 2] >>> j [2, 1, 0] Theoretically, I could then just iterate over range(len(M)) and grab M[i[N]j[N]], but that's not legal. What would be the right way of doing this? Thanks in advance, Carlos From alan.gauld at btinternet.com Mon Aug 4 01:13:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:13:02 +0100 Subject: [Tutor] newbie: write ArcGIS lists to file? References: Message-ID: "zack holden" wrote > I need to begin producing .csv files of this list that I can > access using other programs. > > Would someone be willing to post a few lines of code > showing me how to write the list the code above creates to an > external file? Check the documentation for the csv module, I beliebe it supports both reading and writing CSV files. Alan G. From alan.gauld at btinternet.com Mon Aug 4 01:33:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:33:56 +0100 Subject: [Tutor] List elements as indices to another list References: <48963B74.9000009@gmail.com> Message-ID: "Carlos Laviola" wrote >>>> i > [0, 1, 2] >>>> j > [2, 1, 0] > > Theoretically, I could then just iterate over range(len(M)) and grab > M[i[N]j[N]], but that's not legal. What would be the right way of > doing > this? M [ i[N] ] [ j[N] ] You just missed a couple of brackets... HTH, Alan G From kent37 at tds.net Mon Aug 4 16:04:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 10:04:07 -0400 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <20080804120536.7603E9B056@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> Message-ID: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> On Mon, Aug 4, 2008 at 8:05 AM, Federo wrote: > Kent THANKS! It works great also on real account .. > > Two important Sub-QUESTIONS: > > 1.) Look attached word file. It describes form fields I would like to fill in > and read server resoult.. You just have to mimic what the browser does. Use a Firefox plugin that shows you what is being submitted; TamperData is one. Then set the same fields in your code. > 2.) Could you do the same login logic also with MECHANIZE plagin. There are > some very usefull function in this plagin I might use. However I have No, I'm not familiar with mechanize. Kent From federo at email.si Mon Aug 4 14:05:35 2008 From: federo at email.si (Federo) Date: Mon, 04 Aug 2008 14:05:35 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> Message-ID: <20080804120536.7603E9B056@www1.email.si> Kent THANKS! It works great also on real account .. Two important Sub-QUESTIONS: 1.) Look attached word file. It describes form fields I would like to fill in and read server resoult.. 2.) Could you do the same login logic also with MECHANIZE plagin. There are some very usefull function in this plagin I might use. However I have to be able to login firts.. Plagin download: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Fedo On Sun, 3 Aug 2008 at 23:16:02, Kent Johnson wrote: > On Sun, Aug 3, 2008 at 12:45 PM, Federo wrote: > > Jeff, Kent Hi! > > > > If possible I would most appreciate to use mechanize approach Jeff > suggested. > > Python plagin: http://wwwsearch.sourceforge.net/mechanize/ > > This seems to get to the "Thank you for applying for a Firstrade account." > page: > import urllib2 > import urllib > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) > urllib2.install_opener(opener) > f = opener.open('https://investor.firstrade.com/firstrade/login.do') > data = f.read() > f.close() > > params = dict(username='janezfedero', password='kmet500', destination='') > params['login.x'] = 'Log+In' > params = urllib.urlencode(params) > f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) > data = f.read() > f.close() > print(data) > > Differences from your code: > - Does a GET on the login page - the session cookie is set here, not on the > POST > - Includes all the form parameters > > Kent > > PS Please respond to the list, not to me personally. ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement.doc Type: application/octet-stream Size: 53248 bytes Desc: FormManagement.doc URL: From tomazbevec at yahoo.com Mon Aug 4 17:32:53 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Mon, 4 Aug 2008 08:32:53 -0700 (PDT) Subject: [Tutor] Does unittest slow down code Message-ID: <757462.32952.qm@web32804.mail.mud.yahoo.com> Is code executed within a unit test significantly slower than code executed outside of a unit test? Does code executed within a unit test take up more memory? --TJB From kent37 at tds.net Mon Aug 4 17:53:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 11:53:14 -0400 Subject: [Tutor] Does unittest slow down code In-Reply-To: <757462.32952.qm@web32804.mail.mud.yahoo.com> References: <757462.32952.qm@web32804.mail.mud.yahoo.com> Message-ID: <1c2a2c590808040853p5c89cc9aka1de6d4048c55f17@mail.gmail.com> On Mon, Aug 4, 2008 at 11:32 AM, Tomaz Bevec wrote: > > Is code executed within a unit test significantly slower than code executed outside of a unit test? Does code executed within a unit test take up more memory? Assuming you are asking about the unittest module...No, not unless you do something specific in the unit test, e.g. testing on a large data set would take more memory. Unittest just runs the code you tell it to and looks at the result. It doesn't instrument the code in any way. You do have to load the actual unittest module but I don't think it has any great memory requirements. Are you seeing this behaviour or just asking about it? Kent From Mike.Hansen at atmel.com Mon Aug 4 19:02:48 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 4 Aug 2008 11:02:48 -0600 Subject: [Tutor] Any Italian speakers? In-Reply-To: <8635291937C04629B8D8AB50677E206E@xp> References: <8635291937C04629B8D8AB50677E206E@xp> Message-ID: <7941B2693F32294AAF16C26B679A258D0324C62F@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Sunday, August 03, 2008 4:55 PM > To: tutor at python.org > Subject: [Tutor] Any Italian speakers? > > I received this message which Google tells me is Italian but then > only gives a partial translation... > > Can anyone help? > > ------------------- > voglio chiderti solo 1 cosa ... ma secondo te qualle e il > miglior programma X programmare??? > grazie ... > > da Cristian > ----------------- > > Alan G. Alan, Unfortunately, I only speak and read/write English. Did you find anyone to traslate? I plugged it into Bablefish and tried Italian to English and here's what I got.(Probably the same as you.). "I want chiderti only 1 thing... but according to you qualle and better program X to program? thanks " I also tried Spanish, Potuguese, and Greek, but the Italian one came out the best. Mike From bgailer at gmail.com Mon Aug 4 19:34:14 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 04 Aug 2008 13:34:14 -0400 Subject: [Tutor] Output never stops In-Reply-To: <4895CFBB.1070601@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> <4895CFBB.1070601@abbottdavid.com> Message-ID: <48973D96.5020607@gmail.com> David wrote: [snip] > #!/usr/bin/python > > person = {'Lary':43,'Joan':24} > > choice = 0 > while choice != '-1': > if choice == '': > print "You must enter Lary or Joan to continue! (-1 to quit): " > choice = raw_input( > "Who's age do want to know, Lary or Joan? (-1 to quit): ") > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print "Goodbye!" > > Consider leveraging the dictionary (and some other"Pythonic" refinements). Separate the logic from the data. Now you can add more names and ages without changing the logic. #!/usr/bin/python person = {'Lary':43, 'Joan':24, 'Bob':68} keys = person.keys() names = ', '.join(keys[:-1]) + ' or ' + keys[-1] while True: choice = raw_input("Who's age do want to know, %s? (-1 to quit): " % names) age = person.get(choice, None) if age is not None: print choice + "'s age is:", age elif choice == "-1": print "Goodbye!" break else: print "Invalid choice " + choice -- Bob Gailer 919-636-4239 Chapel Hill, NC From ceasar102 at yahoo.com Mon Aug 4 20:04:45 2008 From: ceasar102 at yahoo.com (ammar azif) Date: Mon, 4 Aug 2008 11:04:45 -0700 (PDT) Subject: [Tutor] My experience on web.py Message-ID: <196711.50013.qm@web56813.mail.re3.yahoo.com> Hi, I am writing this to tell my experience on web.py. Two weeks ago, I was looking for a python web framework that is simple, straight-forward, easy to use and powerful at the same time. Django? stood out as the most popular when I googled. I tried to use django but I found that the framework hides alot of things from me and files are generated by the framework? automaticaly and I felt like I wasnt in control. I know that django is powerful, but the learning curve is too steep for me and? I need to develop my app as soon as possible. I decided to give web.py a try and I found that the framework is easy to use and it gives a lot of control to the developer when handling GET and POST request and all these can be done in a single source code and using this framework has taught me a lot of low level web application programming basics. I might be wrong as I havent try django or any other frameworks yet. Hope python gurus here can share their thoughts on these matters,? -------------- next part -------------- An HTML attachment was scrubbed... URL: From optomatic at rogers.com Mon Aug 4 20:22:34 2008 From: optomatic at rogers.com (Patrick) Date: Mon, 04 Aug 2008 14:22:34 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <489748EA.1080508@rogers.com> I am in the same situation as you. I was looking at Django and Turbogears. I have finally settled on CherryPy, which is also built into Turbogears. Watching this Google talk on Youtube: http://www.youtube.com/watch?v=p-WXiqrzAf8 it seemed to me that Django is well suited for a developer team but is a bit sketchy when you try to scale it down to a single developer. CherryPy seems to work well as a substitute for all-in-one-page CGI scripts without the respawning issues or as a proper MVC web application server. I set up an account at Webfaction. They specialize in Python hosting and you can set up Turbogears, Django, CherryPy etc with a click of a button. I would love to keep this thread going, please feedback as you move along, I feedback too -patrick ammar azif wrote: > Hi, > > I am writing this to tell my experience on web.py. Two weeks ago, I > was looking for a python web framework that is simple, > straight-forward, easy to use and powerful at the same time. Django > stood out as the most popular when I googled. I tried to use django > but I found that the framework hides alot of things from me and files > are generated by the framework automaticaly and I felt like I wasnt > in control. I know that django is powerful, but the learning curve is > too steep for me and I need to develop my app as soon as possible. I > decided to give web.py a try and I found that the framework is easy to > use and it gives a lot of control to the developer when handling GET > and POST request and all these can be done in a single source code and > using this framework has taught me a lot of low level web application > programming basics. I might be wrong as I havent try django or any > other frameworks yet. Hope python gurus here can share their thoughts > on these matters, > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Aug 4 20:26:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 19:26:38 +0100 Subject: [Tutor] Any Italian speakers? References: <8635291937C04629B8D8AB50677E206E@xp> <7941B2693F32294AAF16C26B679A258D0324C62F@csomb01.corp.atmel.com> Message-ID: "Hansen, Mike" wrote > Did you find anyone to traslate? Yes thanks, Daniele (sp?) replied with a translation. There are some Italian idiomatic things there so it confused Google (and Babelfish!) > "I want chiderti only 1 thing... but according to you qualle > and better program X to program? thanks " Exactly what Google said... It seems the reader wants to know which is the best programming language... Thanks anyway, Alan G. From emile at fenx.com Mon Aug 4 20:34:04 2008 From: emile at fenx.com (Emile van Sebille) Date: Mon, 04 Aug 2008 11:34:04 -0700 Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: ammar azif wrote: > ... share their thoughts on these matters, I haven't tried web.py, but my experience with Django is the opposite of yours. Of course, I came to Django after climbing the learning curve of zope, so Django felt easy to deal with in comparison. It just seemed that each time I encountered a behavior that I wanted to change I could quickly locate the source, make the changes, and continue moving forward. Emile From kent37 at tds.net Mon Aug 4 20:46:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 14:46:20 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <489748EA.1080508@rogers.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> Message-ID: <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> On Mon, Aug 4, 2008 at 2:22 PM, Patrick wrote: > it seemed to me that Django is well suited for a developer team but is a bit > sketchy when you try to scale it down to a single developer. Why do you say that? Django works fine with a single developer. Kent From kent37 at tds.net Mon Aug 4 20:50:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 14:50:04 -0400 Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <1c2a2c590808041150i3f702421s33b24c1382df278d@mail.gmail.com> On Mon, Aug 4, 2008 at 2:04 PM, ammar azif wrote: > I tried to use django but I found that the framework hides > alot of things from me and files are generated by the framework > automaticaly and I felt like I wasnt in control. I'm surprised to hear this. Django generates a few very simple files when you start a project but other than that it is your code. I guess there is a lot that goes on under the hood in the models but I always felt like the major parts of the app were clearly exposed. Anyway I have heard good things about web.py too, you should stick with what works for you. Kent From optomatic at rogers.com Mon Aug 4 20:58:43 2008 From: optomatic at rogers.com (Patrick) Date: Mon, 04 Aug 2008 14:58:43 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> Message-ID: <48975163.5030008@rogers.com> Oh oh, I did not mean to slag Django! I was basing this on the talk given by Jacob Kaplin-Moss(one of the developers). He gave a great talk but became a bit evasive when he was questioned about Django scaling down to a single developer, specifically when he was questioned about the template views portion. "IT SEEMED" I am not qualified to give advice on Django, sorry if I ticked off anyone! Anyone here using CherryPy? Did anyone consider it and then pass on it? -Patrick Kent Johnson wrote: > On Mon, Aug 4, 2008 at 2:22 PM, Patrick wrote: > > >> it seemed to me that Django is well suited for a developer team but is a bit >> sketchy when you try to scale it down to a single developer. >> > > Why do you say that? Django works fine with a single developer. > > Kent > > From kent37 at tds.net Mon Aug 4 23:22:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 17:22:31 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <48975163.5030008@rogers.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> <48975163.5030008@rogers.com> Message-ID: <1c2a2c590808041422n3f306423uace953af31f3fd3a@mail.gmail.com> On Mon, Aug 4, 2008 at 2:58 PM, Patrick wrote: > Oh oh, I did not mean to slag Django! I didn't take it that way, no worries! > I was basing this on the talk given by Jacob Kaplin-Moss(one of the > developers). He gave a great talk but became a bit evasive when he was > questioned about Django scaling down to a single developer, specifically > when he was questioned about the template views portion. Strange. I can't think of any reason why Django would not be suitable for a single developer. Of course the developer has to understand HTML and probably CSS and JavaScript but that is no different than any other web development tool. Googling finds this: http://www.cmlenz.net/archives/2006/08/the-python-web-framework which seems to refer to the same talk. I am not a fan of the Django template language - I think it is too restrictive - but I don't see how it is harder to use it as a single developer than it would be for a team... Kent From simozack at yahoo.it Tue Aug 5 11:22:15 2008 From: simozack at yahoo.it (simone) Date: Tue, 05 Aug 2008 11:22:15 +0200 Subject: [Tutor] Any Italian speakers? In-Reply-To: <8635291937C04629B8D8AB50677E206E@xp> References: <8635291937C04629B8D8AB50677E206E@xp> Message-ID: <48981BC7.5030508@yahoo.it> Alan Gauld ha scritto: > ------------------- > voglio chiderti solo 1 cosa ... ma secondo te qualle e il miglior > programma X programmare??? > grazie ... > > da Cristian > ----------------- Literally: ------------------- "I want to ask you only one thing... what's in your opinion the best program to program?" from Cristian ------------------- -- Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From nkv at hcoop.net Tue Aug 5 08:05:01 2008 From: nkv at hcoop.net (nkv at hcoop.net) Date: Tue, 5 Aug 2008 02:05:01 -0400 (EDT) Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <11987.198.182.52.26.1217916301.squirrel@mail.hcoop.net> [..] > share > their thoughts on these > matters,? I've been using TurboGears for a long time now. The documentation is a little patchy (reads more like a bunch of recipes) but the components which form the framework are all separate projects - each individually capable of standing on it's own legs. Also, the TG mailing list is extremely responsive and helpful. It's quick to get an app up and running and while some of the details are hidden, I've found that most of those are the things which I don't want to mess with. It's got a lot of nice components for authentication and things like that which make development quite nice. From ricaraoz at gmail.com Mon Aug 4 16:27:29 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 04 Aug 2008 11:27:29 -0300 Subject: [Tutor] removing whole numbers from text In-Reply-To: References: Message-ID: <489711D1.8030808@bigfoot.com> Dinesh B Vadhia wrote: > I want to remove whole numbers from text but retain numbers attached to > words. All whole numbers to be removed have a leading and trailing space. > > For example, in "the cow jumped-20 feet high30er than the lazy 20 timing > fox who couldn't keep up the 865 meter race." remove the whole numbers > 20 and 865 but keep the 20 in jumped-20 and the 30 in high30er. > > What is the best to do this using re? > > Dinesh >>> text = "the cow jumped-20 feet high30er than the lazy 20 timing fox who couldn't keep up the 865 meter race." >>> ' '.join(i for i in text.split() if not i.isdigit()) "the cow jumped-20 feet high30er than the lazy timing fox who couldn't keep up the meter race." HTH From monjissvel at googlemail.com Tue Aug 5 13:08:57 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 11:08:57 +0000 Subject: [Tutor] removing whole numbers from text In-Reply-To: <489711D1.8030808@bigfoot.com> References: <489711D1.8030808@bigfoot.com> Message-ID: [root at serv ~]# python Python 2.5.1 (r251:54863, Nov 23 2007, 16:16:53) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import re >>> >>> a = 'this is a simple 3xampl3 of 2 or 3 numb3rs' # some text >>> b = re.sub('\b[0-9]\b', 'xx', a) # you need to use the r (raw) or else it does work >>> print b this is a simple 3xampl3 of 2 or 3 numb3rs >>> b = re.sub(r'\b[0-9]\b', 'xx', a) #replace with xx >>> print b this is a simple 3xampl3 of xx or xx numb3rs >>> b = re.sub(r'\b[0-9]\b', '', a) #replace with nothing >>> print b this is a simple 3xampl3 of or numb3rs >>> 2008/8/4 Ricardo Ar?oz > Dinesh B Vadhia wrote: > >> I want to remove whole numbers from text but retain numbers attached to >> words. All whole numbers to be removed have a leading and trailing space. >> For example, in "the cow jumped-20 feet high30er than the lazy 20 timing >> fox who couldn't keep up the 865 meter race." remove the whole numbers 20 >> and 865 but keep the 20 in jumped-20 and the 30 in high30er. >> What is the best to do this using re? >> Dinesh >> > > >>> text = "the cow jumped-20 feet high30er than the lazy 20 timing fox who > couldn't keep up the 865 meter race." > > >>> ' '.join(i for i in text.split() if not i.isdigit()) > "the cow jumped-20 feet high30er than the lazy timing fox who couldn't keep > up the meter race." > > > HTH > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmorcombe at westnet.com.au Tue Aug 5 13:01:59 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Tue, 05 Aug 2008 19:01:59 +0800 Subject: [Tutor] regular expressions Message-ID: <48983327.5040804@westnet.com.au> Could someone please give me some help using the "re" module. This works: -------------------------------- import re text = "Jim is a good guy" s2 = re.sub('Jim', 'Fred', text) print s2 and I get "Fred is a good guy" --------------------------------- If I have: text = "Bill Smith is nice" how do I get rid of "Smith" and just have "Bill is nice" I tried s2 = re.sub('Smith', '', text) but it complained. If I have: text = "Jim likes a girl (Susan)" and I want to get rid of "(Susan)", how do I do this. First, the "(" seems to muck things up. Second, how do I just use "re" to delete characters. I tried using "sub", but it doesn't seem to like Jim Morcombe From arsyed at gmail.com Tue Aug 5 13:51:00 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 5 Aug 2008 07:51:00 -0400 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: <9a2cc7a70808050451t28060c84o5dc5d7237f0d6e7f@mail.gmail.com> On Tue, Aug 5, 2008 at 7:01 AM, Jim Morcombe wrote: > Could someone please give me some help using the "re" module. > > This works: > -------------------------------- > import re > > text = "Jim is a good guy" > > s2 = re.sub('Jim', 'Fred', text) > print s2 > > and I get "Fred is a good guy" > --------------------------------- > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. > What was the error message? It should work fine: In [25]: text = 'Bill Smith is nice' In [26]: re.sub('Smith', '', text) Out[26]: 'Bill is nice' > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > You need to escape the parentheses because those are grouping metacharacters in regular expressions: In [27]: text = 'Jim likes a girl (Susan)' In [28]: re.sub('\(Susan\)', '', text) Out[28]: 'Jim likes a girl ' The regex howot document below explains a lot of this stuff: http://www.amk.ca/python/howto/regex/ > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like > > Jim Morcombe > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From monjissvel at googlemail.com Tue Aug 5 13:57:23 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 11:57:23 +0000 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: here is what my interpreter gives : >>> >>> >>> text = "Bill Smith is nice" >>> print text Bill Smith is nice >>> re.sub('Smith', '', text) 'Bill is nice' >>> text = "Jim likes a girl (Susan)" >>> print text Jim likes a girl (Susan) >>> KeyboardInterrupt >>> re.sub('(Susan)', '', text) 'Jim likes a girl ()' >>> re.sub(r'(Susan)', '', text) 'Jim likes a girl ()' >>> re.sub(r'\(Susan\)', '', text) 'Jim likes a girl ' >>> >>> re.sub('a', 'aa', 'I am a girl') 'I aam aa girl' >>> so your code seems to be working you just maybe don't know about the 'r' which mean raw & which tells python to take the special characters as they are without interpreting them. some special characters are : \n (new line), \b (space), \t (tab); \r (cariage return on windows). 2008/8/5 Jim Morcombe > Could someone please give me some help using the "re" module. > > This works: > -------------------------------- > import re > > text = "Jim is a good guy" > > s2 = re.sub('Jim', 'Fred', text) > print s2 > > and I get "Fred is a good guy" > --------------------------------- > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. > > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like > > Jim Morcombe > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Aug 5 14:41:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 5 Aug 2008 08:41:41 -0400 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: <1c2a2c590808050541s5daa40den4d5c9f537d3c8144@mail.gmail.com> On Tue, Aug 5, 2008 at 7:01 AM, Jim Morcombe wrote: > Could someone please give me some help using the "re" module. > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. Please show the specific error message you get; "it complained" is too vague. > > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like Again, this is too vague. Show us exactly what you tried and what result you got. BTW you don't need the re module to replace fixed strings with new strings, you can use the replace() method of the string: In [1]: text = "Bill Smith is nice" In [5]: text.replace('Smith', '') Out[5]: 'Bill is nice' Kent From bryan.fodness at gmail.com Tue Aug 5 17:08:57 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Tue, 5 Aug 2008 11:08:57 -0400 Subject: [Tutor] iterating data and populating a dictionary Message-ID: i am filling a dictionary with a dictionary and my values for isegment[field] are identical. i can't see where i am overwriting the previous field values. my data looks like Field = aa1 Index = 0.0 Value = 0.0 ... ... Field = aa2 Index = 0.01 Value = 0.5 ... i would like to have something like, {1: {'Value': 0.0, ...}, 2: {'Value': 0.01, ...}} for line in file(data_file): the_line = line.split() if the_line: if the_line[0] == 'Field': field += 1 elif the_line[0] == 'Index': index = float(the_line[-1]) dif_index = index - start_index iindex[field] = dif_index start_index = index elif the_line[0] == 'Value': segment[the_line[1]] = float(the_line[-1])*(ax/40) isegment[field] = segment -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: From monjissvel at googlemail.com Tue Aug 5 17:37:34 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 15:37:34 +0000 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: References: Message-ID: maybe this can help MainDictionary = {} N = 0 for line in open('data_file', 'r'): if line: N += 1 a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} 2008/8/5 Bryan Fodness > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting the > previous field values. > > my data looks like > > Field = aa1 > Index = 0.0 > Value = 0.0 > ... > ... > Field = aa2 > Index = 0.01 > Value = 0.5 > ... > > > i would like to have something like, {1: {'Value': 0.0, ...}, 2: {'Value': > 0.01, ...}} > > for line in file(data_file): > the_line = line.split() > if the_line: > if the_line[0] == 'Field': > field += 1 > elif the_line[0] == 'Index': > index = float(the_line[-1]) > dif_index = index - start_index > iindex[field] = dif_index > start_index = index > elif the_line[0] == 'Value': > segment[the_line[1]] = float(the_line[-1])*(ax/40) > isegment[field] = segment > > > -- > "The game of science can accurately be described as a never-ending insult > to human intelligence." - Jo?o Magueijo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From monjissvel at googlemail.com Tue Aug 5 17:43:41 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 15:43:41 +0000 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: References: Message-ID: oops i forgot to count lines, MainDictionary = {} N = 0 M = 0 for line in open('data_file', 'r'): if line: if M < 3: N += 1 M += 1 a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} else: a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} M = 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From federo at email.si Tue Aug 5 13:22:35 2008 From: federo at email.si (Federo) Date: Tue, 05 Aug 2008 13:22:35 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> Message-ID: <20080805112237.020538F19C@www1.email.si> I have tried but I recived error. Look attached files: FormManagementCode (my code) and FormManagement_Note (headers information). There must be some additional trick to fully master form management .. Fake account is now active. URL: https://investor.firstrade.com/firstrade/login.do On screen: We are enetring Symbole field at the top right User: janezfedero Pass: kmet500 (I left login credentials also in the attached code) Cheers, Fedo On Mon, 4 Aug 2008 at 16:08:33, Kent Johnson wrote: > On Mon, Aug 4, 2008 at 8:05 AM, Federo wrote: > > Kent THANKS! It works great also on real account .. > > > > Two important Sub-QUESTIONS: > > > > 1.) Look attached word file. It describes form fields I would like to fill > in > > and read server resoult.. > > You just have to mimic what the browser does. Use a Firefox plugin > that shows you what is being submitted; TamperData is one. Then set > the same fields in your code. > > > 2.) Could you do the same login logic also with MECHANIZE plagin. There > are > > some very usefull function in this plagin I might use. However I have > > No, I'm not familiar with mechanize. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet500', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() # print(data) params = dict(username='janezfedero', password='kmet500', destination='', contentProvider='pinnacor', quoteSymbol='XSNX', optionChain='XSNX', countryCode='US', optionRange='NTM', tickerSymbol='XSNX', contentType='stockquote', quote.x='submitted') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do', params) data = f.read() f.close() print(data) -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_Note.rtf Type: application/msword Size: 2945 bytes Desc: FormManagement_Note.rtf URL: From alan.gauld at btinternet.com Tue Aug 5 18:51:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Aug 2008 17:51:02 +0100 Subject: [Tutor] iterating data and populating a dictionary References: Message-ID: "Bryan Fodness" wrote > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting > the > previous field values. Show us the full error text do not just summarize. > i would like to have something like, {1: {'Value': 0.0, ...}, 2: > {'Value': Describe the output you expected and what you got (if anything) > for line in file(data_file): > the_line = line.split() > if the_line: > if the_line[0] == 'Field': > field += 1 > elif the_line[0] == 'Index': > index = float(the_line[-1]) > dif_index = index - start_index > iindex[field] = dif_index Here index is assigned to a floating point number. Then it is indexed. Floats don't have indexes... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Aug 5 22:42:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Aug 2008 21:42:59 +0100 Subject: [Tutor] iterating data and populating a dictionary References: Message-ID: "Alan Gauld" wrote >> index = float(the_line[-1]) >> dif_index = index - start_index >> iindex[field] = dif_index > > Here index is assigned to a floating point number. > Then it is indexed. Floats don't have indexes... Just noticed the indexed variable has a double i so not the same. Might be better to pick a more descriptive name though! :-) Alan G. From rdmoores at gmail.com Wed Aug 6 00:49:14 2008 From: rdmoores at gmail.com (Dick Moores) Date: Tue, 5 Aug 2008 15:49:14 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() Message-ID: For a while now I've had trouble with end_fill(). Sometimes I can use it to fill a figure such as a square, triangle or rectangle, but sometimes not. Here's a barebones script using end_fill(). As you can see, it draws a square twice, but fails to fill it. Pleas show me how to use it correctly in tandem with begin_fill(). The Turtle doc is at ============================ from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) for n in range(2): begin_fill() color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() goto(x, -y) goto(-x, -y) goto(-x, y) goto(x, y) end_fill() print "end_fill()" time.sleep(1) clear() ===================================== Thanks, Dick Moores From carroll at tjc.com Wed Aug 6 03:29:37 2008 From: carroll at tjc.com (Terry Carroll) Date: Tue, 5 Aug 2008 18:29:37 -0700 (PDT) Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> Message-ID: On Sun, 3 Aug 2008, CNiall wrote: > >>> 0.2 > 0.20000000000000001 > >>> 0.33 > 0.33000000000000002 > > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the decimal > does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 > and not 0.20000000000000001? It's not a Python thing, it's a computer thing. Thsi would be present regardless of what computer language you're using. An oversimplificationis that computers use binary, i.e., base-2. The only non-1 factor of 2 is 2 itself, and computers can only give you an exact representation of a fraction whose denominator only has factors of 2. So these are exact representations: >>> .5 0.5 >>> .5 # 1/2 0.5 >>> .25 # 1/4 0.25 >>> .125 # 1/8 0.125 >>> .875 # 7/8 0.875 But suppose you want 1/10. Well, 10 is factored into 2 and 5, and that pesky 5 makes it impossible for a computer to store exactly; same with 1/5: >>> .1 # 1/10 0.10000000000000001 >>> .2 # 1/5 0.20000000000000001 Do you remember when you learned decimal fractions in garde school, and realized you couldn't represent, for example, 1/3 or 1/7 exactly? You had to content yourself with 0.3333333.... or 0.14285714285714285... with digits repeating forever? That's the equivalent problem in our usual base-10: we can't exactly represent any fraction unless the denominator factors only into 2s and 5s (which are the factors of 10). So representing 1/2, 1/4, 1/20 all are no problem in decimal; but 1/3 and 1/21 can't be exactly represented. A corallary of this, by the way, is that, because there are so many fractions that can't be exactly represented in binary notation, you should never compare floating point numbers looking for equality. It just won't work. Consider the following code: >>> x = 0.0 >>> while x != 1.0: ... print x ... x = x + 1.0/7.0 You might expect this to look through 0.0, 0.142...., 0.285..., 0.428.... up to 10., and then stop. But it won't. because it never quite equals 1.0. It goes right up to a number near 1.0, that might display as 1.0, but is not really 1.0, and blasts on through to 1.142... etc, in an endless loop. So when comparing floating point numbers you should either use a comparison like >= (if using it as a limit) or a construct like if abs(x-y)<.00001: to see if they're close enough to equal to keep you happy. From alan.gauld at btinternet.com Wed Aug 6 11:41:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Aug 2008 10:41:47 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() References: Message-ID: "Dick Moores" wrote > Here's a barebones script using end_fill(). As you can see, it draws > a > square twice, but fails to fill it. Pleas show me how to use it > correctly in tandem with begin_fill(). > > The Turtle doc is at How odd. I can't get it to work either but it does in the turtle demo. Even cut n pasting the demo code into a function didn't work for me. I'm curious if anyone else gets this one working? I'm on XP, Python 2.5 BTW Alan G. From lie.1296 at gmail.com Wed Aug 6 12:22:22 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 06 Aug 2008 17:22:22 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 16 In-Reply-To: References: Message-ID: <1218018142.6394.13.camel@lieryan-laptop> > Message: 1 > Date: Tue, 5 Aug 2008 11:08:57 -0400 > From: "Bryan Fodness" > Subject: [Tutor] iterating data and populating a dictionary > To: "tutorpythonmailinglist Python" > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting the > previous field values. > > my data looks like > > Field = aa1 > Index = 0.0 > Value = 0.0 > ... > ... > Field = aa2 > Index = 0.01 > Value = 0.5 > ... > > > i would like to have something like, {1: {'Value': 0.0, ...}, 2: > {'Value':0.01, ...}} Why don't you use a list of dictionaries instead of dictionaries of dictionaries? > > for line in file(data_file): > the_line = line.split() It's better to use: line.split('=', 1) then you should consider stripping its values, especially the one to be used as the key to the dictionary. > if the_line: > if the_line[0] == 'Field': > field += 1 if this code snippet is the only code in your program, field would cause NameError. However, I assume you have declared field somewhere outside this line, and field is a local variable. If that is the case, remember that local variable is deleted when it is out of scope. This might be the reason why Fields got overwritten. > elif the_line[0] == 'Index': > index = float(the_line[-1]) If you use .split('=', 1), you can be sure that the value of the dictionary is on the_line[1] and the key of the dictionary is on the_line[0] (assuming = is not a legal character for key name) > dif_index = index - start_index > iindex[field] = dif_index > start_index = index > elif the_line[0] == 'Value': > segment[the_line[1]] = float(the_line[-1])*(ax/40) > isegment[field] = segment This particular snippet isn't enough to localize the source of your problem. From kent37 at tds.net Wed Aug 6 13:50:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Aug 2008 07:50:42 -0400 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: References: Message-ID: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores wrote: > For a while now I've had trouble with end_fill(). Sometimes I can use > it to fill a figure such as a square, triangle or rectangle, but > sometimes not. > > Here's a barebones script using end_fill(). As you can see, it draws a > square twice, but fails to fill it. Pleas show me how to use it > correctly in tandem with begin_fill(). Here is a version that does fill: from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) for n in range(2): color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() begin_fill() goto(x, -y) goto(-x, -y) goto(-x, y) end_fill() print "end_fill()" goto(x, y) time.sleep(1) clear() I have no idea why this one works and yours doesn't. Your program is very similar to the filled square in turtle.demo() which does work. The filling is implemented by drawing a polygon on a Tkinter Canvas; is there something strange about polygons? Kent From rdmoores at gmail.com Wed Aug 6 15:33:51 2008 From: rdmoores at gmail.com (Dick Moores) Date: Wed, 6 Aug 2008 06:33:51 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> Message-ID: On Wed, Aug 6, 2008 at 4:50 AM, Kent Johnson wrote: > On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores wrote: >> For a while now I've had trouble with end_fill(). Sometimes I can use >> it to fill a figure such as a square, triangle or rectangle, but >> sometimes not. >> >> Here's a barebones script using end_fill(). As you can see, it draws a >> square twice, but fails to fill it. Pleas show me how to use it >> correctly in tandem with begin_fill(). > > Here is a version that does fill: > from turtle import * > import time > > setup(width=1000, height=700, startx=0, starty=0) > for n in range(2): > color_name = 'red' > x, y = 50, 50 > color(color_name) > print color_name > up() > goto(x, y) > down() > begin_fill() > goto(x, -y) > goto(-x, -y) > goto(-x, y) > end_fill() > print "end_fill()" > goto(x, y) > time.sleep(1) > clear() > > I have no idea why this one works and yours doesn't. Your program is > very similar to the filled square in turtle.demo() which does work. Well, Kent, it seems you have found the right places for begin_fill() and end_fill(). The 450-line script I was writing now works perfectly at last, in what is now version 15. Thanks very much. And my thanks also to Alan. Dick From norman at khine.net Wed Aug 6 21:59:40 2008 From: norman at khine.net (Norman Khine) Date: Wed, 6 Aug 2008 21:59:40 +0200 Subject: [Tutor] Merging dictionaries Message-ID: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Hello, I am trying to figure out the best way to add results from a poll module that I have working, but am a bit stuck and can't see on how to add the total responses submitted by the user. So far I have an output which puts in a list all the user's responses, such as responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]} .... ] Is this an efficient way to do this, say for example I have 1000's of responses? What is the best way to append value items of dictionaries, such that: responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] is transformmed into: answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} I have tried this: Type "help", "copyright", "credits" or "license" for more information. >>> ret = {} >>> myvalues = [] >>> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] >>> for response in responses: mykeys = [] for answer in response.items(): mykeys.append(answer[0]) for key in mykeys: if not ret.has_key(key): ret[key] = [] else: ret[key].append(answer[1]) >>> print ret {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} But is not correct ;'( And finally, what is the simplest way to count the nummber of occurances, so that: answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} returns totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} I tried this: ret = {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} storage = {} for code in ret: for answer, x in questions.items(): for x in x: if not storage.has_key(x): storage[x] = {'count': 1} else: storage[x]['count'] += 1 print storage But this did not work either. Cheers Norman From kent37 at tds.net Wed Aug 6 23:01:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Aug 2008 17:01:50 -0400 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: <1c2a2c590808061401l30c1adf2r98fc2c6bf73ff8a7@mail.gmail.com> On Wed, Aug 6, 2008 at 3:59 PM, Norman Khine wrote: > So far I have an output which puts in a list all the user's responses, such as > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]} .... ] > > Is this an efficient way to do this, say for example I have 1000's of responses? It's OK, though if you just want the counts, as you create below, you might want to accumulate them directly. > What is the best way to append value items of dictionaries, such that: > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] > > is transformmed into: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} collections.defaultdict is very useful when you want to accumulate dictionary values of any kind. When you look up a key in a defaultdict, if the key is not found, a default value is supplied. Thus you don't have to distinguish the first appearance of a key from subsequent appearances. The other thing you need is list.extend(), which adds the elements of one list to the end of another. In [1]: from collections import defaultdict In [2]: responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] In [3]: answered = defaultdict(list) In [5]: for response in responses: ...: for q, a in response.items(): ...: answered[q].extend(a) In [6]: answered Out[6]: defaultdict(, {'a1': [1, 0], 'a2': [1, 2, 3, 0, 1, 3]}) > And finally, what is the simplest way to count the nummber of occurances, so > that: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > returns > > totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} Again, defaultdict to the rescue: In [8]: totals = {} In [10]: for q, answers in answered.items(): ....: counts = totals[q] = defaultdict(int) ....: for a in answers: ....: counts[a] += 1 In [11]: totals Out[11]: {'a1': defaultdict(, {0: 1, 1: 1}), 'a2': defaultdict(, {0: 1, 1: 2, 2: 1, 3: 2})} Kent From alan.gauld at btinternet.com Thu Aug 7 01:15:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 00:15:46 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> Message-ID: "Dick Moores" wrote > Well, Kent, it seems you have found the right places for > begin_fill() > and end_fill(). Yes, quite bizarrely the fill needs an open shape to fill. If you close the figure and then end_fill it doesn't work. How counter intuitive is that! Oh well, one to remember for future use. Alan G. From gregor.lingl at aon.at Thu Aug 7 02:09:15 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Thu, 07 Aug 2008 02:09:15 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> Message-ID: <489A3D2B.1020603@aon.at> Kent Johnson schrieb: > On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores wrote: > >> For a while now I've had trouble with end_fill(). Sometimes I can use >> it to fill a figure such as a square, triangle or rectangle, but >> sometimes not. >> >> Here's a barebones script using end_fill(). As you can see, it draws a >> square twice, but fails to fill it. Pleas show me how to use it >> correctly in tandem with begin_fill(). >> > > Hi all, Kent's version below repairs the problem more or less accidentally and moreover not completely: (1) the first square is not filled properly; instead a filled pentagon appears after the first traversal of the loop. (2) the filling takes place due to the goto() call after the end_fill() call and before the clear() call. This is due to a bug in turtle.py - interestingly after so many years of use and improvement of turtle.py there still appear new bugs from time to time. The bug consists in a missing update of the Canvas in the fill() function You can repair it by inserting a line at line#309 in turtle.py in the fill method as follows: if self._filling: path = tuple(self._path) smooth = self._filling < 0 if len(path) > 2: item = self._canvas._create('polygon', path, {'fill': self._color, 'smooth': smooth}) self._items.append(item) self._canvas.update() # <=== bug-fix self._path = [] Now for the good news: (1) If you have done this, not only Dick's program works as intended, but you may also write the square_filling program in a cleaner way, for instance like this: from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() for n in range(2): begin_fill() goto(x, -y) goto(-x, -y) goto(-x, y) goto(x, y) end_fill() print "end_fill()" time.sleep(1) clear() (2) Python 2.6 will have a new turtle module - formerly known to some as xturtle.py - which has much more capabilities and which at least doesn't show this bug. Presumably there will appear others, especially in the beginning of it's use. It is contained in Python2.6 beta2, it runs also under Python2.5 and it should be (nearly?) 100%-compatible with the old turtle module. Its documentation can be found here: http://docs.python.org/dev/library/turtle.html#module-turtle It would be really very helpful, if those of you who use to use turtle graphcis would work with this new module in order to reveal as many bugs as possible before the final release of Python 2.6 scheduled for early october 2008. Of course I'd assist if questions or problems would arise. Regards Gregor > Here is a version that does fill: > from turtle import * > import time > > setup(width=1000, height=700, startx=0, starty=0) > for n in range(2): > color_name = 'red' > x, y = 50, 50 > color(color_name) > print color_name > up() > goto(x, y) > down() > begin_fill() > goto(x, -y) > goto(-x, -y) > goto(-x, y) > end_fill() > print "end_fill()" > goto(x, y) > time.sleep(1) > clear() > > I have no idea why this one works and yours doesn't. Your program is > very similar to the filled square in turtle.demo() which does work. > > The filling is implemented by drawing a polygon on a Tkinter Canvas; > is there something strange about polygons? > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From benoit.thiell at cern.ch Thu Aug 7 07:21:36 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Thu, 7 Aug 2008 01:21:36 -0400 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: Dear Norman, I would propose: ret = {} myvalues = [] responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] for response in responses: for answer in response.items() ret.setdefault(response[0], []).append(response[1]) Regards, Benoit Thiell. From technorapture at gmail.com Thu Aug 7 07:42:58 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 7 Aug 2008 01:42:58 -0400 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: References: Message-ID: <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> If you're just going to be using numbers as dictionary keys, it might be simpler just to use a list structure. Dictionaries don't preserve order, so you'd need to write extra code if you ever need to iterate over it in order. Since your code increments field everytime it gets a new record you can just use it as a list index and things should be fine. Of course you might have your own reasons for using a dict, so it's up to you. -- The ByteBaker : http://www.bytebaker.com From cspears2002 at yahoo.com Thu Aug 7 08:01:02 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 6 Aug 2008 23:01:02 -0700 (PDT) Subject: [Tutor] date formatter Message-ID: <440786.53671.qm@web51601.mail.re2.yahoo.com> Hey, I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: #!/usr/bin/python import time class date_format(object): def __init__(self, month, day, year): month_dict = {("jan","january") : 1, ("feb","february") :2, ("mar", "march") : 3, ("apr", "april") : 4, ("may") : 5, ("jun", "june") : 6, ("jul", "july") : 7, ("aug", "august") : 8, ("sep", "september") : 9, ("oct", "october"): 10, ("nov", "november"): 11, ("dec", "december"): 12 } try: month = int(month) except ValueError: for eachKey in month_dict.keys(): if month.lower() in eachKey: month = month_dict[eachKey] else: month = "" if month=="" or day=="" or year=="": self.date = time.localtime() else: self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) def display(self, format_indicator = None): if format_indicator == 'MDY': print time.strftime("%m/%d/%y",self.date) elif format_indicator == 'MDYY': print time.strftime("%m/%d/%Y",self.date) elif format_indicator == 'DMY': print time.strftime("%d/%m/%y",self.date) elif format_indicator == 'DMYY': print time.strftime("%d/%m/%Y",self.date) elif format_indicator == 'MODYY': print time.strftime("%b %d, %Y",self.date) else: print time.strftime("%a %b %d %Y",self.date) if __name__ == "__main__": print "Welcome to the Date Formatter!" month = raw_input("Please enter a month: ") day = raw_input("Please enter a day: ") year = raw_input("Please enter a year: ") date_obj = date_format(month, day, year) format_indicator = raw_input("Enter a format indicator: ") date_obj.display(format_indicator.upper()) I am having trouble dealing with the case where the user actually types in a month's name instead of the number: io at io-station-1 ./chap13 180> python date_format_v01.py Welcome to the Date Formatter! Please enter a month (as a number): Oct Please enter a day: 31 Please enter a year: 1976 Traceback (most recent call last): File "date_format_v01.py", line 53, in ? date_obj = date_format(month, day, year) File "date_format_v01.py", line 24, in __init__ if month.lower() in eachKey: AttributeError: 'int' object has no attribute 'lower' Any suggestions? -Chris From timothy.grant at gmail.com Thu Aug 7 08:05:33 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 6 Aug 2008 23:05:33 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: On Wed, Aug 6, 2008 at 11:01 PM, Christopher Spears wrote: > Hey, > > I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: > > #!/usr/bin/python > > import time > > class date_format(object): > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may") : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > if month=="" or day=="" or year=="": > self.date = time.localtime() > else: > self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) > > def display(self, format_indicator = None): > if format_indicator == 'MDY': > print time.strftime("%m/%d/%y",self.date) > elif format_indicator == 'MDYY': > print time.strftime("%m/%d/%Y",self.date) > elif format_indicator == 'DMY': > print time.strftime("%d/%m/%y",self.date) > elif format_indicator == 'DMYY': > print time.strftime("%d/%m/%Y",self.date) > elif format_indicator == 'MODYY': > print time.strftime("%b %d, %Y",self.date) > else: > print time.strftime("%a %b %d %Y",self.date) > > > if __name__ == "__main__": > print "Welcome to the Date Formatter!" > month = raw_input("Please enter a month: ") > day = raw_input("Please enter a day: ") > year = raw_input("Please enter a year: ") > date_obj = date_format(month, day, year) > format_indicator = raw_input("Enter a format indicator: ") > date_obj.display(format_indicator.upper()) > > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > > Welcome to the Date Formatter! > Please enter a month (as a number): Oct > Please enter a day: 31 > Please enter a year: 1976 > Traceback (most recent call last): > File "date_format_v01.py", line 53, in ? > date_obj = date_format(month, day, year) > File "date_format_v01.py", line 24, in __init__ > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? > -Chris wrap the call to month.lower() in a try/except block. try: if month.lower() ..... except AttributeError: process this as a string instead of a number.... -- Stand Fast, tjg. [Timothy Grant] From wescpy at gmail.com Thu Aug 7 08:39:26 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 6 Aug 2008 23:39:26 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > : > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > : > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? chris, good 1st attempt. all the problems are in the code snippet above. you only have a few flaws in your program preventing it from working: a. you "wipe out" the originally entered month (by continually reassigning the month var) b. you don't break out of the inner for-loop when u find a match and end up wiping out the correct match c. the cause of the exception: the entry for May is a string and not a 1-item tuple. you need a trailing comma "," after "may" to make it a tuple. the reason why the error is triggered is because you set a blank to month for every non-match. so when it gets to may, it makes this comparison: >>> "" in "may" True because of this, it sets... month = month_dict["may"] # so month == 5 so in the next loop iteration, your're trying to do... 5.lower() in eachKey which of course, fails. fix these problems, and you have a working solution! best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Aug 7 08:53:24 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 6 Aug 2008 23:53:24 -0700 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> hmmm, somewhat off-topic, i was partially confused by the Subject line. i thought this post was about merging *dictionaries* and not merging the *contents of multiple dictionaries' values*. for those who are interested in the former, you use the update() method and here is an example: >>> d1 = dict(zip(range(3), range(3))) >>> d1 {0: 0, 1: 1, 2: 2} >>> d2 = dict(zip(range(2,5), [i*2 for i in range(2, 5)])) >>> d2 {2: 4, 3: 6, 4: 8} >>> d1.update(d2) >>> d1 {0: 0, 1: 1, 2: 4, 3: 6, 4: 8} notice that the update will replace any existing key with the corresponding value of the argument dict. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at gmail.com Thu Aug 7 13:19:58 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 07 Aug 2008 04:19:58 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: <489ADA5E.1080607@gmail.com> Christopher Spears wrote: > Hey, > > I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: > Consider reformatting the month_dict so each name and abbreviation is a key. Then you can just look up the potential key rather than looping thru all the keys. That is what dictionaries are for!: month_dict = {"jan" : 1, "january" : 1, "feb" : 2, "february" :2, etc ...} ... except ValueError: if month.lower() in month_dict: month = month_dict[month.lower()] else: month = "" The dict function is also handy here: month_dict = dict( jan = 1, january = 1, feb = 2, february = 2, etc ...) Consider using another dictionary for the formats: format_dict = dict( MDY = "%m/%d/%y", MDYY = "%m/%d/%Y", DMY = "%d/%m/%y", DMYY = "%d/%m/%Y", MODYY = "%b %d, %Y",) > #!/usr/bin/python > > import time > > class date_format(object): > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may") : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > if month=="" or day=="" or year=="": > self.date = time.localtime() > else: > self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) > > def display(self, format_indicator = None): > if format_indicator == 'MDY': > print time.strftime("%m/%d/%y",self.date) > elif format_indicator == 'MDYY': > print time.strftime("%m/%d/%Y",self.date) > elif format_indicator == 'DMY': > print time.strftime("%d/%m/%y",self.date) > elif format_indicator == 'DMYY': > print time.strftime("%d/%m/%Y",self.date) > elif format_indicator == 'MODYY': > print time.strftime("%b %d, %Y",self.date) > else: > print time.strftime("%a %b %d %Y",self.date) > > > if __name__ == "__main__": > print "Welcome to the Date Formatter!" > month = raw_input("Please enter a month: ") > day = raw_input("Please enter a day: ") > year = raw_input("Please enter a year: ") > date_obj = date_format(month, day, year) > format_indicator = raw_input("Enter a format indicator: ") > date_obj.display(format_indicator.upper()) > > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > > Welcome to the Date Formatter! > Please enter a month (as a number): Oct > Please enter a day: 31 > Please enter a year: 1976 > Traceback (most recent call last): > File "date_format_v01.py", line 53, in ? > date_obj = date_format(month, day, year) > File "date_format_v01.py", line 24, in __init__ > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? > -Chris > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From benoit.thiell at cern.ch Thu Aug 7 13:39:55 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Thu, 7 Aug 2008 13:39:55 +0200 Subject: [Tutor] date formatter In-Reply-To: <489ADA5E.1080607@gmail.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> <489ADA5E.1080607@gmail.com> Message-ID: On Thu, 7 Aug 2008, bob gailer wrote: > Christopher Spears wrote: >> Hey, >> >> I'm working on a problem out of Core Python Programming (2nd Edition). >> Basically, I'm creating a class that formats dates. Here is what I have so >> far: >> > > Consider reformatting the month_dict so each name and abbreviation is a key. > Then you can just look up the potential key rather than looping thru all the > keys. That is what dictionaries are for!: > > month_dict = {"jan" : 1, > "january" : 1, > "feb" : 2, > "february" :2, etc ...} > ... > except ValueError: > if month.lower() in month_dict: > month = month_dict[month.lower()] > else: > month = "" > > The dict function is also handy here: > > month_dict = dict( > jan = 1, > january = 1, > feb = 2, > february = 2, etc ...) Dear Christopher, Instead of multiplying the keys for each possible version of the written month, I would rather have: month_dict = {"jan":1, "feb":2, ...} and have: written_month = written_month[:3].lower() if written_month in month_dict: # do something Regards, Benoit. From norman at khine.net Thu Aug 7 14:16:49 2008 From: norman at khine.net (Norman Khine) Date: Thu, 7 Aug 2008 14:16:49 +0200 Subject: [Tutor] Merging dictionaries In-Reply-To: <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> Message-ID: <9c2c8ffb0808070516q39138fb9u327f825081539ac7@mail.gmail.com> Thank you all for the replies. Norman On 8/7/08, wesley chun wrote: > hmmm, somewhat off-topic, i was partially confused by the Subject > line. i thought this post was about merging *dictionaries* and not > merging the *contents of multiple dictionaries' values*. > > for those who are interested in the former, you use the update() > method and here is an example: > > >>> d1 = dict(zip(range(3), range(3))) > >>> d1 > {0: 0, 1: 1, 2: 2} > >>> d2 = dict(zip(range(2,5), [i*2 for i in range(2, 5)])) > >>> d2 > {2: 4, 3: 6, 4: 8} > >>> d1.update(d2) > >>> d1 > {0: 0, 1: 1, 2: 4, 3: 6, 4: 8} > > notice that the update will replace any existing key with the > corresponding value of the argument dict. > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From srilyk at gmail.com Thu Aug 7 14:42:37 2008 From: srilyk at gmail.com (W W) Date: Thu, 7 Aug 2008 07:42:37 -0500 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> References: <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> Message-ID: <333efb450808070542l4b5ec788j3fb66845b948f1dc@mail.gmail.com> On Thu, Aug 7, 2008 at 12:42 AM, Shrutarshi Basu wrote: > If you're just going to be using numbers as dictionary keys, it might > be simpler just to use a list structure. Dictionaries don't preserve > order, so you'd need to write extra code if you ever need to iterate > over it in order. It wouldn't be any (or at least much) more difficult than looping over a list of known/unknown length. Known length: for x in range(0, length): do something with mydict[x] Unknown length, dict keys starting at 0: for x in range(0, len(mydict)): do something with mydict[x] Known length, dict keys starting at 1: for x in range(1, (len(mydict)+1)): do something with mydict[x] Probably not the most elegant solution, but it does work. I can't really think of a particular reason it would be useful, though. The main reason a dict is useful is for key values that won't change, and aren't easily kept track of (i.e. names). It's a lot more difficult (at least for the interpreter, as in processor cycles) to find "John Smith" in a list, than to convert it to a hash value and look it up in a hash table. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Thu Aug 7 15:28:39 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 7 Aug 2008 15:28:39 +0200 Subject: [Tutor] Python and the Global Interpreter Lock Message-ID: Hi there, I just came across something called the Global Interpreter Lock, and apparently its a condition where an interpreter locks resources to avoid sharing them with other apps/ processes on the system? I wish to find out what this means in terms of Python. for example does it mean that Python cannot take advantage of multiple CPUs? And does it mean that only one interpreter will run per box in a hosting environment? I look forward to enlightenment. Thanks, -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Aug 7 15:33:28 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 07 Aug 2008 20:33:28 +0700 Subject: [Tutor] Merging dictionaries In-Reply-To: References: Message-ID: <1218116008.6357.3.camel@lieryan-laptop> > Message: 4 > Date: Wed, 6 Aug 2008 21:59:40 +0200 > From: "Norman Khine" > Subject: [Tutor] Merging dictionaries > To: tutor at python.org > Message-ID: > <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hello, > I am trying to figure out the best way to add results from a poll > module that I > have working, but am a bit stuck and can't see on how to add the total > responses > submitted by the user. > > So far I have an output which puts in a list all the user's responses, > such as > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, > 3]} .... ] > > Is this an efficient way to do this, say for example I have 1000's of > responses? > > What is the best way to append value items of dictionaries, such that: > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, > 3]}] > > is transformmed into: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > I have tried this: > > Type "help", "copyright", "credits" or "license" for more information. > >>> ret = {} > >>> myvalues = [] > >>> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, > 1, 3]}] > >>> for response in responses: > mykeys = [] > for answer in response.items(): > mykeys.append(answer[0]) > for key in mykeys: > if not ret.has_key(key): > ret[key] = [] > else: > ret[key].append(answer[1]) > > >>> print ret > {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} > > But is not correct ;'( You'd want list.extend, not list.append. There is slight difference between list.extend and list.append, extend would iterate through the second list and append each item in the second list to the first list. > > And finally, what is the simplest way to count the nummber of > occurances, so > that: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > returns > > totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} > > > I tried this: > > ret = {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} > storage = {} > for code in ret: > for answer, x in questions.items(): > for x in x: > if not storage.has_key(x): > storage[x] = {'count': 1} > else: > storage[x]['count'] += 1 > print storage > > But this did not work either. > > Cheers > > Norman > > From bgailer at gmail.com Thu Aug 7 16:37:14 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 07 Aug 2008 07:37:14 -0700 Subject: [Tutor] Python and the Global Interpreter Lock In-Reply-To: References: Message-ID: <489B089A.1030806@gmail.com> OkaMthembo wrote: > Hi there, > > I just came across something called the Global Interpreter Lock, and > apparently its a condition where an interpreter locks resources to > avoid sharing them with other apps/ processes on the system? I wish to > find out what this means in terms of Python. for example does it mean > that Python cannot take advantage of multiple CPUs? And does it mean > that only one interpreter will run per box in a hosting environment? See http://en.wikipedia.org/wiki/Global_Interpreter_Lock. This only applies to threads within a Python process, not other apps/prcoesses. > > I look forward to enlightenment. So do I. Who is your guru? From ssmith46 at zimbra.naz.edu Thu Aug 7 16:55:58 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Thu, 7 Aug 2008 10:55:58 -0400 (EDT) Subject: [Tutor] Python and NT Authentication Message-ID: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> Hello, everyone- I'm trying to both learn Python and develop a fairly robust web form with it at the same time... nothing like being thrown into a new job and having to learn a new language to do it! We have ActiveState Python 2.5 installed on an IIS box running Windows 2003. We're doing it this way because we will most likely be switching to Apache / Unix in the future, and we don't want to have to rewrite all of our server-side scripts. Our web server is a domain member. I am coding a form that will allow authenticated NT users to submit project requests. The form will, among other things, need to pull a list of domain users and put it into a dropdown menu, as well as show the username of the current user. Results will be dumped into an ODBC-connected mySQL database, which is working well (it's just the authentication issue that I'm struggling with). I am able to connect to the domain with the following: <%import ldap, sys, win32api LDAP_SERVER='ldap://nazareth.internal' LDAP_USERNAME='myusername at nazareth.internal' LDAP_PASSWORD='mypassword' try: ldap_client = ldap.initialize(LDAP_SERVER) ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) except ldap.INVALID_CREDENTIALS, e: Response.Write("

Invalid credentials

") sys.exit() except ldap.SERVER_DOWN, e: Response.Write("

Your server appears to be down.

") sys.exit() Response.Write("

Connected! All is well.

") ldap_client.unbind() %> However, other than hard-coding the variables, I don't know how to get them from the user, nor do I know how to actually authenticate them. Should I be using Cookies? How is that done? As far as populating the form's dropdown box, I've been using > something similar to: > > <% > import pyodbc > cnxn_ro = pyodbc.connect("DSN=metaproject_ro") > cursor = cnxn_ro.cursor() > cursor.execute("select * from Person order by last_name, first_name") > for row in cursor: > Response.Write("") cursor.close() > %> > > (for testing purposes, I actually built a table in the database just so > that I could populate it programmatically, but this is where I'd like to > pull the info from Active Directory. > > > > Hope someone can help! I've been scouring the web for several hours, and > I'm actually *more* confused than when I started. > > > Thanks! > > > Steven L Smith > Web Developer > Nazareth College of Rochester > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rdmoores at gmail.com Thu Aug 7 18:54:34 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 09:54:34 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: <489A3D2B.1020603@aon.at> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: On Wed, Aug 6, 2008 at 5:09 PM, Gregor Lingl wrote: > This is due to a bug in turtle.py - interestingly after so many years of use > and improvement of turtle.py there still appear new bugs from time to time. > > The bug consists in a missing update of the Canvas in the fill() function > You can repair it by inserting a line at line#309 in turtle.py in the > fill method as follows: > > if self._filling: > path = tuple(self._path) > smooth = self._filling < 0 > if len(path) > 2: > item = self._canvas._create('polygon', path, > {'fill': self._color, > 'smooth': smooth}) > self._items.append(item) > self._canvas.update() # <=== bug-fix > self._path = [] > > Now for the good news: > > (1) If you have done this, not only Dick's program works as > intended, Yes, it does! I've pasted a version at . Thank you! > (2) Python 2.6 will have a new turtle module - formerly known to some > as xturtle.py - which has much more capabilities and which at least doesn't > show > this bug. Presumably there will appear others, especially in the beginning > of > it's use. It is contained in Python2.6 beta2, it runs also under Python2.5 > and it should be (nearly?) 100%-compatible with the old turtle module. > > Its documentation can be found here: > http://docs.python.org/dev/library/turtle.html#module-turtle > > It would be really very helpful, if those of you who use to use turtle > graphcis would work with this new module in order to reveal as many > bugs as possible before the final release of Python 2.6 scheduled for > early october 2008. I got Python2.6 beta2 and copied its turtle.py to my Python 2.5 after renaming it turtle26.py. By now I've spent several hours trying to figure out how to get my program to work well with it. I don't know if I've discovered any bugs, but here are some of the problems I have: 1. The turtle has some behavior I don't see how to eliminate. If you refer to lines 223, 225, 227, 229, etc., you'll see that the turtle always faces in the direction it is moving when drawing a rectangle. Using the Python2.6 beta2 version of turtle.py, the turtle can be seen at each corner spinning to orient itself to the new direction. I don't want this. I thought I could remove the spinning effect by setting the turtle's shape to a circle. But the circle is way bigger than the default turtle. No spinning, but not what I'm after. 2. The turtle can also be seen moving from the last corner of the last rectangle to the first corner of the next. I don't want this. 3. When the screen is cleared between cycles by line 367, the blank screen shows for a second or so. I don't want this. In my program using the old turtle I've had to create colored-backgrounds by drawing a rectangle almost as large as the screen (see my draw_background() beginning at line 365). With the new turtle, the background color can be set by, for example, screen.bgcolor("orange"). But even so, in the V16 I was trying to write, that blank screen still shows for a second or so. With the old turtle, the transition from one "background" to another seems instantaneous. No white blank screen visible at all. 4. I've attempted to make the turtle invisible, but haven't succeeded. I'm guessing that all the problems I've mentioned aren't the result of bugs--rather, I just don't understand the doc. > Of course I'd assist if questions or problems would arise. Thanks. Dick From rdmoores at gmail.com Thu Aug 7 20:02:23 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 11:02:23 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: On Thu, Aug 7, 2008 at 9:54 AM, Dick Moores wrote: > 4. I've attempted to make the turtle invisible, but haven't succeeded. Got it! hideturtle() Dick From alan.gauld at btinternet.com Thu Aug 7 20:26:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 19:26:31 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> Message-ID: "Dick Moores" wrote > 1. The turtle has some behavior I don't see how to eliminate. If you > refer to lines 223, 225, 227, 229, etc., you'll see that the turtle > always faces in the direction it is moving when drawing a rectangle. That is correct behaviour for a turtle! Remember turtle graphics are notionally about moving a physical drawing device (the turtle) around on the floor or desk. If the turtle doesn't turn to face the direction of travel it can't travel that way! IMHO that's just a feature of the technology and any other behaviour would be out of keeping with the intent. > Using the Python2.6 beta2 version of turtle.py, the turtle can be > seen > at each corner spinning to orient itself to the new direction. I > don't > want this. While far from common in turtle implementations (I have only seen it in my old CP/M Logo version) it is a feature that would be true of a physical turtle too. Its not really a bug but a "feature" I guess! > 2. The turtle can also be seen moving from the last corner of the > last > rectangle to the first corner of the next. I don't want this. Again true of a physical turtle... But if you set speed to fastest does that work? Also in the old turtle moduile there was a way to hide the turtles movements completely and just draw the finished graphic - which was orders of magnitude faster for complex shapes - is that still available in turtle26? One way to hide the turtle would be top change colour to the background color. That would make themoving turtle invisible... > 3. When the screen is cleared between cycles by line 367, the blank > screen shows for a second or so. I don't want this. > In my program using the old turtle I've had to create > colored-backgrounds by drawing a rectangle almost as large as the > screen (see my draw_background() beginning at line 365). With the > new > turtle, the background color can be set by, for example, > screen.bgcolor("orange"). But even so, in the V16 I was trying to > write, that blank screen still shows for a second or so. With the > old > turtle, the transition from one "background" to another seems > instantaneous. No white blank screen visible at all. Sounds like a valid complaint that one... > 4. I've attempted to make the turtle invisible, but haven't > succeeded. Should be possible to set color to bgcolor. but set it back to draw the lines or they too will be invisible! > I'm guessing that all the problems I've mentioned aren't the result > of > bugs--rather, I just don't understand the doc. Matybe more not understanding(remembering) the origin of turtle graphics. It was for kids to understand computer graphics... Seeing the shapes being drawn is a big part of that. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 7 20:31:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 19:31:39 +0100 Subject: [Tutor] Python and NT Authentication References: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: "Steven L Smith" wrote in > We have ActiveState Python 2.5 installed on an IIS box running > Windows 2003. We're doing it this way because we will most > likely be switching to Apache / Unix in the future, and we > don't want to have to rewrite all of our server-side scripts. ... > <%import ldap, sys, win32api > LDAP_SERVER='ldap://nazareth.internal' > LDAP_USERNAME='myusername at nazareth.internal' > LDAP_PASSWORD='mypassword' It looks like you are using Active Scripting for the web pages? That probably won't work on Unix/Apache, it might be better to use CGI or one of the web frameworks that will be portable across web servers as well as across OS. Nothing to do with your query but an observation... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dave6502 at googlemail.com Thu Aug 7 23:25:53 2008 From: dave6502 at googlemail.com (dave selby) Date: Thu, 7 Aug 2008 22:25:53 +0100 Subject: [Tutor] Split string on 2 delimiters ? Message-ID: Hi all, Is there a neat way to split a string on either of two delimiters ie space and comma Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From timothy.grant at gmail.com Thu Aug 7 23:36:28 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 14:36:28 -0700 Subject: [Tutor] Split string on 2 delimiters ? In-Reply-To: References: Message-ID: On Thu, Aug 7, 2008 at 2:25 PM, dave selby wrote: > Hi all, > > Is there a neat way to split a string on either of two delimiters ie > space and comma > > Cheers > > Dave >>> import re >>> string = 'this is, a test of splitting; on two delimiters' >>> re.split(r'[,;]', string) ['this is', ' a test of splitting', ' on two delimiters'] >>> re.split(r'[, ]', string) ['this', 'is', '', 'a', 'test', 'of', 'splitting;', 'on', 'two', 'delimiters'] -- Stand Fast, tjg. [Timothy Grant] From kent37 at tds.net Thu Aug 7 23:42:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 7 Aug 2008 17:42:00 -0400 Subject: [Tutor] Split string on 2 delimiters ? In-Reply-To: References: Message-ID: <1c2a2c590808071442n273951f8l8bfbde83df55078e@mail.gmail.com> On Thu, Aug 7, 2008 at 5:25 PM, dave selby wrote: > Hi all, > > Is there a neat way to split a string on either of two delimiters ie > space and comma Use re.split(): In [1]: import re In [2]: data = 'tom,dick harry' In [4]: re.split(r'[, ]', data) Out[4]: ['tom', 'dick', 'harry'] Since you have the full power of re to match your delimiter you could for example allow comma, space or both: In [6]: re.split(r', *| +', 'tom, dick,harry and bill') Out[6]: ['tom', 'dick', 'harry', 'and', 'bill'] Kent From rdmoores at gmail.com Thu Aug 7 23:44:02 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 14:44:02 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld wrote: > "Dick Moores" wrote > >> 1. The turtle has some behavior I don't see how to eliminate. If you >> refer to lines 223, 225, 227, 229, etc., you'll see that the turtle >> always faces in the direction it is moving when drawing a rectangle. > > That is correct behaviour for a turtle! Yes. I wanted that, and set it accordingly. Those lines refer to the program using the 2.5 turtle.py. > Remember turtle graphics are notionally about moving a physical > drawing device (the turtle) around on the floor or desk. If the turtle > doesn't turn to face the direction of travel it can't travel that way! > > IMHO that's just a feature of the technology and any other behaviour > would be out of keeping with the intent. Actually, if you look at those lines, I had to go to some trouble to get the turtle to do that! >> Using the Python2.6 beta2 version of turtle.py, the turtle can be seen >> at each corner spinning to orient itself to the new direction. I don't >> want this. > > While far from common in turtle implementations (I have only seen > it in my old CP/M Logo version) it is a feature that would be true > of a physical turtle too. Its not really a bug but a "feature" I guess! I finally found how to make the turtle disappear permanently. In the new turtle.py, the code is "hideturtle()". >> 2. The turtle can also be seen moving from the last corner of the last >> rectangle to the first corner of the next. I don't want this. > > Again true of a physical turtle... But if you set speed to fastest > does that work? Also in the old turtle moduile there was a way to > hide the turtles movements completely and just draw the finished > graphic - which was orders of magnitude faster for complex > shapes - is that still available in turtle26? Yes, penup(). > One way to hide the turtle would be top change colour to the Thanks for thinking about it, but with hideturtle() I'm a happy camper. >> 3. When the screen is cleared between cycles by line 367, the blank >> screen shows for a second or so. I don't want this. >> In my program using the old turtle I've had to create >> colored-backgrounds by drawing a rectangle almost as large as the >> screen (see my draw_background() beginning at line 365). With the new >> turtle, the background color can be set by, for example, >> screen.bgcolor("orange"). But even so, in the V16 I was trying to >> write, that blank screen still shows for a second or so. With the old >> turtle, the transition from one "background" to another seems >> instantaneous. No white blank screen visible at all. Solved that. I'm pasting the version that uses the new turtle.py. . This runs fine, but I'll be doing more work on it. > Sounds like a valid complaint that one... >> 4. I've attempted to make the turtle invisible, but haven't succeeded. See above. > Should be possible to set color to bgcolor. but set it back to > draw the lines or they too will be invisible! > >> I'm guessing that all the problems I've mentioned aren't the result of >> bugs--rather, I just don't understand the doc. > > Maybe more not understanding(remembering) the origin of turtle graphics. > It was for kids to understand computer graphics... Seeing the shapes > being drawn is a big part of that. Well, I also want to see the rectangles being drawn--by an invisible turtle. ;-) Actually, I got interested in this because of the colors. I had just bought my first LCD monitor, a 22-incher. And I wrote the program so that it prints the color names to the console window. I had been ignorant about colors--had no idea what magenta, chartreuse, turquoise, cyan were, just to mention a few. Thanks, Alan. Dick From gregor.lingl at aon.at Fri Aug 8 00:47:54 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 00:47:54 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> Message-ID: <489B7B9A.6090109@aon.at> Alan Gauld schrieb: > "Dick Moores" wrote > >> 1. The turtle has some behavior I don't see how to eliminate. If you >> refer to lines 223, 225, 227, 229, etc., you'll see that the turtle >> always faces in the direction it is moving when drawing a rectangle. > > That is correct behaviour for a turtle! > Remember turtle graphics are notionally about moving a physical > drawing device (the turtle) around on the floor or desk. If the turtle > doesn't turn to face the direction of travel it can't travel that way! > > IMHO that's just a feature of the technology and any other behaviour > would be out of keeping with the intent. > Hi all, development of this rectangle pattern program is going verry fast and as I see Dick has managed to abridge his program by some fifty lines (using the new turtle module). Most of his questions got superb answers by Alan, so I'll add only a few remarks: In fact Dick doesn't use any turtle graphics functions in it's precise original meaning. Instead he uses a (global) Cartesian coordinate system and moves the turtle only by calling goto(). (This approach is perfectly ok for his task, of course). Turtle graphics by contrast uses a local coordinate system of the "turtle" and moves it by calling only forward(), back(), left() and right() functions. >> Using the Python2.6 beta2 version of turtle.py, the turtle can be seen >> at each corner spinning to orient itself to the new direction. I don't >> want this. So you eliminated the superfluous setheading() calls. > > While far from common in turtle implementations (I have only seen > it in my old CP/M Logo version) it is a feature that would be true > of a physical turtle too. Its not really a bug but a "feature" I guess! > >> 2. The turtle can also be seen moving from the last corner of the last >> rectangle to the first corner of the next. I don't want this. This is ideed an intended difference between the new and the old turtle module. I consider this to be an improvement of the animation of the turtle. (You can observe another improvement by trying out e. g. left(1080) ) The intention is that the beginning programmer can visually observe what he or she has programmed and thus more easily identify errors in his/her program. To that end the turtle moves and turns at the specified speed regardless of the state of the pen (up or down). If you don't like this you can set speed to 0 which - paradoxically - means that the animation is turned off and the turtle jumps instantaneously. (Think of something like speed(False)) > Again true of a physical turtle... But if you set speed to fastest > does that work? Yes, that is speed(0). See above > Also in the old turtle moduile there was a way to > hide the turtles movements completely and just draw the finished > graphic - which was orders of magnitude faster for complex > shapes - is that still available in turtle26? Yes it is (of course ;-) ). Use tracer in the same way as in the old one. > > > One way to hide the turtle would be top change colour to the > background color. That would make themoving turtle invisible... > As Dick discoverd you can use hideturtle() and showturtle() >> 3. When the screen is cleared between cycles by line 367, the blank >> screen shows for a second or so. I don't want this. >> In my program using the old turtle I've had to create >> colored-backgrounds by drawing a rectangle almost as large as the >> screen (see my draw_background() beginning at line 365). With the new >> turtle, the background color can be set by, for example, >> screen.bgcolor("orange"). But even so, in the V16 I was trying to >> write, that blank screen still shows for a second or so. With the old >> turtle, the transition from one "background" to another seems >> instantaneous. No white blank screen visible at all. > > Sounds like a valid complaint that one... This again is a result of the animation of the turtle. Of course a correct use of bgcolor() solves this problem - as Dick did now -, but also use of speed(0) or tracer(False) would have solved it. Regards, Gregor P.S.: If you are interested, you can download a series of sample programs covering a broad range from very easy to fairly advanced, which intend to show some features and capabilities of the new turtle module from here: http://svn.python.org/view/python/trunk/Demo/turtle/ These will be included in the source distribution - but not in the Windows installer. From gregor.lingl at aon.at Fri Aug 8 01:04:14 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 01:04:14 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: <489B7F6E.6010205@aon.at> Hi Dick, first of all, thanks for your efforts using the new turtle module and reporting about your experiences and the problems you ran into. I've already made some remarks on it in a former reply in this thread. > On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld wrote: > > ... >>> 2. The turtle can also be seen moving from the last corner of the last >>> rectangle to the first corner of the next. I don't want this. >>> >> Again true of a physical turtle... But if you set speed to fastest >> does that work? Also in the old turtle moduile there was a way to >> hide the turtles movements completely and just draw the finished >> graphic - which was orders of magnitude faster for complex >> shapes - is that still available in turtle26? >> Here better tracer() should come in! > Yes, penup(). > >> >> Maybe more not understanding(remembering) the origin of turtle graphics. >> It was for kids to understand computer graphics... Seeing the shapes >> being drawn is a big part of that. >> That's why now turtles have got a better animation. (That means: the resulting drawing should be the same weather you use the old module or the new one, but *not* what you see, when you observe the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of course, the now one has a lot of additional enhacements.) Best regards, Gregor > Well, I also want to see the rectangles being drawn--by an invisible turtle. ;-) > > Actually, I got interested in this because of the colors. I had just > bought my first LCD monitor, a 22-incher. And I wrote the program so > that it prints the color names to the console window. I had been > ignorant about colors--had no idea what magenta, chartreuse, > turquoise, cyan were, just to mention a few. > > Thanks, Alan. > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From rdmoores at gmail.com Fri Aug 8 02:38:00 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 17:38:00 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <489B7F6E.6010205@aon.at> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <489B7F6E.6010205@aon.at> Message-ID: On Thu, Aug 7, 2008 at 4:04 PM, Gregor Lingl wrote: > Hi Dick, > > first of all, thanks for your efforts using the new turtle module > and reporting about your experiences and the problems you ran into. Sure. And I'm not finished. There seem to be some interesting new things worth investigating. > I've already made some remarks on it in a former reply in this thread. Yes. Thanks. >> On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld >> wrote: >> ... >>>> >>>> 2. The turtle can also be seen moving from the last corner of the last >>>> rectangle to the first corner of the next. I don't want this. >>>> >>> >>> Again true of a physical turtle... But if you set speed to fastest >>> does that work? Also in the old turtle moduile there was a way to >>> hide the turtles movements completely and just draw the finished >>> graphic - which was orders of magnitude faster for complex >>> shapes - is that still available in turtle26? >>> > > Here better tracer() should come in! 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. http://docs.python.org/dev/library/turtle.html#turtle.tracer >> Yes, penup(). >> >> >>> >>> Maybe more not understanding(remembering) the origin of turtle graphics. >>> It was for kids to understand computer graphics... Seeing the shapes >>> being drawn is a big part of that. >>> > > That's why now turtles have got a better animation. (That means: the > resulting drawing should be > the same weather you use the old module or the new one, but *not* what you > see, when you observe > the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of > course, the now one > has a lot of additional enhacements.) And I'm going to have questions! Already have one. What is tracer()? Thanks for these: And clock.py uses tracer(), so cancel that question. Obvious. Dick =================================================== Have you seen Kelie Feng's video introducing the terrific and free IDE, Ulipad? Get Ulipad 3.9 from svn for the latest revision Mailing list for Ulipad: From rdmoores at gmail.com Fri Aug 8 04:23:08 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 19:23:08 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <489B7F6E.6010205@aon.at> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <489B7F6E.6010205@aon.at> Message-ID: On Thu, Aug 7, 2008 at 4:04 PM, Gregor Lingl wrote: > Hi Dick, > > first of all, thanks for your efforts using the new turtle module > and reporting about your experiences and the problems you ran into. Sure. And I'm not finished. There seem to be some interesting new things worth investigating. > I've already made some remarks on it in a former reply in this thread. Yes. Thanks. >> On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld >> wrote: >> ... >>>> >>>> 2. The turtle can also be seen moving from the last corner of the last >>>> rectangle to the first corner of the next. I don't want this. >>>> >>> >>> Again true of a physical turtle... But if you set speed to fastest >>> does that work? Also in the old turtle moduile there was a way to >>> hide the turtles movements completely and just draw the finished >>> graphic - which was orders of magnitude faster for complex >>> shapes - is that still available in turtle26? >>> > > Here better tracer() should come in! 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. http://docs.python.org/dev/library/turtle.html#turtle.tracer >> Yes, penup(). >> >> >>> >>> Maybe more not understanding(remembering) the origin of turtle graphics. >>> It was for kids to understand computer graphics... Seeing the shapes >>> being drawn is a big part of that. >>> > > That's why now turtles have got a better animation. (That means: the > resulting drawing should be > the same weather you use the old module or the new one, but *not* what you > see, when you observe > the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of > course, the now one > has a lot of additional enhacements.) And I'm going to have questions! Already have one. What is tracer()? Thanks for these: Dick =================================================== Have you seen Kelie Feng's video introducing the terrific and free IDE, Ulipad? Get Ulipad 3.9 from svn for the latest revision Mailing list for Ulipad: From cspears2002 at yahoo.com Fri Aug 8 07:34:05 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 7 Aug 2008 22:34:05 -0700 (PDT) Subject: [Tutor] date formatter In-Reply-To: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> Message-ID: <762599.20477.qm@web51611.mail.re2.yahoo.com> Ok, here is the working version of my program. Thanks for all of the advice: #!/usr/bin/python import time class date_format(object): def __init__(self, month, day, year): month_dict = {("jan","january") : 1, ("feb","february") :2, ("mar", "march") : 3, ("apr", "april") : 4, ("may",) : 5, ("jun", "june") : 6, ("jul", "july") : 7, ("aug", "august") : 8, ("sep", "september") : 9, ("oct", "october"): 10, ("nov", "november"): 11, ("dec", "december"): 12 } try: month_number = int(month) except ValueError: for eachKey in month_dict.keys(): if month.lower() in eachKey: month_number = month_dict[eachKey] break else: month_number = 0 if month_number==0 or day=="" or year=="": self.date = time.localtime() else: self.date = (int(year), month_number, int(day), 0, 0, 0, 0, 1, -1) def display(self, format_indicator = None): if format_indicator == 'MDY': print time.strftime("%m/%d/%y",self.date) elif format_indicator == 'MDYY': print time.strftime("%m/%d/%Y",self.date) elif format_indicator == 'DMY': print time.strftime("%d/%m/%y",self.date) elif format_indicator == 'DMYY': print time.strftime("%d/%m/%Y",self.date) elif format_indicator == 'MODYY': print time.strftime("%b %d, %Y",self.date) else: print time.strftime("%a %b %d %Y",self.date) if __name__ == "__main__": print "Welcome to the Date Formatter!" month = raw_input("Please enter a month (as a number): ") day = raw_input("Please enter a day: ") year = raw_input("Please enter a year: ") date_obj = date_format(month, day, year) format_indicator = raw_input("Enter a format indicator: ") date_obj.display(format_indicator.upper()) --- On Wed, 8/6/08, wesley chun wrote: > From: wesley chun > Subject: Re: [Tutor] date formatter > To: cspears2002 at yahoo.com > Cc: tutor at python.org > Date: Wednesday, August 6, 2008, 11:39 PM > > try: > > month = int(month) > > except ValueError: > > for eachKey in > month_dict.keys(): > > if month.lower() in > eachKey: > > month = > month_dict[eachKey] > > else: > > month = > "" > > : > > I am having trouble dealing with the case where the > user actually types in a month's name instead of the > number: > > io at io-station-1 ./chap13 180> python > date_format_v01.py > > : > > if month.lower() in eachKey: > > AttributeError: 'int' object has no attribute > 'lower' > > > > Any suggestions? > > > chris, > > good 1st attempt. all the problems are in the code snippet > above. you > only have a few flaws in your program preventing it from > working: > > a. you "wipe out" the originally entered month > (by continually > reassigning the month var) > > b. you don't break out of the inner for-loop when u > find a match and > end up wiping out the correct match > > c. the cause of the exception: the entry for May is a > string and not a > 1-item tuple. you need a trailing comma "," after > "may" to make it a > tuple. the reason why the error is triggered is because > you set a > blank to month for every non-match. so when it gets to may, > it makes > this comparison: > > >>> "" in "may" > True > > because of this, it sets... > > month = month_dict["may"] # so month == 5 > > so in the next loop iteration, your're trying to do... > > 5.lower() in eachKey > > which of course, fails. fix these problems, and you have a > working solution! > > best of luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Python Web Development with Django", Addison > Wesley, (c) 2008 > http://withdjango.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com From gregor.lingl at aon.at Fri Aug 8 09:36:01 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 09:36:01 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <489B7F6E.6010205@aon.at> Message-ID: <489BF761.1060805@aon.at> Dick Moores schrieb: >> >> Here better tracer() should come in! >> > > 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. > http://docs.python.org/dev/library/turtle.html#turtle.tracer > tracer is only deprecated as a Turtle-method, because it doesn't concern single turtles but all the turtles on the screen. It will stay as Screen-method and of course also as function. (As a turtle-method it's only there because of compatibility with the old turtle module.) Gregor From gregor.lingl at aon.at Fri Aug 8 09:39:55 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 09:39:55 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - Important note! In-Reply-To: <489B7B9A.6090109@aon.at> References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> <489B7B9A.6090109@aon.at> Message-ID: <489BF84B.9000409@aon.at> > > P.S.: If you are interested, you can download a series of sample programs > covering a broad range from very easy to fairly advanced, which > intend to show some features and capabilities of the new turtle module > from here: > > http://svn.python.org/view/python/trunk/Demo/turtle/ > > These will be included in the source distribution - but not in the > Windows > installer. > > IMPORTANT NOTE! In order to have the examples working correctly you have to have turtle.cfg in the directory where the example scripts are (or in that with turtle.py). An easy way to have a look at all the examplescripts is using turtleDemo.py Gregor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From federo at email.si Fri Aug 8 11:12:18 2008 From: federo at email.si (Federo) Date: Fri, 08 Aug 2008 11:12:18 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> Message-ID: <20080808091219.22A228B9F2@www1.email.si> Kent hi I am still unable to enter data into textbox and getting back server reply. The main problem is that I do not understand which fileds / header to observer using Firefox Fireburg. Atteched you can see headers I went through. With red font I marked differences among stages. In nider of the headers I didn't find fieldds you included in your workable login code. Questions: 1.) Could you send print screens of what you are using in Firefox Fireburg 2.) In case I am using the currect headres, I would appreciate you mark on the attached document with pink font important fields to be included in the code in order to be able to get data from server. 3.) The most usefull (the quickest to understand and re-use) would be if you coud make workable code to get server reply for XSNX stock ticker(on screen top left corner: field Symbol - enter XSNX). Once I would see this I would be able to adjust other searches by myselves. This would be realy usefull knowledge. At the moment I am able to do web control with iMacro only. I would like to switch to Python! Login - fake account https://investor.firstrade.com/firstrade/login.do User: janezfedero Pass: kmet555 Side where stock to enter stock Symbole: https://investor.firstrade.com/firstrade/mainmenu.do Workable login code: (The code open main side on which stock symbol can be entered. The question is how to what fields form header to be used and how to put this in the code. Headers can be seen in the attached word file) import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() # print(data) f = opener.open('https://investor.firstrade.com/firstrade/stockorder.do', params) data = f.read() f.close() print(data) On Mon, 4 Aug 2008 at 16:08:33, Kent Johnson wrote: > On Mon, Aug 4, 2008 at 8:05 AM, Federo wrote: > > Kent THANKS! It works great also on real account .. > > > > Two important Sub-QUESTIONS: > > > > 1.) Look attached word file. It describes form fields I would like to fill > in > > and read server resoult.. > > You just have to mimic what the browser does. Use a Firefox plugin > that shows you what is being submitted; TamperData is one. Then set > the same fields in your code. > > > 2.) Could you do the same login logic also with MECHANIZE plagin. There > are > > some very usefull function in this plagin I might use. However I have > > No, I'm not familiar with mechanize. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_Note.rtf Type: application/msword Size: 33888 bytes Desc: FormManagement_Note.rtf URL: From kent37 at tds.net Fri Aug 8 13:49:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 07:49:06 -0400 Subject: [Tutor] date formatter In-Reply-To: <762599.20477.qm@web51611.mail.re2.yahoo.com> References: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> <762599.20477.qm@web51611.mail.re2.yahoo.com> Message-ID: <1c2a2c590808080449v48486405yaa7d02cd2975a7db@mail.gmail.com> On Fri, Aug 8, 2008 at 1:34 AM, Christopher Spears wrote: > Ok, here is the working version of my program. Thanks for all of the advice: > > #!/usr/bin/python > > import time > > class date_format(object): This is a bit of a misnomer, you aren't formatting the date, you are parsing it. > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may",) : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > > try: > month_number = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month_number = month_dict[eachKey] > break month_dict might as well be a list, you aren't using the dict-ness of it at all. months = [ (("jan","january") , 1), ... ] try: month_number = int(month) except ValueError: for names, number in months(): if month.lower() in names: month_number = number break else: month_number = 0 You might be interested in this project: http://code-bear.com/code/parsedatetime/ Kent From kent37 at tds.net Fri Aug 8 13:54:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 07:54:41 -0400 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <20080808091219.22A228B9F2@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> Message-ID: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> On Fri, Aug 8, 2008 at 5:12 AM, Federo wrote: > Kent hi > > I am still unable to enter data into textbox and getting back server reply. The > main problem is that I do not understand which fileds / header to observer > using Firefox Fireburg. Atteched you can see headers I went through. With red > font I marked differences among stages. In nider of the headers I didn't find > fieldds you included in your workable login code. Hi Federo, This isn't really a Python question anymore, it is a matter of figuring out what the server requires. You have to look at the form data as well as the headers. TamperData is one Firefox pluging that can do that, I'm sure there are others as well. Kent From spython01 at gmail.com Fri Aug 8 17:56:27 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 11:56:27 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays Message-ID: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> Hi Everyone, I would like to create a two-dimensional array but am confused as to how to go about it. I've read about Numeric Python and Numpy. Are they one and the same? Also, how do I install them? I am working on a Windows machine. I've been getting the following error messages: >>> import Numeric Traceback (most recent call last): File "", line 1, in import Numeric ImportError: No module named Numeric >>> from Numeric import * Traceback (most recent call last): File "", line 1, in from Numeric import * ImportError: No module named Numeric I then downloaded and installed release 1.1.1 of the Numpy package from this site: http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 After restarting the shell, I still get the same errors above (though I do have this directory now: C:\Python25\Lib\site-packages\numpy). Anyone know how to correctly install and use this package? Thanks in advance. Samir From kent37 at tds.net Fri Aug 8 18:25:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 12:25:11 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> Message-ID: <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> On Fri, Aug 8, 2008 at 11:56 AM, S Python wrote: > Hi Everyone, > > I would like to create a two-dimensional array but am confused as to > how to go about it. > > I've read about Numeric Python and Numpy. Are they one and the same? No, they are not the same. Numeric is older; NumArray is another older package. You should use Numpy if you can. http://numpy.scipy.org/#older_array > I then downloaded and installed release 1.1.1 of the Numpy package > from this site: > http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 > > After restarting the shell, I still get the same errors above (though > I do have this directory now: C:\Python25\Lib\site-packages\numpy). > > Anyone know how to correctly install and use this package? Now you should be able to import numpy. Kent From spython01 at gmail.com Fri Aug 8 18:29:53 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 12:29:53 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> Message-ID: <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> > No, they are not the same. Numeric is older; NumArray is another older > package. You should use Numpy if you can. > http://numpy.scipy.org/#older_array > > > Now you should be able to import numpy. > > Kent > Thanks, Kent. I ended up using: >>> from numpy import * I wasn't sure what the difference was between this and >>> import numpy Thanks! Samir From timothy.grant at gmail.com Fri Aug 8 19:25:43 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 8 Aug 2008 10:25:43 -0700 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> Message-ID: On Fri, Aug 8, 2008 at 9:29 AM, S Python wrote: >> No, they are not the same. Numeric is older; NumArray is another older >> package. You should use Numpy if you can. >> http://numpy.scipy.org/#older_array >> > >> >> Now you should be able to import numpy. >> >> Kent >> > > Thanks, Kent. I ended up using: >>>> from numpy import * > > I wasn't sure what the difference was between this and >>>> import numpy > > Thanks! > > Samir In general "from import *" is a very bad idea. import imports a module into its own namespace (e.g., to access its functionality you would have to do ".foo() and .bar()" The form that you chose to use imports all of a module's contents into the current namespace. This means you can call "foo()" and "bar()" directly, but it also means that if you have coded a "foo()" and a "bar()" you will not have access to the functions in the module you just imported. -- Stand Fast, tjg. [Timothy Grant] From rambert.marc at free.fr Fri Aug 8 18:26:39 2008 From: rambert.marc at free.fr (Marc Rambert) Date: Fri, 8 Aug 2008 18:26:39 +0200 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 Message-ID: hi, I would like to make some regular expression, unfortunately I can't because the backslash doesn't work at all on IDLE 1.2.2 did someone already try this on a MacBook? The combination to do the backslash works properly (\ as you can see) but not in IDLE Doesn't someone notice already these ? thanks for you feedback Marc From gregor.lingl at aon.at Fri Aug 8 20:47:11 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 20:47:11 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: References: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: <489C94AF.6080502@aon.at> Hi Dick, just to show you a bit of the versatility of the new turtle module I've prepared to tiny rectangle-generator program examples. They intentionally use different programming styles and also turtle graphics techniques different from the ones you used to accomplish something similar to what you did, of course in a very simplified way and without your eleborated user interface and colormanagement. ----------- Version 1: procedural, using stamp() ----------- from turtle import * from random import random, randint from time import sleep MAXLEN = 30 MAXWID = 25 def randomcolor(): return random(), random(), random() reset() title("Python turtle graphics: random rectangle generator") hideturtle() resizemode("user") shape("square") for cycle in range(randint(3, 5)): bgcolor(randomcolor()) for rect in range(randint(5,10)): shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID, randint(3, 10)) color(randomcolor(), randomcolor()) stamp() sleep(0.5) sleep(1) clearstamps() ----------- Version 2: object oriented, uses a list of turtles, which change their properties (size, color, visibility) ----------- from turtle import Screen, Turtle from random import random, randint from time import sleep MAXLEN = 30 MAXWID = 25 def randomcolor(): return random(), random(), random() class RectGenerator(object): def __init__(self): self.s = s = Screen() s.reset() s.title("Python turtle graphics: random rectangle generator") self.rectturtles = [] for n in range(10): t = Turtle(visible=False) t.hideturtle() t.resizemode("user") t.shape("square") self.rectturtles.append(t) def run(self): for cycle in range(randint(3, 5)): self.s.bgcolor(randomcolor()) n = randint(5,10) for index in range(n): t = self.rectturtles[index] t.shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID, randint(3, 10)) t.color(randomcolor(), randomcolor()) t.showturtle() sleep(0.5) sleep(1) for t in self.s.turtles(): t.hideturtle() if __name__ == "__main__": rg = RectGenerator() rg.run() Hope you like it Gregor From spython01 at gmail.com Fri Aug 8 21:07:03 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 15:07:03 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> Message-ID: <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> > In general "from import *" is a very bad idea. > > import imports a module into its own namespace (e.g., to > access its functionality you would have to do ".foo() and > .bar()" The form that you chose to use imports all of a > module's contents into the current namespace. This means you can call > "foo()" and "bar()" directly, but it also means that if you have coded > a "foo()" and a "bar()" you will not have access to the functions in > the module you just imported. > Timothy, Thanks for the clarification. I had always wondered what the difference was. Samir From bgailer at gmail.com Fri Aug 8 23:12:04 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 08 Aug 2008 17:12:04 -0400 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 In-Reply-To: References: Message-ID: <489CB6A4.7090504@gmail.com> Marc Rambert wrote: > hi, > > I would like to make some regular expression, unfortunately I can't > because the backslash doesn't work Please explain "doesn't work". I interpret that as "I press the \ key and nothing shows up in the active window." -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From joefazee at gmail.com Fri Aug 8 23:22:50 2008 From: joefazee at gmail.com (A. Joseph) Date: Fri, 8 Aug 2008 14:22:50 -0700 Subject: [Tutor] I need a Python mentor Message-ID: Hello everybody, i`m new to this list. I was programming in PHP before, of recent I started learning python. I need someone who can be giving me some assignment based on the chapter I read in the book, and the person will sometime review my code and tell me if it`s well structured. Thanks- -------------- next part -------------- An HTML attachment was scrubbed... URL: From flaxeater at gmail.com Fri Aug 8 23:36:45 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Fri, 8 Aug 2008 17:36:45 -0400 Subject: [Tutor] I need a Python mentor In-Reply-To: References: Message-ID: <584940990808081436r2164b0bem490ecc0b912de9da@mail.gmail.com> Actually the way this list works is there is no one person who will do this. However if you pose a specific question I'm sure you will get several helpful people will respond. Like this. What book did you read and what topics did it cover? From there someone perhaps even myself will be able to make up something nice for you to program. Then when you have problems with the program come back and ask questions. Since you already programmed in PHP I don't think you'll have too much trouble picking up python. On Fri, Aug 8, 2008 at 5:22 PM, A. Joseph wrote: > Hello everybody, i`m new to this list. I was programming in PHP before, of > recent I started learning python. I need someone who can be giving me some > assignment based on the chapter I read in the book, and the person will > sometime review my code and tell me if it`s well structured. > > Thanks- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From airchia at gmail.com Fri Aug 8 23:41:38 2008 From: airchia at gmail.com (Nick Scholtes) Date: Fri, 8 Aug 2008 16:41:38 -0500 Subject: [Tutor] I need a Python mentor In-Reply-To: References: Message-ID: Hi, I'm a beginner in python, so I can't be a mentor, but here are some links that may help: http://uselesspython.com/ Python Wiki at: http://wiki.python.org/ Also google Think Python. It is a great resource. Nick On Fri, Aug 8, 2008 at 4:22 PM, A. Joseph wrote: > Hello everybody, i`m new to this list. I was programming in PHP before, of > recent I started learning python. I need someone who can be giving me some > assignment based on the chapter I read in the book, and the person will > sometime review my code and tell me if it`s well structured. > > Thanks- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Art: bellsoffreedom.cgsociety.org/gallery/ Blog: cognitivealchemy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 8 23:55:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Aug 2008 22:55:05 +0100 Subject: [Tutor] I need a Python mentor References: Message-ID: "A. Joseph" wrote > Hello everybody, i`m new to this list. I was programming in PHP > before, of > recent I started learning python. I need someone who can be giving > me some > assignment based on the chapter I read in the book, and the person > will > sometime review my code and tell me if it`s well structured. While some individual may volunteer its unlikely. The way the list works you pose questions and anyone on the list who knows (or thinks they do) the answer will reply. If you have code either post it in a mail(if short) or post a link to pastebin or some similar site. Hopefully some folks will have the time and intreest to review it. If you have studied a tyopic and want ideas on how to put it into practice just ask. Be as specific as possible. State where you are studying - tutorial, book, video etc. If you are getting errors post a short program that demonstrates the error plus all of the error text. You should get a reply pretty quickly. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 8 23:59:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Aug 2008 22:59:51 +0100 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" forArrays References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com><1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com><50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> Message-ID: "S Python" wrote > Thanks for the clarification. I had always wondered what the > difference was. A useful tip is that if you have a long module name you can also use import module as shortname eg import numpy as n and then access numpy.foo() as n.foo() Sacves a lot of typing for a slight loss of clarity in maintenance - you have to remember which module the short names refer to! I tend to use full names in real code and use the abbreviated form when using the >>> prompt. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Aug 9 00:31:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 18:31:53 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> Message-ID: <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> On Fri, Aug 8, 2008 at 1:25 PM, Timothy Grant wrote: > In general "from import *" is a very bad idea. > > import imports a module into its own namespace (e.g., to > access its functionality you would have to do ".foo() and > .bar()" The form that you chose to use imports all of a > module's contents into the current namespace. This means you can call > "foo()" and "bar()" directly, but it also means that if you have coded > a "foo()" and a "bar()" you will not have access to the functions in > the module you just imported. Another reason not to use "from xx import *" is that it can make it very difficult to discover where a name is defined. If you have several "from xx import *" lines and then later you use a function "foo()" there is no easy way to tell which module foo came from. An alternative is to list just the names you want to import: from xx import foo Kent From spython01 at gmail.com Sat Aug 9 00:54:51 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 18:54:51 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" forArrays In-Reply-To: References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> Message-ID: <50a597410808081554r777ce184j2d05d58ca43560a8@mail.gmail.com> > A useful tip is that if you have a long module name you can also use > > import module as shortname > > eg > > import numpy as n > > and then access numpy.foo() as > > n.foo() > > Sacves a lot of typing for a slight loss of clarity in > maintenance - you have to remember which module the > short names refer to! I tend to use full names in real code > and use the abbreviated form when using the >>> prompt. > Alan - Great suggestion! As I'm reading through the numpy documentation, there are a lot of great functions that I'd like to learn to use so your advice definitely helps. I was getting tired of constantly having to type "numpy.array" or "numpy.ones" all the time. Thanks again. Samir From spython01 at gmail.com Sat Aug 9 00:55:39 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 18:55:39 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> Message-ID: <50a597410808081555s7459e282k1ceb274d3f7a0fe1@mail.gmail.com> > Another reason not to use "from xx import *" is that it can make it > very difficult to discover where a name is defined. If you have > several "from xx import *" lines and then later you use a function > "foo()" there is no easy way to tell which module foo came from. > > An alternative is to list just the names you want to import: > from xx import foo > > Kent > Kent - Another great point. Thanks for contributing to the list. Samir From rdmoores at gmail.com Sat Aug 9 01:32:14 2008 From: rdmoores at gmail.com (Dick Moores) Date: Fri, 8 Aug 2008 16:32:14 -0700 Subject: [Tutor] To Tutor subscribers: should I send detailed questions about the Python 2.6b2's Turtle to the list? Message-ID: The thread I started continues, and now concerns mainly the new Turtle module in Python 2.6b2. I am very interested in this, but I'm wondering is there are other 'kids" out there who are. Should I ask our resident expert, Gregor Lingl directly, or through the list? Opinions, please? Dick Moores, who is in his 2nd kidhood. From alan.gauld at btinternet.com Sat Aug 9 03:19:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Aug 2008 02:19:02 +0100 Subject: [Tutor] To Tutor subscribers: should I send detailed questionsabout the Python 2.6b2's Turtle to the list? References: Message-ID: "Dick Moores" wrote > The thread I started continues, and now concerns mainly the new > Turtle > module in Python 2.6b2. I am very interested in this, but I'm > wondering is there are other 'kids" out there who are. Should I ask > our resident expert, Gregor Lingl directly, or through the list? > > Opinions, please? Turtle is often used by beginners. Understanding the new modules foibles early seems a reasonable thread to pursue on this list. Lets just try to keep it in a single thread so that those who are not interested can filter it out and those searching in the future can find the full discourse. My view FWIW, Alan G From rdm at rcblue.com Sat Aug 9 12:12:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 09 Aug 2008 03:12:57 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 Message-ID: <20080809101310.2AE531E4002@bag.python.org> Gregor, 1. I want the window to open with the right edge 0 pixels from the right edge of my screen. However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't work. I have to do the nearest thing, setup(width=.75, height=.915, startx=-1, starty=0). A small thing, but what's wrong with perfection. 2. There's a lot I don't understand in turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"]) What is '_CFG'? And how should anyone know what it is? What is "leftright"? And how to use it? What is "topbottom"? And how to use it? 3. http://docs.python.org/dev/library/turtle.html#turtle.stamp "turtle.stamp() Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id)." But in your version 1 (), the turtle is hidden by hideturtle()! What are you stamping? It seems the shape, or rectangle. If so, why does the doc say 'turtle'? 4. For my random_rectangles.py program I've started to try out the new turtle. (See the current state of random_rectanglesV16_web.py at .) The only downside I've found is that the new turtle is much faster that the old. I want to set the speed so that the outlines of rectangles are drawn slowly enough that the user (me at present) can both appreciate the colors and have time to check the names of the colors being printed in the console window. Using the old turtle, I found that a default delay of 1 ((delay(1)) was just right; with the new turtle, setting a delay of even 50 affects only the first cycle of rectangles. So I don't use delay at all. Setting the slowest speed of 1 (speed(1)) is still too fast. How can I slow down the drawing of the rectangles? 5. I've been unable to figure out how to use onclick() (). I'd like to find a way to pause my script by clicking on the screen -- so I could snag an image of what's showing, and then click again to restart the drawing of the rectangles. And in addition, being able to stop the program with a double click on the screen would be very handy. Could you explain how to do these, if in fact they are possible? That's all for now. Thanks, Dick From bgailer at gmail.com Sat Aug 9 17:02:33 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 09 Aug 2008 11:02:33 -0400 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 In-Reply-To: <530AA005-9130-4238-B212-D662E56DA7DD@free.fr> References: <489CB6A4.7090504@gmail.com> <530AA005-9130-4238-B212-D662E56DA7DD@free.fr> Message-ID: <489DB189.6080507@gmail.com> Please always reply to tutor at python.org as well as me. All of us can help and learn. Marc Rambert wrote: > >> Marc Rambert wrote: >>> hi, >>> >>> I would like to make some regular expression, unfortunately I can't >>> because the backslash doesn't work >> >> Please explain "doesn't work". >> >> I interpret that as "I press the \ key and nothing shows up in the >> active window." >> > hi yes you are right and this is when I am in french keyboard. I can't help here but perhaps someone else can. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From rdm at rcblue.com Sat Aug 9 17:08:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 09 Aug 2008 08:08:35 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <20080809101310.2AE531E4002@bag.python.org> References: <20080809101310.2AE531E4002@bag.python.org> Message-ID: <20080809151353.E03D81E4002@bag.python.org> An HTML attachment was scrubbed... URL: From noshius at gmail.com Sat Aug 9 17:55:43 2008 From: noshius at gmail.com (Joshua Nikkel) Date: Sat, 9 Aug 2008 11:55:43 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: References: Message-ID: I've pasted the following from my python shell. Please note that the first two lines of code are taken directly from the standard tutorial files under section 3.1.2. Will someone please tell me why something as basic and straightforward as this will not work? Everything else seems to work just fine, but not this. All I need is someway to get the length of a string... please help, nosh Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 ==== No Subprocess ==== >>> s = 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "", line 1, in len(s) TypeError: 'str' object is not callable >>> s 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "", line 1, in len(s) TypeError: 'str' object is not callable >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtp at nc.rr.com Sat Aug 9 18:28:50 2008 From: jtp at nc.rr.com (James) Date: Sat, 9 Aug 2008 12:28:50 -0400 Subject: [Tutor] Unable to catch exception Message-ID: All, I'm having a rather strange problem that I'm hoping someone can shed some light on. I'm trying to catch a BadStatusLine exception raised by the httplib library. Below is the traceback that Python gives me when something goes wrong with one of my programs: ----- Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "cherryTree.py", line 237, in run qDump = browser.open( url ).read() # get the new c3 queue File "/usr/lib/python2.5/site-packages/mechanize/_mechanize.py", line 203, in open return self._mech_open(url, data) File "/usr/lib/python2.5/site-packages/mechanize/_mechanize.py", line 229, in _mech_open response = UserAgentBase.open(self, request, data) File "/usr/lib/python2.5/site-packages/mechanize/_opener.py", line 181, in open response = urlopen(self, req, data) File "/usr/lib/python2.5/urllib2.py", line 399, in _open '_open', req) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/site-packages/mechanize/_http.py", line 700, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.5/site-packages/mechanize/_http.py", line 675, in do_open r = h.getresponse() File "/usr/lib/python2.5/httplib.py", line 928, in getresponse response.begin() File "/usr/lib/python2.5/httplib.py", line 385, in begin version, status, reason = self._read_status() File "/usr/lib/python2.5/httplib.py", line 349, in _read_status raise BadStatusLine(line) BadStatusLine ----- This error happens when I try to open a page using mechanize. From what I gather this error only happens when the web server returns an unknown error. The error only happens once every blue moon, but to avoid a crash I setup a try/catch. try: catch BadStatusLine: print "yuck!" However, somehow the thread that this code is in still raised a BadStatusLine exception and the thread stopped cold. Thoughts on how to possibly fix this? Thanks! -j From mwalsh at mwalsh.org Sat Aug 9 21:59:00 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 09 Aug 2008 14:59:00 -0500 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: References: Message-ID: <489DF704.8080905@mwalsh.org> Joshua Nikkel wrote: > IDLE 1.2.2 ==== No Subprocess ==== >>>> s = 'supercalifragilisticexpialidocious' >>>> len(s) > Traceback (most recent call last): > File "", line 1, in > len(s) > TypeError: 'str' object is not callable My guess would be that you've reassigned the name 'len' to some other object, in this case a string. Does the error persist after you restart IDLE (or Restart Shell from the Shell menu)? HTH, Marty From dave6502 at googlemail.com Sun Aug 10 00:03:22 2008 From: dave6502 at googlemail.com (dave selby) Date: Sat, 9 Aug 2008 23:03:22 +0100 Subject: [Tutor] importing path question Message-ID: Hi all, I have a main directory 'kmotion2' where python scripts live. They access a library of scripts in 'kmotion2/core' as 'kmotion2/core' has a __init__.py file. However I now need to create a new directory 'utilities' inside 'kmotion2' that also needs to access scripts in 'core' kmotion2 directory | | core utilities So I need to import up the tree then back down. Is this possible ? Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From o.lenstra at gmail.com Sun Aug 10 02:24:52 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 02:24:52 +0200 Subject: [Tutor] Problems with Gauge Bar. Message-ID: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> Hello mail list ;) I've been developing a program for a while now (I am still a beginner though) and I want to add a progress bar (gauge bar) to my program. I am having quite some trouble actually implementing it though. I attached the file TSO.pyw which is my current project. I want to keep it within 1 python file if it's possible. Because I want to turn it into a single executable file. I am using wxPython for my GUI and a Win32API module. I hope to hear from you. Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: TSO.pyw URL: From queprime at gmail.com Sun Aug 10 06:57:27 2008 From: queprime at gmail.com (Que Prime) Date: Sat, 9 Aug 2008 21:57:27 -0700 Subject: [Tutor] IP address parse Message-ID: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> I'm trying to parse a log file for all ip addresses but can't get my RE to work. Thanks in advance for pointing me in the right direction #IP address parse ############################## import re infile = open("host0_declare.txt","r") outfile = open("out.txt","w") patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3}) for line in infile: m = patt.match(line) if m: outfile.write("%s.%s.%s.%s\n"%m.groups()) infile.close() outfile.close() ############################# -------------- next part -------------- An HTML attachment was scrubbed... URL: From timothy.grant at gmail.com Sun Aug 10 07:46:53 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 9 Aug 2008 22:46:53 -0700 Subject: [Tutor] IP address parse In-Reply-To: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> Message-ID: On Sat, Aug 9, 2008 at 9:57 PM, Que Prime wrote: > I'm trying to parse a log file for all ip addresses but can't get my RE to > work. Thanks in advance for pointing me in the right direction > > > #IP address parse > > ############################## > import re > > infile = open("host0_declare.txt","r") > outfile = open("out.txt","w") > > patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3}) > > for line in infile: > m = patt.match(line) > if m: > outfile.write("%s.%s.%s.%s\n"%m.groups()) > > infile.close() > outfile.close() > ############################# > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Well there's one glaring problem, but I'll put that down to a re-keying error. there are no quote marks around your pattern string. However, the likely problem is that you are using re.match() instead of re.search(). Your re will ONLY match if the only thing on the line matches your pattern. -- Stand Fast, tjg. [Timothy Grant] From broek at cc.umanitoba.ca Sun Aug 10 07:38:18 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 00:38:18 -0500 Subject: [Tutor] using generators to mock raw_input for doctest Message-ID: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> Hi all, I'm building a tool that will be run in a shell and depends heavily on raw_input. I'm also using doctest (mostly via doctest.testfile) to create unit tests for it. After thinking a while about how to use doctest for invocations of raw_input, I came up with the general sort of idea shown in the toy code below. I have two questions: 1) As I've never really made generators `mine,' I'm not sure if this is the best (read `best' as `easiest and simplest') way to use a generator for this task. Should I be doing it differently? 2) Is there some better way to enable doctesting of code that uses raw_input? All I found when googling was the suggestion that in place of: def myfunc(): # code employing raw_input here one could write: def myfunc(input_meth=raw_input): # code with raw_input calls replaced with input_meth calls but that seems like complicating my code for the non-doctest case. Perhaps that worries me too much, though---I've yet to become test infected ;-) Thanks for any input, Brian vdB import sys class myraw(object): def __init__(self, values): self.values = values self.stream = self.mygen() def mygen(self): for i in self.values: yield i def readline(self): return str(self.stream.next()) def double_user_input(): """A silly example to illustrate my method for testing. >>> sys.stdin = myraw([1,21,12.5,3.1415]) >>> double_user_input() 2 >>> double_user_input() 42 >>> double_user_input() 25 >>> double_user_input() # doctest: +ELLIPSIS 6.28300... >>> sys.stdin = sys.__stdin__ """ val = float(raw_input()) * 2 val = [val, int(val)][val == int(val)] return val def __test(): import doctest doctest.testmod() if __name__ == "__main__": __test() From rosenville at gmail.com Sun Aug 10 07:58:53 2008 From: rosenville at gmail.com (Josh Rosen) Date: Sat, 9 Aug 2008 22:58:53 -0700 Subject: [Tutor] IP address parse In-Reply-To: <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> Message-ID: <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> On Aug 9, 2008, at 10:46 PM, Josh Rosen wrote: > There are a few different problems in your code. First off, regular > expressions must be passed to re.compile() as strings. > >> patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. >> (\[0-9]{1,3}) > > should read > > patt = re.compile(r"(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. > (\[0-9]{1,3})"). > > I've used a raw string literal here to prevent Python from > interpreting the backslashes as character escapes. However, this > regular expression still won't work. If you're going to use a > character class, there's no need to put a backslash in front of it. > Correcting this, the line becomes: > > patt = re.compile(r"([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9] > {1,3})") > > This works, but it can be made simpler by using the shorthand > notation \d in place of [0-9]: > > patt = re.compile(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})") > > Since it doesn't look like you're doing anything with the parts of > the ip besides writing the whole ip to a file, you can eliminate the > capturing parentheses in your regular expression and replace them > with a single pair: > > patt = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") > > The string formatting expression becomes: > > outfile.write("%s\n" % m.groups()) > > Hope this helps, > Josh > > > On Aug 9, 2008, at 9:57 PM, Que Prime wrote: > >> I'm trying to parse a log file for all ip addresses but can't get >> my RE to work. Thanks in advance for pointing me in the right >> direction >> >> >> #IP address parse >> >> ############################## >> import re >> >> infile = open("host0_declare.txt","r") >> outfile = open("out.txt","w") >> >> patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. >> (\[0-9]{1,3}) >> >> for line in infile: >> m = patt.match(line) >> if m: >> outfile.write("%s.%s.%s.%s\n"%m.groups()) >> >> infile.close() >> outfile.close() >> ############################# >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > From gregor.lingl at aon.at Sun Aug 10 08:59:38 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sun, 10 Aug 2008 08:59:38 +0200 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <20080809151353.E03D81E4002@bag.python.org> References: <20080809101310.2AE531E4002@bag.python.org> <20080809151353.E03D81E4002@bag.python.org> Message-ID: <489E91DA.8070001@aon.at> Dick Moores schrieb: > At 03:12 AM 8/9/2008, Dick Moores wrote: >> 4. For my random_rectangles.py program I've started to try out the >> new turtle. (See the current state of random_rectanglesV16_web.py at >> < http://py77.python.pastebin.com/d3e842821>.) >> The only >> downside I've found is that the new turtle is much faster that the >> old. I want to set the speed so that the outlines of rectangles are >> drawn slowly enough that the user (me at present) can both appreciate >> the colors and have time to check the names of the colors being >> printed in the console window. Using the old turtle, I found that a >> default delay of 1 ((delay(1)) was just right; with the new turtle, >> setting a delay of even 50 affects only the first cycle of >> rectangles. So I don't use delay at all. Setting the slowest speed of >> 1 (speed(1)) is still too fast. How can I slow down the drawing of >> the rectangles? > > I seem to have solved #4. > > I had been using tracer() as tracer(True) in my function draw_rect(). > In rereading the doc, I noticed that < > http://docs.python.org/dev/library/turtle.html#turtle.tracer> > has > "turtle.tracer(/flag=None/, /delay=None/)" > > so in draw_rect() I tried changing tracer(True) to tracer(True, dly). > (See the new version, random_rectanglesV17_web.py, at < > http://py77.python.pastebin.com/f54c9211f>, lines 220, 230, 240, etc.) > > Then I enabled the user to enter both speed and delay, with a default > speed of 1 and a default delay of 15 (see the new function > get_speed_and_delay_from_user(), lines 153-179). On my computer, these > defaults seemed to be ideal. > That's fine! > But now I have another puzzle: As long as delay is kept constant, it > doesn't seem to matter what speed is chosen -- from the slowest of 1 > to the fastest of 0. Why is speed irrelevant? Did you observe that faster speeds need arguments in the range from 2 to 10? That means speed(10) is fastest speed. Gregor > > Dick > > BTW at < http://py77.python.pastebin.com/f54c9211f>, if you click on > the 'view diff' link just above the code, you'll get a diff with the > immediately previous version. > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Aug 10 10:15:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 09:15:39 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> Message-ID: "Olrik Lenstra" wrote > I've been developing a program for a while now (I am still a > beginner > though) and I want to add a progress bar (gauge bar) to my program. > I am having quite some trouble actually implementing it though. I > attached > the file TSO.pyw which is my current project. Can you show us what you have tried so far? > I want to keep it within 1 python file if it's possible. Because I > want to > turn it into a single executable file. You can use multiple files and still produce an EXE using py2exe or similar. There is no need to keep it in one file. Alan G From o.lenstra at gmail.com Sun Aug 10 12:49:04 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 12:49:04 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> Message-ID: <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> This is the part I tried to get the Bar in. I actually got it in GUI wise. But I had no idea to let it run the moment I clicked "Scan" I got the code I tried to put in from another python file that I found somewhere on the net. It's attached as test.pyw <<< class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(300, 280), style = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) self.timer = wx.Timer(self, 1) self.count = 0 panel = wx.Panel(self, -1) introFont = wx.Font(10, wx.ROMAN, wx.NORMAL, wx.NORMAL) introText = wx.StaticText(panel, -1, introRaw,(50, 10), style=wx.ALIGN_CENTRE) introText.SetFont(introFont) wx.Button(panel, 1, 'Scan!', (115, 90)) wx.Button(panel, 2, 'Logs', (115, 120)) wx.Button(panel, 3, 'Version', (115, 150)) wx.Button(panel, 4, 'Credits', (115, 180)) wx.Gauge(panel, 5, 50, (50, 210), size=(250, 25)) self.Bind(wx.EVT_BUTTON, self.OnScan, id=1) self.Bind(wx.EVT_BUTTON, self.OnLogs, id=2) self.Bind(wx.EVT_BUTTON, self.OnVersion, id=3) self.Bind(wx.EVT_BUTTON, self.OnCredits, id=4) >>> Alan, I'm using pyinstaller. is it possible to make several python files into a single exe? If so, Can you direct me to maybe some documentation? (I might have overlooked it.) The program runs fine and works perfectly as the code is right now, But while I'm asking for the bar, can I ask for some advice on the following bit of code too? <<< ##------------------------------------------------------------------------------ ## Define all the private IP ranges that we're not going to filter in ## the ipconfig part of the program. ## From private4 to private19 is actually 1 range. (Needs to be looked at.) ##------------------------------------------------------------------------------ private1 = r"192\.168\.\d+\.\d+" private2 = r"169\.254\.\d+\.\d+" private3 = r"10\.\d+\.\d+\.\d+" private4 = r"172\.16\.\d+\.\d+" private5 = r"172\.17\.\d+\.\d+" private6 = r"172\.18\.\d+\.\d+" private7 = r"172\.19\.\d+\.\d+" private8 = r"172\.20\.\d+\.\d+" private9 = r"172\.21\.\d+\.\d+" private10 = r"172\.22\.\d+\.\d+" private11 = r"172\.23\.\d+\.\d+" private12 = r"172\.24\.\d+\.\d+" private13 = r"172\.25\.\d+\.\d+" private14 = r"172\.26\.\d+\.\d+" private15 = r"172\.27\.\d+\.\d+" private16 = r"172\.28\.\d+\.\d+" private17 = r"172\.29\.\d+\.\d+" private18 = r"172\.30\.\d+\.\d+" private19 = r"172\.31\.\d+\.\d+" ##------------------------------------------------------------------------------ ## Define concealip. This will make sure no public addresses will be published ## on the forums and decreasing the risk for the poster. ##------------------------------------------------------------------------------ def concealip(): ##------------------------------------------------------------------------------ ## Start a loop to replace the public addresses with X's. ## Currently this part is really inefficient. ##------------------------------------------------------------------------------ lines = file('ipconfig.txt', "r+").readlines() for i in range(len(lines)): if re.search("IP\D+ \:", lines[i]): if not re.search(private1, lines[i]): if not re.search(private2, lines[i]): if not re.search(private3, lines[i]): if not re.search(private4, lines[i]): if not re.search(private5, lines[i]): if not re.search(private6, lines[i]): if not re.search(private7, lines[i]): if not re.search(private8, lines[i]): if not re.search(private9, lines[i]): if not re.search(private10, lines[i]): if not re.search(private11, lines[i]): if not re.search(private12, lines[i]): if not re.search(private13, lines[i]): if not re.search(private14, lines[i]): if not re.search(private15, lines[i]): if not re.search(private16, lines[i]): if not re.search(private17, lines[i]): if not re.search(private18, lines[i]): if not re.search(private19, lines[i]): lines[i] = lines[i].replace('1', 'x') lines[i] = lines[i].replace('2', 'x') lines[i] = lines[i].replace('3', 'x') lines[i] = lines[i].replace('4', 'x') lines[i] = lines[i].replace('5', 'x') lines[i] = lines[i].replace('6', 'x') lines[i] = lines[i].replace('7', 'x') lines[i] = lines[i].replace('8', 'x') lines[i] = lines[i].replace('9', 'x') lines[i] = lines[i].replace('0', 'x') >>> This bit of code is meant to X-away public IP addresses on an ipconfig log. It works perfectly but I think it's way to large or ineffective. Since I'm only a beginner I left it at this for now, Is there a way for me to improve this? Thanks for all the help!! Regards, Olrik 2008/8/10 Alan Gauld > > "Olrik Lenstra" wrote > > I've been developing a program for a while now (I am still a beginner >> though) and I want to add a progress bar (gauge bar) to my program. >> I am having quite some trouble actually implementing it though. I attached >> the file TSO.pyw which is my current project. >> > > Can you show us what you have tried so far? > > I want to keep it within 1 python file if it's possible. Because I want to >> turn it into a single executable file. >> > > You can use multiple files and still produce an EXE using > py2exe or similar. There is no need to keep it in one file. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 10 15:51:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 14:51:32 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: "Olrik Lenstra" wrote > This is the part I tried to get the Bar in. I actually got it in GUI > wise. > But I had no idea to let it run the moment I clicked "Scan" OK, Normally you have to update the bar values from inside a loop on your Scan method. In practice you probably need to use a timer to relinquish control back to the GUI so that the Guage refreshes itself. In pseudo code: def onScan(self): self.myfile = open('foo.txt') self.count = 0 self.setTimer(0.01, self.processLine) def processLine(self) line = self.myfile.readline() if line: processLine(line) self.count += 1 self.myGauge.setValue(count) self.setTimer(0.01, self.processLine) else: self.myGuage.setValue(0) This also allows the user to use the GUI while the scan is running > Alan, I'm using pyinstaller. is it possible to make several python > files > into a single exe? Yes, it must be since every time you import a module you are using another file. Its quite hard to write any useful application in Python without importing at least one module. Your files are no different to the standard modules like os, sys, time, etc... > If so, Can you direct me to maybe some documentation? (I > might have overlooked it.) Sorry, I've never used pyinstaller but if it can't do this it isn't of much use! > while I'm asking for the bar, can I ask for some advice on the > following bit > of code too? Of course! :-) > ## Define all the private IP ranges that we're not going to filter > in > ## the ipconfig part of the program. > ## From private4 to private19 is actually 1 range. (Needs to be > looked at.) > ##------------------------------------------------------------------------------ > private1 = r"192\.168\.\d+\.\d+" > private2 = r"169\.254\.\d+\.\d+" > private3 = r"10\.\d+\.\d+\.\d+" > ... > private19 = r"172\.31\.\d+\.\d+" Why not put them in a list or tuple called privates? It will save typing and: > lines = file('ipconfig.txt', "r+").readlines() > for i in range(len(lines)): > if re.search("IP\D+ \:", lines[i]): > if not re.search(private1, lines[i]): > if not re.search(private2, lines[i]): > .... > if not re.search(private19, lines[i]): The if not search lines could then be replaced by a loop. This has the added advantage that you can change the list of privates(adding or deleting entries)) without changing this code. lines = file('ipconfig.txt', "r+").readlines() for i in range(len(lines)): if re.search("IP\D+ \:", lines[i]): for p in patterns: if search(p,lines[i]): break else: # equivalent of the end of your chain Another approach would be to compbine all the private IP addresses into a single long regex. You can then do a single search for the pattern. This would be faster but slightly harder to read/debug. Choosing the right data structure is half the battle in writing clean code. If you find yourself writing code that is obviously cumbersome go back and think about whether you can design a better data struvcture. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From o.lenstra at gmail.com Sun Aug 10 16:21:16 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 16:21:16 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: <3c8f6fd70808100721w30cb9ee1of289c478e716dc7d@mail.gmail.com> I'm probably asking for a lot here. But I don't think I understand this fully. This is the part I tried to get the Bar in. I actually got it in GUI wise. >> But I had no idea to let it run the moment I clicked "Scan" >> > > OK, Normally you have to update the bar values from inside a > loop on your Scan method. In practice you probably need to > use a timer to relinquish control back to the GUI so that the > Guage refreshes itself. In pseudo code: > def onScan(self): > self.myfile = open('foo.txt') > self.count = 0 > self.setTimer(0.01, self.processLine) > > def processLine(self) > line = self.myfile.readline() > if line: > processLine(line) > self.count += 1 > self.myGauge.setValue(count) > self.setTimer(0.01, self.processLine) > else: > self.myGuage.setValue(0) > > This also allows the user to use the GUI while the scan is running > Ok. So lets see if I got this right. In the onScan you define self.myfile to open 'foo.txt' One thing I don't get here is what is foo.txt used for? Then you set the count to 0 Then you set the timer to 0.01 with the event processLine? then in the processLine you add 1 to the count with every line that is read? ## Define all the private IP ranges that we're not going to filter in >> ## the ipconfig part of the program. >> ## From private4 to private19 is actually 1 range. (Needs to be looked >> at.) >> >> ##------------------------------------------------------------------------------ >> private1 = r"192\.168\.\d+\.\d+" >> private2 = r"169\.254\.\d+\.\d+" >> private3 = r"10\.\d+\.\d+\.\d+" >> ... >> private19 = r"172\.31\.\d+\.\d+" >> > > Why not put them in a list or tuple called privates? > It will save typing and: > > lines = file('ipconfig.txt', "r+").readlines() >> for i in range(len(lines)): >> if re.search("IP\D+ \:", lines[i]): >> if not re.search(private1, lines[i]): >> if not re.search(private2, lines[i]): >> .... >> if not re.search(private19, lines[i]): >> > > The if not search lines could then be replaced by a loop. > This has the added advantage that you can change the > list of privates(adding or deleting entries)) without > changing this code. > > lines = file('ipconfig.txt', "r+").readlines() > for i in range(len(lines)): > if re.search("IP\D+ \:", lines[i]): > for p in patterns: > if search(p,lines[i]): > break > else: > # equivalent of the end of your chain > > Another approach would be to compbine all the private IP > addresses into a single long regex. You can then do a > single search for the pattern. This would be faster but > slightly harder to read/debug. > I'll try to implement that loop :) Thanks for the help! Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Sun Aug 10 16:26:35 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 10 Aug 2008 10:26:35 -0400 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: On Sun, Aug 10, 2008 at 6:49 AM, Olrik Lenstra wrote: > The program runs fine and works perfectly as the code is right now, But > while I'm asking for the bar, can I ask for some advice on the following bit > of code too? > > <<< > ##------------------------------------------------------------------------------ > ## Define all the private IP ranges that we're not going to filter in > ## the ipconfig part of the program. > ## From private4 to private19 is actually 1 range. (Needs to be looked at.) > ##------------------------------------------------------------------------------ > private1 = r"192\.168\.\d+\.\d+" > private2 = r"169\.254\.\d+\.\d+" > private3 = r"10\.\d+\.\d+\.\d+" > private4 = r"172\.16\.\d+\.\d+" > private5 = r"172\.17\.\d+\.\d+" > private6 = r"172\.18\.\d+\.\d+" > private7 = r"172\.19\.\d+\.\d+" > private8 = r"172\.20\.\d+\.\d+" > private9 = r"172\.21\.\d+\.\d+" > private10 = r"172\.22\.\d+\.\d+" > private11 = r"172\.23\.\d+\.\d+" > private12 = r"172\.24\.\d+\.\d+" > private13 = r"172\.25\.\d+\.\d+" > private14 = r"172\.26\.\d+\.\d+" > private15 = r"172\.27\.\d+\.\d+" > private16 = r"172\.28\.\d+\.\d+" > private17 = r"172\.29\.\d+\.\d+" > private18 = r"172\.30\.\d+\.\d+" > private19 = r"172\.31\.\d+\.\d+" > How about r = re.compile(r"(\d+)\.(\d+)\.\d+\.\d+") m = re.search(line[i]) if m: n1, n2 = map(int,m.groups()) # n1, n2 now have the first two numbers of the IP address Once you have n1, n2, you can check what range the ip is in and act accordingly. Greg From rdm at rcblue.com Sun Aug 10 16:28:33 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 10 Aug 2008 07:28:33 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <489E913D.60507@aon.at> References: <20080809101310.2AE531E4002@bag.python.org> <489E913D.60507@aon.at> Message-ID: <20080810142948.CB5711E4003@bag.python.org> At 11:57 PM 8/9/2008, you wrote: >Dick Moores schrieb: >>Gregor, >> >> >>1. I want the window to open with the right edge 0 pixels from the >>right edge of my screen. >>However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't >>work. I have to do the nearest thing, >>setup(width=.75, height=.915, startx=-1, starty=0). A small thing, >>but what's wrong with perfection. >Hi Dick, >a good observation, but I think this cannot be changed, because of > > >>> -0 == 0 >True OK. I just thought there might be a workaround. Or should be. >in Python >>2. There's a lot I don't understand in >>turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], >>startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"]) >> >>What is '_CFG'? And how should anyone know what it is? >>What is "leftright"? And how to use it? >>What is "topbottom"? And how to use it? >_CFG is an internal dictionary, which contains configuration data. >You can change these >by editing adding or editing the turtle.cfg file (an example is in >the Demo directory). >How to do this you can find here: > >http://docs.python.org/dev/library/turtle.html#how-to-configure-screen-and-turtles > I suppose you'll add a mention of '_CFG' to that? >>3. http://docs.python.org/dev/library/turtle.html#turtle.stamp >> >>"turtle.stamp() >>Stamp a copy of the turtle shape onto the canvas at the current >>turtle position. Return a stamp_id for that stamp, which can be >>used to delete it by calling clearstamp(stamp_id)." >> >>But in your version 1 >>(), the >>turtle is hidden by hideturtle()! What are you stamping? It seems >>the shape, or rectangle. If so, why does the doc say 'turtle'? >there will be stamped the shape of the turtle, that appeared if it >were not hidden. But what get's 'stamped' is not only the turtle, is it. That's what is confusing, IMO. And would it not be a good idea to define 'stamp'? >General remark: you can investigate Python and especially its turtle >module interactively >using IDLE. But note: in the case of graphics (Tkinter and >especially turtle.py) you have to >use the -n switch of IDLE. So the link calling idle must look >something like this: > >/... ../... ../python /... ../.../.../idle.pyw -n > >the dotted parts representig the path according to your system configuration > >If you have done this onceyou can issue function calls on after another and >observe what happens. E. g.: > > >>> from turtle import * > >>> reset() > >>> shape("square") > >>> color("blue", "red") > >>> resizemode("user") # at first no visual effect, but ... > >>> turtlesize(2,3,5) > >>> fd(100) > >>> left(45) > >>> pensize(8) > >>> fd(100) > >>> left(90) > >>> pencolor("green") > >>> fd(100) > >>> turtlesize(1,5) > >>> left(1080) > >>> stamp() >8 > >>> left(45) > >>> ht() > >>> fd(100) > >>> stamp() >9 > >>> left(45) > >>> fd(100) > >>> stamp() >10 > >>> > >... and so on. >If you want to know how some function works and the docs >don't give you a proper clue, simply try out. Ah. Very good. After doing that I understand a lot more now. However, it was of no help with "leftright" or "topbottom" of my question #2. >>4. For my random_rectangles.py program I've started to try out the >>new turtle. (See the current state of random_rectanglesV16_web.py >>at .) The only downside >>I've found is that the new turtle is much faster that the old. I >>want to set the speed so that the outlines of rectangles are drawn >>slowly enough that the user (me at present) can both appreciate the >>colors and have time to check the names of the colors being printed >>in the console window. Using the old turtle, I found that a default >>delay of 1 ((delay(1)) was just right; with the new turtle, setting >>a delay of even 50 affects only the first cycle of rectangles. So I >>don't use delay at all. Setting the slowest speed of 1 (speed(1)) >>is still too fast. How can I slow down the drawing of the rectangles? >I suppose you have some call of reset() or clear() which resets the >delay. So try a >delay call at the beginning of every cycle. You're right! The clear() between cycles was doing that. So now I have speed(spd) at the top of draw_rect(). And now I find that speed(4) and delay(15) work the best for what I want. So those are now the defaults. BTW the latest version is . Now the user can accept all the defaults at once. (See the prompt for this, line 427. Also, the dimensions of the window and of the rectangles are now proportional to the size and resolution of the user's monitor. See new function adjust_for_monitor_size_and_resolution(), line 196, and revised function get_next_rect_params(), lines 207-209. >>5. I've been unable to figure out how to use onclick() >>(). >>I'd like to find a way to pause my script by clicking on the screen >>-- so I could snag an image of what's showing, and then click again >>to restart the drawing of the rectangles. And in addition, being >>able to stop the program with a double click on the screen would be >>very handy. Could you explain how to do these, if in fact they are possible? >This idea for an event driven program affords a bit of different >thinking and a different >program structure. I'll come up with a proposition and an explanation of some >prerequisites in another posting. (I have not got the time to do >that now). Great! Thank you. Dick From o.lenstra at gmail.com Sun Aug 10 16:38:26 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 16:38:26 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> That bit of code doesn't make a lot of sense to me so far. I don't see how that could "X" out a public address. (I do appreciate the help!) Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Sun Aug 10 17:41:23 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 10 Aug 2008 11:41:23 -0400 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> Message-ID: On Sun, Aug 10, 2008 at 10:38 AM, Olrik Lenstra wrote: > That bit of code doesn't make a lot of sense to me so far. > I don't see how that could "X" out a public address. > > (I do appreciate the help!) > > Regards, > Olrik > r = re.compile(r"(\d+)\.(\d+)\.\d+\.\d+") m = re.search(lines[i]) # search returns a match object if m: # the match object will be "None" if there is no match n1, n2 = m.groups() # n1, and n2 contain the strings corresponding to the parts # of the regexp in parentheses above # e.g., n1 == '192' and n2 == '168' n1 = int(n1) n2 = int(n2) # convert them to integers (I used the "map" trick before to do this in one line) # n1, n2 now have the first two numbers of the IP address # Once you have n1, n2, you can check what range the ip is in and act accordingly. # I left this out before, but here's how you might do the check if ( n1 == 10 or (n1 == 192 and n2 == 168) or (n1 == 169 and n2 == 254) or (n1 == 172 and n2 >= 16 and n2 <= 31)): lines[i] = r.sub("xxx.xxx.xxx.xxx",lines[i]) # using sub is a little more compact Check out the python regular expression howto - http://www.amk.ca/python/howto/regex/ Greg From xboxmuncher at gmail.com Sun Aug 10 18:28:16 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 10 Aug 2008 12:28:16 -0400 Subject: [Tutor] Back-end Bittorrent Client in python Message-ID: I want to be able to download bittorrent files with the bittorrent protocol in my python program using only the native libraries in it. All I am interested is being able to download & upload simultanaeously, reading parts that make up the torrent package and being able to choose files/folders to download, when uploading being able to point to other directories and locations where the files reside. (not necessarily in the same hierarchy/architecture of the original torrent package) I don't quite know what to call this behavior that I'm wanting. I would call it a bittorrent class that I can use to download and control the protocol within my python program... A shell? A back-end bittorrent client.. I'd appreciate some pointers on where to get started implementing something like this, and how I can take advantage of a lot of other BT clients that already exist in python. IE: I've read about official BT client, bitornado, ABC client, etc.. but they all seem to be stand-alone clients for users interesting in downloading the torrent packages. I want something that I can implement and manipulate within my own program. -thanks for your time -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 10 19:23:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 18:23:22 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com><3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <3c8f6fd70808100721w30cb9ee1of289c478e716dc7d@mail.gmail.com> Message-ID: "Olrik Lenstra" wrote > I'm probably asking for a lot here. But I don't think I understand > this > fully. Thats OK. >> def onScan(self): >> self.myfile = open('foo.txt') >> self.count = 0 >> self.setTimer(0.01, self.processLine) >> >> def processLine(self) >> line = self.myfile.readline() >> if line: >> processLine(line) >> self.count += 1 >> self.myGauge.setValue(count) >> self.setTimer(0.01, self.processLine) >> else: >> self.myGuage.setValue(0) > Ok. So lets see if I got this right. In the onScan you define > self.myfile to > open 'foo.txt' One thing I don't get here is what is foo.txt used > for? Its the file that you want to scan - assuming there is a file. It could be a list or anything else - I don't actually know from your code what onScan is supposed to do! :-) > Then you set the count to 0 > Then you set the timer to 0.01 with the event processLine? Thats right. The idea is to set up a timer to fire after 1/100 of a second. Then in processLine set up another one after processing each line until the file (or list etc) is scanned. > then in the processLine you add 1 to the count with every line that > is read? Yes and set the Guage value to whatever count is. Then next time the GUI draws itself the new cvalue will appear in the guage. The important bit is that: 1) We use onScan to initialise things not to actually do the processing 2) We create the timer each time we process some data (you could opt to process more than one line - say batches of 10, but the important point is that its only ever a short period of processing. 3) We update the count and then the guage after each batch completes HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nosh3141 at gmail.com Sat Aug 9 17:45:04 2008 From: nosh3141 at gmail.com (Joshua Nikkel) Date: Sat, 9 Aug 2008 11:45:04 -0400 Subject: [Tutor] something is fundamentally wrong... Message-ID: I've pasted the following from my python shell. Please note that the first two lines of code are taken directly from the standard tutorial files under section 3.1.2. Will someone please tell me why something as basic and straightforward as this will not work? Everything else seems to work just fine, but not this. All I need is someway to get the length of a string... please help, nosh Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 ==== No Subprocess ==== >>> s = 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "", line 1, in len(s) TypeError: 'str' object is not callable >>> s 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "", line 1, in len(s) TypeError: 'str' object is not callable >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From federo at email.si Sat Aug 9 17:57:14 2008 From: federo at email.si (Federo) Date: Sat, 09 Aug 2008 17:57:14 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> Message-ID: <20080809155715.F0E698FFFC@www1.email.si> Kent hi I do hope we are now close to the final solution. I have used Firefox plagin TamperData as you suggested and concequently amanded the code. Header Fields are know clear (you can see them in the attached file). There is some problem with Python code: import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() #print(data) #params2 = dict(contentProvider='pinnacor', quoteSymbol='goog', optionChain='goog', countryCode='US', optionRange='NTM', tickerSymbol='goog', ContentType='stockQuote') params2['contentProvider'] = 'pinnacor' params2['quoteSymbol'] = 'goog' params2['optionChain'] = 'goog' params2['countryCode'] = 'US' params2['optionRange'] = 'NTM' params2['tickerSymbol'] = 'goog' params2['contentType'] = 'stockQuote' params2['quote.x'] = 'submitted' f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do', params2) data2 = f.read() f.close() print(data2) Error Message: File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1115, in https_open return self.do_open(httplib.HTTPSConnection, req) File "C:\Python25\lib\urllib2.py", line 1079, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers) File "C:\Python25\lib\httplib.py", line 866, in request self._send_request(method, url, body, headers) File "C:\Python25\lib\httplib.py", line 892, in _send_request self.send(body) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "C:\Python25\lib\httplib.py", line 1108, in send return self._ssl.write(stuff) TypeError: write() argument 1 must be string or read-only buffer, not dict Cheers, Fedo On Fri, 8 Aug 2008 at 13:56:29, Kent Johnson wrote: > On Fri, Aug 8, 2008 at 5:12 AM, Federo wrote: > > Kent hi > > > > I am still unable to enter data into textbox and getting back server reply. > The > > main problem is that I do not understand which fileds / header to observer > > using Firefox Fireburg. Atteched you can see headers I went through. With > red > > font I marked differences among stages. In nider of the headers I didn't > find > > fieldds you included in your workable login code. > > Hi Federo, > > This isn't really a Python question anymore, it is a matter of > figuring out what the server requires. You have to look at the form > data as well as the headers. TamperData is one Firefox pluging that > can do that, I'm sure there are others as well. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_VPR.doc Type: application/octet-stream Size: 146944 bytes Desc: FormManagement_VPR.doc URL: From federo at email.si Sat Aug 9 21:48:41 2008 From: federo at email.si (Federo) Date: Sat, 09 Aug 2008 21:48:41 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> Message-ID: <20080809194842.9A6A08B9F0@www1.email.si> Kent, Bellow is the last code I tried. The code open main page however down not open main page with server reply for symbol GOOG. I include in code everythig in POSTDATA. Other fields seem irelevant. Entire header is attached. Sorry for being persistent but I DO WANT to master this technology! Cheers, Ales import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() #f.close() #print(data) params2 = dict(contentProvider='pinnacor', quoteSymbol='goog', optionChain='goog', countryCode='US', optionRange='NTM', tickerSymbol='goog', ContentType='stockQuote') params2['contentProvider'] = 'pinnacor' #params2['quoteSymbol'] = 'goog' #params2['optionChain'] = 'goog' #params2['countryCode'] = 'US' #params2['optionRange'] = 'NTM' #params2['tickerSymbol'] = 'goog' #params2['contentType'] = 'stockQuote' #params2['quote.x'] = 'submitted' #params2 = 'contentProvider=pinnacor"eSymbol=goog&optionChain=goog&ountryCode=US&opti onRange=NTM&tickerSymbol=goog&contentType=stockQuote"e.x=submitted' params2 = urllib.urlencode(params2) f = opener.open ('https://investor.firstrade.com/firstrade/mainmenu.do', params2) data2 = f.read() f.close() print(data2) On Fri, 8 Aug 2008 at 13:56:29, Kent Johnson wrote: > On Fri, Aug 8, 2008 at 5:12 AM, Federo wrote: > > Kent hi > > > > I am still unable to enter data into textbox and getting back server reply. > The > > main problem is that I do not understand which fileds / header to observer > > using Firefox Fireburg. Atteched you can see headers I went through. With > red > > font I marked differences among stages. In nider of the headers I didn't > find > > fieldds you included in your workable login code. > > Hi Federo, > > This isn't really a Python question anymore, it is a matter of > figuring out what the server requires. You have to look at the form > data as well as the headers. TamperData is one Firefox pluging that > can do that, I'm sure there are others as well. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_VPR.doc Type: application/octet-stream Size: 153088 bytes Desc: FormManagement_VPR.doc URL: From rt8396 at gmail.com Sun Aug 10 00:33:06 2008 From: rt8396 at gmail.com (r t) Date: Sat, 9 Aug 2008 17:33:06 -0500 Subject: [Tutor] running python script Message-ID: currently i have a batch file that is associated with .txt extentions so when i double click on a text file, windows runs the batch file that then sends command line args to MY text editor program..."Texteditor.py", instead of Microsofts *feature rich* Crappad. :-P this works, but the problem is the commad prompt stays open in the background cluttering up my desktop. So, 1. How do i close the command prompt after starting my program??? here is my one line batch script: C:\Python25\python.exe C:\Python25\TextEditor.py %1 2. or how do i do this in a much more elegant way?? i know there is a win32 ShellExecute fuction that will open a file WITHOUT "CMD" but i dont know how to make this work for what i am doing with file associations if there is a better way to do this, i am open to suggestion vista & py2.5 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Aug 10 19:54:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 13:54:41 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: References: Message-ID: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> On Sat, Aug 9, 2008 at 12:28 PM, James wrote: > All, > > I'm having a rather strange problem that I'm hoping someone can shed > some light on. I'm trying to catch a BadStatusLine exception raised by > the httplib library. > The error only happens once every blue moon, but to avoid a crash I > setup a try/catch. > > try: > > catch BadStatusLine: > print "yuck!" > > However, somehow the thread that this code is in still raised a > BadStatusLine exception and the thread stopped cold. How did you import BadStatusLine? One strange gotcha about except statements is that the except clause is not evaluated until an exception is raised, so you can have an invalid name and you won't know it. For example this runs fine, even though foo is not defined: In [1]: try: ...: 1 ...: except foo: ...: pass ...: Out[1]: 1 OTOH if an exception is raised it causes a NameError: In [2]: try: ...: 1/0 ...: except foo: ...: pass ...: --------------------------------------------------------------------------- Traceback (most recent call last) /Users/kent/ in () : name 'foo' is not defined Kent From bgailer at gmail.com Sun Aug 10 19:57:49 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 10 Aug 2008 13:57:49 -0400 Subject: [Tutor] IP matching?. In-Reply-To: References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> Message-ID: <489F2C1D.3010804@gmail.com> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Aug 10 19:56:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 13:56:42 -0400 Subject: [Tutor] importing path question In-Reply-To: References: Message-ID: <1c2a2c590808101056n78ea3e26mca8bf6f3c1f6c837@mail.gmail.com> On Sat, Aug 9, 2008 at 6:03 PM, dave selby wrote: > Hi all, > > I have a main directory 'kmotion2' where python scripts live. They > access a library of scripts in 'kmotion2/core' as 'kmotion2/core' has > a __init__.py file. However I now need to create a new directory > 'utilities' inside 'kmotion2' that also needs to access scripts in > 'core' > > kmotion2 directory > | | > core utilities > > So I need to import up the tree then back down. Is this possible ? Yes, assuming kmotion2 is in your Python path (which it should be to allow importing from core at all) you can just import core.whatever as usual. Kent From kent37 at tds.net Sun Aug 10 20:03:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 14:03:38 -0400 Subject: [Tutor] using generators to mock raw_input for doctest In-Reply-To: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> References: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> Message-ID: <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> On Sun, Aug 10, 2008 at 1:38 AM, wrote: > 2) Is there some better way to enable doctesting of code that uses > raw_input? All I found when googling was the suggestion that in place of: > > def myfunc(): > # code employing raw_input here > > one could write: > > def myfunc(input_meth=raw_input): > # code with raw_input calls replaced with input_meth calls > > but that seems like complicating my code for the non-doctest case. It is not going to make your code more complicated - the client code doesn't change at all and in myfunc you just change your use of raw_input() to input_meth(). If you declare def myfunc(raw_input=raw_input): you don't even have to change the body of myfunc. > class myraw(object): > def __init__(self, values): > self.values = values > self.stream = self.mygen() > def mygen(self): > for i in self.values: > yield i > def readline(self): > return str(self.stream.next()) This is needlessly complex. The values argument must be iterable (or the for loop would break) so you might as well use its iterator instead of making your own: class myraw(object): def __init__(self, values): self.stream = iter(values) def readline(self): return str(self.stream.next()) Kent From bermanrl at embarqmail.com Sun Aug 10 20:04:12 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Sun, 10 Aug 2008 14:04:12 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: References: Message-ID: <489F2D9C.4010002@embarqmail.com> An HTML attachment was scrubbed... URL: From timothy.grant at gmail.com Sun Aug 10 20:21:02 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sun, 10 Aug 2008 11:21:02 -0700 Subject: [Tutor] running python script In-Reply-To: References: Message-ID: On Sat, Aug 9, 2008 at 3:33 PM, r t wrote: > currently i have a batch file that is associated with .txt extentions > so when i double click on a text file, windows runs the batch file that then > sends command line args to MY text editor program..."Texteditor.py", instead > of Microsofts feature rich Crappad. :-P > this works, but the problem is the commad prompt stays open in the > background > cluttering up my desktop. > So, > 1. How do i close the command prompt after starting my program??? > > here is my one line batch script: > C:\Python25\python.exe C:\Python25\TextEditor.py %1 > > 2. or how do i do this in a much more elegant way?? > > i know there is a win32 ShellExecute fuction that will open a file WITHOUT > "CMD" > but i dont know how to make this work for what i am doing with file > associations > if there is a better way to do this, i am open to suggestion > > vista & py2.5 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Have you tried using pythonw instead of python? -- Stand Fast, tjg. [Timothy Grant] From broek at cc.umanitoba.ca Sun Aug 10 21:16:26 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 14:16:26 -0500 Subject: [Tutor] using generators to mock raw_input for doctest In-Reply-To: <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> References: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> Message-ID: <20080810141626.5obl6s14c0sg08o8@webware.cc.umanitoba.ca> ----- Message from kent37 at tds.net --------- Date: Sun, 10 Aug 2008 14:03:38 -0400 From: Kent Johnson Reply-To: Kent Johnson Subject: Re: [Tutor] using generators to mock raw_input for doctest > On Sun, Aug 10, 2008 at 1:38 AM, wrote: > >> 2) Is there some better way to enable doctesting of code that uses >> raw_input? All I found when googling was the suggestion that in place of: >> >> def myfunc(): >> # code employing raw_input here >> >> one could write: >> >> def myfunc(input_meth=raw_input): >> # code with raw_input calls replaced with input_meth calls >> >> but that seems like complicating my code for the non-doctest case. > > It is not going to make your code more complicated - the client code > doesn't change at all and in myfunc you just change your use of > raw_input() to input_meth(). If you declare > def myfunc(raw_input=raw_input): > you don't even have to change the body of myfunc. Thanks for the reply, Kent. I didn't express myself well. What I meant was I didn't quite like the complication of the signature for no gain from the non-testing client's side. I'm thinking not that it would make the code harder to use, but rather a bit harder to figure out how to use---but I may well over-rate the cognitive overhead involved :-) > This is needlessly complex. I suspected as much :-) > The values argument must be iterable (or > the for loop would break) so you might as well use its iterator > instead of making your own: > > class myraw(object): > def __init__(self, values): > self.stream = iter(values) > def readline(self): > return str(self.stream.next()) Thanks again, Brian vdB From broek at cc.umanitoba.ca Sun Aug 10 22:03:20 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 15:03:20 -0500 Subject: [Tutor] puzzling EOFError when mocking raw_input in doctest Message-ID: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> Hi all, I've continued playing about with mocking raw_input in doctests in light of Kent's reply. I've hit an odd thing---if my substitute for raw_input returns '', I get an EOFError. The code below shows the problem. It arises equally if myrawalt is used in the doctest in place of myraw, so I am sure the problem has nothing to do with the use of iter. I can work around the problem in my actual target code---that code, like the toy code below, calls strip() on the results of raw_input, so I can get away with having my raw_input substitute return ' ' in place of ''. But, I cannot figure out why the EOFError comes up. Any thoughts? Thanks and best, Brian vdB class myraw(object): def __init__(self, values): self.stream = iter(values) def readline(self): return str(self.stream.next()) class myrawalt(object): def __init__(self, values): self.values = values self.count = 0 def readline(self): data = str(self.values[self.count]) self.count += 1 return data def double_input(): """>>> import sys >>> sys.stdin = myraw([21,3.1415]) >>> double_input(); double_input() # doctest: +ELLIPSIS 42 6.28300... >>> sys.stdin = myraw([' ',]) >>> double_input() 0 >>> sys.stdin = myraw(['',]) >>> double_input() # Failing test 0 """ val = raw_input().strip() or 0 val = float(val) * 2 val = [val, int(val)][val == int(val)] return val def __test(): import doctest doctest.testmod() if __name__ == "__main__": __test() From alan.gauld at btinternet.com Sun Aug 10 23:30:03 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 22:30:03 +0100 Subject: [Tutor] running python script References: Message-ID: "r t" wrote > this works, but the problem is the commad prompt stays open in the > background cluttering up my desktop. > So, > 1. How do i close the command prompt after starting my program??? You don't. Instead you arrange for it not to open in the first place! The trick is to run the program using pythonw.exe which is associated with files ending .pyw. Thus rename your TextEdit.py to TextEdit.pyw and all should be well! > here is my one line batch script: > C:\Python25\python.exe C:\Python25\TextEditor.py %1 Or in this case substitute pythonw.exe for python.exe But to save trouble when you upgrade python I'd do two things: 1) move your textedit,py file into another folder not under python. 2) rename the file .pyw as above 3) replace the line above with START /B textedit.pyw HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Aug 10 23:58:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 17:58:55 -0400 Subject: [Tutor] IP address parse In-Reply-To: <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> Message-ID: <1c2a2c590808101458g7d186942jbf381e6c50ad8eda@mail.gmail.com> On Sun, Aug 10, 2008 at 1:58 AM, Josh Rosen wrote: >> Since it doesn't look like you're doing anything with the parts of the ip >> besides writing the whole ip to a file, you can eliminate the capturing >> parentheses in your regular expression and replace them with a single pair: >> >> patt = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") There is no need for the outer parentheses either. Kent From xboxmuncher at gmail.com Mon Aug 11 00:09:27 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 10 Aug 2008 18:09:27 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? Message-ID: I want to download a file via HTTP GET protocol (perhaps HTTP POST in the future, whatever method should allow relativly easy changes to be made to use POST later on) I need to send custom headers like in urllib2.urlrequest() I need to be able to monitor the download progress WHILE it downloads like the hook function in urllib I looked into urllib2 and it did everything except allow me to check the progress of the download during the download, it only downloads the file first with urlopen(). I also tried urllib and the reporthook function is great, except I can't send custom headers! I wish I could send a REQ object to the urlretrieve() function in urllib that way I can prepare those custom headers.. :( I was looking at the httplib library, its a little complicated/intimidating to me, maybe it can be done in this? Anyways, i would appreciate if soemone could write me a quick example to do this, or point me to the right library/funcs to do it. I want to be able to do it in native python libraries. -thanks for reading -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtp at nc.rr.com Mon Aug 11 00:16:38 2008 From: jtp at nc.rr.com (James) Date: Sun, 10 Aug 2008 18:16:38 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> References: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> Message-ID: Kent, I'm not importing BadStatusLine. I'm only importing mechanize, which downloads a page repeatedly. From time to time a BadStatusLine exception is raised. I'm unsure how to go about catching it. Thoughts? -j On Sun, Aug 10, 2008 at 1:54 PM, Kent Johnson wrote: > On Sat, Aug 9, 2008 at 12:28 PM, James wrote: >> All, >> >> I'm having a rather strange problem that I'm hoping someone can shed >> some light on. I'm trying to catch a BadStatusLine exception raised by >> the httplib library. >> The error only happens once every blue moon, but to avoid a crash I >> setup a try/catch. >> >> try: >> >> catch BadStatusLine: >> print "yuck!" >> >> However, somehow the thread that this code is in still raised a >> BadStatusLine exception and the thread stopped cold. > > How did you import BadStatusLine? > > One strange gotcha about except statements is that the except clause > is not evaluated until an exception is raised, so you can have an > invalid name and you won't know it. For example this runs fine, even > though foo is not defined: > In [1]: try: > ...: 1 > ...: except foo: > ...: pass > ...: > Out[1]: 1 > > OTOH if an exception is raised it causes a NameError: > In [2]: try: > ...: 1/0 > ...: except foo: > ...: pass > ...: > --------------------------------------------------------------------------- > Traceback (most recent call last) > > /Users/kent/ in () > > : name 'foo' is not defined > > Kent > From kent37 at tds.net Mon Aug 11 00:18:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:18:40 -0400 Subject: [Tutor] puzzling EOFError when mocking raw_input in doctest In-Reply-To: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> References: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> Message-ID: <1c2a2c590808101518p3f7e577drd6a95fff267acc70@mail.gmail.com> On Sun, Aug 10, 2008 at 4:03 PM, wrote: > > Hi all, > > I've continued playing about with mocking raw_input in doctests in light of > Kent's reply. > > I've hit an odd thing---if my substitute for raw_input returns '', I get an > EOFError. The code below shows the problem. It arises equally if myrawalt is > used in the doctest in place of myraw, so I am sure the problem has nothing > to do with the use of iter. I can work around the problem in my actual > target code---that code, like the toy code below, calls strip() on the > results of raw_input, so I can get away with having my raw_input substitute > return ' ' in place of ''. But, I cannot figure out why the EOFError comes > up. Any thoughts? My guess, to verify look at the source for raw_input() or experiment... readline() normally includes the \n in the line it returns. It will only return an empty string on EOF. So the raw_input() is seeing the empty line, interpreting it as EOF, and raising EOFError. My suggestion - in your mock stdin, append a \n to the provided data. Also you might want to change the name, you are replacing sys.stdin, not raw_input(). Kent From kent37 at tds.net Mon Aug 11 00:42:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:42:27 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? In-Reply-To: References: Message-ID: <1c2a2c590808101542r11de76f6h3f2bef4f63b96a5a@mail.gmail.com> On Sun, Aug 10, 2008 at 6:09 PM, xbmuncher wrote: > I want to download a file via HTTP GET protocol (perhaps HTTP POST in the > future, whatever method should allow relativly easy changes to be made to > use POST later on) > I need to send custom headers like in urllib2.urlrequest() > I need to be able to monitor the download progress WHILE it downloads like > the hook function in urllib > > I looked into urllib2 and it did everything except allow me to check the > progress of the download during the download, it only downloads the file > first with urlopen(). I also tried urllib and the reporthook function is > great, except I can't send custom headers! I wish I could send a REQ object > to the urlretrieve() function in urllib that way I can prepare those custom > headers.. :( > > Anyways, i would appreciate if soemone could write me a quick example to do > this, or point me to the right library/funcs to do it. I want to be able to > do it in native python libraries. urllib2.urlopen() doesn't read the data from the remote site, it returns a file-like object with a read() method. You can read the data in chunks and call a reporthook yourself. Take a look at the source to URLopener.retrieve() in urllib.py for some hints. Kent From kent37 at tds.net Mon Aug 11 00:45:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:45:11 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: References: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> Message-ID: <1c2a2c590808101545n6eac5985wf77cef890f9eec9d@mail.gmail.com> On Sun, Aug 10, 2008 at 6:16 PM, James wrote: > Kent, > > I'm not importing BadStatusLine. I'm only importing mechanize, which > downloads a page repeatedly. From time to time a BadStatusLine > exception is raised. I'm unsure how to go about catching it. Try adding from httplib import BadStatusLine to the top of your module. Kent From noshius at gmail.com Mon Aug 11 02:30:10 2008 From: noshius at gmail.com (Joshua Nikkel) Date: Sun, 10 Aug 2008 20:30:10 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: References: <489F2D9C.4010002@embarqmail.com> Message-ID: ah that was it. I had a variable named len earlier. On a restart it was fine. Thanks! On Sun, Aug 10, 2008 at 2:04 PM, Robert Berman wrote: > No. Not so. > > Observe, please: > Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.2.2 ==== No Subprocess ==== > >>> import math > >>> math.sqrt(1054.12) > 32.467214232206615 > >>> s = 'supercalifragilisticexpialidocious' > >>> s > 'supercalifragilisticexpialidocious' > >>> len(s) > 34 > >>> > > Have you by any chance assigned the function len to something else? > Otherwise, it should work really well. If you do help(len) in the shell, wha > dos it tell you. > > Robert > > Joshua Nikkel wrote: > > I've pasted the following from my python shell. Please note that the first > two lines of code are taken directly from the standard tutorial files under > section 3.1.2. Will someone please tell me why something as basic and > straightforward as this will not work? Everything else seems to work just > fine, but not this. All I need is someway to get the length of a string... > > please help, > > nosh > > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.2.2 ==== No Subprocess ==== > >>> s = 'supercalifragilisticexpialidocious' > >>> len(s) > Traceback (most recent call last): > File "", line 1, in > len(s) > TypeError: 'str' object is not callable > >>> s > 'supercalifragilisticexpialidocious' > >>> len(s) > Traceback (most recent call last): > File "", line 1, in > len(s) > TypeError: 'str' object is not callable > >>> > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric at ericabrahamsen.net Mon Aug 11 08:52:07 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 11 Aug 2008 14:52:07 +0800 Subject: [Tutor] requests/responses from urllib2 Message-ID: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> I've got a question about the way urllib2 makes its requests. If I've got a python web framework running behind a web server, and that framework uses urllib2 to make a request to another server, how does that traffic go in and out of my server machine? The python docs say that urllib2 requires the socket library to work, so I assume it's a socket of some sort, but I don't really understand how that socket is addressed, from the point of view of the third-party server that is receiving my urllib2 request, and returning the response. Where does it appear to be coming from? If my web server (lighttpd in this case) is set to listen on a particular port, is there any way that it can 'see' that traffic and interact with it, or is it purely between the python library and the outside world? Thanks for any enlightenment! Eric From alan.gauld at btinternet.com Mon Aug 11 10:49:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Aug 2008 09:49:28 +0100 Subject: [Tutor] requests/responses from urllib2 References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> Message-ID: "Eric Abrahamsen" wrote > that traffic go in and out of my server machine? The python docs say > that urllib2 requires the socket library to work, so I assume it's a > socket of some sort, but I don't really understand how that socket > is addressed, from the point of view of the third-party server that > is receiving my urllib2 request, and returning the response. Virtually all network comms is over sockets. Your web browser uses sockets every time it connects to a web server. Your web server is using sockets to receive those requests. The urllib implementation has to use the Python socket module so there is a dependency but thats just what you'd expect. It has to talk to a socket somehow and if it didn't use the socket library directly it would either use a higher level library that in turn used socket, or else it would have to implement sockets itself at the C level. > it appear to be coming from? If my web server (lighttpd in this > case) is set to listen on a particular port, is there any way that > it can 'see' that traffic and interact with it, or is it purely > between the python library and the outside world? Your web server likely listens on port 80. The urllib will send to port 80 by default. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Aug 11 12:54:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Aug 2008 06:54:40 -0400 Subject: [Tutor] requests/responses from urllib2 In-Reply-To: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> Message-ID: <1c2a2c590808110354k1a879a6dm4777d446ea972994@mail.gmail.com> On Mon, Aug 11, 2008 at 2:52 AM, Eric Abrahamsen wrote: The python docs say that urllib2 requires the > socket library to work, so I assume it's a socket of some sort, but I don't > really understand how that socket is addressed, from the point of view of > the third-party server that is receiving my urllib2 request, and returning > the response. Where does it appear to be coming from? The request comes from your web server, that is what the other server will see. > If my web server > (lighttpd in this case) is set to listen on a particular port, is there any > way that it can 'see' that traffic and interact with it, or is it purely > between the python library and the outside world? I'm not sure if you want to see the traffic coming in from your users, or the traffic from your server to the third-party server. I don't know what kind of interaction you want, either. Most web frameworks have a way to log the requests they receive. There may be a debug mode that includes request and response headers in the log. You could turn on debug mode in httplib, this will give you details about the outgoing traffic. I don't think it will affect the incoming traffic but I'm not certain. See http://personalpages.tds.net/~kent37/kk/00010.html#e10debugging Kent From ssmith46 at zimbra.naz.edu Mon Aug 11 14:14:30 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 08:14:30 -0400 (EDT) Subject: [Tutor] Accessing LDAP Message-ID: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> Any ideas how I can pull a list of domain users from an LDAP server and use it programmatically in a Python web application? Thanks! From dextrous85 at gmail.com Mon Aug 11 14:17:43 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Aug 2008 17:47:43 +0530 Subject: [Tutor] Accessing LDAP In-Reply-To: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> References: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> I think this can be of some help to you http://tgolden.sc.sabren.com/python/active_directory.html On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith wrote: > Any ideas how I can pull a list of domain users from an LDAP server and use > it programmatically in a Python web application? > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rudy.schockaert at gmail.com Mon Aug 11 15:04:50 2008 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Mon, 11 Aug 2008 15:04:50 +0200 Subject: [Tutor] Accessing LDAP In-Reply-To: <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> References: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> Message-ID: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> If by LDAP server you mean Active Directory, then Tim's active_directory module is certainly the way to go. If you want a more generic LDAP approach, you could give python-ldapa try. On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh wrote: > I think this can be of some help to you > http://tgolden.sc.sabren.com/python/active_directory.html > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith wrote: > >> Any ideas how I can pull a list of domain users from an LDAP server and >> use it programmatically in a Python web application? >> >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ssmith46 at zimbra.naz.edu Mon Aug 11 15:13:28 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 09:13:28 -0400 (EDT) Subject: [Tutor] Accessing LDAP In-Reply-To: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> Message-ID: <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> It is indeed an active directory server, but the sysadmin tells me that it is configured to respond to normal ldap queries as well. I tried Tim's module, and it's giving me an "operations error" when I try to use his code snippet to list users... ----- Original Message ----- From: "Rudy Schockaert" To: "vishwajeet singh" Cc: "Steven L Smith" , "tutor" Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York Subject: Re: [Tutor] Accessing LDAP If by LDAP server you mean Active Directory, then Tim's active_directory module is certainly the way to go. If you want a more generic LDAP approach, you could give python-ldapa try. On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh wrote: > I think this can be of some help to you > http://tgolden.sc.sabren.com/python/active_directory.html > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith wrote: > >> Any ideas how I can pull a list of domain users from an LDAP server and >> use it programmatically in a Python web application? >> >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dextrous85 at gmail.com Mon Aug 11 15:15:38 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Aug 2008 18:45:38 +0530 Subject: [Tutor] Accessing LDAP In-Reply-To: <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> References: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> I have used it and it works pretty well for me.Can you show the code snippet you are trying to execute?? On Mon, Aug 11, 2008 at 6:43 PM, Steven L Smith wrote: > It is indeed an active directory server, but the sysadmin tells me that it > is configured to respond to normal ldap queries as well. > > I tried Tim's module, and it's giving me an "operations error" when I try > to use his code snippet to list users... > > > ----- Original Message ----- > From: "Rudy Schockaert" > To: "vishwajeet singh" > Cc: "Steven L Smith" , "tutor" > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > If by LDAP server you mean Active Directory, then Tim's active_directory > module is certainly the way to go. > If you want a more generic LDAP approach, you could give > python-ldapa try. > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh >wrote: > > > I think this can be of some help to you > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith >wrote: > > > >> Any ideas how I can pull a list of domain users from an LDAP server and > >> use it programmatically in a Python web application? > >> > >> Thanks! > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Cheers, > > Vishwajeet > > http://www.singhvishwajeet.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ssmith46 at zimbra.naz.edu Mon Aug 11 15:21:02 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 09:21:02 -0400 (EDT) Subject: [Tutor] Accessing LDAP In-Reply-To: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> Message-ID: <923693530.6467611218460862676.JavaMail.root@nazoli1.optimizedlearn.com> <% import active_directory for person in active_directory.search ("objectCategory='Person'"): Response.Write(person.displayName) %> Results in... Python ActiveX Scripting Engine error '80020009' Traceback (most recent call last): File "