From wescpy at gmail.com Sat Apr 1 01:26:57 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 15:26:57 -0800 Subject: [Tutor] removing file from zip archive. In-Reply-To: <200603291442.13643.keosophon@khmeros.info> References: <200603291442.13643.keosophon@khmeros.info> Message-ID: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> > How can we remove one file inside of a zip archive? > > import zipfile > ziparchive = zipfile.ZipFile('test.odt', 'r') > xmldata = ziparchive.read('content.xml') > ziparchive.close <--- ADD "( )" HERE TOO Sophon, You can remove any number of files from a ZIP file, but it has to be processed manually by you. When you read() a file from a ZIP archive, you actually have all the data with you, i.e. xmldata. All you have to do is to open another file to write it out to disk, i.e., f = open('content.xml', 'w') f.write(xmldata) f.close() hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From broek at cc.umanitoba.ca Sat Apr 1 02:32:16 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Fri, 31 Mar 2006 18:32:16 -0600 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables Message-ID: <442DCA10.9020104@cc.umanitoba.ca> Hi all, I've been too busy with life to do much Python of late. So, I am a bit rusty. :-( I've got some code that does what it needs to but I think I might be overlooking a much smoother way to get what I need. The code takes a list of strings and returns a list of dictionaries, where each dictionary uses the strings from the list as keys and booleans as values. The dictionary list contains a dictionary exhibiting each possible combination of booleans over the keys, where these combinations are listed in a systematic way. This code works: def tva_dict_maker(atoms): tvas = [] val = False for k in range(2**len(atoms)): tvas.append(dict()) for i in range(len(atoms)): key = atoms[i] for j in range(2**len(atoms)): if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: val = not val tvas[j][key]=val return tvas The output I desire is easier to see with a bit of processing (to impose order on the dicts). So, def display_tvas(tvas): for i in tvas: for j in sorted(i): print "%s:%s\t" %(j, i[j]), print Then, the output is like so: >>> atoms = ["a","b","c"] >>> tvas = tva_dict_maker(atoms) >>> display_tvas(tvas) a:True b:True c:True a:True b:True c:False a:True b:False c:True a:True b:False c:False a:False b:True c:True a:False b:True c:False a:False b:False c:True a:False b:False c:False >>> As desired :-) But, I can't shake the feeling I'm doing this in a harder than necessary way :-| [This is in the context of writing a program to generate truth-tables for sentential logic, so that I can easily create answered exercises for a critical thinking course I've been teaching. (As it is for a Philosophy class, the truth-values are listed in the opposite order than in a CompSci context.)] Any suggestions would be welcome. Best to all, Brian vdB From srini_iyyer_bio at yahoo.com Sat Apr 1 02:39:30 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 31 Mar 2006 16:39:30 -0800 (PST) Subject: [Tutor] Python + PostGreSQL In-Reply-To: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> Message-ID: <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> Dear group, I want to connect python to postgresql. My python dist. is 2.4.2 My postgres: 8.1.2 My system: Linux Enterprise Linux, Intel Xeon, 4GB RAM. I tried to install pygresql: version: 3.8, it failed throwing exception : Exception: pg_config tool is not available. I gave another try on google and Postgres site and found Pypgsql, PoPy and psycopg1. I am confused now. Which is the most promising connection between Python and Postgres now. Aplogies, if this question is inappropriate on this forum. Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ilias at lazaridis.com Sat Apr 1 02:48:19 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 01 Apr 2006 03:48:19 +0300 Subject: [Tutor] Looking for Constructs to Remove Redundant Code In-Reply-To: <442D2FCF.3000704@tds.net> References: <442D2FCF.3000704@tds.net> Message-ID: Kent Johnson wrote: ... Thank you for your comments. I realize that my request was not very clear. I make a 2nd attemp, more simplified: I have this python code: class Car(BaseClass) : manufacturer = stringFactory() model = stringFactory() modelYear = integerFactory() def __str__(self): return '%s %s %s' % (self.modelYear, self.manufacturer, self.model) def stringFactory(self) s = String() # creates a string object #... # does several things return s # returns the string object - and would like to see it e.g. this way: class Car(BaseClass): manufacturer = stringFactory(2) model = stringFactory(3) modelYear = integerFactory(1) def stringFactory(self, position) s = String() # creates a string object ... # does several things # creates somehow the __str__ functionality... return s # returns the string object - hope this is now more clear. . -- http://lazaridis.com From bill at celestial.net Sat Apr 1 03:01:57 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 31 Mar 2006 17:01:57 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> References: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> Message-ID: <20060401010157.GA59681@alexis.mi.celestial.com> On Fri, Mar 31, 2006, Srinivas Iyyer wrote: >Dear group, > >I want to connect python to postgresql. >My python dist. is 2.4.2 >My postgres: 8.1.2 >My system: Linux Enterprise Linux, Intel Xeon, 4GB >RAM. > >I tried to install pygresql: version: 3.8, it failed >throwing exception : Exception: pg_config tool is not >available. > >I gave another try on google and Postgres site and >found Pypgsql, PoPy and psycopg1. I think that psycopg is generally considered the preferred package. I have been using it with several systems including Zope, and sqlobject. So far I haven't tried psycopg2. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 A child can go only so far in life without potty training. It is not mere coincidence that six of the last seven presidents were potty trained, not to mention nearly half of the nation's state legislators. -- Dave Barry From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 04:27:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 31 Mar 2006 18:27:02 -0800 (PST) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442DCA10.9020104@cc.umanitoba.ca> Message-ID: > Then, the output is like so: > > >>> atoms = ["a","b","c"] > >>> tvas = tva_dict_maker(atoms) > >>> display_tvas(tvas) > a:True b:True c:True > a:True b:True c:False > a:True b:False c:True > a:True b:False c:False > a:False b:True c:True > a:False b:True c:False > a:False b:False c:True > a:False b:False c:False Hi Brian, We might be able to take advantage of the recursive nature of this problem. I'll sketch out the idea and try to fight the temptation to write it out in full. *grin* If you haven't encountered recursion before, please shout out and ask for more details. When we look above, we're looking at the solution for tva_dict_maker-ing the list ['a', 'b', 'c']. But let's imagine what tva_dict_maker() looks like for a slightly smaller problem, for ['b', 'c']: b:True c:True b:True c:False b:False c:True b:False c:False If we look at this and use our pattern-matching abilities, we might say that the solution for ['b', 'c'] really looks like half of the solution for ['a', 'b', 'c'] That is, to get: tva_dict_maker(['a', 'b', 'c']) all we really need are the results of tva_dict_maker(['b', 'c']). We can then twiddle two copies of the samller solution to make 'a' either True or False, combine them together, and we've got it. Recursive approachs have two parts to them, a "base" case and an "inductive" case: 1. Figure out solutions for really simple examples. For example, in the problem above, We know that something like: tva_dict_maker(['c']) has a very simple solution, since we're only dealing with a list of one element. ([{'c': True}, {'c' : False}]) 2. And for larger problems, let's figure out a way to break the problem into something smaller. We might be able to take the solution of the smaller problem and make it scale up. So a recursive approach will typically fit some template like this: ## Pseduocode ######################################################### def recursive_problem(some_problem): if some_problem is really obviously simple: return the obviously simple answer to some_problem otherwise: smaller_problem = some way of making some_problem slightly smaller. On lists, usually attack list[1:]. small_solution = recursive_problem(smaller_problem) full_solution = twiddle small_solution somehow to make it solve some_problem return full_solution ####################################################################### If you have more questions, please feel free to ask! From wescpy at gmail.com Sat Apr 1 04:38:58 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 18:38:58 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401010157.GA59681@alexis.mi.celestial.com> References: <78b3a9580603311526p3b24a28fgef835cd123917af5@mail.gmail.com> <20060401003930.76138.qmail@web38109.mail.mud.yahoo.com> <20060401010157.GA59681@alexis.mi.celestial.com> Message-ID: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> > >I tried to install pygresql: version: 3.8, it failed > >throwing exception : Exception: pg_config tool is not > >available. > > > >I gave another try on google and Postgres site and > >found Pypgsql, PoPy and psycopg1. > > I think that psycopg is generally considered the preferred > package. as bill has suggested, it does appear that psycopg is the preferred from what i've seen. popy is outdated and (i believe) merged with PyGreSQL which is the one that PostgreSQL has in their tree as it's been around the longest. however rather than just talking about another adapter because your current one doesn't work, i'm more curious as to why you are having problems with PyGreSQL. i've never had a problem with it... how did you do your installation? (yes, we're lucky that PostgreSQL has multiple adapters available as other RDBMSs don't have these options.) --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From srini_iyyer_bio at yahoo.com Sat Apr 1 05:00:43 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 31 Mar 2006 19:00:43 -0800 (PST) Subject: [Tutor] Python + PostGreSQL In-Reply-To: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> Message-ID: <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> Thanks Bill, and wesley, Psycopg worked for me. I had to use setup.cfg . Regular setup.py did not work. AFA, pygresql I did used this some 2 years back. However, the install was pretty easy due to proper redhat rpm updates. I felt more comfortable with PyGreSQL. I liked it somehow. tar -xvf PyGreSQL.tar cd PyGreSQL-3.8/ sudo python setup.py build sh: pg_config: command not found Traceback (most recent call last): File "setup.py", line 77, in ? pg_include_dir = pg_config('includedir') File "setup.py", line 47, in pg_config raise Exception, "pg_config tool is not available." Exception: pg_config tool is not available. My pg_config is in : /usr/local/pgsql/bin/pg_config thanks Srini --- w chun wrote: > > >I tried to install pygresql: version: 3.8, it > failed > > >throwing exception : Exception: pg_config tool is > not > > >available. > > > > > >I gave another try on google and Postgres site > and > > >found Pypgsql, PoPy and psycopg1. > > > > I think that psycopg is generally considered the > preferred > > package. > > > as bill has suggested, it does appear that psycopg > is the preferred > from what i've seen. popy is outdated and (i > believe) merged with > PyGreSQL which is the one that PostgreSQL has in > their tree as it's > been around the longest. > > however rather than just talking about another > adapter because your > current one doesn't work, i'm more curious as to why > you are having > problems with PyGreSQL. i've never had a problem > with it... how did > you do your installation? (yes, we're lucky that > PostgreSQL has > multiple adapters available as other RDBMSs don't > have these options.) > > --wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - > "Core Python Programming", Prentice Hall, > (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From wescpy at gmail.com Sat Apr 1 08:03:33 2006 From: wescpy at gmail.com (w chun) Date: Fri, 31 Mar 2006 22:03:33 -0800 Subject: [Tutor] Python + PostGreSQL In-Reply-To: <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> References: <78b3a9580603311838l5affda5fub6c634a2ae4e678@mail.gmail.com> <20060401030043.77787.qmail@web38106.mail.mud.yahoo.com> Message-ID: <78b3a9580603312203r1829906fq57bc3ec1d177f512@mail.gmail.com> hi srini, i don't know what your system configuration was like for the installation, but from what i saw in your post (below), it just seems like /usr/local/pgsql/bin was not in your path since it looks like "sh" could not find the pg_config command, not Python (which choked afterwards). anyway, if you got psycopg working for you, then just leave it. :-) cheers, -wesley > sh: pg_config: command not found > : > My pg_config is in : /usr/local/pgsql/bin/pg_config From sanelson at gmail.com Sat Apr 1 09:10:10 2006 From: sanelson at gmail.com (Steve Nelson) Date: Sat, 1 Apr 2006 08:10:10 +0100 Subject: [Tutor] Inverted Index Algorithm In-Reply-To: <442DA17E.9020800@tds.net> References: <442DA17E.9020800@tds.net> Message-ID: On 3/31/06, Kent Johnson wrote: > Steve Nelson wrote: > > Do you need help getting started with Python or with inverted indexing > in particular? Sorry - I should have been clearer. I'm reasonably confident in Python, and if I get stuck with that side of things will ask for help. I was more struggling with the Inverted Indexing bit. I think I want to write a program that will do text searches on documents, to learn about and compare the two approaches I've heard of - Inverted Indexing and Signature Files. SO I think I am asking for help at the logical / implementation level. My understanding so far goes something like this: Suppose I have three documents - as a trivial but fun example, we could make them song lyrics. The simplest thing that could possibly work would be to supply one or two words and literally scan every word in the song for a match. This has two disadvantages - firstly it is likely to produce false positives, and secondly it is likely to be very inefficient. The next step would be to introduce an index. I think again, the simplest thing that could possibly work would be a literal index of every word and every document in which it appears. This would save processing time, but wouldn't be very intelligent. This is where I think the inverted indexing comes in. As I understand it we can now produce an index of key words, with document name and location in document for each key word. This makes the search more involved, and more intelligent. Finally we could have some logic that did some set analysis to return only results that make sense. Am I thinking along the right lines, or have I misunderstood? Could someone perhaps come up with some code snippets that make clearer examples? I also need to think about signature files, but I havn't really any idea how these work. Thanks all! S. > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From aguffabuff at hotmail.com Sat Apr 1 09:18:34 2006 From: aguffabuff at hotmail.com (Ars) Date: Fri, 31 Mar 2006 23:18:34 -0800 Subject: [Tutor] Capture keyboard input even without python in focus Message-ID: What commands could capture input from the keyboard (and the mouse while we're at it) even when the running python program isn't the program in focus? Sorta like a keylogger, though that's not my goal (wouldn't be very secret with a python console running anyways lol.) -Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060331/82cce315/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 09:42:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 31 Mar 2006 23:42:57 -0800 (PST) Subject: [Tutor] Inverted Index Algorithm In-Reply-To: Message-ID: > The next step would be to introduce an index. I think again, the > simplest thing that could possibly work would be a literal index of > every word and every document in which it appears. This would save > processing time, but wouldn't be very intelligent. Yes, that's right, that's the idea of an inverted index. > This is where I think the inverted indexing comes in. As I understand > it we can now produce an index of key words, with document name and > location in document for each key word. This makes the search more > involved, and more intelligent. Finally we could have some logic that > did some set analysis to return only results that make sense. Location information would help allow you to do things like phrase or proximity matching. Another thing that might help is term frequency (tf). You might want to check out documentation about Lucene: http://lucene.apache.org/java/docs/index.html as they're the premier open source search library. They have a presentation that gives a good overview of the techniques used in a fast search engine: http://lucene.sourceforge.net/talks/inktomi/ If you want to reuse their engine, the OSAF folks have even written Python bindings to the library: http://pylucene.osafoundation.org/ From francois.schnell at gmail.com Sat Apr 1 10:31:04 2006 From: francois.schnell at gmail.com (francois schnell) Date: Sat, 1 Apr 2006 10:31:04 +0200 Subject: [Tutor] Capture keyboard input even without python in focus In-Reply-To: References: Message-ID: <13a83ca10604010031o4eb19716jc869288c763abb9e@mail.gmail.com> Hello, On windows OS I'm using the nice pyhook module: "The pyHook library wraps the low-level mouse and keyboard hooks in the Windows Hooking API for use in Python applications. " See tutorial here: http://www.cs.unc.edu/~parente/tech/tr08.shtml francois On 01/04/06, Ars wrote: > > What commands could capture input from the keyboard (and the mouse while > we're at it) even when the running python program isn't the program in > focus? Sorta like a keylogger, though that's not my goal (wouldn't be very > secret with a python console running anyways lol.) > > -Jack > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060401/ad66735a/attachment.htm From kent37 at tds.net Sat Apr 1 13:12:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 06:12:02 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> Message-ID: <442E6002.7010207@tds.net> jonasmg at softhome.net wrote: > Kent Johnson writes: > > >>jonasmg at softhome.net wrote: >> >> >>>List of states: >>>http://en.wikipedia.org/wiki/U.S._state >>> >>>: soup = BeautifulSoup(html) >>>: # Get the second table (list of states). >>>: table = soup.first('table').findNext('table') >>>: print table >>> >>>... >>> >>>WY >>>Wyo. >>>Wyoming >>>Cheyenne >>>Cheyenne >>>>>src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin >>>g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" >>>longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> >>> >>> >>> >>>Of each row (tr), I want to get the cells (td): 1,3,4 >>>(postal,state,capital). But cells 3 and 4 have anchors. >> >>So dig into the cells and get the data from the anchor. >> >>cells = row('td') >>cells[0].string >>cells[2]('a').string >>cells[3]('a').string >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > > for row in table('tr'): > cells = row('td') > print cells[0] > > IndexError: list index out of range It works for me: In [1]: from BeautifulSoup import BeautifulSoup as bs In [2]: soup=bs(''' ...: WY ...: Wyo. ...: Wyoming ...: Cheyenne ...: Cheyenne ...: ...: ...: ''' ...: ...: ...: ...: ) In [18]: rows=soup('tr') In [19]: rows Out[19]: [ WY Wyo. Wyoming Cheyenne Cheyenne Wyoming, Cheyenne, Cheyenne, It may be that Python isn't the best solution for you here. Are there >extended-precision libraries for Visual Basic? Alas, none that I know of that are reliable and not incredibly expensive, been looking for years, plus Im hooped because I have to work with VB 4.0 instead of 6 +, guh.... >Regards, >Matt Matt..... good name, why do I always seem to get along with Matts, you people keep popping up in my life and its always a blast! Best regards, D

_______________________________________________________________
Get the FREE email that has everyone talking at
http://www.mail2world.com
Unlimited Email Storage – POP3 – Calendar – SMS – Translator – Much More!
-------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060331/7ba4da51/attachment.html From jonasmg at softhome.net Sat Apr 1 14:22:23 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 05:22:23 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442E6002.7010207@tds.net> References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> Message-ID: Kent Johnson writes: > jonasmg at softhome.net wrote: >> Kent Johnson writes: >> >> >>>jonasmg at softhome.net wrote: >>> >>> >>>>List of states: >>>>http://en.wikipedia.org/wiki/U.S._state >>>> >>>>: soup = BeautifulSoup(html) >>>>: # Get the second table (list of states). >>>>: table = soup.first('table').findNext('table') >>>>: print table >>>> >>>>... >>>> >>>>WY >>>>Wyo. >>>>Wyoming >>>>Cheyenne >>>>Cheyenne >>>>>>>src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin >>>>g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" >>>>longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> >>>> >>>> >>>> >>>>Of each row (tr), I want to get the cells (td): 1,3,4 >>>>(postal,state,capital). But cells 3 and 4 have anchors. >>> >>>So dig into the cells and get the data from the anchor. >>> >>>cells = row('td') >>>cells[0].string >>>cells[2]('a').string >>>cells[3]('a').string >>> >>>Kent >>> >>>_______________________________________________ >>>Tutor maillist - Tutor at python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >> for row in table('tr'): >> cells = row('td') >> print cells[0] >> >> IndexError: list index out of range > > It works for me: > > > In [1]: from BeautifulSoup import BeautifulSoup as bs > > In [2]: soup=bs(''' > ...: WY > ...: Wyo. > ...: Wyoming > ...: Cheyenne > ...: Cheyenne > ...: title=""> ...: > src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyomin > ...: g.svg/45px-Flag_of_Wyoming.svg.png" width="45" alt="" height="30" > ...: longdesc="/wiki/Image:Flag_of_Wyoming.svg" /> > ...: > ...: ''' > ...: > ...: > ...: > ...: ) > > In [18]: rows=soup('tr') > > In [19]: rows > Out[19]: > [ > WY > Wyo. > Wyoming > Cheyenne > Cheyenne > title=""> longdesc="/wiki/Image:Flag_ > ] > > In [21]: cells=rows[0]('td') > > In [22]: cells > Out[22]: > [WY, > Wyo., > Wyoming, > Cheyenne, > Cheyenne, > title=""> longdesc="/wiki/Image:Flag_ > > In [23]: cells[0].string > Out[23]: 'WY' > > In [24]: cells[2].a.string > Out[24]: 'Wyoming' > > In [25]: cells[3].a.string > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Yes, ok. But so, it is only possible get data from a row (rows[0]) cells=rows[0]('td') And I want get data from all rows. I have trying with several 'for' setences but i can not. From kent37 at tds.net Sat Apr 1 14:50:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 07:50:53 -0500 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> Message-ID: <442E772D.9020409@tds.net> jonasmg at softhome.net wrote: > Yes, ok. But so, it is only possible get data from a row (rows[0]) > > cells=rows[0]('td') > > And I want get data from all rows. I have trying with several 'for' setences > but i can not. Can you show us what you tried? Have you read a Python tutorial? It seems like some of the things you are struggling with might be addressed in general Python material. Kent From kent37 at tds.net Sat Apr 1 14:56:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 07:56:23 -0500 Subject: [Tutor] Python, VB math simple problem In-Reply-To: <0db901c65545$92b249a0$70cb010a@mail2world.com> References: <0db901c65545$92b249a0$70cb010a@mail2world.com> Message-ID: <442E7877.8080904@tds.net> Mr X wrote: > > > Hi looking for help with what should be a fairly simple Python problem, > relating to VB inter-operability. > Got a great response from a fellow named Matt at help at python.org, > pointed me in some good directions - some areas, concerns still foggy > on, the below thread is included.... any feedback on this simple dilemma > would be very appreciated. You can use py2exe to make an executable from a python program. Or the VB program could invoke a command line like "python prog.py data.txt" without needing to use py2exe. You can also write COM servers in Python. Kent > > Thanks, > > D > > thread follows below; > > ------------------------------------ > > To: help at python.org > Subject: Problem with Python math functions and VB > Date: 3/30/2006 9:39:28 PM > Download Message Display Headers Printer Friendly > Previous | Next > > Wondering if you might either know how to solve the following. > > I've a background in Visual Basic, and am using an old version, 4.0, it > compiles to a smaller executable which I prefer. I find myself in an odd > situation, needing a very simple yet powerful capability of Python for a > VB app > Im working on. > > Simply, a large 300 digit number is divided by a smaller number ranging > from 1 to 3 digits. I.e; > > This large 300 digit number is generated as a string from the VB app, > and I want to input this somehow > from the VB app directly to Python for simple math operations. > > Where; x = 300 digit number, y = divisor ( say '37') > > > x / 37 > > I want to divide x by y but I want the remainder of this division to at > least 3 or 4 decimal places, so my Python script at the command line; > > x %y /y. = z > > So now I want to take the resultant, the full number plus its remainder, > and I want to round this number up > to the next highest number and divide it by the same constant; > > z rounded up to next highest number (never the lowest) > > so > > z /y = z Long > > Remove the 'L' at the end, round up the last digit of z = Z > > Then; > > Z %y /y. = a > > Then I want the last five digits of z (not Z) and a truncated at the > end, so the last digit before > the decimal point and the four digits past the decimal point printed to > a text file. > > I want to be able to open the text file with the VB app and use this > data as inputs. > ========== > > Ok, so here is my dilemma, I know VERY litle about Python and a fair bit > about VB. > > Ideally, I'd love to be able to simply have some extremely small > executable that just accepts inputs > does the calculations above and then spits out the outputs. If it were > possible to write some > simple lines of math code in Python and then compile these scripts in > Python to a Windows > compatible executable,that would be fantastic. > > If I could simply have my VB app, 'call' the name of the tiny Python > executable, and then the Python executable > just automatically looked for a named text file (created by the VB app) > and extracted the 300 digit number from this, then performed the calcs, > then spit this data out as a new text file name it created, which I > could then use the VB app to open and read from, THAT would be ideal. > > However, I don't know if Python can compile scripts to an exe? If it can > how could I find out how to do this? > > If it doesn't, how could I get VB to directly pass commands to the > Python command line and then automatically > extract the outputs? Shelling out from VB to Python would be tough to > the command line I think, since the Python command line uses the 'Edit / > Mark, Paste' approach to inserting, copy inputs, outputs and this would > be virtually untenable, as far as I can tell to automate in a VB shell > out routine. > > So basically, how the heck can I access Pythons ability to perform > simple calculations on very large numbers, easily, from within VB 4.0 ? > There must be a way, it seems like such a simple think to do, especially > since the actual math operations are so simple, straight forward, and > would never change..... > > Any ideas? > > > > ------ > Matthew, thanks for your response. > > <-----Original Message-----> > >From: Matthew Dixon Cowles > >Sent: 3/31/2006 9:41:18 AM > >To: durango at mail2world.com > >Cc: help at python.org > >Subject: Re: [Python-Help] Problem with Python math functions and VB > > >I'm sure that there's a way to do that, but I'm not familiar with > >Visual Basic and I don't know what inter-process communication > >facilities it offers. > > Is there a person or group you might direct me to that has worked with this > inter-process communication between VB and Python? > > >I don't think that Python is going to be able to do that for you out > >of the box. Hundreds of digits of floating-point precision is a lot. > > Could you explain that a bit more, sorry Im not sure what you mean > by 'out of the box' ? If I run the Python command line screen in windows > and manually type out a very large number, say 180 digits; where 'X' = > very large number; > > X %37 /37. > > returns what Im after, value wise..... but of course I don't want to do > this manually each time > for every dividend. > > >You might find that one of the Python modules that let you use an > >extended-precision library would do what you want. GMPY is one: > > >http://gmpy.sourceforge.net/ > > Hey, thats interesting, wonder if these modules can be operated on with > VB..... > > >> So now I want to take the resultant, the full number plus its > >> remainder, and I want to round this number up > >> to the next highest number and divide it by the same constant; > > > >That's easy enough. > > > >> I want to be able to open the text file with the VB app and use this > >> data as inputs. > > > >Python can write to a file without any trouble, so it that form of > >inter-process communication suits you, you shouldn't have much > >trouble. I assume that Visual Basic has an easy way to start a > >program and supply it with arguments, so you could have your Python > >program get its inputs from sys.argv. > > What is sys.argv ? Thats really good news. In fact, all I really need > for the moment is > a python executable that; > > ================ > PYTHON ALGORITHM ABSTRACT > > a) opens a text file > b) reads a string from the file, which is a very large number > c) performs simple arithmetic operations; > > X %37 /37. = y (four digit remainder after decimal point) > X /37 = w (quotient as long, the resulting output is stored as a > variable, the 'L' suffix tagged on the end of this resultant then gets > removed. > then the last digit in the quotient resultant string is increased in > value by one, rounded upwards = 'Z' > > then > > Z %37 /37. = a > > then, y and a are printed to a text file with hard returns between them. > Thats it, thats all I need to do. > =================== > >Alas, it's not going to be extremely small. There isn't a compiler > >from Python to machine code. Py2exe will bundle a Python program, > >with everything that it needs to run, into a single executable > >archive. But the archive isn't small. Py2exe is at: > > > >http://www.py2exe.org/ > > the most important thing is the functionality, I'll sacrifice size if I > have to. My guess is this should work based on your comments, because > perhaps all I really have to do is have VB dump out the value of the > Very large number, `180 to 300 digits or so', to a text file, which then > becomes the input data for the Python executable, and then if I simply > call the name of the Python executable from VB as an instance, > then the Python App runs, spits out the data as a new text file, then > the VB app goes and opens the new text file and reads in the values, > and voila! There it is. I'm pretty sure I can call the Python app from > VB....... the alternative to all this would be to try and feed Python > scripts > directly to Python from VB, which I have NO idea how to do or where to > begin.... and am guessing would be much more messy... > > I haven't programmed in Python, how would the "PYTHON ALGORITHM > ABSTRACT" I describe above look like, code wise? > Is this fairly easy for you to describe? > > >It may be that Python isn't the best solution for you here. Are there > >extended-precision libraries for Visual Basic? > > Alas, none that I know of that are reliable and not incredibly > expensive, been looking for years, plus Im hooped because I have to work > with VB 4.0 instead of 6 +, guh.... > > >Regards, > >Matt > > Matt..... good name, why do I always seem to get along with Matts, you > people keep popping up in my life and its always a blast! > > Best regards, > > D > > _______________________________________________________________ > Get the FREE email that has everyone talking at http://www.mail2world.com > Unlimited Email Storage ? POP3 ? Calendar ? SMS ? Translator ? Much More! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat Apr 1 19:06:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 1 Apr 2006 18:06:43 +0100 Subject: [Tutor] i need help please read (fwd) References: <015d01c64e7d$d0d31210$0b01a8c0@xp> <4ce40aaa0603241927n3aba0f68wd018216f9f750995@mail.gmail.com> Message-ID: <000f01c655ae$a6d5ae90$0b01a8c0@xp> Tom, I'm still struggling, but based on what Danny Yoo deduced I'll assume you are talking anbout a dialog box or window of some sort rather than drawing a graphical box? > ok ill tell you want im doing i want to make a box using python that if > you > put the box over a number on the computer screen it pops up inside the box Do you mean a bit like the magnifier applet that ships with Windows? It magnifies whatever is underneath it on the main screen? If so thats a really tough task. It is possible in Python but it requires an in-depth knowledge of how Windows works - much more than I have! > and the number can be altered in the box and however you alter it on the > box > it turns into that or show what you altered in place of the number you put > it over get what im saying And modifying the number underneath is much much harder again. It might not even be possible! You can alter it in your own program but to make that take effect on the underlying application would require that you find out what application was diswplaying the number and then find a way to write to that application. These are very deep and difficult programming tasks! Its theoretically possible in Python, but its very difficult. Even in C++ it would be a real challenge. Alan G. Just back from a week's vacation in Spain. From jonasmg at softhome.net Sat Apr 1 19:39:21 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 10:39:21 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: <442E772D.9020409@tds.net> References: <442D4E38.9050508@tds.net> <442D54DD.3070605@tds.net> <442D5B05.5020607@tds.net> <442D608E.9080102@tds.net> <442E6002.7010207@tds.net> <442E772D.9020409@tds.net> Message-ID: Kent Johnson writes: > jonasmg at softhome.net wrote: >> Yes, ok. But so, it is only possible get data from a row (rows[0]) >> >> cells=rows[0]('td') >> >> And I want get data from all rows. I have trying with several 'for' setences >> but i can not. > > Can you show us what you tried? > > Have you read a Python tutorial? It seems like some of the things you > are struggling with might be addressed in general Python material. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You consider a thing about me. If I ask something it is because I cannot find the solution. I do not it by whim. Yes, I have read tutorials about python, and I have looked for this problem in this mail list using a web searcher as alltheweb, and I have even looked for in the google groups about python. * for rows in table('tr'): print rows('td') it fails when i'm going to get data of each cell using: for rows in table('tr'): print rows('td')[0] * for rows in table('tr'): for cell in rows('td'): print cell The same, using print cell[0] From nospamformeSVP at gmail.com Sat Apr 1 21:25:47 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 14:25:47 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses Message-ID: Hi: I am trying to use Doctest and am having trouble using the ellipsis feature when trying to match an object reference. Here is the code: def add_change_listener(self, listener): ''' Returns list of listeners just for testing. >>> def mock_listener(): ... pass >>> model = Model() >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS [] ''' self.listeners.append(listener) return self.listeners This is what I get back: Trying: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expecting: [] ********************************************************************** File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, in __main__.Model.add_change_listener Failed example: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expected: [] Got: [] As far as I can tell from the Doctest documentation this test should have passed. Any help on what I am doing wrong would be much appreciated. Thanks, Don. From kent37 at tds.net Sat Apr 1 21:51:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 14:51:33 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: Message-ID: <442ED9C5.8070007@tds.net> Don Taylor wrote: > Hi: > > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. What version of Python are you using? The ELLIPSIS comment was added in Python 2.4. Kent > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ... pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ********************************************************************** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] > > As far as I can tell from the Doctest documentation this test should > have passed. > > Any help on what I am doing wrong would be much appreciated. > > Thanks, > > Don. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ukc802591034 at btconnect.com Sat Apr 1 22:32:25 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 21:32:25 +0100 Subject: [Tutor] Python tutor References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: "Noufal Ibrahim" wrote in message news:26346.203.145.176.76.1143532255.squirrel at members.hcoop.net... > Greetings all, Greetings, > the reader learns stuff). Another example that comes to mind is the > tcltutor program to learn TCL. It contains an instruction window, a > code window and an output window. The user is told something, they try > it and the output is visible. I personally used it when I was learning > TCL. The tcltutor is fabulous and I've often toyed with the idea of trying to build a Pythonic version. I particularly like the way you can toggle from newbie view to expert view and get the same feature described in friendly English prose through to the bare man pages. > The python tutorial is great and probably all one needs to learn the > language but I think a more interactive program to teach it might be I tried at one stage producing JavaScripted versions of the code in my tutor where you could step through the code with the active line being highlighted in colour - like a debugger. But after struggling for ages to get one short example to work it seemed too much like hard work! > Do you all think it'll be a worthwhile project? I think it would be a great project. The other one in similar vein is to do a demo program of the Tkinter (and the Tix widgets too) similar to the Tcl/Tk demo program. Again I've had it on my list of 'things to do' for several years now! Alan G. (Back from a weeks vacation in sunny Spain! :-) From dyoo at hkn.eecs.berkeley.edu Sat Apr 1 22:37:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Apr 2006 12:37:41 -0800 (PST) Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: Message-ID: > > Have you read a Python tutorial? It seems like some of the things you > > are struggling with might be addressed in general Python material. > > > You consider a thing about me. If I ask something it is because I cannot > find the solution. I do not it by whim. Hello Jonas, Yes, but don't take Kent's question as a personal insult --- he's asking because it looks like you're having trouble interpreting error messages or considering border cases. If you're doing HTML parsing, there's an unspoken assumption that you've already mastered basic programming. After reading the questions you're asking, I agree with Kent; you're struggling with things that you should have already covered in tutorials. Out of curiosity, what tutorials have you looked at? Give us links, and we'll take a look and evaluate them for accuracy. Some Python tutorials are good, but some of them out there are quite bad too. The ones linked from: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers and: http://wiki.python.org/moin/BeginnersGuide/Programmers should be ok. > * for rows in table('tr'): print rows('td') > > it fails when i'm going to get data of each cell using: > > for rows in table('tr'): print rows('td')[0] Just to clarify: when you say it "fails", please try to be more specific. What exactly does Python report as the error? I see that you mention the error message here: http://mail.python.org/pipermail/tutor/2006-March/046103.html But are you looking at the error message and trying to understand what it's saying? It says that the cell doesn't have a zeroth element. And this is probably true! I wouldn't disbelieve the computer on this one. *grin* TD elements probably won't have nested sub-elements. But they may have a 'string' attribute, though, which is what Kent's example used to pull the text out of the TD. But your reply to his message doesn't look like it even responds to Kent's example. It is unclear to us why you're not reading or understanding his example, and just going off and doing something else. If you don't understand a reply, try asking a question about it: we'll be happy to elaborate. Try not to go off so quickly and ignore responses: it gives the impression that you don't care enough to read through things. Anyway, the program snippet above makes assumptions, so let's get those out of the way. Concretely: for rows in table('tr'): print rows('td')[0] makes an assumption that is not necessarely true: * It assumes that each row has a td element. Do you understand the border case here? In particular: * What if you hit a TR table row that does not have any TD columns? >From viewing the wiki web page you gave as an example, I can see several TR's in the page's content that do not have TD's, but only TH's. I'm not certain what BeautifulSoup will do in this situtation --- I suspect that it'll return None --- but in any case, your code has to account for this possibility. From singingxduck at gmail.com Sat Apr 1 23:04:29 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 01 Apr 2006 16:04:29 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442DCA10.9020104@cc.umanitoba.ca> References: <442DCA10.9020104@cc.umanitoba.ca> Message-ID: <442EEADD.7040705@gmail.com> Brian van den Broek wrote: >Hi all, > >I've been too busy with life to do much Python of late. So, I am a bit >rusty. :-( > >I've got some code that does what it needs to but I think I might be >overlooking a much smoother way to get what I need. > >The code takes a list of strings and returns a list of dictionaries, >where each dictionary uses the strings from the list as keys and >booleans as values. The dictionary list contains a dictionary >exhibiting each possible combination of booleans over the keys, where >these combinations are listed in a systematic way. > >This code works: > >def tva_dict_maker(atoms): > > tvas = [] > val = False > > for k in range(2**len(atoms)): > tvas.append(dict()) > > for i in range(len(atoms)): > key = atoms[i] > > for j in range(2**len(atoms)): > if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: > val = not val > tvas[j][key]=val > > return tvas > >The output I desire is easier to see with a bit of processing (to >impose order on the dicts). So, > >def display_tvas(tvas): > for i in tvas: > for j in sorted(i): > print "%s:%s\t" %(j, i[j]), > print > >Then, the output is like so: > > >>> atoms = ["a","b","c"] > >>> tvas = tva_dict_maker(atoms) > >>> display_tvas(tvas) >a:True b:True c:True >a:True b:True c:False >a:True b:False c:True >a:True b:False c:False >a:False b:True c:True >a:False b:True c:False >a:False b:False c:True >a:False b:False c:False > >>> > >As desired :-) > >But, I can't shake the feeling I'm doing this in a harder than >necessary way :-| > >[This is in the context of writing a program to generate truth-tables >for sentential logic, so that I can easily create answered exercises >for a critical thinking course I've been teaching. (As it is for a >Philosophy class, the truth-values are listed in the opposite order >than in a CompSci context.)] > >Any suggestions would be welcome. > >Best to all, > >Brian vdB >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > What this shouts immediately to me, at least, is binary numbers and bool(). Just use your favorite binary conversion recipe, and count down from int(len(atoms)*"1",2), converting as you go. And then you take the boolean value of each digit of the binary number. If you need help, let me know as I've completed a working model. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From nospamformeSVP at gmail.com Sat Apr 1 23:12:33 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:12:33 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: <442ED9C5.8070007@tds.net> References: <442ED9C5.8070007@tds.net> Message-ID: <442EECC1.8040801@gmail.com> Kent Johnson wrote: > Don Taylor wrote: > >>Hi: >> >>I am trying to use Doctest and am having trouble using the ellipsis >>feature when trying to match an object reference. > > > What version of Python are you using? The ELLIPSIS comment was added in > Python 2.4. > I am using 2.4.2 Don. From ukc802591034 at btconnect.com Sat Apr 1 23:28:44 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 22:28:44 +0100 Subject: [Tutor] Apple Remote "Mouse" References: <20060331042331.75343.qmail@web50405.mail.yahoo.com> Message-ID: "Johnston Jiaa" wrote in message > I recently bought a Macbook Pro from Apple. I'm jealous already... > As it comes with a remote, I thought it would be great to use it as > a mouse when not in Front Row. ... > Is there any way to manipulate the cursor position on the screen using > Python? This is really about programming Cocoa more than it is about Python. You need to look at how you would do this in Objective C first then translate that to Python using the Cocoa wrappers for MacPython. It should all be feasible but I'd start looking on the Apple development sites first - have you checked the fantastic programmer's pages on the Apple site at: http://developer.apple.com/ If you haven't already done so sogn up to the developers email list. Not only do you get advance news of developments in Apple land but they post new articles and how-tos every week or so. Also worth keeping an eye on is O'Reilly's MacDevCenter http://www.macdevcenter.com/ And finally Stepwise's Vermont recipes are great: http://www.stepwise.com/ Look in particular at the starting Cocoa and Articles links. For your purpose you will need to create mouse events and then post them to the applications event queue using the postEvent method. There are several factory methods available for creating events. Warning: This is not a trivial task and will involve some fairly deep reading about the Apple event model and the mouse event definitions in particular. But it is doable. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nospamformeSVP at gmail.com Sat Apr 1 23:33:45 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:33:45 -0500 Subject: [Tutor] Python tutor In-Reply-To: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: Noufal Ibrahim wrote: > Greetings all, > Are there any programs for python that offer an "interactive" tutorial? > Something on the lines of the builtin emacs tutorial (which is While it is not really what you had in mind, I have just discovered the Python Challenge - and it is a lot of fun. http://www.pythonchallenge.com/ Don. From ukc802591034 at btconnect.com Sat Apr 1 23:30:49 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Sat, 1 Apr 2006 22:30:49 +0100 Subject: [Tutor] how to get the content of an XML elements. References: <200603311906.26110.keosophon@khmeros.info> Message-ID: "Keo Sophon" wrote in message news:200603311906.26110.keosophon at khmeros.info... > Is there anyway to get the content of an XML elements. I am using xml.dom. For true XML I think ElemTree (by Fred Lundh?) is the best approach. Try a Google search. Kent uses it as I recall. Alan G. From kent37 at tds.net Sat Apr 1 23:47:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Apr 2006 16:47:06 -0500 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: References: <200603311906.26110.keosophon@khmeros.info> Message-ID: <442EF4DA.4050304@tds.net> Alan Gauld wrote: > "Keo Sophon" wrote in message > news:200603311906.26110.keosophon at khmeros.info... > > >>Is there anyway to get the content of an XML elements. I am using xml.dom. > > > For true XML I think ElemTree (by Fred Lundh?) is the best approach. > Try a Google search. Yes, it's ElementTree though. Keo, what do you mean, "get the content of an XML elements"? Kent From jonasmg at softhome.net Sat Apr 1 23:51:36 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 14:51:36 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: Danny Yoo writes: > > >> > Have you read a Python tutorial? It seems like some of the things you >> > are struggling with might be addressed in general Python material. >> >> >> You consider a thing about me. If I ask something it is because I cannot >> find the solution. I do not it by whim. > > Hello Jonas, > > Yes, but don't take Kent's question as a personal insult --- he's asking > because it looks like you're having trouble interpreting error messages or > considering border cases. > Sorry Kent if my answer was very rude. I very was tired to try many things without no good result. > Anyway, the program snippet above makes assumptions, so let's get those > out of the way. Concretely: > > for rows in table('tr'): > print rows('td')[0] > > makes an assumption that is not necessarely true: > > * It assumes that each row has a td element. > > Do you understand the border case here? In particular: > > * What if you hit a TR table row that does not have any TD columns? > Danny, you give me the idea. The problem is that the first row has TH columns (not TD). So: for row in table('tr'): if row('td'): print row('td')[0].string From nospamformeSVP at gmail.com Sat Apr 1 23:51:37 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 16:51:37 -0500 Subject: [Tutor] Python tutor In-Reply-To: References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: Alan Gauld wrote: > > I tried at one stage producing JavaScripted versions of the code in my > tutor where you could step through the code with the active line being > highlighted in colour - like a debugger. But after struggling for ages to > get > one short example to work it seemed too much like hard work! > I found this site the other day and I thought that it would not be too difficult to generalize this technique into a simple tool for authoring tutorials. http://www.jorendorff.com/toys/ Don. From jonasmg at softhome.net Sun Apr 2 00:14:14 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sat, 01 Apr 2006 15:14:14 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: And the solution to get the state and capital columns (where there are anchors): for row in table('tr'): for cell in row.fetch('a')[0:2]: print cell.string From alan.gauld at freenet.co.uk Sun Apr 2 00:49:16 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 1 Apr 2006 23:49:16 +0100 Subject: [Tutor] Python tutor References: <26346.203.145.176.76.1143532255.squirrel@members.hcoop.net> Message-ID: <013001c655de$81750b70$0b01a8c0@xp> >> I tried at one stage producing JavaScripted versions of the code in my > > I found this site the other day and I thought that it would not be too > difficult to generalize this technique into a simple tool for authoring > tutorials. > > http://www.jorendorff.com/toys/ Yes, this is similar to something else I tried which was a collapsing editor style presentation where you could collapse or expand functions. The problem was that I found it difficult to get a version that worked properly on all browsers and the amount of code to get it universal was too much for me to tolerate in a web page! (I'm a minimalist when it comes to HTML!) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tim.peters at gmail.com Sun Apr 2 01:12:04 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 1 Apr 2006 18:12:04 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: Message-ID: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> [Don Taylor] > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ... pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ********************************************************************** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] That "should work", provided there aren't differences in whitespace that are invisible to us in this medium. For example, if, in your source file, there's actually a (one or more) trailing space on your line of expected output, then it would _not_ match the actual output. Try adding +REPORT_NDIFF to your #doctest options; that will point out all differences (including whitespace). From artificiallystupid at yahoo.com Sun Apr 2 01:13:55 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Sat, 1 Apr 2006 15:13:55 -0800 (PST) Subject: [Tutor] Apple Remote "Mouse" Message-ID: <20060401231355.36011.qmail@web50409.mail.yahoo.com> Hey Alan, I'm fairly new to programming and this is my first Apple computer. It arrives on Monday, I've been waiting for ages. Amazon took forever shipping it out. Anyway, this will ultimately be a true learning experience -- I'll tell you how it turns out! Many thanks for giving me these pointers, I'll check out all the sites and be immersed in all these Apple pages the next couple of weeks or so. Johnston Jiaa (artificiallystupid at yahoo.com) --------------------------------- Blab-away for as little as 1?/min. Make PC-to-Phone Calls using Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060401/a7732018/attachment.htm From nospamformeSVP at gmail.com Sun Apr 2 01:30:07 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Sat, 01 Apr 2006 18:30:07 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> References: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> Message-ID: Tim Peters wrote: > That "should work", provided there aren't differences in whitespace > that are invisible to us in this medium. For example, if, in your > source file, there's actually a (one or more) trailing space on your > line of expected output, then it would _not_ match the actual output. > Try adding +REPORT_NDIFF to your #doctest options; that will point out > all differences (including whitespace). Oh, thank you! Yes, there was a trailing whitespace. And yes I did read the manual that warned about this but I guess it did not register deep enough into my reptile brain (you know, the Python brain). I will try not to do this again (and I probably won't). Don. From tim.peters at gmail.com Sun Apr 2 01:42:29 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 1 Apr 2006 18:42:29 -0500 Subject: [Tutor] Doctest, object references and the use of ellipses In-Reply-To: References: <1f7befae0604011512m4d169e3ft3ca776ef352b50df@mail.gmail.com> Message-ID: <1f7befae0604011542j615906a8wa5904635bfd0840@mail.gmail.com> [Tim Peters] >> That "should work", provided there aren't differences in whitespace >> that are invisible to us in this medium. For example, if, in your >> source file, there's actually a (one or more) trailing space on your >> line of expected output, then it would _not_ match the actual output. >> Try adding +REPORT_NDIFF to your #doctest options; that will point out >> all differences (including whitespace). [Don Taylor] > Oh, thank you! Cool -- glad it worked! > Yes, there was a trailing whitespace. And yes I did read the manual > that warned about this but I guess it did not register deep enough into > my reptile brain (you know, the Python brain). > > I will try not to do this again (and I probably won't). I'll share a secret :-) I work on Python development, and a few times per week I run this from the root of a Python checkout (this is on Windows, BTW): python \Python24\Tools\Scripts\reindent.py -r . reindent.py is in your distribution too. It ensures (by rewriting files as needed) that all .py files reachable from "." conform to core Python's whitespace standards, which includes things like 4-space indentation, no hard tab characters, and no trailing whitespace on any lines. All the .py files in a distribution are automatically kept free of "whitespace surprises" this way. You're allowed to run that on your code too ;-) From dyoo at hkn.eecs.berkeley.edu Sun Apr 2 03:54:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Apr 2006 17:54:37 -0800 (PST) Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: Message-ID: > And the solution to get the state and capital columns (where there are > anchors): > > for row in table('tr'): > for cell in row.fetch('a')[0:2]: > print cell.string Hi Jonas, That's good to hear! So does everything work for you then? From jonasmg at softhome.net Sun Apr 2 10:46:35 2006 From: jonasmg at softhome.net (jonasmg at softhome.net) Date: Sun, 02 Apr 2006 01:46:35 -0700 Subject: [Tutor] BeautifulSoup - getting cells without new line characters In-Reply-To: References: Message-ID: Danny Yoo writes: > > >> And the solution to get the state and capital columns (where there are >> anchors): >> >> for row in table('tr'): >> for cell in row.fetch('a')[0:2]: >> print cell.string > > Hi Jonas, > > That's good to hear! So does everything work for you then? > Now yes, this problem has been resolved. Thanks! From k.r.fry at durham.ac.uk Mon Apr 3 13:36:12 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 12:36:12 +0100 Subject: [Tutor] oserror [errno 20] Message-ID: <443108AC.2000205@durham.ac.uk> Hi, I am new to this list, and also to Python. I am trying to get Python to loop through the directory DATADIR which contains the data I want to read. I get an error: "oserror [errno 20] : Not a directory: "Katiescint.py" The section of code is shown below: for subdir in os.listdir(DATADIR): #loop through list of strings file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits file and reads summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the summation results file for writing to spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the spot-by-spot file for writing to output='' print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' I would be very grateful if anyone could help me. Thanks! From ewald.ertl at hartter.com Mon Apr 3 15:11:55 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 03 Apr 2006 15:11:55 +0200 Subject: [Tutor] oserror [errno 20] In-Reply-To: <443108AC.2000205@durham.ac.uk> References: <443108AC.2000205@durham.ac.uk> Message-ID: <44311F1B.7000501@hartter.com> Hi, k r fry wrote: > Hi, I am new to this list, and also to Python. > I am trying to get Python to loop through the directory DATADIR which > contains the data I want to read. I get an error: "oserror [errno 20] > : Not a directory: "Katiescint.py" > > The section of code is shown below: > > for subdir in os.listdir(DATADIR): #loop through list of os.listdir() lists the content of the directory referenced by DATADIR. If regular files are in this directory, these are also listed. You have to check, if subdir is really a directory before using this any further. > strings > > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens > flux.fits file and reads > > summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the > summation results file for writing to > > spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the > spot-by-spot file for writing to > > output='' > print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' > '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' > > I would be very grateful if anyone could help me. Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > HTH Ewald From janos.juhasz at VELUX.com Mon Apr 3 17:14:16 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 3 Apr 2006 17:14:16 +0200 Subject: [Tutor] defined() In-Reply-To: Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060403/5058fac0/attachment.html From tim.golden at viacom-outdoor.co.uk Mon Apr 3 17:23:12 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 3 Apr 2006 16:23:12 +0100 Subject: [Tutor] defined() Message-ID: [J?nos Juh?sz] | I can't find the defined() function in python, so I used | | 'variable name' in dir() | | for check if the variable defined. | | >>> name = 'Joe' | >>> if 'name' in dir(): | ... print name | ... I'm not entirely sure where you'd want to use this, but probably the most Pythonic way of doing this would be: name = "Joe" try: name except NameError: print "name not defined" else: print "name defined" I suspect that your idea of variable definition doesn't quite match Python's concept. In short, it's impossible to "declare" a variable in Python without binding it to *something*. ie a variable is always a binding to an object, not a hole waiting to be filled. You could, if you wanted, initialise name to None (or some other sentinel value) and then check against that, either explicitly: if name is None: print "name unitialised" or by taking advantage of the fact that several empty objects in Python are considered False: if not Name: print "name unitialised" Hope that helps more than it confuses. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From stvsmth at gmail.com Mon Apr 3 17:26:37 2006 From: stvsmth at gmail.com (stv) Date: Mon, 3 Apr 2006 11:26:37 -0400 Subject: [Tutor] List methods/comps Best Practices Message-ID: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> I just thumped my head against the wall for a few hours on something, and I was wondering if it's just my green-ness in Python, or if I'm doing something unsavory. I had several list comprehensions that I was mucking with; these lists are working on a simple subclass of the built-in list object. They looked liked this: filelist = getFilesToAdd() filelist2 = getFilesToDel() adds = MyList('foo') dels = MyList('bar') [adds.add_changes('foo', path) for path in filelist] [dels.add_changes('bar', path) for path in filelist2] # return all changes, deletes first return dels.extend(adds) Since extend returns None, I ran into a lot of not-iterable errors when calling this code. So I fixed this with dels.extend(adds) return dels And all is good, although it took way more head scratching than typing . (In writing this, I now vaguely remember one of my tutorials warning me about something ... maybe this was that? :) So my question is this: Is this just one of those things that I learn the hard way in Pthon & that's it, or am I doing something weird? I shoulda figured this out when I was debugging the method in the interpreter and my original list comprehensions returned [adds.add_changes('foo', path) for path in filelist] >>> [None, None, None] as each call to add_changes returned no value. Alas, I'm not that smart. Is it bad form to not have an "assignment" for the list comps? From khp at pflaesterer.de Mon Apr 3 18:20:06 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Mon, 03 Apr 2006 18:20:06 +0200 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> (stv's message of "Mon, 3 Apr 2006 11:26:37 -0400") References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: On 3 Apr 2006, stvsmth at gmail.com wrote: > I had several list comprehensions that I was mucking with; these lists > are working on a simple subclass of the built-in list object. They > looked liked this: > > filelist = getFilesToAdd() > filelist2 = getFilesToDel() > > adds = MyList('foo') > dels = MyList('bar') > > [adds.add_changes('foo', path) for path in filelist] > [dels.add_changes('bar', path) for path in filelist2] > > # return all changes, deletes first > return dels.extend(adds) > > Since extend returns None, I ran into a lot of not-iterable errors > when calling this code. So I fixed this with > > dels.extend(adds) > return dels > > And all is good, although it took way more head scratching than typing > . (In writing this, I now vaguely remember one of my tutorials warning > me about something ... maybe this was that? :) > > So my question is this: Is this just one of those things that I learn > the hard way in Pthon & that's it, or am I doing something weird? I > shoulda figured this out when I was debugging the method in the > interpreter and my original list comprehensions returned > > [adds.add_changes('foo', path) for path in filelist] > >>> [None, None, None] > > as each call to add_changes returned no value. Alas, I'm not that > smart. Is it bad form to not have an "assignment" for the list comps? In short: IMO yes it's not good practice; the list comprehension is used to create a list. If you don't need the list write a loop. So don't write: [adds.add_changes('foo', path) for path in filelist] but: for path in filelist: adds.add_changes('foo', path) Or show us more explicitly what you want to achieve, sice you don't tell us what add_changes() does. Karl -- Please do *not* send copies of replies to me. I read the list From ukc802591034 at btconnect.com Mon Apr 3 19:07:26 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 3 Apr 2006 18:07:26 +0100 Subject: [Tutor] defined() References: Message-ID: > I can't find the defined() function in python, so I used >'variable name' in dir() > Is it really missing, or I am just so simple ? It is really missing, just as it is for most programming languages. Which language(s) do you know that has such a feature? And why do you consider it so useful that you expect to find it in Python? The main place where I could see such a thing being useful would be in dynamically loaded code but then the usual approach is to load a dictionary and an 'in' check suffices. I'm interested in what use you would make of such a thing? -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ukc802591034 at btconnect.com Mon Apr 3 19:57:33 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 3 Apr 2006 18:57:33 +0100 Subject: [Tutor] oserror [errno 20] References: <443108AC.2000205@durham.ac.uk> Message-ID: "k r fry" wrote in message news:443108AC.2000205 at durham.ac.uk... > Hi, I am new to this list, and also to Python. > I am trying to get Python to loop through the directory DATADIR which > contains the data I want to read. I get an error: "oserror [errno 20] > : Not a directory: "Katiescint.py" That tells you that the code is finding a file called Katiescint.py in DATADIR and that youy are trying to treat it as a directory when it clearly isn't. But it's better to send the whole stacktrace error message in future since that tells us *where* the problem lies as well as what it is! > for subdir in os.listdir(DATADIR): #loop through list of listdir lists files as well as directories. > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') > #opens flux.fits file and reads I'll need to take your word for that. I assume FITS is a module? and Read is a function within that module? All caps normally indicates a constant in Python - its only a convention but a pretty common one. And functions usually start in lowercase (and classes in uppercase) but again thats a convention and less rigorously followed. Also 'file' is a function (actually an alias for open() ) so using it as a variable name could cause confusion. > summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the > spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the And here is where you use the file as a directory and cause the error. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From victor at grupocdm.com Mon Apr 3 17:40:59 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 03 Apr 2006 10:40:59 -0500 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> References: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> Message-ID: <1144078859.20791.4.camel@elrond> On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote: > Aha! John wrote: > > "Are you sure you haven't mistakenly assigned something other than a > dict to D or D['d'] ?" > > Thanks for the tip! Yup that was it (and apologies for not reporting > the problem more precisely). I hadn't initialized the nested > dictionary before trying to assign to it. (I think Perl doesn't > require initialization of dictionaries prior to assignment, which in > this case, would be a nice thing...) > > >>> D['c']['a'] = 1 #ooops > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 'c' > >>> D['c'] = {} > >>> D['c']['a'] = 1 > >>> D > {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}} > You can check if the dictionary key exists prior to assigning to it: >>> if not D.has_key('c'): ... D['c'] = {} >>> D['c']['a'] = 1 From dyoo at hkn.eecs.berkeley.edu Mon Apr 3 20:39:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Apr 2006 11:39:56 -0700 (PDT) Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: <1144078859.20791.4.camel@elrond> Message-ID: > You can check if the dictionary key exists prior to assigning to it: > > >>> if not D.has_key('c'): > ... D['c'] = {} > >>> D['c']['a'] = 1 Hi Victor, Another approach is to use the badly-named "setdefault()" method which is a close analogue to Perl's "autovivification" feature: ###### >>> D = {} >>> D.setdefault('c', {})['a'] = 1 >>> D {'c': {'a': 1}} ###### Good luck! From kent37 at tds.net Mon Apr 3 20:57:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Apr 2006 14:57:07 -0400 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: <44317003.8060007@tds.net> stv wrote: > # return all changes, deletes first > return dels.extend(adds) > > Since extend returns None, I ran into a lot of not-iterable errors > when calling this code. So I fixed this with > > dels.extend(adds) > return dels > > And all is good, although it took way more head scratching than typing > . (In writing this, I now vaguely remember one of my tutorials warning > me about something ... maybe this was that? :) > > So my question is this: Is this just one of those things that I learn > the hard way in Pthon & that's it, or am I doing something weird? In general, mutating methods return None. For example list.append(), list.sort(), list.extend() all return None. This is an intentional design choice in Python. The idea is it keeps you from mistakenly mutating an object. Kent From alan.gauld at freenet.co.uk Mon Apr 3 21:38:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 3 Apr 2006 20:38:08 +0100 Subject: [Tutor] Bigrams and nested dictionaries References: <6FD8FE0A-2A38-4611-A207-5743FF863C5A@columbus.rr.com> <1144078859.20791.4.camel@elrond> Message-ID: <005301c65756$22f91130$0b01a8c0@xp> > On Wed, 2006-03-29 at 00:15 -0500, Michael Broe wrote: > You can check if the dictionary key exists prior to assigning to it: > >>>> if not D.has_key('c'): > ... D['c'] = {} >>>> D['c']['a'] = 1 And since 2.4? if 'c' in D: ... Alan G. From victor at grupocdm.com Tue Apr 4 00:08:00 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Mon, 03 Apr 2006 17:08:00 -0500 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <1144102080.20791.8.camel@elrond> On Mon, 2006-04-03 at 11:39 -0700, Danny Yoo wrote: > > You can check if the dictionary key exists prior to assigning to it: > > > > >>> if not D.has_key('c'): > > ... D['c'] = {} > > >>> D['c']['a'] = 1 > > > Hi Victor, > > Another approach is to use the badly-named "setdefault()" method which is > a close analogue to Perl's "autovivification" feature: > > ###### > >>> D = {} > >>> D.setdefault('c', {})['a'] = 1 > >>> D > {'c': {'a': 1}} > ###### > > Good luck! > Thanks to both Danny and Alan. Great tips. Victor From stvsmth at gmail.com Tue Apr 4 00:19:59 2006 From: stvsmth at gmail.com (stv) Date: Mon, 3 Apr 2006 18:19:59 -0400 Subject: [Tutor] List methods/comps Best Practices In-Reply-To: References: <9493d0340604030826q4aa24faatc176d8d205382d95@mail.gmail.com> Message-ID: <9493d0340604031519i1621185u2c6bdb4c5d7b881a@mail.gmail.com> > So don't write: > [adds.add_changes('foo', path) for path in filelist] > but: > for path in filelist: adds.add_changes('foo', path) Excellent point; new toy, got carrid away :) I feel silly on that one. And now that I've made the return list.extend(foo) mistake, I'll surely neve- ... er, wait a long time before I make that mistake again. Thanks folks. On 4/3/06, Karl Pfl?sterer wrote: From hugonz-lists at h-lab.net Tue Apr 4 01:00:14 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 03 Apr 2006 17:00:14 -0600 Subject: [Tutor] defined() In-Reply-To: References: Message-ID: <4431A8FE.7060100@h-lab.net> Alan Gauld wrote: > Which language(s) do you know that has such a feature? > And why do you consider it so useful that you expect to find > it in Python? I'm not the original poster, but being a perlhead before, I can say it exists in Perl. It is very often used too. I used to miss it at first, but normally I now do the right thing semantically. Counting on the variable being defined or not is simply another bit of information. Assigning a value for that case is much cleaner. It is not used for black magic in Perl, AFAIK. Just normal testing. Hugo From bgailer at alum.rpi.edu Tue Apr 4 03:10:34 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 03 Apr 2006 18:10:34 -0700 Subject: [Tutor] defined() In-Reply-To: <4431A8FE.7060100@h-lab.net> References: <4431A8FE.7060100@h-lab.net> Message-ID: <4431C78A.8010702@alum.rpi.edu> Hugo Gonz?lez Monteverde wrote: > Alan Gauld wrote: > > >> Which language(s) do you know that has such a feature? >> And why do you consider it so useful that you expect to find >> it in Python? >> > > I'm not the original poster, but being a perlhead before, I can say it > exists in Perl. It is very often used too. > And you can "roll your own" in Python: def defined(name): return name in globals() > I used to miss it at first, but normally I now do the right thing > semantically. Counting on the variable being defined or not is simply > another bit of information. Assigning a value for that case is much cleaner. > > It is not used for black magic in Perl, AFAIK. Just normal testing. > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From tim at johnsons-web.com Tue Apr 4 03:10:05 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 17:10:05 -0800 Subject: [Tutor] defined() In-Reply-To: References: Message-ID: <20060404011005.GJ13866@johnsons-web.com> * Alan Gauld [060403 09:10]: > > > I can't find the defined() function in python, so I used > >'variable name' in dir() > > > Is it really missing, or I am just so simple ? > > It is really missing, just as it is for most programming languages. > Which language(s) do you know that has such a feature? > And why do you consider it so useful that you expect to find > it in Python? In rebol, there is a predicate called value? Sample console session below: >> test: [a 1 b 2 c 3] == [one 1 two 2 three 3] >> value? test/1 == false >> value? test/2 == true == [a 1 b 2 c 3] >> test/a == 1 Don't as much about lisp as I do rebol and python, but lisp has symbols, which don't necessarily have values. > The main place where I could see such a thing being useful > would be in dynamically loaded code but then the usual > approach is to load a dictionary and an 'in' check suffices. > Rebol doesn't have dictionaries (it should IMHO), you could also use value? after importing a module to check if some word existed in the module namespace. Kind of like hasattr() > I'm interested in what use you would make of such a thing? My business partner is a perl programmer. He uses defined() a lot, I think, I've seen it in his code.... I use value? a lot in rebol. I like python's in operator. Very handy tim -- Tim Johnson http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Tue Apr 4 04:06:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Apr 2006 19:06:28 -0700 (PDT) Subject: [Tutor] defined() In-Reply-To: <20060404011005.GJ13866@johnsons-web.com> Message-ID: > > I'm interested in what use you would make of such a thing? > My business partner is a perl programmer. He uses defined() a lot, I > think, I've seen it in his code.... Hello! The common idiom in Perl, I think, is to at least declare the variable, even if one doesn't give an initial value, like this: ############################################# ## Perl pseudocode ## use strict; my $name; ## do things here that should initialize name if (! defined($name)) { # handle degenerate case here } ############################################# But this is very different than: ############################################# ## Perl pseudocode that doesn't use strict ## do things here that should initialize name if (! defined($name)) { # handle degenerate case here } ############################################# Now, if your business partner doesn't have the line 'use strict' in their code, then give them a good kick and tell them to use it! It's criminal for a professonal Perl programmer not to "use strict", and I feel almost foolish about bringing this up. But it has to be said, just in case. *grin* In Python, the first assignment to a variable name has the same effect as declaration, so the first Perl snippet has a translation like: ############################################# ## Python pseudocode name = None ## do things here that should initialize name if name is None: ## handle degenerate case here ############################################# where we can use None as our uninitialized value. Hope this helps! From tim at johnsons-web.com Tue Apr 4 04:26:04 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 18:26:04 -0800 Subject: [Tutor] defined() In-Reply-To: References: <20060404011005.GJ13866@johnsons-web.com> Message-ID: <20060404022604.GK13866@johnsons-web.com> * Danny Yoo [060403 18:14]: > > > > I'm interested in what use you would make of such a thing? > > My business partner is a perl programmer. He uses defined() a lot, I > > think, I've seen it in his code.... > > Now, if your business partner doesn't have the line 'use strict' in their > code, then give them a good kick and tell them to use it! It's criminal > for a professonal Perl programmer not to "use strict", I'm sure he has his "stay out of jail card". I know he always uses it. -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Apr 4 04:28:46 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Apr 2006 18:28:46 -0800 Subject: [Tutor] defined() In-Reply-To: <4431C78A.8010702@alum.rpi.edu> References: <4431A8FE.7060100@h-lab.net> <4431C78A.8010702@alum.rpi.edu> Message-ID: <20060404022846.GL13866@johnsons-web.com> * Bob Gailer [060403 17:12]: > > def defined(name): > return name in globals() > Hah! Good tip. I'll call it value() I think "language wars" are a waste of time, but I like the way that using different languages inform the programmer. cheers tj -- Tim Johnson http://www.alaska-internet-solutions.com From hokkakada at khmeros.info Tue Apr 4 04:32:25 2006 From: hokkakada at khmeros.info (kakada) Date: Tue, 04 Apr 2006 09:32:25 +0700 Subject: [Tutor] file? Message-ID: <4431DAB9.3050405@khmeros.info> Hi all, How can we know that one specific file is already exist in filesystem? for instance, I want to read zipfile by issuing code: import zipfile ziparchive = zipfile.ZipFile(inputfilename, "r") if the inputfilename doesn't exist then an error would be occurred. I want to catch up this special case first. Thanks, da From john at fouhy.net Tue Apr 4 04:39:12 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 4 Apr 2006 14:39:12 +1200 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <5e58f2e40604031939q6aceceafi5f525a90084a7ffe@mail.gmail.com> On 04/04/06, kakada wrote: > How can we know that one specific file is already exist in filesystem? Have a look in the os and os.path modules. In this case, os.path.exists is probably what you want: if not os.path.exists(inputfilename): print 'Oops, file does not exist!' sys.exit() ziparchive = zipfile.ZipFile(inputfilename, 'r') # ... -- John. From kent37 at tds.net Tue Apr 4 04:41:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Apr 2006 22:41:45 -0400 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <4431DCE9.5060908@tds.net> kakada wrote: > Hi all, > > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: > > import zipfile > ziparchive = zipfile.ZipFile(inputfilename, "r") > > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. if os.path.isfile(inputfilename): # file exists Kent From david at graniteweb.com Tue Apr 4 05:26:06 2006 From: david at graniteweb.com (David Rock) Date: Mon, 3 Apr 2006 22:26:06 -0500 Subject: [Tutor] file? In-Reply-To: <4431DAB9.3050405@khmeros.info> References: <4431DAB9.3050405@khmeros.info> Message-ID: <20060404032606.GA8068@wdfs.graniteweb.com> * kakada [2006-04-04 09:32]: > Hi all, > > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: > > import zipfile > ziparchive = zipfile.ZipFile(inputfilename, "r") > > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. The key here is to actually "catch" the exception. Python is very good at assuming something will work, and then deal only with the exceptions: import zipfile try: ziparchive = zipfile.ZipFile(inputfilename, "r") except: print "error accessing file" You could get fancy and deal with various exceptions or read traceback info, too. Using the try block is generally considered a more Pythonic way of handling the problem. :-) -- David Rock david at graniteweb.com From mbroe at columbus.rr.com Tue Apr 4 06:37:21 2006 From: mbroe at columbus.rr.com (Michael Broe) Date: Tue, 4 Apr 2006 00:37:21 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: Well coming up with this has made me really love Python. I worked on this with my online pythonpenpal Kyle, and here is what we came up with. Thanks to all for input so far. My first idea was to use a C-type indexing for-loop, to grab a two- element sequence [i, i+1]: dict = {} for i in range(len(t) - 1): if not dict.has_key(t[i]): dict[t[i]] = {} if not dict[t[i]].has_key(t[i+1]): dict[t[i]][t[i+1]] = 1 else: dict[t[i]][t[i+1]] += 1 Which works, but. Kyle had an alternative take, with no indexing, and after we worked on this strategy it seemed very Pythonesque, and ran almost twice as fast. ---- #!/usr/local/bin/python import sys file = open(sys.argv[1], 'rb').read() # We imagine a 2-byte 'window' moving over the text from left to right # # +-------+ # L o n | d o | n . M i c h a e l m a s t e r m ... # +-------+ # # At any given point, we call the leftmost byte visible in the window 'L', and the # rightmost byte 'R'. # # +-----------+ # L o n | L=d R=o | n . M i c h a e l m a s t e r m ... # +-----------+ # # When the program begins, the first byte is preloaded into L, and we position R # at the second byte of the file. # dict = {} L = file[0] for R in file[1:]: # move right edge of window across the file if not L in dict: dict[L] = {} if not R in dict[L]: dict[L][R] = 1 else: dict[L][R] += 1 L = R # move character in R over to L # that's it. here's a printout strategy: for entry in dict: print entry, ':', sum(dict[entry].values()) print dict[entry] print ---- From singingxduck at gmail.com Tue Apr 4 06:52:53 2006 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 4 Apr 2006 00:52:53 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <3449428f0604032152p43e4412fk38bb2ca2ffe38d81@mail.gmail.com> My only comment is that this considers spaces and punctuation (like parentheses, brackets, etc.), too, which I assume you don't want seeing as how that has little to do with natural languages. My suggestion would be to remove the any punctuation or whitespace keys from the dictionary after you've built the dictionary. Unless, of course, you're interested in what letter words start with, in which case you could somehow merge them into a single key? Cheers, Orri On 4/4/06, Michael Broe wrote: > > Well coming up with this has made me really love Python. I worked on > this with my online pythonpenpal Kyle, and here is what we came up > with. Thanks to all for input so far. > > My first idea was to use a C-type indexing for-loop, to grab a two- > element sequence [i, i+1]: > > dict = {} > for i in range(len(t) - 1): > if not dict.has_key(t[i]): > dict[t[i]] = {} > if not dict[t[i]].has_key(t[i+1]): > dict[t[i]][t[i+1]] = 1 > else: > dict[t[i]][t[i+1]] += 1 > > Which works, but. Kyle had an alternative take, with no indexing, and > after we worked on this strategy it seemed very Pythonesque, and ran > almost twice as fast. > > ---- > > #!/usr/local/bin/python > > import sys > file = open(sys.argv[1], 'rb').read() > > # We imagine a 2-byte 'window' moving over the text from left to right > # > # +-------+ > # L o n | d o | n . M i c h a e l m a s t e > r m ... > # +-------+ > # > # At any given point, we call the leftmost byte visible in the window > 'L', and the > # rightmost byte 'R'. > # > # +-----------+ > # L o n | L=d R=o | n . M i c h a e l m a s t > e r m ... > # +-----------+ > # > # When the program begins, the first byte is preloaded into L, and we > position R > # at the second byte of the file. > # > > dict = {} > > L = file[0] > for R in file[1:]: # move right edge of window across the file > if not L in dict: > dict[L] = {} > > if not R in dict[L]: > dict[L][R] = 1 > else: > dict[L][R] += 1 > > L = R # move character in R over to L > > # that's it. here's a printout strategy: > > for entry in dict: > print entry, ':', sum(dict[entry].values()) > print dict[entry] > print > > ---- > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060404/9873c3f4/attachment.html From kaushalshriyan at gmail.com Tue Apr 4 08:22:04 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 4 Apr 2006 11:52:04 +0530 Subject: [Tutor] Hi Message-ID: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> Hi ALL A simple query is that the python mailing List is python powered What does "python powered" means thanks Regards Kaushal From janos.juhasz at VELUX.com Tue Apr 4 08:44:35 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 4 Apr 2006 08:44:35 +0200 Subject: [Tutor] defined() In-Reply-To: Message-ID: Dear Tim, Dear Alan, >> I can't find the defined() function in python, so I used >>'variable name' in dir() > >> Is it really missing, or I am just so simple ? > > It is really missing, just as it is for most programming languages. > Which language(s) do you know that has such a feature? I should came from Marco Cantu's Delphi 2005 book, that I have read just recently. But I am unable to find it again. > And why do you consider it so useful that you expect to find > it in Python? I don't miss it. It was just a foggy engram, that I couldn't find in the help :) > The main place where I could see such a thing being useful > would be in dynamically loaded code but then the usual > approach is to load a dictionary and an 'in' check suffices. > > I'm interested in what use you would make of such a thing? I just started to make a .leo file, where I wanted to place my scripts. http://webpages.charter.net/edreamleo/front.html I just tried to collect all of my scripts (sql, wmi, admin, snmp ...), and html references, admin knowledge, passwords for active devices... into one place, that can be shared with my colleagues with detailed description about the usage and the reasons to use of them. Leo seems to be a very good candidate for that. An sql script seems to be like this. --------- << ScalaDB >> data = Query(<< Sql >>) << Show Data >> ------------ In the leo file the << ScalaDB >> is simple replaced by the << ScalaDB >> subtree. The script is created dinamically from the texts in the tree. So I just wanted to check in the << Show Data >> part, if the data is defined previously or not. Yours sincerely, ______________________________ Janos Juhasz From alan.gauld at freenet.co.uk Tue Apr 4 09:47:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 4 Apr 2006 08:47:07 +0100 Subject: [Tutor] file? References: <4431DAB9.3050405@khmeros.info> Message-ID: <00a501c657bb$f9658a40$0b01a8c0@xp> > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: Take a look in the os.path module. There is explanation of how to check for various aspects of files (including existence) in my web tutor Operating System topic. > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. The other approach, implied in your question is simply to *try* to *open* for read: try: open(inputfilename) except IOError: # it presumably didn't exist, so deal with it HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sanelson at gmail.com Tue Apr 4 10:35:33 2006 From: sanelson at gmail.com (Steve Nelson) Date: Tue, 4 Apr 2006 09:35:33 +0100 Subject: [Tutor] Hi In-Reply-To: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> References: <6b16fb4c0604032322u390f7e73y5a22477acd534002@mail.gmail.com> Message-ID: On 4/4/06, Kaushal Shriyan wrote: > Hi ALL > > A simple query is that the python mailing List is python powered > > What does "python powered" means The list, and many like it, use a piece of software called Mailman, which is written in Python. A few years back, the tool of choice was Majordomo, but Mailman is now very popular, partly because of its easy-to-use web interface. > Kaushal S. From titvirak at khmeros.info Tue Apr 4 10:56:27 2006 From: titvirak at khmeros.info (=?UTF-8?B?4Z6R4Z634Z6P4Z+S4Z6Z4Z6c4Z634Z6a4Z+I?=) Date: Tue, 04 Apr 2006 15:56:27 +0700 Subject: [Tutor] how to get data from xml Message-ID: <443234BB.8040703@khmeros.info> Dear all Pythoners, I am quiet new to python and now working with xml. I have an xml like this: 0x6B 0x78 0x4B 0x58 0x67 0x63 0x71 0x43 0x51 0x6A and I want to get data for KA, KHA, KO and so on. Can you guide me a way. Btw, I'm using dom for xml. Thanks, Titvirak From kent37 at tds.net Tue Apr 4 11:57:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 05:57:54 -0400 Subject: [Tutor] Bigrams and nested dictionaries In-Reply-To: References: Message-ID: <44324322.8060906@tds.net> Michael Broe wrote: > dict = {} dict is the name of the builtin dictionary class, so you shouldn't use it as the name of your dict - you shadow the built-in name. file is also a built-in name. > > L = file[0] > for R in file[1:]: # move right edge of window across the file > if not L in dict: > dict[L] = {} > > if not R in dict[L]: > dict[L][R] = 1 > else: > dict[L][R] += 1 I might write it this way: dictL = dict.setdefault(L, {}) dictL[R] = dictL.setdefault(R, 0) + 1 though I'm not sure which way will be faster. Kent From kent37 at tds.net Tue Apr 4 12:06:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 06:06:24 -0400 Subject: [Tutor] how to get data from xml In-Reply-To: <443234BB.8040703@khmeros.info> References: <443234BB.8040703@khmeros.info> Message-ID: <44324520.1060103@tds.net> ????????? wrote: > Dear all Pythoners, > > I am quiet new to python and now working with xml. I have an xml like this: > > > >
> > 0x6B > 0x78 > 0x4B > 0x58 > 0x67 > 0x63 > 0x71 > 0x43 > 0x51 > 0x6A > > > and I want to get data for KA, KHA, KO and so on. Can you guide me a > way. Btw, I'm using dom for xml. I don't know much about xml.dom but it is easy with ElementTree: data = '''
0x6B 0x78 0x4B 0x58 0x67 0x63 0x71 0x43 0x51 0x6A
''' from elementtree import ElementTree as ET doc = ET.fromstring(data) consonants = doc.find('.//CONSONANTS') for consonant in consonants: print consonant.tag, consonant.text Kent From python at kapitalisten.no Tue Apr 4 12:55:28 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 4 Apr 2006 12:55:28 +0200 (CEST) Subject: [Tutor] Bits Message-ID: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> Hello. Is it possible to read the bits (the 0's and 1's) of a string or a file with Python? What module would I use? Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Tue Apr 4 13:51:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 07:51:46 -0400 Subject: [Tutor] Bits In-Reply-To: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> References: <35105.193.71.38.142.1144148128.squirrel@mail.sporck.net> Message-ID: <44325DD2.70809@tds.net> ?yvind wrote: > Hello. > > Is it possible to read the bits (the 0's and 1's) of a string or a file > with Python? What module would I use? I don't know exactly what you mean by "read the bits" but you can use data = open('afile', 'b').read() to get the data into a string byte1=ord(data[1]) to get a character as binary data byte1 & 1 to extract a single bit You might also be interested in the struct module which lets you extract larger data (e.g. ints and floats) from a string. Kent From ktalanet at yahoo.es Tue Apr 4 15:40:44 2006 From: ktalanet at yahoo.es (Miquel Oliete) Date: Tue, 04 Apr 2006 15:40:44 +0200 Subject: [Tutor] Protected methods/variables Message-ID: <4432775C.2050806@yahoo.es> Hello everybody I have been programming in object oriented languages for several years and I'm learning python now. I have missed protected method/variables in Python. How do you declare methods/variables used only by a class and their derived classes? Thanks in advance -- Miquel Oliete (a.k.a. Ktal?) http://apetite4destruction.org/blog Powered by Debian GNU/Linux Sid ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From ukc802591034 at btconnect.com Tue Apr 4 18:47:29 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Tue, 4 Apr 2006 17:47:29 +0100 Subject: [Tutor] defined() References: Message-ID: >> Which language(s) do you know that has such a feature? > > I should came from Marco Cantu's Delphi 2005 book, that I have read just > recently. > But I am unable to find it again. I'd be very surprised if it came from Delphi for two reasons: a) I used Delphi a lot for several years and never came across it! :-) b) Delphi (or Object Pascal) is strictly statically typed and wouldn't even compile with any undefined values in the code. BUT... I just checked and it *is* in Delphi - a new feature in Delphi 6. BUT it's not a language feature rather it is a compiler directive like the C #ifdef. (And starts with uppercase D BTW). His example: //-------------------- const debugControl = 2 {$IF Defined(DEBUG) and DebugControl > 3} // do stuff here {$IFEND} //--------------------- There is also a Declared directive too. These are not primarily intended for determining whether a variable is defined or declared but to determine whether a particular language feature has been defined or constant declared in the current version of Delphi (post version 6 of course!) Now that's an entirely different question in terms of how we do that in Python! Which I'll lreave as an excercise for the readers ;-) -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ukc802591034 at btconnect.com Tue Apr 4 19:07:06 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Tue, 4 Apr 2006 18:07:06 +0100 Subject: [Tutor] Protected methods/variables References: <4432775C.2050806@yahoo.es> Message-ID: "Miquel Oliete" wrote in message news:4432775C.2050806 at yahoo.es... > I have been programming in object oriented languages for several years > and I'm learning python now. Congratulations :-) > I have missed protected method/variables in Python. In what sense have you missed them? Have you been hitting a lot of bugs because you didn't have them? OIr do you just mean you are having withdrawal symptoms after working in more conservative OOP languages like C++/Java etc? > How do you declare methods/variables used only by a class > and their derived classes? You don't. Protected was a scheme introduced by Bjarne Stroustrup at the behest of Mark Linton to support Mark's Interviews GUI library in C++ (version 1.2) and subsequently copied in Java. They are part of the statically and strictly typed idioms of OOP used in those languages. However Stroustrup writes in his book "The Design & Evolution of C++" : "In retrospect, I think that protected is a case where "good arguments" and fashion overcame my better judgement..." And Linton himself withdrew support for protected members from Interviews around the same time - they were causing bugs and maintenance problems! Most OOP languages and especially dynamic OOP languages prefer the freedom of expression and flexibility that dynamic typing (or duck typing as its sometimes called) affords. Objective C tries to combine boith with mixed results. But in practice I can honestly say I have never missed having the protected keyword (I do occasionally like to use private - for which there is a convention in Python) but never have I missed protected. What do you find you need it for? -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Tue Apr 4 19:21:48 2006 From: wescpy at gmail.com (w chun) Date: Tue, 4 Apr 2006 10:21:48 -0700 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432775C.2050806@yahoo.es> References: <4432775C.2050806@yahoo.es> Message-ID: <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> > I have missed protected method/variables in Python. How do you declare > methods/variables used only by a class and their derived classes? hi Ktal?, welcome to Python! you missed "protection" in OOP with Python bceause there are no such declarations in Python! 1) there is a privacy *hint*, which is using "__" to start a variable or method name with, e.g., def __myMaybePrivateMethod(self,...). this does name-mangle the attribute at run-time, however the algorithm is fairly well-known and easy to crack: self._CLASS__myMaybePrivateMethod(). for more on this see,: http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 2) however, with Python's new-style classes introduced back in 2.2, there are much more powerful security mechanisms you can employ so that you can customize any or all of your attributes (data attributes [variables] or methods) to give it the most fine-grained security you can imagine. - you can use property() for your attributes to assign a getter, setter, and deleter method that get executed every time someone tries to access, set, and delete an instance attribute: | class C(object): | def getx(self): return self.__x | def setx(self, value): self.__x = value | def delx(self): del self.__x | x = property(getx, setx, delx, "I'm the 'x' property.") - you can use descriptors (__get__, __set__, __delete__) that get executed every time someone tries to access, set, and remove your object... this allows you to really customize instances and how attribute access occurs. using descriptors, you can bypass the regular way of attribute search, i.e., x.foo normally looks at object 'x' for 'foo', and if not found, searches type(x) for 'foo', and then it progresses this search to ancestor classes. with descriptors, you can override this default behavior to make instances differ from one another. in fact, properties (as seen above) is an example of a descriptor! - you can use __slots__ to restrict arbirtrary creation of (dynamic) instrance attributes - you can even customize how classes are created (by using metaclasses and __metaclass__) so as you can see, you can do a lot more with Python classes than what you can do with 'private', 'protected', 'friend', or 'protected friend'. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Apr 4 19:43:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 13:43:01 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> References: <4432775C.2050806@yahoo.es> <78b3a9580604041021g64409eb4g2d2063f2dfe7af1e@mail.gmail.com> Message-ID: <4432B025.3080805@tds.net> w chun wrote: >> I have missed protected method/variables in Python. How do you declare >> methods/variables used only by a class and their derived classes? > > hi Ktal?, > > welcome to Python! you missed "protection" in OOP with Python bceause > there are no such declarations in Python! > > 1) there is a privacy *hint*, which is using "__" to start a variable > or method name with, e.g., def __myMaybePrivateMethod(self,...). > this does name-mangle the attribute at run-time, however the algorithm > is fairly well-known and easy to crack: > self._CLASS__myMaybePrivateMethod(). for more on this see,: > http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 1a) start a variable name with _ which is a hint to users of the class that the variable is for internal use only. > - you can use __slots__ to restrict arbirtrary creation of (dynamic) > instrance attributes You can do this, but it is generally considered a misuse of __slots__ and potentially problematic. Python takes the attitude that "we're all adults here" and doesn't try to hide anything. The _ naming convention is part of this culture - you tell the users to keep hands off, but if they don't, on their head be it! Kent From mhansen at cso.atmel.com Tue Apr 4 21:09:32 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 04 Apr 2006 13:09:32 -0600 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432B025.3080805@tds.net> Message-ID: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> > > - you can use __slots__ to restrict arbirtrary creation of > (dynamic) > > instrance attributes > > You can do this, but it is generally considered a misuse of > __slots__ and potentially problematic. > I'll bite. What is the proper/intended use of __slots__? Does it have something to do with memory? Mike From kent37 at tds.net Tue Apr 4 21:25:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Apr 2006 15:25:05 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> Message-ID: <4432C811.3050908@tds.net> Mike Hansen wrote: >>> - you can use __slots__ to restrict arbirtrary creation of >> (dynamic) >>> instrance attributes >> You can do this, but it is generally considered a misuse of >> __slots__ and potentially problematic. >> > > I'll bite. What is the proper/intended use of __slots__? Does it have > something to do with memory? Yes, it is intended specifically to reduce memory consumption of objects that are going to be instantiated a lot. I'm not sure how many counts as a lot, but in the thousands at least. Using __slots__ saves the cost of the attribute dict for each instance. Kent From john.corry at ntlworld.com Tue Apr 4 23:33:18 2006 From: john.corry at ntlworld.com (John Corry) Date: Tue, 4 Apr 2006 22:33:18 +0100 Subject: [Tutor] Space the final frontier! Message-ID: Dear All, I am having difficulty removing white spaces from my file. The file is 999 lines long and looks like the sample below: 001, new field,dial= 028 90 79 0154, dial= 002, borfiled, dial= 02890 618521, dial= 003, newcomp, dial=02890419689, dial= The program, I am using to import the file does not like the spaces around the numbers. The number should look like the "dial=02890419689" in the third line. Thus the sample above should look like: 001,newfield,dial=02890790154,dial= 002,borfiled,dial=02890618521,dial= 003,newcomp,dial=02890419689,dial= I have searched the tutor mailbag already and have picked up some good tips on join, split and re but I can't seem to get it to work. I am using the following code. filename = "c:/test.txt" import string import os import re listy = [] input = open( filename, 'r') #read access for line in input.readlines(): y = line listy.append(y) print listy x = listy.pop() re.sub(r'\s', '', x) print y,x del input It produces the output: ['001, new field,dial= 028 90 79 0154, dial=\n'] 001, new field,dial= 028 90 79 0154, dial= 001, new field,dial= 028 90 79 0154, dial= ['002, borfiled, dial= 02890 618521, dial=\n'] 002, borfiled, dial= 02890 618521, dial= 002, borfiled, dial= 02890 618521, dial= ['003, newcomp, dial=02890419689, dial='] 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial= Any help would be greatly appreciated. Regards, John. From derobins at scs.uiuc.edu Wed Apr 5 01:06:25 2006 From: derobins at scs.uiuc.edu (Dana Robinson) Date: Tue, 4 Apr 2006 18:06:25 -0500 Subject: [Tutor] Question about large numbers of arguments Message-ID: Hello, Suppose you have a situation where you have a large number of command-line options that you will parse with getopt. You want to keep track of these as you move around in the code and do various things. Is it more Pythonic to: Have the functions take large numbers of parameters. or Create an options class to pass the options around. I personally think the latter would look a lot cleaner once the number of options got up to around a half dozen, but I usually see the "large number of parameters" style in other people's code. I suppose I can lessen some of the noise by using Python's rules for argument defaults, but I think that just adds to the confusion. Thanks, Dana Robinson From mwhite3 at ttsd.k12.or.us Wed Apr 5 01:28:38 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Tue, 4 Apr 2006 16:28:38 -0700 Subject: [Tutor] Space the final frontier! In-Reply-To: References: Message-ID: <20060404232837.GD2730@ttsd.k12.or.us> Hi John, It would be easier to do all of your whitespace elimination before you append the string to your list(s). Something like this I should get you started: for line in input.readlines(): line = re.sub('[\s]+', '', line) listy.append(line) print listy bonus points for appending the return from re.sub to your list. :) -mtw On Tue, Apr 04, 2006 at 10:33:18PM +0100, John Corry (john.corry at ntlworld.com) wrote: > Dear All, > > I am having difficulty removing white spaces from my file. The file is 999 > lines long and looks like the sample below: > > 001, new field,dial= 028 90 79 0154, dial= > 002, borfiled, dial= 02890 618521, dial= > 003, newcomp, dial=02890419689, dial= > > The program, I am using to import the file does not like the spaces around > the numbers. The number should look like the "dial=02890419689" in the > third line. Thus the sample above should look like: > > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= > > I have searched the tutor mailbag already and have picked up some good tips > on join, split and re but I can't seem to get it to work. > > I am using the following code. > > filename = "c:/test.txt" > import string > import os > import re > listy = [] > input = open( filename, 'r') #read access > for line in input.readlines(): > y = line > listy.append(y) > print listy > x = listy.pop() > > re.sub(r'\s', '', x) > print y,x > > del input > > It produces the output: > > ['001, new field,dial= 028 90 79 0154, dial=\n'] > 001, new field,dial= 028 90 79 0154, dial= > 001, new field,dial= 028 90 79 0154, dial= > > ['002, borfiled, dial= 02890 618521, dial=\n'] > 002, borfiled, dial= 02890 618521, dial= > 002, borfiled, dial= 02890 618521, dial= > > ['003, newcomp, dial=02890419689, dial='] > 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial= > > Any help would be greatly appreciated. > > Regards, > > John. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From bgailer at alum.rpi.edu Wed Apr 5 01:30:37 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 04 Apr 2006 16:30:37 -0700 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: References: Message-ID: <4433019D.4050201@alum.rpi.edu> Dana Robinson wrote: > Hello, > > Suppose you have a situation where you have a large number of command-line > options that you will parse with getopt. You want to keep track of these > as you move around in the code and do various things. > > Is it more Pythonic to: > > Have the functions take large numbers of parameters. > > or > > Create an options class to pass the options around. > IMHO the above or a dictionary. > > I personally think the latter would look a lot cleaner once the number of > options got up to around a half dozen, but I usually see the "large number > of parameters" style in other people's code. I suppose I can lessen some > of the noise by using Python's rules for argument defaults, but I think > that just adds to the confusion. > > Thanks, > > Dana Robinson > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ryang at gol.com Wed Apr 5 02:22:27 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Wed, 5 Apr 2006 09:22:27 +0900 Subject: [Tutor] Space the final frontier! In-Reply-To: Message-ID: <002601c65847$058bfb20$030ba8c0@RYAN> [Sorry for the initial misfire, John] > [mailto:tutor-bounces at python.org] On Behalf Of John Corry > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= Hi John: I believe the common idiom in this case is ''.join( theString.split( ' ' ) ) >>> theLines = [ '001,newfield,dial=02890790154,dial=', '002,borfiled,dial=02890618521,dial=', '003,newcomp,dial=02890419689,dial='] >>> for line in theLines: print ''.join( line.split( ' ' ) ) 001,newfield,dial=02890790154,dial= 002,borfiled,dial=02890618521,dial= 003,newcomp,dial=02890419689,dial= Regards, Ryan --- Ryan Ginstrom http://ginstrom.com From Carlo.Capuano at iter.org Wed Apr 5 09:39:52 2006 From: Carlo.Capuano at iter.org (Carlo Capuano) Date: Wed, 5 Apr 2006 09:39:52 +0200 Subject: [Tutor] Space the final frontier! Message-ID: <0F4FBAD10465E047ADB7E8C74B4C189B35B99C@de-iws-xch01.iter.org> Hi! > I am having difficulty removing white spaces from my file. The file is > 999 line = line.replace(' ','') should do the work Carlo. From info at harrycorry.com Wed Apr 5 09:46:51 2006 From: info at harrycorry.com (John Corry) Date: Wed, 5 Apr 2006 08:46:51 +0100 Subject: [Tutor] Space the final frontier Message-ID: Dear All, Thanks for the prompt replies. I have now processed my file with 999 lines and it took seconds. It was beautiful. Your advice was spot on. I have enclosed the code that I ended up with. Instead of appending it to a list, I just wrote it to another file in the corrected format. filename = "a:/calllist.csv" filename2 = "c:/calllist.csv" import string import os import re listy = [] input = open( filename, 'r') #read access input2 = open(filename2, 'w') for line in input.readlines(): line = re.sub('[\s]+', '', line) y = line x = "\n" z = y + x input2.write(z) del input del input2 Thanks again, John. From kent37 at tds.net Wed Apr 5 12:03:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 06:03:26 -0400 Subject: [Tutor] Space the final frontier In-Reply-To: References: Message-ID: <443395EE.1020504@tds.net> John Corry wrote: > Your advice was spot on. I have enclosed the code that I ended up with. > Instead of appending it to a list, I just wrote it to another file in the > corrected format. A few notes below: > > > filename = "a:/calllist.csv" > filename2 = "c:/calllist.csv" > import string > import os > import re > listy = [] You don't use string, os or listy so these lines can be removed > input = open( filename, 'r') #read access > input2 = open(filename2, 'w') > for line in input.readlines(): > line = re.sub('[\s]+', '', line) > y = line > x = "\n" > z = y + x > input2.write(z) I would write either line += "\n" input2.write(line) or input2.write(line) input2.write("\n") BTW input2 is not such a good name for an output file! > > del input > del input2 del is not needed here, you should use input.close() # not really needed input2.close() I say "not really needed" because for an input file you probably don't care exactly when it is closed. For an output file I always close it as soon as I am done writing. But maybe I am just teaching my own bad habits here! Kent From wescpy at gmail.com Wed Apr 5 12:46:47 2006 From: wescpy at gmail.com (w chun) Date: Wed, 5 Apr 2006 03:46:47 -0700 Subject: [Tutor] Protected methods/variables In-Reply-To: <4432C811.3050908@tds.net> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> <4432C811.3050908@tds.net> Message-ID: <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> On 4/4/06, Kent Johnson wrote: > Mike Hansen wrote: > >>> - you can use __slots__ to restrict arbirtrary creation of > >> (dynamic) > >>> instrance attributes > >> You can do this, but it is generally considered a misuse of > >> __slots__ and potentially problematic. what specific problems were you thinking of? i would say that's it's clumsy to use during development because you're constantly changing __dict__ by adding new instance attributes, etc., so i only add a __slots__ when i'm finally done with the coding and want to prevent others from creating (dynamically) more instance attributes. it's too bad, because it sort goes against Zen#19 (namespaces are a honking good idea). > > I'll bite. What is the proper/intended use of __slots__? Does it have > > something to do with memory? > > Yes, it is intended specifically to reduce memory consumption of objects > that are going to be instantiated a lot. I'm not sure how many counts as > a lot, but in the thousands at least. Using __slots__ saves the cost of > the attribute dict for each instance. right, a class will either have __slots__ or __dict__ but not both. -- 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 janos.juhasz at VELUX.com Wed Apr 5 13:06:58 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 5 Apr 2006 13:06:58 +0200 Subject: [Tutor] Space the final frontier! In-Reply-To: Message-ID: Hi John, what do you think about this? def InplaceReplace(filename): lines = open(filename, 'r').readlines() lines = [line.replace(' ', '') for line in lines] open(filename, 'wt').writelines(lines) It works well on so small files. Yours sincerely, ______________________________ J?nos Juh?sz > Message: 2 > Date: Tue, 4 Apr 2006 22:33:18 +0100 > From: "John Corry" > Subject: [Tutor] Space the final frontier! > To: > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > Dear All, > I am having difficulty removing white spaces from my file. The file is 999 > lines long and looks like the sample below: > 001, new field,dial= 028 90 79 0154, dial= > 002, borfiled, dial= 02890 618521, dial= > 003, newcomp, dial=02890419689, dial= > The program, I am using to import the file does not like the spaces around > the numbers. The number should look like the "dial=02890419689" in the > third line. Thus the sample above should look like: > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= From alan.gauld at freenet.co.uk Wed Apr 5 13:34:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 12:34:17 +0100 Subject: [Tutor] Question about large numbers of arguments References: Message-ID: <01ab01c658a4$dffb0a50$0b01a8c0@xp> > Suppose you have a situation where you have a large number of command-line > options that you will parse with getopt. You want to keep track of these > as you move around in the code and do various things. > > Is it more Pythonic to: > > Have the functions take large numbers of parameters. > > Create an options class to pass the options around. Neither, the most Pythonic way IMHO is to use a dictionary and possibly combine with Pythons variable arguments syntax as described in section 4.7.3/4 of the official tutor. > I personally think the latter would look a lot cleaner once the number of > options got up to around a half dozen, but I usually see the "large number > of parameters" style in other people's code. Classes without behaviour are really just glorified dictionaries so I prefer to use a dictionary. The **args mechanism provides a good way to pass these to functions. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keosophon at khmeros.info Wed Apr 5 13:32:56 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:32:56 +0700 Subject: [Tutor] convert decimal to hexa, to octal and vice versa. Message-ID: <200604051832.56959.keosophon@khmeros.info> Hi, How to convert a decimal number to hexadecimal, octal and vice versa? Thanks, phon From keosophon at khmeros.info Wed Apr 5 13:35:17 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:35:17 +0700 Subject: [Tutor] convert an integer number to string. Message-ID: <200604051835.17577.keosophon@khmeros.info> hi, how to convert an integer number to string? thanks, phon From alan.gauld at freenet.co.uk Wed Apr 5 13:41:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 12:41:56 +0100 Subject: [Tutor] Space the final frontier References: Message-ID: <01b301c658a5$f145f620$0b01a8c0@xp> > Thanks for the prompt replies. I have now processed my file with 999 > lines > and it took seconds. It was beautiful. Glad it works, a couple of tweaks: > filename = "a:/calllist.csv" > filename2 = "c:/calllist.csv" > import string > import os You don't use os or string so don't need to import them > import re And you don't really need re either, see below... > listy = [] > input = open( filename, 'r') #read access > input2 = open(filename2, 'w') input is a builtin function so using it as a variable name could cause confusion - input1 would be more consistent. Although calling the second one output might be more accurate? > for line in input.readlines(): > line = re.sub('[\s]+', '', line) you can just use the string replace method which for simple replacements is faster than re and much less complex. line = line.replace(' ','') > y = line > x = "\n" > z = y + x you don't really need all that > input2.write(z) input2.write(line + '\n') is just as clear if not clearer! At least I think so! :-) > del input > del input2 You should use close on a file not del. input1.close() input2.close() HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keosophon at khmeros.info Wed Apr 5 13:42:37 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 5 Apr 2006 18:42:37 +0700 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: <442EF4DA.4050304@tds.net> References: <200603311906.26110.keosophon@khmeros.info> <442EF4DA.4050304@tds.net> Message-ID: <200604051842.37211.keosophon@khmeros.info> On Sunday 02 April 2006 04:47, Kent Johnson wrote: > Alan Gauld wrote: > > "Keo Sophon" wrote in message > > news:200603311906.26110.keosophon at khmeros.info... > > > >>Is there anyway to get the content of an XML elements. I am using > >> xml.dom. > > > > For true XML I think ElemTree (by Fred Lundh?) is the best approach. > > Try a Google search. > > Yes, it's ElementTree though. > > Keo, what do you mean, "get the content of an XML elements"? > > Kent for example: ..... someone at email.com ..... I would like to get "someone at email.com" of . How to do that? Phon From purple.meteor at gmail.com Wed Apr 5 13:45:03 2006 From: purple.meteor at gmail.com (Olivier D.) Date: Wed, 5 Apr 2006 13:45:03 +0200 Subject: [Tutor] convert an integer number to string. In-Reply-To: <200604051835.17577.keosophon@khmeros.info> References: <200604051835.17577.keosophon@khmeros.info> Message-ID: <1a4188f0604050445k170e434cw8016ea2cfb7ab051@mail.gmail.com> On 4/5/06, Keo Sophon wrote: > > how to convert an integer number to string? Use str(object) to convert an object to a string. For example: >>> str(42) '42' The reverse function is int(x) to convert a string to an integer: >>> int('42') 42 From ukc802591034 at btconnect.com Wed Apr 5 13:48:08 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Wed, 5 Apr 2006 12:48:08 +0100 Subject: [Tutor] convert decimal to hexa, to octal and vice versa. References: <200604051832.56959.keosophon@khmeros.info> Message-ID: "Keo Sophon" wrote in message news:200604051832.56959.keosophon at khmeros.info... > How to convert a decimal number to hexadecimal, octal and vice versa? The number is stored in binary on the computer so you never convert the number itself, what you convert is the representation of that number as a string. The easiest way (and the one with most control) is to use string formatting: number = 42 print "%X" % number print "%x" % number print "%05x" % number print "%o" % number etc. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From noufal at nibrahim.net.in Wed Apr 5 13:50:14 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 5 Apr 2006 17:20:14 +0530 (IST) Subject: [Tutor] convert decimal to hexa, to octal and vice versa. In-Reply-To: <200604051832.56959.keosophon@khmeros.info> References: <200604051832.56959.keosophon@khmeros.info> Message-ID: <44362.203.145.176.76.1144237814.squirrel@members.hcoop.net> On Wed, April 5, 2006 5:02 pm, Keo Sophon wrote: > Hi, > > How to convert a decimal number to hexadecimal, octal and vice versa? >>> foo = 2 >>> str(foo) # Integer to string '2' >>> oct(15) # Integer to octal '017' >>> hex(15) # Integer to hex '0xf' >>> int(0xf) # Hex to decimal integer -- -NI From kent37 at tds.net Wed Apr 5 14:15:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 08:15:33 -0400 Subject: [Tutor] Protected methods/variables In-Reply-To: <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> References: <000001c6581b$4dfbb2a0$28645f0a@mikehansen> <4432C811.3050908@tds.net> <78b3a9580604050346u43c7f4b0m5fafe1313af1cce0@mail.gmail.com> Message-ID: <4433B4E5.4030105@tds.net> w chun wrote: > On 4/4/06, Kent Johnson wrote: >> Mike Hansen wrote: >>>>> - you can use __slots__ to restrict arbirtrary creation of >>>> (dynamic) >>>>> instrance attributes >>>> You can do this, but it is generally considered a misuse of >>>> __slots__ and potentially problematic. > > what specific problems were you thinking of? i would say that's it's > clumsy to use during development because you're constantly changing > __dict__ by adding new instance attributes, etc., so i only add a > __slots__ when i'm finally done with the coding and want to prevent > others from creating (dynamically) more instance attributes. it's too > bad, because it sort goes against Zen#19 (namespaces are a honking > good idea). The main problem seems to be that it can be broken by inheritance. A base or derived class can have a __dict__ which then allows additional attributes to be added even if the derived or base class uses __slots__. I admit to arguing from authority here but the consistent message on c.l.py from those who should know is, don't use __slots__ to restrict assignment, use __setattr__ instead; __slots__ should be used as a memory optimization only. Search c.l.py for discussion. >>> I'll bite. What is the proper/intended use of __slots__? Does it have >>> something to do with memory? >> Yes, it is intended specifically to reduce memory consumption of objects >> that are going to be instantiated a lot. I'm not sure how many counts as >> a lot, but in the thousands at least. Using __slots__ saves the cost of >> the attribute dict for each instance. > > right, a class will either have __slots__ or __dict__ but not both. As noted above, that is not necessarily true when inheritance is involved. Kent From kent37 at tds.net Wed Apr 5 14:28:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 08:28:53 -0400 Subject: [Tutor] how to get the content of an XML elements. In-Reply-To: <200604051842.37211.keosophon@khmeros.info> References: <200603311906.26110.keosophon@khmeros.info> <442EF4DA.4050304@tds.net> <200604051842.37211.keosophon@khmeros.info> Message-ID: <4433B805.2000101@tds.net> Keo Sophon wrote: > On Sunday 02 April 2006 04:47, Kent Johnson wrote: >> Alan Gauld wrote: >>> "Keo Sophon" wrote in message >>> news:200603311906.26110.keosophon at khmeros.info... >>> >>>> Is there anyway to get the content of an XML elements. I am using >>>> xml.dom. >>> For true XML I think ElemTree (by Fred Lundh?) is the best approach. >>> Try a Google search. >> Yes, it's ElementTree though. >> >> Keo, what do you mean, "get the content of an XML elements"? >> >> Kent > > for example: > > ..... > someone at email.com > ..... > > I would like to get "someone at email.com" of . With ElementTree it would be something like doc = ElementTree.parse('file.xml') to = doc.find('//to') print to.text Kent From python at venix.com Wed Apr 5 14:57:28 2006 From: python at venix.com (Python) Date: Wed, 05 Apr 2006 08:57:28 -0400 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: <01ab01c658a4$dffb0a50$0b01a8c0@xp> References: <01ab01c658a4$dffb0a50$0b01a8c0@xp> Message-ID: <1144241849.6491.1370.camel@www.venix.com> On Wed, 2006-04-05 at 12:34 +0100, Alan Gauld wrote: > > Suppose you have a situation where you have a large number of command-line > > options that you will parse with getopt. You want to keep track of these > > as you move around in the code and do various things. > > > > Is it more Pythonic to: > > > > Have the functions take large numbers of parameters. > > > > Create an options class to pass the options around. > > Neither, the most Pythonic way IMHO is to use a dictionary and > possibly combine with Pythons variable arguments syntax as > described in section 4.7.3/4 of the official tutor. > > > I personally think the latter would look a lot cleaner once the number of > > options got up to around a half dozen, but I usually see the "large number > > of parameters" style in other people's code. > > Classes without behaviour are really just glorified dictionaries so > I prefer to use a dictionary. The **args mechanism provides a > good way to pass these to functions. Just to expand on that a little bit, one useful coding trick where you use only a few of the parameters is to define the function as: def myfunc(param6, param11, param17, **extra): # The parameters you care about are unpacked for you # The rest are in extra # use the ** syntax to pass the dictionary in to your function myfunc( **param_dict) Coming up with better names is left as an exercise for the reader. I mostly use this when dealing with HTML forms with many variables. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ray.allen at sant.ox.ac.uk Wed Apr 5 16:07:37 2006 From: ray.allen at sant.ox.ac.uk (Ray Allen) Date: Wed, 5 Apr 2006 15:07:37 +0100 Subject: [Tutor] date conversion Message-ID: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> I would like Python to convert a date returned by MySQL (2006-04-05) to a user readable format such as 05-Apr-2006 for display and then to convert it back to ISO format for update. What is the most convenient way of doing this? I'm struggling to understand the datetime module's functionality. Ray Allen From kent37 at tds.net Wed Apr 5 16:50:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 10:50:33 -0400 Subject: [Tutor] date conversion In-Reply-To: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> Message-ID: <4433D939.3030007@tds.net> Ray Allen wrote: > I would like Python to convert a date returned by MySQL (2006-04-05) to a > user readable format such as 05-Apr-2006 for display and then to convert it > back to ISO format for update. Here's one way: In [1]: from datetime import date In [2]: data = '2006-04-05' Use split() and int() to convert to a list of year, month, day In [4]: ymd = map(int, data.split('-')) In [5]: ymd Out[5]: [2006, 4, 5] Turn it into a date. The * makes the list act like individual parameters. In [6]: d=date(*ymd) In [7]: d Out[7]: datetime.date(2006, 4, 5) See the docs for the time module for info about strftime() format codes In [8]: d.strftime('%d-%b-%Y') Out[8]: '05-Apr-2006' ISO format is built-in. In [9]: d.isoformat() Out[9]: '2006-04-05' For other input formats you might have to use time.strptime() to convert to a time tuple, then pass the first three elements do date(): In [10]: import time In [15]: t=time.strptime(data, '%Y-%m-%d') In [16]: t Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) In [17]: date(*t[:3]) Out[17]: datetime.date(2006, 4, 5) Kent From brian at daviesinc.com Wed Apr 5 16:56:00 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 10:56:00 -0400 Subject: [Tutor] date conversion In-Reply-To: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> Message-ID: <4433DA80.5080704@daviesinc.com> I wrote something similar on my blog some time back.. http://phplogix.com/codefool/?postid=13 This is for converting Apache logfiles to a ISO formatted date for mysql.. It could easily be reversed, with a little tweaking.. :) to wit: def mreplace(s, chararray, newchararray): for a, b in zip(chararray, newchararray): s = s.replace(a, b) return s olddatestring = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') newdatestring = ('01','02','03','04','05','06','07','08','09','10','11','12') def clftosql(date): ttime = date.split(":",1) time = ttime[1] datelist = ttime[0].split('/') #should be , E.G DD,MM,YYYY we need YYYY-MM-DD for sql day = datelist[0] month = datelist[1] year = datelist[2] newdate = year+'-'+month+'-'+day+' '+time return newdate then you can take a date stamp from an Apache CLF log like this : 01/Oct/2000:00:00:00 (after you regex it out of the log with: datechk = re.compile('([0-9]+/.../[0-9][0-9][0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9])') of course) and run the functions thus: mydate = mreplace(dated,olddatestring,newdatestring) mydate1 = clftosql(mydate) Ray Allen wrote: > I would like Python to convert a date returned by MySQL (2006-04-05) to a > user readable format such as 05-Apr-2006 for display and then to convert it > back to ISO format for update. What is the most convenient way of doing > this? I'm struggling to understand the datetime module's functionality. > Ray Allen > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:4433d45e204351006614580! > > From brian at daviesinc.com Wed Apr 5 17:11:08 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 11:11:08 -0400 Subject: [Tutor] date conversion In-Reply-To: <4433DA80.5080704@daviesinc.com> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433DA80.5080704@daviesinc.com> Message-ID: <4433DE0C.4030106@daviesinc.com> Oh yeah - you can also simply use Mysql's date_format() function when you query the database ?? select date_format(column_name,'%d-%b-%Y') as formatted_date from table where blah; would output the date as 05-Apr-2006 http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html Brian Gustin wrote: > I wrote something similar on my blog some time back.. > http'://phplogix.com/codefool/?postid=13 > This is for converting Apache logfiles to a ISO formatted date for > mysql.. It could easily be reversed, with a little tweaking.. :) > > > to wit: > def mreplace(s, chararray, newchararray): > for a, b in zip(chararray, newchararray): > s = s.replace(a, b) > return s > > olddatestring = > ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') > > newdatestring = > ('01','02','03','04','05','06','07','08','09','10','11','12') > > def clftosql(date): > ttime = date.split(":",1) > time = ttime[1] > datelist = ttime[0].split('/') > #should be , E.G DD,MM,YYYY we need YYYY-MM-DD for sql > day = datelist[0] > month = datelist[1] > year = datelist[2] > newdate = year+'-'+month+'-'+day+' '+time > return newdate > > then you can take a date stamp from an Apache CLF log like this : > 01/Oct/2000:00:00:00 (after you regex it out of the log with: > > datechk = > re.compile('([0-9]+/.../[0-9][0-9][0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9])') > > of course) > > and run the functions thus: > > mydate = mreplace(dated,olddatestring,newdatestring) > mydate1 = clftosql(mydate) > > > Ray Allen wrote: > >>I would like Python to convert a date returned by MySQL (2006-04-05) to a >>user readable format such as 05-Apr-2006 for display and then to convert it >>back to ISO format for update. What is the most convenient way of doing >>this? I'm struggling to understand the datetime module's functionality. >>Ray Allen >> >>_______________________________________________ >>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 > > !DSPAM:4433db1a224961964068235! > > From rfquerin at gmail.com Wed Apr 5 17:16:14 2006 From: rfquerin at gmail.com (Richard Querin) Date: Wed, 5 Apr 2006 11:16:14 -0400 Subject: [Tutor] preliminary app design question Message-ID: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> I am planning to write a program (or series of programs) and want some advice beforehand. I've written a few small programs with Python and wxPython, but nothing very complex. I want to write a suite of in-house structural engineering design programs for my own purposes. I want to do the following: - write each program independently as a standalone structural design app - design and write the programs in such a way that in the future I can create a project app that would link all these smaller apps together (to store a bunch of these different designs under a single project for instance) - I want the input/output of each program to be easily adaptable and readable by the 'project app' in the future - I would want the individual programs to have file formats that are easily extensible as I add features to them - The 'project app' would have to be extensible in that I could link smaller apps to it as I create them and it should be able to handle revisions to these smaller apps as I make them. Obviously this won't happen right away, I would likely develop each small design app as a standalone and then when I've got 3 or 4 done I would tie them together with the project app. My question before I start is whether or not using an XML format for the individual file formats is the way to go, and if I have to anticipate every little thing in the file formats before hand. I don't want to do this, I would rather like to be able to just add and modify things as I go with the least amount of hassle along the way. Any ideas on how to generally approach the file formats? Any suggestions would be greatly appreciated. I have zero experience with XML at this point, and very modest experience with Python/wxPython, but necessity is the mother of invention and I can learn what I need to know I think. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/9005006a/attachment.htm From srini_iyyer_bio at yahoo.com Wed Apr 5 19:03:56 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 10:03:56 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists - walking over lists and their elements In-Reply-To: <4433DA80.5080704@daviesinc.com> Message-ID: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Dear Tutors, I have a huge string and 2 lists. List A consists of tabed elements, where first tab represents entry somewhere in string(ndat). ndat has 'Contig27915_RC' and List A [nbat]has 'Contig27915_RC\tXM_945977'. List B [nmlist]has elements, for instance ['XM_945977\tNM_152513']. Now my task, is to take each element in nbat(listA) search in string ndat and nmlist, if found in nmlist, replace with its tabed counterpart in ndat string. How did I choose to solve: 1. I could not think in the most smartest way as said easily above. Say take element from nbat, see if modified version of it available in nmlist, if found replace that modifed element in string. So I chose to take element from listA (nbat), search in string ndat. If found replace with it tabed element(Contig27915_RC\tXM_945977 => XM_945977) and store that in a new list. Now loop over this new list for each element check if a new version available in nmlist. If so replace and print. One of the proble is that, Contig27915_RC is seen associated with many XM entries in nbat. However, with the above script I could replace only once in xta. I could not print Contig27915_RC with many XM_ guys in nbat. How can this be done. Finally, this whole process seems to be more cumbersome to me. Could any one tip me with a new way of dealing this 3 way mapping. Thanks Script: xt = '' for m in nbat: cols = m.split('\t') old = cols[0] new = cols[1] if ndat.find(old): xt = ndat.replace(old,new) xta = xt.split('\n') >>> for x in xta: ... for m in nmlist: ... cols = m.split('\t') ... colold = cols[0] ... colnew = cols[1] ... if x == colold: ... print x+'\t'+colnew ... XM_945977 NM_152513 -XTA result --- snip--- Contig25622_RC Contig13475_RC Contig40179_RC XM_945977 <- <- <- ['Contig27915_RC\tXM_945977'] Contig44682_RC Contig35934_RC -------------- ndat = """Pro25G\nvariant_gridline\nG3PDH_570\nPro25G_onG3PDH570_20bp\nPro25G_onG3PDH570_10Ts\nr60_1\nr60_3\nr60_n9\nr60_a22\nr60_a104\nr60_a107\nr60_a135\nr60_a97\nr60_a20\nr60_n11\nContig45645_RC\nContig44916_RC\nD25272\nJ00129\nContig29982_RC\nContig26811\nD25274\nContig36292\nContig42854\nContig34839\nContig8376_RC\nContig42014_RC\nD49958\nContig25622_RC\nContig13475_RC\nContig40179_RC\nContig27915_RC\nContig44682_RC\nContig35934_RC\nContig29373_RC\nAF155648\nContig46975_RCx""" nbat = ['Contig45645_RC\tNM_022469', 'Contig44916_RC\tNM_080764', 'J00129\tNM_005141', 'Contig29982_RC\tNM_173833', 'D25274\tNM_006908', 'D25274\tNM_018890', 'D25274\tNM_198829', 'D49958\tNM_201591', 'D49958\tNM_005277', 'D49958\tNM_201592', 'Contig13475_RC\tNM_212555', 'Contig40179_RC\tNM_138570', 'Contig27915_RC\tXM_934912', 'Contig27915_RC\tXM_934911', 'Contig27915_RC\tXM_934908', 'Contig27915_RC\tXM_934906', 'Contig27915_RC\tXM_934902', 'Contig27915_RC\tXM_934901', 'Contig27915_RC\tXM_934899', 'Contig27915_RC\tXM_934897', 'Contig27915_RC\tXM_934896', 'Contig27915_RC\tXM_945989', 'Contig27915_RC\tXM_945987', 'Contig27915_RC\tXM_945986', 'Contig27915_RC\tXM_945985', 'Contig27915_RC\tXM_945983', 'Contig27915_RC\tXM_945982', 'Contig27915_RC\tXM_945980', 'Contig27915_RC\tXM_945978', 'Contig27915_RC\tXM_945977'] nmlist = ['XM_929405\tNM_001039615', 'XM_934896\tNM_152513', 'XM_934897\tNM_152513', 'XM_934899\tNM_152513', 'XM_934901\tNM_152513', 'XM_934902\tNM_152513', 'XM_934904\tNM_152513', 'XM_934906\tNM_152513', 'XM_934908\tNM_152513', 'XM_934911\tNM_152513', 'XM_934912\tNM_152513', 'XM_945977\tNM_152513', 'XM_945978\tNM_152513', 'XM_945980\tNM_152513', 'XM_945982\tNM_152513', 'XM_945983\tNM_152513', 'XM_945984\tNM_152513', 'XM_945985\tNM_152513', 'XM_945986\tNM_152513', 'XM_945987\tNM_152513', 'XM_945989\tNM_152513', 'XM_085261\tNM_001039958', 'XM_938609\tNM_001039958', 'XM_373868\tNM_001009931', 'NM_001012239\tNM_173683', 'XM_929314\tNM_001609', 'XM_940521\tNM_001609', 'XM_932741\tNM_001262', 'XM_945305\tNM_001262', 'XM_928890\tNM_152830'] __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From srini_iyyer_bio at yahoo.com Wed Apr 5 19:09:39 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 10:09:39 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists - In-Reply-To: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Message-ID: <20060405170939.55189.qmail@web38108.mail.mud.yahoo.com> Sorry for the very long email. and I my brain is dead to create some related generic snippet. Thus, I shrunk the string and lists into as short as I could. apologies again. srini --- Srinivas Iyyer wrote: > Dear Tutors, > I have a huge string and 2 lists. List A consists > of > tabed elements, where first tab represents entry > somewhere in string(ndat). > ndat has 'Contig27915_RC' and List A [nbat]has > 'Contig27915_RC\tXM_945977'. List B [nmlist]has > elements, for instance ['XM_945977\tNM_152513']. > Now > my task, is to take each element in nbat(listA) > search > in string ndat and nmlist, if found in nmlist, > replace > with its tabed counterpart in ndat string. > > How did I choose to solve: > 1. I could not think in the most smartest way as > said > easily above. Say take element from nbat, see if > modified version of it > available in nmlist, if found replace that modifed > element in string. > > So I chose to take element from listA (nbat), search > in string ndat. If found replace with it tabed > element(Contig27915_RC\tXM_945977 => XM_945977) and > store that in a new list. Now loop over this new > list > for each element check if a new version available in > nmlist. If so replace and print. > > One of the proble is that, Contig27915_RC is seen > associated with many XM entries in nbat. However, > with the above script I could replace only once in > xta. I could not print Contig27915_RC with many XM_ > guys in nbat. How can this be done. > > Finally, this whole process seems to be more > cumbersome to me. Could any one tip me with a new > way > of dealing this 3 way mapping. > > Thanks > > Script: > > xt = '' > for m in nbat: > cols = m.split('\t') > old = cols[0] > new = cols[1] > if ndat.find(old): > xt = ndat.replace(old,new) > > xta = xt.split('\n') > >>> for x in xta: > ... for m in nmlist: > ... cols = m.split('\t') > ... colold = cols[0] > ... colnew = cols[1] > ... if x == colold: > ... print x+'\t'+colnew > ... > XM_945977 NM_152513 > > > -XTA result --- snip--- > Contig25622_RC > Contig13475_RC > Contig40179_RC > XM_945977 <- <- <- ['Contig27915_RC\tXM_945977'] > Contig44682_RC > Contig35934_RC > -------------- > > > > > > > ndat = > """Pro25G\nvariant_gridline\nG3PDH_570\nPro25G_onG3PDH570_20bp\nPro25G_onG3PDH570_10Ts\nr60_1\nr60_3\nr60_n9\nr60_a22\nr60_a104\nr60_a107\nr60_a135\nr60_a97\nr60_a20\nr60_n11\nContig45645_RC\nContig44916_RC\nD25272\nJ00129\nContig29982_RC\nContig26811\nD25274\nContig36292\nContig42854\nContig34839\nContig8376_RC\nContig42014_RC\nD49958\nContig25622_RC\nContig13475_RC\nContig40179_RC\nContig27915_RC\nContig44682_RC\nContig35934_RC\nContig29373_RC\nAF155648\nContig46975_RCx""" > > > nbat = ['Contig45645_RC\tNM_022469', > 'Contig44916_RC\tNM_080764', 'J00129\tNM_005141', > 'Contig29982_RC\tNM_173833', 'D25274\tNM_006908', > 'D25274\tNM_018890', 'D25274\tNM_198829', > 'D49958\tNM_201591', 'D49958\tNM_005277', > 'D49958\tNM_201592', 'Contig13475_RC\tNM_212555', > 'Contig40179_RC\tNM_138570', > 'Contig27915_RC\tXM_934912', > 'Contig27915_RC\tXM_934911', > 'Contig27915_RC\tXM_934908', > 'Contig27915_RC\tXM_934906', > 'Contig27915_RC\tXM_934902', > 'Contig27915_RC\tXM_934901', > 'Contig27915_RC\tXM_934899', > 'Contig27915_RC\tXM_934897', > 'Contig27915_RC\tXM_934896', > 'Contig27915_RC\tXM_945989', > 'Contig27915_RC\tXM_945987', > 'Contig27915_RC\tXM_945986', > 'Contig27915_RC\tXM_945985', > 'Contig27915_RC\tXM_945983', > 'Contig27915_RC\tXM_945982', > 'Contig27915_RC\tXM_945980', > 'Contig27915_RC\tXM_945978', > 'Contig27915_RC\tXM_945977'] > > nmlist = ['XM_929405\tNM_001039615', > 'XM_934896\tNM_152513', 'XM_934897\tNM_152513', > 'XM_934899\tNM_152513', 'XM_934901\tNM_152513', > 'XM_934902\tNM_152513', 'XM_934904\tNM_152513', > 'XM_934906\tNM_152513', 'XM_934908\tNM_152513', > 'XM_934911\tNM_152513', 'XM_934912\tNM_152513', > 'XM_945977\tNM_152513', 'XM_945978\tNM_152513', > 'XM_945980\tNM_152513', 'XM_945982\tNM_152513', > 'XM_945983\tNM_152513', 'XM_945984\tNM_152513', > 'XM_945985\tNM_152513', 'XM_945986\tNM_152513', > 'XM_945987\tNM_152513', 'XM_945989\tNM_152513', > 'XM_085261\tNM_001039958', > 'XM_938609\tNM_001039958', > 'XM_373868\tNM_001009931', > 'NM_001012239\tNM_173683', > 'XM_929314\tNM_001609', 'XM_940521\tNM_001609', > 'XM_932741\tNM_001262', 'XM_945305\tNM_001262', > 'XM_928890\tNM_152830'] > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam > protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From python at venix.com Wed Apr 5 19:32:38 2006 From: python at venix.com (Python) Date: Wed, 05 Apr 2006 13:32:38 -0400 Subject: [Tutor] date conversion In-Reply-To: <4433D939.3030007@tds.net> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433D939.3030007@tds.net> Message-ID: <1144258358.6491.1409.camel@www.venix.com> On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: > Ray Allen wrote: > > I would like Python to convert a date returned by MySQL (2006-04-05) Kent's advice below is of course correct, but I'd bet your variable is already a datetime.date (or mx.DateTime.Date with older Python releases). In that case you'd already be at step 7. When executing your update statement use the args field. cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) You should not have to worry about getting your date into the proper string format for the database SQL syntax. Here's the help from MySQLdb: help(curs.execute) execute(self, query, args=None) method of MySQLdb.cursors.Cursor instance Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any > to a > > user readable format such as 05-Apr-2006 for display and then to convert it > > back to ISO format for update. > > Here's one way: > > In [1]: from datetime import date > > In [2]: data = '2006-04-05' > > Use split() and int() to convert to a list of year, month, day > In [4]: ymd = map(int, data.split('-')) > > In [5]: ymd > Out[5]: [2006, 4, 5] > > Turn it into a date. The * makes the list act like individual parameters. > In [6]: d=date(*ymd) > > In [7]: d > Out[7]: datetime.date(2006, 4, 5) > > See the docs for the time module for info about strftime() format codes > In [8]: d.strftime('%d-%b-%Y') > Out[8]: '05-Apr-2006' > > ISO format is built-in. > In [9]: d.isoformat() > Out[9]: '2006-04-05' > > > For other input formats you might have to use time.strptime() to convert > to a time tuple, then pass the first three elements do date(): > > In [10]: import time > > In [15]: t=time.strptime(data, '%Y-%m-%d') > > In [16]: t > Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) > > In [17]: date(*t[:3]) > Out[17]: datetime.date(2006, 4, 5) > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 -- Lloyd Kvam Venix Corp From kent37 at tds.net Wed Apr 5 19:50:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Apr 2006 13:50:06 -0400 Subject: [Tutor] date conversion In-Reply-To: <1144258358.6491.1409.camel@www.venix.com> References: <004601c658ba$5c4e8950$1fe801a3@sant.ox.ac.uk> <4433D939.3030007@tds.net> <1144258358.6491.1409.camel@www.venix.com> Message-ID: <4434034E.9050200@tds.net> Python wrote: > On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: >> Ray Allen wrote: >>> I would like Python to convert a date returned by MySQL (2006-04-05) > > Kent's advice below is of course correct, but I'd bet your variable is > already a datetime.date (or mx.DateTime.Date with older Python > releases). In that case you'd already be at step 7. > > When executing your update statement use the args field. > > cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) > > > You should not have to worry about getting your date into the proper > string format for the database SQL syntax. Good point. You may well be getting some kind of date object back from MySQL, too, rather than a string. Kent From alan.gauld at freenet.co.uk Wed Apr 5 20:44:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 19:44:19 +0100 Subject: [Tutor] preliminary app design question References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> Message-ID: <020b01c658e0$f2ebdc20$0b01a8c0@xp> > wxPython, but nothing very complex. I want to write a suite of in-house > structural engineering design programs for my own purposes. Sounds emminently pythonic. > - write each program independently as a standalone structural design app > - design and write the programs in such a way that in the future I can > create a project app that would link all these smaller apps together Sounds like creating each app as a class which can be instantiated on demand by the master application would be a possible design option. > - I want the input/output of each program to be easily adaptable and > readable by the 'project app' in the future > - I would want the individual programs to have file formats that are > easily > extensible as I add features to them Almost a definition of what XML is good for. A data format that can be changed without breaking legacy code. > - The 'project app' would have to be extensible in that I could link > smaller apps to it as I create them and it should be able to handle > revisions to these smaller apps as I make them. The class approach coupled to a config XML file would do this. Define a file that looks something like My Foo App Foo MyName AnotherName My Bar App Bar SomeName Then you can read that and use it to construct a menu or set of buttons or toolbar or whatever. > Obviously this won't happen right away, I would likely develop each > small design app as a standalone and then when I've got 3 or 4 done > I would tie them together with the project app. Why wait for 3 or 4 just add them one by one! Its just aase of editing the config file... In fact you could eveb make a config applet to create the xml entries as your first project! > My question before I start is whether or not using an XML format for the > individual file formats is the way to go, I'd say definitely its exactly ythe kind of thing XML is good at. > if I have to anticipate every little thing in the file formats before > hand. The whole point of XML is you can modify the file content and the legacy applications will parse out the bits they need and the new apps will read both the old bits and the new bits. XML is often over-hyped and over-used but for this kind of task it is absolutely perfect IMHO. > I have zero experience with XML at this point, Investigate ElementTree - its much easier than the standard xml dom and sax parsers that ship with Python. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 5 20:48:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 5 Apr 2006 19:48:27 +0100 Subject: [Tutor] Mapping elements in various lists - walking over lists andtheir elements References: <20060405170357.9274.qmail@web38110.mail.mud.yahoo.com> Message-ID: <020f01c658e1$870363b0$0b01a8c0@xp> > One of the proble is that, Contig27915_RC is seen > associated with many XM entries in nbat. However, > with the above script I could replace only once in > xta. I could not print Contig27915_RC with many XM_ > guys in nbat. How can this be done. > > Finally, this whole process seems to be more > cumbersome to me. Could any one tip me with a new way > of dealing this 3 way mapping. A common generic way to deal with this is to construct an intermediate data model such as a dictionary that contains the key element and a list of the keyed items in the file. The list could be the items themselves ort a tuple containing such info as their index (or seek position). Then you can iterate over the data making multiple changes as defined in the data structure. This is somewhat similar to a thread last month, take a look in the archives for more ideas. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From srini_iyyer_bio at yahoo.com Wed Apr 5 21:49:30 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 5 Apr 2006 12:49:30 -0700 (PDT) Subject: [Tutor] Mapping elements in various lists In-Reply-To: <020f01c658e1$870363b0$0b01a8c0@xp> Message-ID: <20060405194930.71006.qmail@web38110.mail.mud.yahoo.com> Hi Alan, Thank you again. I did not give a try by using dictionary power. It works now. Thanks again for tip. -srini. dida = {} for m in nbat: cols = m.split('\t') old = cols[0] dida.setdefault(old,[]).append(cols[1]) lista = ndat.split('\n') result = [] for i in lista: items = dida.get(i) if items is None: result.append(i) else: for x in items: result.append(i+'\t'+x) for x in result: tabs = x.split('\t') if len(tabs)>1: for m in nmlist: cols = m.split('\t') colold = cols[0] colnew = cols[1] if tabs[1] == colold: print x+'\t'+colnew else: print x :-)) RESULT: Contig34839 Contig8376_RC Contig42014_RC Contig25622_RC Contig27915_RC XM_934912 NM_152513 Contig27915_RC XM_934911 NM_152513 Contig27915_RC XM_934908 NM_152513 Contig27915_RC XM_934906 NM_152513 Contig27915_RC XM_934902 NM_152513 Contig27915_RC XM_934901 NM_152513 Contig27915_RC XM_934899 NM_152513 Contig27915_RC XM_934897 NM_152513 Contig27915_RC XM_934896 NM_152513 Contig27915_RC XM_945989 NM_152513 Contig27915_RC XM_945987 NM_152513 Contig27915_RC XM_945986 NM_152513 Contig27915_RC XM_945985 NM_152513 Contig27915_RC XM_945983 NM_152513 Contig27915_RC XM_945982 NM_152513 Contig27915_RC XM_945980 NM_152513 Contig27915_RC XM_945978 NM_152513 Contig27915_RC XM_945977 NM_152513 Contig44682_RC Contig35934_RC Contig29373_RC --- Alan Gauld wrote: > > One of the proble is that, Contig27915_RC is seen > > associated with many XM entries in nbat. However, > > with the above script I could replace only once in > > xta. I could not print Contig27915_RC with many > XM_ > > guys in nbat. How can this be done. > > > > Finally, this whole process seems to be more > > cumbersome to me. Could any one tip me with a new > way > > of dealing this 3 way mapping. > > A common generic way to deal with this is to > construct an > intermediate data model such as a dictionary that > contains > the key element and a list of the keyed items in the > file. > The list could be the items themselves ort a tuple > containing > such info as their index (or seek position). Then > you can iterate > over the data making multiple changes as defined in > the > data structure. > > This is somewhat similar to a thread last month, > take a look > in the archives for more ideas. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From hugonz-lists at h-lab.net Thu Apr 6 00:01:25 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 05 Apr 2006 16:01:25 -0600 Subject: [Tutor] preliminary app design question In-Reply-To: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> Message-ID: <44343E35.9060306@h-lab.net> Richard Querin wrote: > My question before I start is whether or not using an XML format for the > individual file formats is the way to go, and if I have to anticipate > every little thing in the file formats before hand. I don't want to do > this, I would rather like to be able to just add and modify things as I > go with the least amount of hassle along the way. Any ideas on how to > generally approach the file formats? > To quote PJE in http://dirtsimple.org/2004/12/python-is-not-java.html (Python is not JAVA) --- XML is not the answer. It is not even the question. To paraphrase Jamie Zawinski on regular expressions, "Some people, when confronted with a problem, think "I know, I'll use XML." Now they have two problems." --- Now seriously. Are there file formats meant to be used and understood by other programs in principle (we know it is a nice feature, but is it necessary?)? If the answer is yes, then XML may be the solution. Looks like what you are trying to accomplish can be done wrapping functionality into modules, then adding them together (classes, functions, etc) using a GUI master program. Saving complex data structures to files in Python is easy. Let it be pickling or using a Python database, like Kirbybase or Gadfly. If you need to communicate this to other applications, you may use simple extensions like those in XML-RPC(still no XML design and/or parsing). As for anticipating every single thing in the file format, this depends on whether you need to have fancy things like backwards compatibility. I would guess some dynamic data structure that allows for extension (like a dictionary of attributes, where you can always add new attributes) will do. hope this rant helps a bit Hugo > Any suggestions would be greatly appreciated. > > I have zero experience with XML at this point, and very modest > experience with Python/wxPython, but necessity is the mother of > invention and I can learn what I need to know I think. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hugonz-lists at h-lab.net Thu Apr 6 00:03:41 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 05 Apr 2006 16:03:41 -0600 Subject: [Tutor] Question about large numbers of arguments In-Reply-To: References: Message-ID: <44343EBD.4000205@h-lab.net> Dana Robinson wrote: > > Have the functions take large numbers of parameters. > > or > > Create an options class to pass the options around. > > Pythonically, I heard the distinct scream of DICTIONARYYYY in my head. Hugo From falcon3166 at hotmail.com Thu Apr 6 00:58:58 2006 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 5 Apr 2006 16:58:58 -0600 Subject: [Tutor] What's the invalid syntax? Message-ID: Hey all, What's the invalid syntax in the following code? I tried figuring it out by myself, and I couldn't. # This program finds the date of Easter Sunday between the years 1900 & 2099. # By Nathan Pinno # Inspired by Programming and Problem Solving with Java, 1st ed., question 3, page 207. def date(): int year year = int(raw_input("Year please: ")) if (year < 1900 || year > 2099): print year, " is invalid. Please enter a year between 1900 & 2099." else: if (year == 1954 || year == 1981 || year == 2049 || year == 2076): # For the years when the calculation would be 1 week late. int a, b, c, d, e, f a = year % 19 b = year % 4 c = year % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 f = (22 + d + e) - 7 if (f < 31): # To see if the date is in March or April. print "Easter Sunday is March ", f, "." else: print "Easter Sunday is April ", (f-31), "." else: # For all other years. int a, b, c, d, e, f a = year % 19 b = year % 4 c = year % 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 f = (22 + d + e) if (f < 31): # Same as above. print "Easter Sunday is March ", f, "." else: print "Easter Sunday is April ", (f-31), "." date() The editor highlights the word year in the line: int year after I hit okay when this message pops up: Invalid syntax. Thanks in advance, Nathan Pinno Web Surfer's Store http://www.websurfstore.ca MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/79c94f33/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060405/79c94f33/attachment.gif From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 01:26:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Apr 2006 16:26:01 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? In-Reply-To: Message-ID: > What's the invalid syntax in the following code? I tried figuring it out > by myself, and I couldn't. > > The editor highlights the word year in the line: > > int year > > after I hit okay when this message pops up: > > Invalid syntax. Hi Nathan, I would believe the editor. *grin* Python doesn't support saying declarative things like "int year": that's something that just doesn't translate from Java to Python. Just for your understanding: your environment is highlighting the word 'year' only because it really doesn't know what you're trying to do. In this particular case, Python thinks that you might be trying to apply the int() function on year, but in that case, you'd need parens, like: int(year) So that's why it's highlighting year: you're missing parens under this interpretation of the situation. But, as you know, it's completely misunderstanding things. Still, even though the error message is slightly inaccurate, it's correct in the sense that the problem is on that line: you don't predeclare variable or their types in Python. From brian at daviesinc.com Thu Apr 6 01:30:22 2006 From: brian at daviesinc.com (Brian Gustin) Date: Wed, 05 Apr 2006 19:30:22 -0400 Subject: [Tutor] What's the invalid syntax? In-Reply-To: References: Message-ID: <4434530E.5050000@daviesinc.com> define year first I.E. year=0 int(year) or leave the int year out of your code completely - you do not need to typecast - it is set as an integer in the following line. Nathan Pinno wrote: > Hey all, > > What's the invalid syntax in the following code? I tried figuring it out > by myself, and I couldn't. > > # This program finds the date of Easter Sunday between the years 1900 & > 2099. > # By Nathan Pinno > # Inspired by Programming and Problem Solving with Java, 1st ed., > question 3, page 207. > def date(): > int year > year = int(raw_input("Year please: ")) > if (year < 1900 || year > 2099): > print year, " is invalid. Please enter a year between 1900 & 2099." > else: > if (year == 1954 || year == 1981 || year == 2049 || year == > 2076): # For the years when the calculation would be 1 week late. > int a, b, c, d, e, f > a = year % 19 > b = year % 4 > c = year % 7 > d = (19 * a + 24) % 30 > e = (2 * b + 4 * c + 6 * d + 5) % 7 > f = (22 + d + e) - 7 > if (f < 31): # To see if the date is in March or April. > print "Easter Sunday is March ", f, "." > else: > print "Easter Sunday is April ", (f-31), "." > else: # For all other years. > int a, b, c, d, e, f > a = year % 19 > b = year % 4 > c = year % 7 > d = (19 * a + 24) % 30 > e = (2 * b + 4 * c + 6 * d + 5) % 7 > f = (22 + d + e) > if (f < 31): # Same as above. > print "Easter Sunday is March ", f, "." > else: > print "Easter Sunday is April ", (f-31), "." > date() > > The editor highlights the word year in the line: > > int year > > after I hit okay when this message pops up: > > Invalid syntax. > > Thanks in advance, > Nathan Pinno > Web Surfer's Store http://www.websurfstore.ca > > MSN Messenger: falcon3166 at hotmail.com > Yahoo! Messenger: spam_swatter31 > ICQ: 199020705 > !DSPAM:443450a9253311285612896! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:443450a9253311285612896! From rozdaniel at hotmail.com Thu Apr 6 02:22:53 2006 From: rozdaniel at hotmail.com (Ros Daniel) Date: Wed, 05 Apr 2006 20:22:53 -0400 Subject: [Tutor] Urgent question about program debugging Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/04f325b0/attachment-0001.htm From blackspeckpotato at frontiernet.net Thu Apr 6 03:46:48 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 18:46:48 -0700 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <005501c6591b$f847ec50$01fea8c0@silver> Hi, I'm a Python newbie, but I went over the code, and I think the problem is in choice number 2. ### for father_son in father_son: print father_son ### father_son becomes a string here. Regards, Charles B. ----- Original Message ----- From: Ros Daniel To: tutor at python.org Sent: Wednesday, April 05, 2006 5:22 PM Subject: [Tutor] Urgent question about program debugging I just created a "who's your daddy?" program--one of the challenges in the michael dawson book. It was working well, and I tested all the different instructions, and then for some reason, it stopped working. Specifically, whenever I enter the name of a father, it tells me it doesn't exist, although it does, because when you list all the fathers, you can see it exists, and I set it up in the dictionary. It may be that I've missed something. I know I saved this program so many times, maybe I changed something without realising it, although I've been through every line of code numerous times. I don't know how to use the IDLE debugger, which could be part of my problem. The help file doesn't seem to help. Here's the code: # This program lets the user enter the first and last name of a male # and produces the name of his son. The user will also be able # to add, replace, and delete son-father pairs. father_son = {"Kirk Douglas" : "Michael Douglas", "James Brolin" : "Josh Brolin", "Marlon Brando" : "Christian Brando", "George Best" : "Calum Best", "David Beckham" : "Brooklyn Beckham", "Bob Dylan" : "Jakob Dylan"} choice = None while choice != "0": print \ """ Welcome to Who's Your Daddy? A mini database of fathers and sons. When entering names, please use both the first name and the last name. 0 - Exit 1 - List all Father-Son Pairs 2 - List all Fathers 3 - Look Up Father-Son Pairs 4 - Add a Father-Son Pair 5 - Delete a Father-Son Pair 6 - Replace the Son of a Father-Son Pair 7 - Replace a Father-Son Pair """ choice = raw_input("Choice: ") print # exit program if choice == "0": print "\nGoodbye." # list all father-son pairs elif choice == "1": print "\nLIST OF ALL FATHER-SON PAIRS\n" print father_son # list all fathers elif choice == "2": print "LIST OF ALL FATHERS\n" for father_son in father_son: print father_son # look up father-son pairs elif choice == "3": term = raw_input("Type in the name of the father of this pair: ") if term in father_son: definition = father_son[term] print term, "is the father of", definition else: print "\nSorry,", term, "doesn't exist." # add a father-son pair elif choice == "4": term = raw_input("Type in the name of the father you want to add: ") if term not in father_son: definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "\nThank you. Your new father-son pair has been added." print term, "is the father of", definition else: print term, "already exists in the database. Try updating the entry." # delete a father-son pair elif choice == "5": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to delete: ") if term in father_son: definition = father_son[term] del father_son[term] print term, "and his son", definition, "have been removed from the database." else: print "\nI don't recognise this name. Try adding it as an entry." # replace the son of a father-son pair elif choice == "6": term = raw_input("Type in the name of the father whose son you want \ to replace: ") if term in father_son: definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "\nThank you. Your change has been made.", term, "is now \ the father of", definition else: print "\nSorry, that name doesn't exist." # replace a father-son pair elif choice == "7": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to replace: ") if term in father_son: term = raw_input("Type in name of this 'replacement' father: ") definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "A new father-son pair has been added.", term, "is the \ father of", definition else: print "\nSorry, but", choice, "isn't a valid choice." raw_input("\n\nPress the enter key to exit") ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/94ce10e6/attachment.html From blackspeckpotato at frontiernet.net Thu Apr 6 04:43:09 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 19:43:09 -0700 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <008a01c65923$d7328ea0$01fea8c0@silver> Hi Ros, I placed two new lines of code in your choices 2 and 7. The new lines have comments trailing them. In choice 7, you forgot to delete the previous father_son pair (as you had done in choice 5). Regards, Charles ####### # list all fathers elif choice == "2": print "LIST OF ALL FATHERS\n" print father_son.keys() # print fathers - their the keys # replace a father-son pair elif choice == "7": term = raw_input("Type in the name of the father which corresponds \ to the father-son pair you want to replace: ") if term in father_son: del father_son[term] # delete previous father_son pair term = raw_input("Type in name of this 'replacement' father: ") definition = raw_input("Type in the name of this person's son: ") father_son[term] = definition print "A new father-son pair has been added.", term, "is the \ father of", definition else: print "\nSorry, but", choice, "isn't a valid choice." -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060405/74a25874/attachment.htm From justin.mailinglists at gmail.com Thu Apr 6 05:23:29 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Thu, 6 Apr 2006 11:23:29 +0800 Subject: [Tutor] regular expressions - backslashes Message-ID: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> a colleague demonstrated a problem he had with regular expressions >>> apppath = os.path.abspath(os.curdir) >>> apppath 'C:\\napp_and_author_query\\napp_and_author_query\\a b c d' >>> template = r'\files' >>> template '\\files' >>> re.sub(r'(?i)', apppath, template) 'C:\napp_and_author_query\napp_and_author_query\x07 b c d\\files' >>> print re.sub(r'(?i)', apppath, template) C: app_and_author_query app_and_author_query b c d\files >>> for this particular use-case, I myself prefer using string formatting but I still would like to know what's wrong with the above usage of re.sub Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 From keosophon at khmeros.info Thu Apr 6 05:22:07 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Thu, 6 Apr 2006 10:22:07 +0700 Subject: [Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8') Message-ID: <200604061022.07601.keosophon@khmeros.info> Hi, Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both case I used: if isinstance(u,str): print "just string" else: print "unicode" the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and u=str.decode('utf-8') are the same. How about the processing inside? is it same? Phon From titvirak at khmeros.info Thu Apr 6 06:23:10 2006 From: titvirak at khmeros.info (=?UTF-8?B?4Z6R4Z634Z6P4Z+S4Z6Z4Z6c4Z634Z6a4Z+I?=) Date: Thu, 06 Apr 2006 11:23:10 +0700 Subject: [Tutor] OR operator? Message-ID: <443497AE.9050107@khmeros.info> Hi, I'm trying with this operator, could it possible? fruit1 = 'apple' fruit2 = 'orange' fruits = fruit1 or fruit2 is 'orange' = fruits ? From blackspeckpotato at frontiernet.net Thu Apr 6 07:50:30 2006 From: blackspeckpotato at frontiernet.net (Charles Bartley) Date: Wed, 5 Apr 2006 22:50:30 -0700 Subject: [Tutor] OR operator? References: <443497AE.9050107@khmeros.info> Message-ID: <00b501c6593e$036ff0b0$01fea8c0@silver> > > I'm trying with this operator, could it possible? > > fruit1 = 'apple' > fruit2 = 'orange' > > fruits = fruit1 or fruit2 > > is 'orange' = fruits ? Maybe this: ####### fruit1 = 'apple' fruit2 = 'orange' fruits = [fruit1, fruit2] print 'orange' in fruits # prints the boolean result of 'orange in fruits' ####### Regards, Charles B. From alan.gauld at freenet.co.uk Thu Apr 6 09:40:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 08:40:02 +0100 Subject: [Tutor] What's the invalid syntax? References: Message-ID: <025001c6594d$518396d0$0b01a8c0@xp> > What's the invalid syntax in the following code? I tried figuring it out > by > myself, and I couldn't. > > # Inspired by Programming and Problem Solving with Java, 1st ed., question > def date(): > int year > year = int(raw_input("Year please: ")) > The editor highlights the word year in the line: > > int year That'd be because int year is invalid syntax in Python. You don't need to decalre variables prior to use in Python as you do in Java. Also names in Python are not typed. Alan G From alan.gauld at freenet.co.uk Thu Apr 6 09:48:49 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 08:48:49 +0100 Subject: [Tutor] Urgent question about program debugging References: Message-ID: <025501c6594e$8d18ed20$0b01a8c0@xp> > father_son = {"Kirk Douglas" : "Michael Douglas", > "James Brolin" : "Josh Brolin", > "Bob Dylan" : "Jakob Dylan"} > > elif choice == "2": > print "LIST OF ALL FATHERS\n" > for father_son in father_son: > print father_son You are replacing the reference to the dictionary with a single key entry here. You probably intended for father in father_son: print father > # look up father-son pairs > elif choice == "3": > term = raw_input("Type in the name of the father of this pair: ") > if term in father_son: father_son is no longer the dictionary but refers to the last father! It should work if you don't list the fathers first! :-) > elif choice == "4": > term = raw_input("Type in the name of the father you want to add: > ") > if term not in father_son: > definition = raw_input("Type in the name of this person's son: > ") > father_son[term] = definition As a wee point, its usually considered a bad idea to name variables after their syntax meaning rather than their meaning in the program. Thus this would be better written: father = raw_input(...) if father not in father_son: son = raw_input(...) father_son[father] = son HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Apr 6 11:54:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 05:54:41 -0400 Subject: [Tutor] regular expressions - backslashes In-Reply-To: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> References: <3c6718980604052023o47368cd5m31d87d9af0bbe01@mail.gmail.com> Message-ID: <4434E561.3050800@tds.net> Justin Ezequiel wrote: > a colleague demonstrated a problem he had with regular expressions > >>>> apppath = os.path.abspath(os.curdir) >>>> apppath > 'C:\\napp_and_author_query\\napp_and_author_query\\a b c d' >>>> template = r'\files' >>>> template > '\\files' >>>> re.sub(r'(?i)', apppath, template) > 'C:\napp_and_author_query\napp_and_author_query\x07 b c d\\files' >>>> print re.sub(r'(?i)', apppath, template) > C: > app_and_author_query > app_and_author_query b c d\files The problem is that the re engine itself is interpreting the backslashes in the replacement pattern. Here is a simpler example: In [34]: import re In [35]: text = 'abcabc' With a single slash you get a newline even though the slash is a literal in the replacement string: In [36]: re.sub('a', r'\n', text) Out[36]: '\nbc\nbc' So if you want a literal \ in your replacement text you have to escape the \, even in a raw string: In [37]: re.sub('a', r'\\n', text) Out[37]: '\\nbc\\nbc' If it isn't a raw string, you need four \! In [39]: re.sub('a', '\\\\n', text) Out[39]: '\\nbc\\nbc' You can use re.escape() to introduce the needed slashes: In [38]: re.sub('a', re.escape(r'\n'), text) Out[38]: '\\nbc\\nbc' Kent From kent37 at tds.net Thu Apr 6 12:01:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 06:01:58 -0400 Subject: [Tutor] testing u=unicode(str, 'utf-8') and u = str.decode('utf-8') In-Reply-To: <200604061022.07601.keosophon@khmeros.info> References: <200604061022.07601.keosophon@khmeros.info> Message-ID: <4434E716.7060906@tds.net> Keo Sophon wrote: > Hi, > > Today i tested u=unicode(str,'utf-8') and u=str.decode('utf-8'). Then in both > case I used: > > if isinstance(u,str): > print "just string" > else: > print "unicode" > > the result of both case are "unicode". So it seems u=unicode(str,'utf-8') and > u=str.decode('utf-8') are the same. How about the processing inside? is it > same? I don't know the details of how they are implemented but they do have the same result. As far as I know you can use whichever form you find more readable. There are a few special-purpose encodings for which the result of decode() is a byte string rather than a unicode string; for these encodings, you have to use str.decode(). For example: In [42]: 'abc'.decode('string_escape') Out[42]: 'abc' In [44]: unicode('abc', 'string_escape') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: decoder did not return an unicode object (type=str) Kent From kaushalshriyan at gmail.com Thu Apr 6 12:36:11 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 6 Apr 2006 16:06:11 +0530 Subject: [Tutor] Logical Operators Message-ID: <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23@mail.gmail.com> Hi I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm about Logical operators I didnot understood >>> x = 5 >>> x and 1 1 >>> y = 0 >>> y and 1 0 How 5 and 1 means 1 and 0 and 1 means 0 Thanks Regards Kaushal From rfquerin at gmail.com Thu Apr 6 12:39:31 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 6 Apr 2006 06:39:31 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <020b01c658e0$f2ebdc20$0b01a8c0@xp> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> Message-ID: <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> On 4/5/06, Alan Gauld wrote: > > > Sounds like creating each app as a class which can be instantiated on > demand by the master application would be a possible design option. I guess writing the master program (or some simplified version of it) would be required from the start in order to make launching the separate design programs possible (for testing, debugging etc..). The class approach coupled to a config XML file would do this. > Define a file that looks something like > > > > My Foo App > Foo > > > > MyName > > > > AnotherName > > > > > > My Bar App > Bar > > > > SomeName > > > > > > > Then you can read that and use it to construct a menu or set of buttons > or toolbar or whatever. So for the master program this makes sense. However, what about the input/output data of each individual design app. All the different programs will share some common data but each one may have different components, and some will be large arrays of numbers, is XML still applicable for that type of file data? I think my first task will likely be settling on what I need each component of the system to do and how they will interact. It's becoming more complex the more I discuss it.. ;) > Obviously this won't happen right away, I would likely develop each > > small design app as a standalone and then when I've got 3 or 4 done > > I would tie them together with the project app. > > Why wait for 3 or 4 just add them one by one! Its just aase of editing > the config file... In fact you could eveb make a config applet to create > the xml entries as your first project! Ease myself into it. ;) Investigate ElementTree - its much easier than the standard xml dom > and sax parsers that ship with Python. I have the documentation printed out for study. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060406/e07c327b/attachment.html From rfquerin at gmail.com Thu Apr 6 12:42:04 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 6 Apr 2006 06:42:04 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <44343E35.9060306@h-lab.net> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <44343E35.9060306@h-lab.net> Message-ID: <7d81675b0604060342h27710530p71425d6a17d18746@mail.gmail.com> On 4/5/06, Hugo Gonz?lez Monteverde wrote: > > > Now seriously. Are there file formats meant to be used and understood by > other programs in principle (we know it is a nice feature, but is it > necessary?)? There will be input data and output results from program A that may be utilized by program B. If the two independent designs are linked to the same project then they will share this data, if they aren't part of the same project they wouldn't. I would assume that would mean that the file formats of all the design programs would have to be readable and changeable by the master program. Not sure if this necessitates XML, but to me it seems like standardizing the formats will make things simpler. hope this rant helps a bit It did. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060406/7a42538e/attachment.htm From alan.gauld at freenet.co.uk Thu Apr 6 13:36:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 12:36:06 +0100 Subject: [Tutor] preliminary app design question References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> Message-ID: <027901c6596e$4b89bb30$0b01a8c0@xp> >> The class approach coupled to a config XML file would do this. > > Define a file that looks something like >> >> >> >> My Foo App >> >> >> MyName >> >So for the master program this makes sense. However, what about the >input/output data of each individual design app. OK The params can be used to point at some common database or file. > will share some common data but each one may have different > components, and some will be large arrays of numbers, is XML > till applicable for that type of file data? Personally I wouldn't use XML for content data which is repeated in large volume - the overheads are too high. This is where I'd consider using a shared class or dictionary to define the data and then pickle and/or shelve to save instances. Either that or go with a lightweight database such as SqlLite. > I think my first task will likely be settling on what I need > each component of the system to do and how they will interact. There are two sepoarate areas of concern. 1) The master app and its applet launching mechanism 2) The common data between applets The solutions are likely to be different. For the common data look at each common class and its responsibilities. What should that class be able to provide in the way of sertvices for the applets to consume. The applets then become a fairly simple set of scenarios stitching together the services provided by the shared classes. Without more specific knowledge of your problem domain I can't be more specififc but this is afaily common approach used in Financial and Customer Handling applications for example. > It's becoming more complex the more I discuss it.. ;) They always do! Sometimes its better to just make a start on the bits you think you do understand and see how it hangs together. A very rough master application laiunching a single applet using a minimal set of shared data would be a good goal for starters. HTH, Alan G. From alan.gauld at freenet.co.uk Thu Apr 6 13:46:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 12:46:37 +0100 Subject: [Tutor] OR operator? References: <443497AE.9050107@khmeros.info> Message-ID: <028601c6596f$c382a9c0$0b01a8c0@xp> > I'm trying with this operator, could it possible? > > fruit1 = 'apple' > fruit2 = 'orange' > > fruits = fruit1 or fruit2 > > is 'orange' = fruits ? Why not just try it at the python prompt?! And you would find that no, fruits = 'apple' (The order is because fruits is a name which references a value. orange is a value so cannot reference anything else, so 'orange' = fruits is actually an impossible concept!). The reason for the result is the way Python evaluates 'or' expressions. Python considers non-empty strings (like 'apple') to be true. Python also evaluates an 'or' by evaluating the first element and, if it is true then it doesn't bother evaluating the second element since the 'or' must be true if the first part is true. This is known as "short-circuit evaluation". If you did fruit3 = "" fruits = fruit3 or fruit2 this time fruits would equal 'orange' because the first item was an empty string which Python considers to be false so it had to evaluate the second item. Finally, it could be argued that the 'or' should return 'true' or 'false but because Python considers values to be either true or false it just returns the value. I suspect that if boolean values had been in Python at the beginning the result would be different but they weren't and it isn't! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Apr 6 14:31:52 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 08:31:52 -0400 Subject: [Tutor] preliminary app design question In-Reply-To: <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> References: <7d81675b0604050816v4f0ee8e4y599ccd91365f0a1a@mail.gmail.com> <020b01c658e0$f2ebdc20$0b01a8c0@xp> <7d81675b0604060339k13a975a7lf11511b2c41d765b@mail.gmail.com> Message-ID: <44350A38.2000604@tds.net> Richard Querin wrote: > > On 4/5/06, *Alan Gauld* > wrote: > > Sounds like creating each app as a class which can be instantiated on > demand by the master application would be a possible design option. > > I guess writing the master program (or some simplified version of it) > would be required from the start in order to make launching the separate > design programs possible (for testing, debugging etc..). Not really. You just have to write the separate design programs in a way that they can be integrated with a larger whole. This means, write the functional part of the program with an API that can be easily be invoked to make it do the work. The API can be class-based, as Alan suggests, or standalone functions, whichever is simpler. Then for a standalone program you can write a main() function that works from the command line or a GUI. For your master program you can invoke the API from whatever framework you come up with. > > The class approach coupled to a config XML file would do this. > Define a file that looks something like > > > Then you can read that and use it to construct a menu or set of buttons > or toolbar or whatever. XML is obviously a bit controversial, you have several contrasting opinions already. I have successfully used XML and a DOM data model in several applications and I would do it again. For configuration I would look at something simpler, possibly a Python module that configures other modules or maybe a plug-in mechanism. Or possibly you just write your master program to call the subprograms as libraries without any dynamic configuration at all - just hard-code it. I should note that my experience with XML data models is from using the excellent dom4j library with Jython. I haven't found any Python XML packages available for Windows that have the same combination of power and ease-of-use as dom4j. > I think my first task will likely be settling on what I need each > component of the system to do and how they will interact. It's becoming > more complex the more I discuss it.. ;) I would say your first task is to write some code that does something useful. Then write some more and make them work together. Repeat as necessary. Don't try to figure it all out up front. > > > Obviously this won't happen right away, I would likely develop each > > small design app as a standalone and then when I've got 3 or 4 done > > I would tie them together with the project app. When you have two standalone apps then you can reasonably think about how to tie them together. Before then too soon - you don't know what the standalone apps are going to look like until you make them. After you have three is getting to be too late - when you integrate the apps you will discover things you want to change about them to make the integration easier, and that will inform the way you create the next app. Don't leave out the unit tests - when you want to change your apps for integration (or any other reason) the unit tests will give you confidence that you haven't broken anything. Also writing the apps to be testable will help make them usable from another app. Kent From kaushalshriyan at gmail.com Thu Apr 6 15:06:53 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 6 Apr 2006 18:36:53 +0530 Subject: [Tutor] Logical Operaor Message-ID: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Hi I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm about Logical operators I didnot understood >>> x = 5 >>> x and 1 1 >>> y = 0 >>> y and 1 0 How 5 and 1 means 1 and 0 and 1 means 0 Thanks Regards Kaushal From jasonkeen at gmail.com Thu Apr 6 15:40:11 2006 From: jasonkeen at gmail.com (Jason Keen) Date: Thu, 6 Apr 2006 09:40:11 -0400 Subject: [Tutor] Logical Operaor In-Reply-To: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> References: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Message-ID: <889f4f6f0604060640v1346e08al3dfc7a993af24847@mail.gmail.com> In python, any nonzero number is considered to mean "True". Zero is considered to be "False". The "and" logical operation evaluates to "True" only if both terms are true. On 4/6/06, Kaushal Shriyan wrote: > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>> x = 5 > >>> x and 1 > 1 > >>> y = 0 > >>> y and 1 > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From RPhillips at engineer.co.summit.oh.us Thu Apr 6 16:15:03 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Thu, 06 Apr 2006 10:15:03 -0400 Subject: [Tutor] preliminary app design question Message-ID: You might also consider JSON (http://www.json.org), which is generally lighter weight than XML, fairly human-readable, and useful in several languages (most, anymore) . Python, Javascript, and ECMAScript use it natively through Eval(), if you don't have security concerns; or through a wrapper if security is an issue. Python's pprint module will be a help if you go that route. I find it useful in development, so even if I am going to use some other storage, I'll leave any toJSON() and fromJSON() functions I write in place, anyway. Ron From alan.gauld at freenet.co.uk Thu Apr 6 17:53:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 6 Apr 2006 16:53:06 +0100 Subject: [Tutor] Logical Operators References: <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23@mail.gmail.com> Message-ID: <02ab01c65992$4b8e6bc0$0b01a8c0@xp> > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > You might find the functional programming topic in my tutorial interesting for a comparison. Look at the subsection "Short Circuit Evaluation" for some relevant examples. > I did not understood >>> x = 5 >>> x and 1 >1 >>> y = 0 >>> y and 1 >0 > > How 5 and 1 means 1 and 0 and 1 means 0 In Python any non zero value is considered True. So 5 and 1 are two true values and True and True = True whereas 0 and 1 means: False and True = False (ie zero) Are you familiar with Trutrh tables and the concepts of Boolean Logic? If not you may need some further explanation. If so a reasonable explanation appears on Wikipedia: http://en.wikipedia.org/wiki/Truth_table HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Barry.Carroll at psc.com Thu Apr 6 18:44:26 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 6 Apr 2006 09:44:26 -0700 Subject: [Tutor] Logical Operators Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3641@eugsrv400.psc.pscnet.com> Greetings, Kaushal: There are two topics to understand here: 1. what "TRUE" and "FALSE" mean in Python, and 2. how Python evaluates "X and Y". The tutorial "Instant Python" by Magnus Lie Hetland has good, short descriptions of these two topics, so I'll borrow from it. You can find the document at: http://www.hetland.org/python/instant-python.php 1. "All values in Python can be used as logic values. Some of the more "empty" ones, like [], 0, "" and None represent logical falsity, while most other values (like [0], 1 or "Hello, world") represent logical truth." In your examples, 5 and 1 are both considered 'TRUE', while 0, of course, is considered "FALSE". 2. "Now, logical expressions like a and b are evaluated like this: First, check if a is true. If it is not, then simply return it. If it is, then simply return b (which will represent the truth value of the expression.) The corresponding logic for a or b is: If a is true, then return it. If it isn't, then return b." Python evaluates your example expressions like this: a. Get the first sub-expression. x Get the value of x. 5 Is 5 a "TRUE" value? Yes Since the operator is "and", get the second sub-expression. 1 Is 1 a "TRUE" value? Yes Return it. 1 b. Get the first sub-expression. y Get the value of y. 0 Is 0 a "TRUE" value? No Since the operator is "and", STOP and return the sub-expression. 0 Does this help? Try this: change the 'and' operator in your examples to 'or'. What would the return value be now? 5 or 1 = ??? 0 or 1 = ??? Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Thu, 6 Apr 2006 16:06:11 +0530 > From: "Kaushal Shriyan" > Subject: [Tutor] Logical Operators > To: tutor at python.org > Message-ID: > <6b16fb4c0604060336p74dbe676jb88838d0d9aa5b23 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>> x = 5 > >>> x and 1 > 1 > >>> y = 0 > >>> y and 1 > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal From tiagosaboga at terra.com.br Thu Apr 6 20:08:26 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 15:08:26 -0300 Subject: [Tutor] mysql store directory information Message-ID: <200604061508.26844.tiagosaboga@terra.com.br> Hi! As a first part of a project, I need to store a directory tree in a mysql db. I'm wondering if there is a canonical way of doing that. I don't know if it's an appropriate question for this list, but I think it's not only a choice of db design, but also a choice of appropriate python tools. My first approach is a table with the following columns: id - path - file name - size I'm starting to code it, and I'd like to know if you have a better suggestion... thanks. Tiago. From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 20:41:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 11:41:39 -0700 (PDT) Subject: [Tutor] mysql store directory information In-Reply-To: <200604061508.26844.tiagosaboga@terra.com.br> Message-ID: On Thu, 6 Apr 2006, Tiago Saboga wrote: > As a first part of a project, I need to store a directory tree in a > mysql db. I'm wondering if there is a canonical way of doing that. I > don't know if it's an appropriate question for this list, but I think > it's not only a choice of db design, but also a choice of appropriate > python tools. Hi Tiago, What are the interesting features of a directory? You might want to first model what you want, and then figure out an appropriate database table structure to represent that model. > My first approach is a table with the following columns: > id - path - file name - size So maybe we can say that a Directory can be modeled as: ###### class Directory: def __init__(self, id, path, file_name, size): self.id = id self.path = path self.file_name = file_name self.size = size ###### But why will you want to store this structure in the database, if it's already available on disk? Why not query the directory directly? > I'm starting to code it, and I'd like to know if you have a better > suggestion... I'd flesh out a few more of the requirements first; the requirement to store the directory in the database is slightly vague, so you probably will want to ask more questions about what the problem's really about. You might find something like SQLObject useful: http://www.sqlobject.org/ http://www.turbogears.org/about/sqlobject.html where you go fairly directly from data model to SQL table structure with SQLObject providing the default mapping strategy. From broek at cc.umanitoba.ca Thu Apr 6 02:51:33 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 05 Apr 2006 19:51:33 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <442EEADD.7040705@gmail.com> References: <442DCA10.9020104@cc.umanitoba.ca> <442EEADD.7040705@gmail.com> Message-ID: <44346615.5030205@cc.umanitoba.ca> Orri Ganel said unto the world upon 01/04/06 03:04 PM: > Brian van den Broek wrote: >> Then, the output is like so: >> >> >>> atoms = ["a","b","c"] >> >>> tvas = tva_dict_maker(atoms) >> >>> display_tvas(tvas) >> a:True b:True c:True >> a:True b:True c:False >> a:True b:False c:True >> a:True b:False c:False >> a:False b:True c:True >> a:False b:True c:False >> a:False b:False c:True >> a:False b:False c:False >> >>> > What this shouts immediately to me, at least, is binary numbers and > bool(). Just use your favorite binary conversion recipe, and count down > from int(len(atoms)*"1",2), converting as you go. And then you take the > boolean value of each digit of the binary number. If you need help, let > me know as I've completed a working model. > > HTH, > Orri Hi Orri, thanks for the suggestion, and apologies for the delayed response. I absolutely agree that the problem is connected to binary representations of integers as you suggest. The problem -- given my needs -- with your suggested approach is in "use your favo[u*]rite binary conversion recipe". I want my code to be stand alone and I feel fairly safe in asserting that if I implemented your suggestion in a self-contained chunk of code, I'd end up with something more complex than the code I originally posted. In effect, my original code exploited the same principle, without actually going through the binary representation. I am of course open to the possibility that my suspicion is ill-grounded ;-) But, thanks! Best, Brian vdB [*] I'm Canadian, eh! ;-) From broek at cc.umanitoba.ca Thu Apr 6 02:40:14 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 05 Apr 2006 19:40:14 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: References: Message-ID: <4434636E.5020308@cc.umanitoba.ca> Danny Yoo said unto the world upon 31/03/06 08:27 PM: > >>Then, the output is like so: >> >> >>> atoms = ["a","b","c"] >> >>> tvas = tva_dict_maker(atoms) >> >>> display_tvas(tvas) >>a:True b:True c:True >>a:True b:True c:False >>a:True b:False c:True >>a:True b:False c:False >>a:False b:True c:True >>a:False b:True c:False >>a:False b:False c:True >>a:False b:False c:False > > > Hi Brian, > > We might be able to take advantage of the recursive nature of this > problem. > > I'll sketch out the idea and try to fight the temptation to write it out > in full. *grin* If you haven't encountered recursion before, please shout > out and ask for more details. Hi Danny and all, thanks for the response and my apologies for the delayed reply. (No internet at home and end of academic term death-march conspired :-) My first thought about how to tackle the problem was indeed to do it recursively. I got bogged down and ended up with the alternate approach I posted in the original post. Your post got me to take another bash and I obtained a recursive solution. But, subject to the caveat that my recursive solution might well be non-optimal, the non-recursive approach seems a bit better to me. Opinions welcome :-) My recursive solution: def recursive_tva_dict_maker(atoms, recursed=False): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = recursive_tva_dict_maker(atoms[1:], True) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp if not recursed: # if test seemed cheaper than pointless sorting tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas My non-recursive solution: def tva_dict_maker(atoms): tvas = [] val = False for k in range(2**len(atoms)): tvas.append(dict()) for i in range(len(atoms)): key = atoms[i] for j in range(2**len(atoms)): if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: val = not val tvas[j][key]=val return tvas The two functions have identical output. I don't much care about time or resources, as atoms will in practice never be more than 4 or 5 items long. (So, the recursive solution could be simplified by getting rid of the if guard on the sorting. That the ultimate output be so sorted is essential, however.) I'm more concerned with style and clarity. Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 23:38:24 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 14:38:24 -0700 (PDT) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: <4434636E.5020308@cc.umanitoba.ca> Message-ID: > Your post got me to take another bash and I obtained a recursive > solution. But, subject to the caveat that my recursive solution might > well be non-optimal, the non-recursive approach seems a bit better to > me. Opinions welcome :-) > > My recursive solution: > > def recursive_tva_dict_maker(atoms, recursed=False): > > tvas = [{atoms[0]:True}, {atoms[0]:False}] > > if atoms[1:]: > temp = [] > rest = recursive_tva_dict_maker(atoms[1:], True) > > for r in rest: > for tva in tvas: > new = tva.copy() > new.update(r) > temp.append(new) > tvas = temp > > if not recursed: # if test seemed cheaper than pointless sorting > tvas.sort(key = lambda x: [x[y] for y in sorted(x)], > reverse=True) > > return tvas Hi Brian, One way to get rid of the 'recursed' flag is to refactor slightly, and break out the sorting in another helper function, like this: ################################################################## def tva_dict_maker(atoms): tvas = tiva_helper(atoms) tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas def tva_helper(atoms): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = recursive_tva_dict_maker(atoms[1:]) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp return tvas ################################################################## This way, tva_helper() doesn't have to care about sorting, since tva_dict_maker() will do it instead. Here's a slightly wordier version of what you have, but taken to a far extreme. *grin* ################################################################## ## In the comments below, an "assignment" is a dictionary ## that maps atoms to booleans. def make_truth_table(atoms): """make_truth_table: (listof atoms) -> (listof assignment) Builds a small truth table of all possibilities.""" if atoms == []: ## the empty case is one with the "empty" assignment! return [{}] else: sub_assignments = make_truth_table(atoms[1:]) return (extend_all(sub_assignments, {atoms[0] : True}) + extend_all(sub_assignments, {atoms[0] : False})) def extend_all(assignments, extension): """extend_all: (listof assignment) assignment -> (listof assignment) Takes each assignment in the list of assignments, and enhances it with the extension. """ return [extend_assignment(single, extension) for single in assignments] def extend_assignment(assignment, extension): """extend_assignment: assignment assignment -> assignment Takes the assignment and creates a new one that extends the first with the extension.""" extended = assignment.copy() extended.update(extension) return extended ################################################################## As you can tell, I really like helper functions. *grin* I've tried to document as best I can to make it clearer how the recursive approach breaks things down. [non-recursive code cut] > The two functions have identical output. I don't much care about time or > resources, as atoms will in practice never be more than 4 or 5 items > long. (So, the recursive solution could be simplified by getting rid of > the if guard on the sorting. That the ultimate output be so sorted is > essential, however.) > > I'm more concerned with style and clarity. Yes, I agree that the readability of the code is primary. Understandng the recursive approach depends on the reader's comfort with recursive functions, and the non-recursive code depends on the reader's comfort with arithmetic operators. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Apr 6 23:56:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Apr 2006 14:56:16 -0700 (PDT) Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: Message-ID: > One way to get rid of the 'recursed' flag is to refactor slightly, and > break out the sorting in another helper function, like this: > > ################################################################## > def tva_dict_maker(atoms): > tvas = tiva_helper(atoms) ^^^^^^^^^^^ > tvas.sort(key = lambda x: [x[y] for y in sorted(x)], > reverse=True) > return tvas > > def tva_helper(atoms): > tvas = [{atoms[0]:True}, {atoms[0]:False}] > if atoms[1:]: > temp = [] > rest = recursive_tva_dict_maker(atoms[1:]) ^^^^^^^^^^^^^^^^^^^^^^^^ > for r in rest: > for tva in tvas: > new = tva.copy() > new.update(r) > temp.append(new) > tvas = temp > return tvas > ################################################################## Hi Brian, Gaaa. When I renamed 'recursive_tva_dict_maker' to tva_helper, I forgot to rename the recursive call too, and I left a few misspellings in there too! My apologies: I must must test code before posting... *sigh* The code above should have been: ######################################################## def tva_dict_maker(atoms): tvas = tva_helper(atoms) tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas def tva_helper(atoms): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = tva_helper(atoms[1:]) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp return tvas ######################################################## From jramakrishnan at neuropace.com Fri Apr 7 02:16:04 2006 From: jramakrishnan at neuropace.com (Janesh Ramakrishnan) Date: Thu, 6 Apr 2006 17:16:04 -0700 Subject: [Tutor] Tutor Digest, Vol 25, Issue 83 Message-ID: <405EDF2FA0855E43B27EA6DAFA1C78CEE66D42@laguna.neuropace.com> Hi Kent: Thanks for your response. The Grep function does a really good job of searching across .py files in a directory or subdirectories for the specific keyword/string. In the PythonWin interpreter 2.1, Go to File -> New -> Grep and the search string can be entered. It is useful in searching strings across multiple files, especially in large projects. ~Janesh Message: 1 Date: Thu, 30 Mar 2006 21:22:39 -0500 From: Kent Johnson Subject: Re: [Tutor] Searching across .Py files for a particular string/ character Cc: tutor at python.org Message-ID: <442C926F.3080007 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Janesh Ramakrishnan wrote: > Hi Folks, > > I was wondering what would be the best way to look up a string across > different files in the Python interpreter (PythonWin 2.4). The find function only finds files within currently open files. If I have a folder of .py scripts and need to look up a specific keyword or string among all these files within the project folder, is there any method that you'd recommend? I would do that in my editor, probably. But Python can get a list of files in a directory with os.listdir(). Loop over the files, use os.path.join() to make a full path, open the file, read the data, look for the string in the data. Kent From broek at cc.umanitoba.ca Fri Apr 7 02:19:42 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 06 Apr 2006 19:19:42 -0500 Subject: [Tutor] Logical Operaor In-Reply-To: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> References: <6b16fb4c0604060606p5ce8c00fv25b21f2d800fe09e@mail.gmail.com> Message-ID: <4435B01E.8020607@cc.umanitoba.ca> Kaushal Shriyan said unto the world upon 06/04/06 08:06 AM: > Hi > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm > about Logical operators > > I didnot understood > > >>>> x = 5 >>>> x and 1 > > 1 > >>>> y = 0 >>>> y and 1 > > 0 > > How 5 and 1 means 1 and 0 and 1 means 0 > > Thanks > > Regards > > Kaushal Kaushal, as Jason pointed out, any non-zero number evaluates to True. Also, any non-empty list, string, dict, etc. Witness: >>> bool(6) True >>> bool(0) False >>> bool("non-empty string") True >>> bool(' ') True >>> bool('') False The other part of the puzzle is that 'and' and 'or' are "short-circuit" operators. 'or' works like this: return the first value flanking the or if that evaluates to True. Otherwise return the second value: >>> 42 or 0 42 >>> 0 or 42 42 >>> 7 or 42 7 >>> 42 or 7 42 >>> 0 or [] [] >>> [] or 0 0 >>> 'and' works similarly. It returns the first value if that evaluates to False. Otherwise, it returns the second: >>> 42 and 7 7 >>> 7 and 42 42 >>> 0 and [] 0 >>> [] and 0 [] >>> HTH, Brian vdB From broek at cc.umanitoba.ca Fri Apr 7 02:27:59 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 06 Apr 2006 19:27:59 -0500 Subject: [Tutor] request for sugestions on fragement of code for generating truth-tables In-Reply-To: References: Message-ID: <4435B20F.8040709@cc.umanitoba.ca> Danny Yoo said unto the world upon 06/04/06 04:38 PM: > Yes, I agree that the readability of the code is primary. Understandng > the recursive approach depends on the reader's comfort with recursive > functions, and the non-recursive code depends on the reader's comfort with > arithmetic operators. But all arithmetical operations are recursively definable from 0 and sucessorship, so what's the difference? ;-) In all seriousness, though: thanks for the further comments and the helper-function-intense sample code. I'll have a think before I try to decide which I prefer -- I like the division of responsibilities, but worry that the conceptual units have become a bit too small for taste. And, fret not over the typos that you followed up about. I parsed as intended just fine. :-) Thanks again, Brian vdB From justin.mailinglists at gmail.com Fri Apr 7 02:40:32 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 7 Apr 2006 08:40:32 +0800 Subject: [Tutor] regular expressions - backslashes Message-ID: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> Kent wrote: """The problem is that the re engine itself is interpreting the backslashes in the replacement pattern. With a single slash you get a newline even though the slash is a literal in the replacement string: So if you want a literal \ in your replacement text you have to escape the \, even in a raw string: """ Thanks. will try to convince my colleague to use string formatting if he insists on regexp then he can do re.sub(r'(?i)', apppath.replace('\\', '\\\\'), template) re.escape does not quite work for my example >>> re.sub(r'(?i)', re.escape(apppath), template) 'C\\:\\napp\\_and\\_author\\_query\\napp\\_and\\_author\\_query\\a\\ b\\ c\\ d\\files' >>> print re.sub(r'(?i)', re.escape(apppath), template) C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files From tiagosaboga at terra.com.br Fri Apr 7 03:54:01 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 22:54:01 -0300 Subject: [Tutor] mysql store directory information In-Reply-To: References: Message-ID: <200604062254.01725.tiagosaboga@terra.com.br> Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > On Thu, 6 Apr 2006, Tiago Saboga wrote: > > As a first part of a project, I need to store a directory tree in a > > mysql db. I'm wondering if there is a canonical way of doing that. I > > don't know if it's an appropriate question for this list, but I think > > it's not only a choice of db design, but also a choice of appropriate > > python tools. > > Hi Tiago, > > What are the interesting features of a directory? You might want to first > model what you want, and then figure out an appropriate database table > structure to represent that model. Hi, and thank you. I knew I had to explain longer what I wanted, but I was kind of frustrated by the difficulty of writing in english. But I'll try to think less about it, and go further. As I said, this is part of a project. For each of these files, I'll have a database of informations, and this is what really matters, and I have a data model for that. But I want also to able to find these files, which are on removable media (cds and dvds). As I'll have to store where's the file, I thought I could as well store some other basic infos, at least the size (I really don't know yet what else could be useful later). > > My first approach is a table with the following columns: > > id - path - file name - size > > So maybe we can say that a Directory can be modeled as: > > ###### > class Directory: > def __init__(self, id, path, file_name, size): > self.id = id > self.path = path > self.file_name = file_name > self.size = size > ###### > > But why will you want to store this structure in the database, if it's > already available on disk? Why not query the directory directly? See above. > > > I'm starting to code it, and I'd like to know if you have a better > > suggestion... > > I'd flesh out a few more of the requirements first; the requirement to > store the directory in the database is slightly vague, so you probably > will want to ask more questions about what the problem's really about. > > > > You might find something like SQLObject useful: > > http://www.sqlobject.org/ > http://www.turbogears.org/about/sqlobject.html > > where you go fairly directly from data model to SQL table structure with > SQLObject providing the default mapping strategy. Hey, this is *really* great ;-) Hey, I love it. OK, but now why would I use such a directory class as you proposed above? (preliminar question: isn't it rather a file class, as it has only one filename? Anyway, I see your point.) I would make a SQLobject class for files, and feed it with something like def get_dirtree(path): tree = [] for dirpath, dirnames, filenames in os.walk(path): if filenames: for file in filenames: size = os.path.getsize(os.path.join(dirpath,file)) tree.append((dirpath,file,size)) return tree What do you think? Of course, it could be the __init__ function of class, but I don't see why. Thanks, again. Tiago. From amonroe at columbus.rr.com Fri Apr 7 04:10:48 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 6 Apr 2006 22:10:48 -0400 Subject: [Tutor] mysql store directory information In-Reply-To: <200604062254.01725.tiagosaboga@terra.com.br> References: <200604062254.01725.tiagosaboga@terra.com.br> Message-ID: <187954756196.20060406221048@columbus.rr.com> > Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > model for that. But I want also to able to find these files, which are on > removable media (cds and dvds). As I'll have to store where's the file, I > thought I could as well store some other basic infos, at least the size (I > really don't know yet what else could be useful later). You could cheat and just use "Cathy" from this site: http://rvas.webzdarma.cz/ :^) It's one of my favorite utilities. Alan From tiagosaboga at terra.com.br Fri Apr 7 04:36:08 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 6 Apr 2006 23:36:08 -0300 Subject: [Tutor] mysql store directory information In-Reply-To: <187954756196.20060406221048@columbus.rr.com> References: <200604062254.01725.tiagosaboga@terra.com.br> <187954756196.20060406221048@columbus.rr.com> Message-ID: <200604062336.08641.tiagosaboga@terra.com.br> Em Qui 06 Abr 2006 23:10, R. Alan Monroe escreveu: > > Em Qui 06 Abr 2006 15:41, Danny Yoo escreveu: > > > > model for that. But I want also to able to find these files, which are on > > removable media (cds and dvds). As I'll have to store where's the file, I > > thought I could as well store some other basic infos, at least the size > > (I really don't know yet what else could be useful later). > > You could cheat and just use "Cathy" from this site: > http://rvas.webzdarma.cz/ Looks like an interesting piece of software, but as far as I can see it's only for windows and it's not open-source (and hence, not portable). And it still lacks some nice features I'd like to have. Finally, I chose this project because I'll use tools I want to learn. So I'll stick with it ;-) Thanks! TIago. From kent37 at tds.net Fri Apr 7 04:47:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Apr 2006 22:47:18 -0400 Subject: [Tutor] regular expressions - backslashes In-Reply-To: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> References: <3c6718980604061740p1461ae00wd5ed0d6815e7ffa7@mail.gmail.com> Message-ID: <4435D2B6.9040900@tds.net> Justin Ezequiel wrote: > will try to convince my colleague to use string formatting > if he insists on regexp then he can do > re.sub(r'(?i)', apppath.replace('\\', '\\\\'), template) > > re.escape does not quite work for my example > >>>> re.sub(r'(?i)', re.escape(apppath), template) > 'C\\:\\napp\\_and\\_author\\_query\\napp\\_and\\_author\\_query\\a\\ > b\\ c\\ d\\files' >>>> print re.sub(r'(?i)', re.escape(apppath), template) > C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files OK, I didn't realize re.escape() was so aggressive. Depending on how you are going to use the file paths, another alternative is just to use / instead of \, that will work fine within Python even on Windows. Kent From ml.cyresse at gmail.com Fri Apr 7 14:24:46 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 00:24:46 +1200 Subject: [Tutor] Python performance resources & resouce usage hints Message-ID: Hi, I've developed what would be my largest Python app to date. And, going from the crude Windows Task Manager, it's trying to use as much CPU time as it can get when it's idle. This, no doub,t is due to my design. I have an UDP socket server, a packet cruncher, and a DAO. Each resides in it's own thread, and each thread is connected to the next by a Queue. So it's server ---> cruncher --> DAO. Each thread's run() method basically looks like this - while True: try: data = self.queue.get(False) self.DAO.send_data(data) except Empty: if self.shutdown: print "\DAO closing" return continue i.e. each thread is looping endlessly until data arrives via the queue. I can't believe it chews the CPU time the way it does, but I suppose it's easy to do so. My query to the list is twofold - First, if anyone knows of any websites with articles on Python threading optimisation/pitfalls websites, I'd be greatly appreciative. I've been reading the Performance tips on the official wiki, so if there's anything similar I'd be keen to look at it. Okay, the 2nd piece of advice I'm seeking, is what would be the most efficient path here? My initial thoughts are along three lines: Either: A) Increase the queue size of the socket servers B) Use timer threads to 'pulse' my threads. Or: A) Increase the queue size of the socket servers B) Use blocking queues Or: A) Use blocking queues with a timeout B) Use the socket servers to "wake" processing threads As Python doesn't have sleeping threads etc, the third option is my current measure of last resort, as there'll be some substantial rejigging, and I'm not overly experienced with threads. On the wiki http://wiki.python.org/moin/PythonSpeed/PerformanceTips#periodic, I read that "There is a function in the sys module, setcheckinterval, which you can call to tell the interpreter how often to perform these periodic checks." Should I even think about that? I'm not after performance so much as less utilisation of system resources... Much thanks for any guidance offered. Regards, Liam Clarke From josipl2000 at yahoo.com Fri Apr 7 12:51:39 2006 From: josipl2000 at yahoo.com (josip) Date: Fri, 7 Apr 2006 03:51:39 -0700 (PDT) Subject: [Tutor] function caller Message-ID: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Hi, Can someone explain me function and caller relationship when passing arguments? Thanks --------------------------------- How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060407/7b00a92d/attachment.htm From carlos at carlosbenevides.com Fri Apr 7 16:53:00 2006 From: carlos at carlosbenevides.com (Carlos Benevides) Date: Fri, 07 Apr 2006 09:53:00 -0500 Subject: [Tutor] Quick question, Message-ID: <44367CCC.6010309@carlosbenevides.com> Hi, Can someone tell me what the r before the expression means, as in "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? I've seen regular expressions both ways, and I've seen them work with or without the r. Just wondering what it does, or if it makes a difference. Thanks. From kent37 at tds.net Fri Apr 7 18:10:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 12:10:37 -0400 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: Message-ID: <44368EFD.4090303@tds.net> Liam Clarke wrote: > Hi, > > I've developed what would be my largest Python app to date. And, going > from the crude Windows Task Manager, it's trying to use as much CPU > time as it can get when it's idle. > > This, no doub,t is due to my design. > > I have an UDP socket server, a packet cruncher, and a DAO. > Each resides in it's own thread, and each thread is connected to the > next by a Queue. > > So it's server ---> cruncher --> DAO. > > Each thread's run() method basically looks like this - > > while True: > try: > data = self.queue.get(False) > self.DAO.send_data(data) > except Empty: > if self.shutdown: > print "\DAO closing" > return > continue > > > i.e. each thread is looping endlessly until data arrives via the > queue. I can't believe it chews the CPU time the way it does, but I > suppose it's easy to do so. Yes, it's easy. You have basically told the thread to check the queue as often as possible. So it is running as fast as it can, checking the queue and handling whatever comes its way. > > My query to the list is twofold - > > First, if anyone knows of any websites with articles on Python > threading optimisation/pitfalls websites, I'd be greatly appreciative. There's not much. This might help: http://linuxgazette.net/107/pai.html This book is excellent for teaching some of the tools that are used for communication and synchronization between threads: http://greenteapress.com/semaphores/ There are many threading related recipes in the Python Cookbook, both online and printed. http://aspn.activestate.com/ASPN/Cookbook/Python > Okay, the 2nd piece of advice I'm seeking, is what would be the most > efficient path here? > My initial thoughts are along three lines: > > Either: > > A) Increase the queue size of the socket servers I don't see how that would help. > B) Use timer threads to 'pulse' my threads. That's a lot of additional complexity. > A) Increase the queue size of the socket servers > B) Use blocking queues > > Or: > > A) Use blocking queues with a timeout > B) Use the socket servers to "wake" processing threads These are all better. > > As Python doesn't have sleeping threads etc, the third option is my > current measure of last resort, as there'll be some substantial > rejigging, and I'm not overly experienced with threads. Use time.sleep() to sleep a thread. The simplest fix is to add a time.sleep() into your loops. Then the thread will check the queue, process any work, and sleep for a little while. (This is called a busy loop.) The disadvantage of this solution is that there is a trade off between CPU usage and responsiveness. If the sleep is very short, the thread will be very responsive but it will still run a lot and use CPU when idling. If you make the timeout long, the idle CPU will be very low but responsiveness will be poor. If you can live with a response delay of 0.05 or 0.1 second, try that, it should cut the CPU usage dramatically. Even a 0.01 delay might make a big difference. A better fix is to use blocking queues or other blocking events. In this approach, a thread will block until there is something to do, then wake up, do its work and go back to sleep. The hitch here is you need to find another way to signal the thread to exit. One possibility is just to mark them as daemon threads, then they will exit when your app exits. This is a very simple solution if you don't have any cleanup actions you want to do in the threads. Another possibility might be to send a "quit" message in the queue. When the thread sees the special quit message, it forwards it to the next thread and exits. If neither of these work then you could use a queue.get() with a timeout so you check the done flag periodically. Kent From noufal at nibrahim.net.in Fri Apr 7 18:19:09 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Fri, 7 Apr 2006 21:49:09 +0530 (IST) Subject: [Tutor] Quick question, In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <46680.203.145.176.76.1144426749.squirrel@members.hcoop.net> On Fri, April 7, 2006 8:23 pm, Carlos Benevides wrote: > Hi, > > Can someone tell me what the r before the expression means, as in > "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? r is the way of making a string "raw". This means that escape characters will not be interpreted. Here is an example that should make it clear. >>> foo = "This is \t me" >>> print foo This is me >>> foo = r"This is \t me" >>> print foo This is \t me >>> Since slashes are used often for writing regexps, it's useful to make the strings raw. Peace. -- -NI From hugonz-lists at h-lab.net Fri Apr 7 18:42:37 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 10:42:37 -0600 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: Message-ID: <4436967D.1080106@h-lab.net> Liam Clarke wrote: > Each thread's run() method basically looks like this - > > while True: > try: > data = self.queue.get(False) > self.DAO.send_data(data) > except Empty: > if self.shutdown: > print "\DAO closing" > return > continue > > Hi Liam, I checked the response by Kent. I completely agree with him in that the problem is the endless polling you have. However, you do not have to implement a sleep in your loop; the main issue may be that you are not using the facilities of the 'get' method in the queue. From the queue docs: get( [block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case). You are not using the optional timeout and blocking which 'get' provides (!) Try setting it and see your CPU usage go down. This will implement blocking, and the queue will be used as soon as data is there. Set block to True and a timeout if you need to use it (looks like you only need blocking) while True: try: data = self.queue.get(True) self.DAO.send_data(data) Hope that helps, Hugo From hugonz-lists at h-lab.net Fri Apr 7 18:51:29 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 10:51:29 -0600 Subject: [Tutor] function caller In-Reply-To: <20060407105139.89245.qmail@web60819.mail.yahoo.com> References: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Message-ID: <44369891.90005@h-lab.net> josip wrote: > Can someone explain me function and caller relationship when passing > arguments? Hi... what do you mean? Is there something specific you're not getting if you take a look at: http://www.ibiblio.org/obp/thinkCSpy/chap03.htm http://docs.python.org/tut/node6.html#SECTION006600000000000000000 We'd be glad to help with that, but we need the doubt to be more specific. Hugo From hugonz-lists at h-lab.net Fri Apr 7 19:06:40 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 07 Apr 2006 11:06:40 -0600 Subject: [Tutor] Quick question, In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <44369C20.7050909@h-lab.net> Carlos Benevides wrote: > Hi, > > Can someone tell me what the r before the expression means, as in > "re.compile(r'(\.exe|\.zip|\.pif|\.scr|\.ps|\.pdf|\.ppt)$')"? It is not specific to regular expressions, it is called a raw string. http://docs.python.org/tut/node5.html From jjabson at yahoo.com Fri Apr 7 19:15:03 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Fri, 7 Apr 2006 10:15:03 -0700 (PDT) Subject: [Tutor] string formatting question Message-ID: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Hello, I'm trying to replace some strings in a line of text, using some regex functions. My question is: If there's more then one regex grouping I want to replace in one line of a file, how can I use the String Formatting operator (%s) in two places? Here's the line it matches in the file: Here's the regex: m_sock = re.compile('(portNumber=)"\d+" (tcpORudp=)"[A-Z]+"') My replace should look like this: \1 "112" \2 "TCP" (obviously "112" and "TCP" would be varibles) My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) But of course this does not work! :-( Is there a better way to do this? Or am I just doing this all wrong? Thanks in advance! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Fri Apr 7 19:45:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 13:45:28 -0400 Subject: [Tutor] string formatting question In-Reply-To: <20060407171503.17438.qmail@web53710.mail.yahoo.com> References: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Message-ID: <4436A538.8070502@tds.net> Jerome Jabson wrote: > Hello, > > I'm trying to replace some strings in a line of text, > using some regex functions. My question is: If there's > more then one regex grouping I want to replace in one > line of a file, how can I use the String Formatting > operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? > > Here's the line it matches in the file: > > address="64.41.134.60"/> > > Here's the regex: > m_sock = re.compile('(portNumber=)"\d+" > (tcpORudp=)"[A-Z]+"') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? > > My replace should look like this: > \1 "112" \2 "TCP" > (obviously "112" and "TCP" would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent > > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) > > But of course this does not work! :-( Is there a > better way to do this? Or am I just doing this all > wrong? > > Thanks in advance! > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Apr 7 19:53:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 13:53:38 -0400 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: <4436967D.1080106@h-lab.net> References: <4436967D.1080106@h-lab.net> Message-ID: <4436A722.4040707@tds.net> Hugo Gonz?lez Monteverde wrote: > You are not using the optional timeout and blocking which 'get' provides (!) > > Try setting it and see your CPU usage go down. This will implement > blocking, and the queue will be used as soon as data is there. Set block > to True and a timeout if you need to use it (looks like you only need > blocking) > > while True: > try: > data = self.queue.get(True) > self.DAO.send_data(data) I think he will need the timeout too, otherwise the shutdown flag will only be checked when there is work which is probably not what he wants. I agree, this is a good solution. Kent From alan.gauld at freenet.co.uk Fri Apr 7 20:10:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Apr 2006 19:10:43 +0100 Subject: [Tutor] string formatting question References: <20060407171503.17438.qmail@web53710.mail.yahoo.com> Message-ID: <032801c65a6e$966965f0$0b01a8c0@xp> > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) The format operator takes a tuple: twork = m_sock.sub('\1 %s \2 %s' % (port_num, proto), twork) So I removed the comma after the string, used a single percent operator and I put the two variables in a tuple HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Apr 7 20:14:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 7 Apr 2006 19:14:00 +0100 Subject: [Tutor] function caller References: <20060407105139.89245.qmail@web60819.mail.yahoo.com> Message-ID: <033201c65a6f$0bd75950$0b01a8c0@xp> > Hi, Hi, > Can someone explain me function and caller relationship when passing > arguments? There is an explanation of this in vitually any tutorial on Python. Haver you read any of these? Have you any experience in other languages that we can relate an explanation too? For example, you could read the Modules and Functions topic in my tutor. If you still don't undeerstand come back with a specific question and we can try to help some more. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jjabson at yahoo.com Fri Apr 7 20:18:18 2006 From: jjabson at yahoo.com (Jerome Jabson) Date: Fri, 7 Apr 2006 11:18:18 -0700 (PDT) Subject: [Tutor] string formatting question Message-ID: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Hi Kent, Sorry I didn't make my question clearer. Bascially I want to replace this line: With: So the regex grouping are that I want to keep portNumber= and tcpORudp= and replace the values. Which will be varibles in my code. The question is more on the string formatting in the replace. How do use two %s in one statement? i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Thanks again! > Hello, > > I'm trying to replace some strings in a line of text, > using some regex functions. My question is: If there's > more then one regex grouping I want to replace in one > line of a file, how can I use the String Formatting > operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? > > Here's the line it matches in the file: > > address="64.41.134.60"/> > > Here's the regex: > m_sock = re.compile('(portNumber=)"\d+" > (tcpORudp=)"[A-Z]+"') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? > > My replace should look like this: > \1 "112" \2 "TCP" > (obviously "112" and "TCP" would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent > > My problem now is how do I construct the replace > statement? > twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, > twork) > > But of course this does not work! :-( Is there a > better way to do this? Or am I just doing this all > wrong? > > Thanks in advance! > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Apr 7 20:27:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 11:27:50 -0700 (PDT) Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: <4436A722.4040707@tds.net> Message-ID: On Fri, 7 Apr 2006, Kent Johnson wrote: > Hugo González Monteverde wrote: > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > Try setting it and see your CPU usage go down. This will implement > > blocking, and the queue will be used as soon as data is there. Set block > > to True and a timeout if you need to use it (looks like you only need > > blocking) > > > > while True: > > try: > > data = self.queue.get(True) > > self.DAO.send_data(data) > > I think he will need the timeout too, otherwise the shutdown flag will > only be checked when there is work which is probably not what he wants. This could be fixed: when setting the 'shutdown' flag, also push a sentinel piece of data into the queue. That'll wake the thread back up, and that'll give it the opportunity to process a shutdown. The thread here: http://mail.python.org/pipermail/tutor/2006-January/044557.html has some more examples of this. Hope this helps! From kent37 at tds.net Fri Apr 7 20:28:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 14:28:54 -0400 Subject: [Tutor] string formatting question In-Reply-To: <20060407181818.43293.qmail@web53713.mail.yahoo.com> References: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Message-ID: <4436AF66.307@tds.net> Jerome Jabson wrote: > Hi Kent, > > Sorry I didn't make my question clearer. Bascially I > want to replace this line: > > address="64.41.134.60"/> > > With: > > address="64.41.134.60"/> > > So the regex grouping are that I want to keep > portNumber= and tcpORudp= and replace the values. > Which will be varibles in my code. > > The question is more on the string formatting in the > replace. How do use two %s in one statement? > > i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Ok, actually now I can reread your original question and it makes sense :-) I think I'm having an off day for answering questions. I'm glad Alan is with it :-) he gave the answer you need. Kent From Barry.Carroll at psc.com Fri Apr 7 20:56:51 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 11:56:51 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> Greetings: I'm not certain this is the right forum for this question. If not, please point me to the correct one. I am using the unittest module to test a package our team is writing. I presently have three modules of test cases and a top level module to run the entire suite. The hierarchy looks like this: testsymgen top level testsymc39 61 test cases testsym25 44 test cases testsymc93 0 test cases (so far) testsymgen is a very simple file. Here it is: >>>>> import unittest from testsymc39 import * from testsym25 import * from testsymc93 import * if __name__=='__main__': unittest.main( ) >>>>> Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test cases are executed. Can anyone tell me why this should happen. Is there some sort of limit on the number of test cases that can be run in a batch? Thanks in advance for your help. Regards, Barry Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Fri Apr 7 21:42:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Apr 2006 15:42:15 -0400 Subject: [Tutor] Unittest not running all test cases In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3644@eugsrv400.psc.pscnet.com> Message-ID: <4436C097.8080406@tds.net> Carroll, Barry wrote: > Greetings: > > I'm not certain this is the right forum for this question. If not, please point me to the correct one. > > I am using the unittest module to test a package our team is writing. > I presently have three modules of test cases and a top level module to run the entire suite. The hierarchy looks like this: > testsymgen top level > testsymc39 61 test cases > testsym25 44 test cases > testsymc93 0 test cases (so far) > > testsymgen is a very simple file. Here it is: > > import unittest > from testsymc39 import * > from testsym25 import * > from testsymc93 import * > > > if __name__=='__main__': > unittest.main( ) > > Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test cases are executed. Can anyone tell me why this should happen. Is there some sort of limit on the number of test cases that can be run in a batch? I don't think there is a limit like this. I wonder, do you have any name collisions? For example if testsymc39 and testsym25 both contain class TestSym then only the second one will run because it will shadow the name from the first module. If this is the case you need a more sophisticated way of accumulating tests. You might want to look into using nose or one of the other test-discovery frameworks listed here: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools Kent From khp at pflaesterer.de Fri Apr 7 22:28:28 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri, 07 Apr 2006 22:28:28 +0200 Subject: [Tutor] string formatting question In-Reply-To: <20060407181818.43293.qmail@web53713.mail.yahoo.com> (Jerome Jabson's message of "Fri, 7 Apr 2006 11:18:18 -0700 (PDT)") References: <20060407181818.43293.qmail@web53713.mail.yahoo.com> Message-ID: On 7 Apr 2006, jjabson at yahoo.com wrote: > Sorry I didn't make my question clearer. Bascially I > want to replace this line: > > address="64.41.134.60"/> > > With: > > address="64.41.134.60"/> > > So the regex grouping are that I want to keep > portNumber= and tcpORudp= and replace the values. > Which will be varibles in my code. > > The question is more on the string formatting in the > replace. How do use two %s in one statement? > > i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) You could write it simply like that: Python> s = '' Python> re.sub('".*?"','"%s"',s,2) '' Python> re.sub('".*?"','"%s"',s,2) % ('1000', 'TCP') '' Or you could exploit the fact that you can use a function instead of a simply string as substitution; in that function you can do really complicated things. Karl -- Please do *not* send copies of replies to me. I read the list From ml.cyresse at gmail.com Sat Apr 8 00:11:28 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 10:11:28 +1200 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: <4436A722.4040707@tds.net> Message-ID: Thanks very much all. :) I'll have a crack this afternoon and let you know. Kent - the increase in the queue size for the socket server is to allow for any delay in processing packets; it has a default queue size of 5 and then it starts rejecting packets; more of a safety policy when reducing CPU usage than a direct attempt to reduce CPU usage. Once again, thanks for the input! On 4/8/06, Danny Yoo wrote: > > > On Fri, 7 Apr 2006, Kent Johnson wrote: > > > Hugo Gonz?lez Monteverde wrote: > > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > > > Try setting it and see your CPU usage go down. This will implement > > > blocking, and the queue will be used as soon as data is there. Set block > > > to True and a timeout if you need to use it (looks like you only need > > > blocking) > > > > > > while True: > > > try: > > > data = self.queue.get(True) > > > self.DAO.send_data(data) > > > > I think he will need the timeout too, otherwise the shutdown flag will > > only be checked when there is work which is probably not what he wants. > > > This could be fixed: when setting the 'shutdown' flag, also push a > sentinel piece of data into the queue. That'll wake the thread back up, > and that'll give it the opportunity to process a shutdown. > > The thread here: > > http://mail.python.org/pipermail/tutor/2006-January/044557.html > > has some more examples of this. > > > Hope this helps! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From Barry.Carroll at psc.com Sat Apr 8 00:34:33 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 15:34:33 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3646@eugsrv400.psc.pscnet.com> Kent: I just rechecked my class names, and there are no duplicates. I was careful to preface all of the classes in testsymc39 with 'C39...', and used 'S25...' in testsym25. Likewise, the classes in each module have names that describe the type of data being tested, so names are unique within each module as well. Is there a maximum length for class names? Some of my class names are pretty long, and only differ in the last few characters. I'd be surprised if that were the case in Python, but I'm short on other ideas. Thanks for your help. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Date: Fri, 07 Apr 2006 15:42:15 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Unittest not running all test cases > Cc: tutor at python.org > Message-ID: <4436C097.8080406 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > <> > > I don't think there is a limit like this. I wonder, do you have any name > collisions? For example if testsymc39 and testsym25 both contain class > TestSym then only the second one will run because it will shadow the > name from the first module. > > If this is the case you need a more sophisticated way of accumulating > tests. You might want to look into using nose or one of the other > test-discovery frameworks listed here: > http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools > > Kent From ml.cyresse at gmail.com Sat Apr 8 01:34:22 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 8 Apr 2006 11:34:22 +1200 Subject: [Tutor] Python performance resources & resouce usage hints In-Reply-To: References: <4436A722.4040707@tds.net> Message-ID: Well, thanks very much Kent, Hugo and Danny. I went with the "never-ending blocking queues" and sentinel data approach. When running tests with a continual stream of packets being received 3ms apart, CPU usage peaked at 15%, was usually around 7-9%, and when deployed the packets will separated by seconds rather than milliseconds. Thanks for the assistance, I've now overcome my fear of blocking I/O :). Regards, Lia, Clarke On 4/8/06, Liam Clarke wrote: > Thanks very much all. :) I'll have a crack this afternoon and let you know. > > Kent - the increase in the queue size for the socket server is to > allow for any delay in processing packets; it has a default queue size > of 5 and then it starts rejecting packets; more of a safety policy > when reducing CPU usage than a direct attempt to reduce CPU usage. > > Once again, thanks for the input! > > On 4/8/06, Danny Yoo wrote: > > > > > > On Fri, 7 Apr 2006, Kent Johnson wrote: > > > > > Hugo Gonz?lez Monteverde wrote: > > > > You are not using the optional timeout and blocking which 'get' provides (!) > > > > > > > > Try setting it and see your CPU usage go down. This will implement > > > > blocking, and the queue will be used as soon as data is there. Set block > > > > to True and a timeout if you need to use it (looks like you only need > > > > blocking) > > > > > > > > while True: > > > > try: > > > > data = self.queue.get(True) > > > > self.DAO.send_data(data) > > > > > > I think he will need the timeout too, otherwise the shutdown flag will > > > only be checked when there is work which is probably not what he wants. > > > > > > This could be fixed: when setting the 'shutdown' flag, also push a > > sentinel piece of data into the queue. That'll wake the thread back up, > > and that'll give it the opportunity to process a shutdown. > > > > The thread here: > > > > http://mail.python.org/pipermail/tutor/2006-January/044557.html > > > > has some more examples of this. > > > > > > Hope this helps! > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From intermezzoooh at gmail.com Sat Apr 8 01:36:53 2006 From: intermezzoooh at gmail.com (Jesse) Date: Fri, 7 Apr 2006 17:36:53 -0600 Subject: [Tutor] Beginner question (variables, namespaces...) Message-ID: Why is it that when one variable is assigned a value in terms of another variable, assigning a new value to the first doesn't change the value of the second? This is giving me a huge headache, since I have a bunch of variables defined in terms of one another, and I want to be able to dynamically update them (I did not include the definitions of the functions overstock and roundup, but they work): stock = float(raw_input("Enter stock (in terms of portions: ")) container = float(raw_input("Enter portions per container: ")) price_per_container = float(raw_input("Enter price per container: ")) weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) extra = overstock(stock, weekly_quota) # overstock returns 0 if the first argument is less than the second; otherwise it returns the difference between the first argument and the second. need = weekly_quota - extra buy_containers = roundup(need/container) # roundup rounds a non-integer to the next highest integer buy_portions = buy_containers * container leftover = buy_portions - need cost = price_per_container * buy_containers I would like to write a function that will update the values of the above variables given an increase in only the stock variable. Otherwise I'd have to repeat a bunch of code...:( Jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060407/ef87eacb/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 02:02:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 17:02:54 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: Message-ID: On Fri, 7 Apr 2006, Jesse wrote: > Why is it that when one variable is assigned a value in terms of another > variable, assigning a new value to the first doesn't change the value of > the second? Hi Jesse, If you have a "variable" that depends on the values of other parameters, that's just begging to be represented as a function. Let's look at some of those computations: > stock = float(raw_input("Enter stock (in terms of portions: ")) > container = float(raw_input("Enter portions per container: ")) > price_per_container = float(raw_input("Enter price per container: ")) > weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) > extra = overstock(stock, weekly_quota) > need = weekly_quota - extra > buy_containers = roundup(need/container) # roundup rounds a non-integer to > the next highest integer > buy_portions = buy_containers * container > leftover = buy_portions - need > cost = price_per_container * buy_containers Yeah, rather than code these as explicit variables, I'd strongly recommend rewriting each of these as functions. Concretely: #################################################### def extra(stock, weekly_quota): return overstock(stock, weekly_quota) def need(stock, weekly_quota): return weekly_quota - extra(stock, weekly_quota) def buy_containers(stock, weekly_quota, container): return roundup(need(stock, weekly_quota) - extra(stock, weekly_quota)) ... #################################################### It's a little ugly, but this coding explicitely defines the dependencies between the inputs into our system and the expected outputs. When we look at buy_containers(), we can easily see that any change in the stock, weekly_quote, or container parameters may have some profound affect on the output to buy_containers(). That dependency between input and output is what we try to capture when we write a function. So if you recode your assignment statements as function definitions, you should be better able to handle changes to your input. If we think of the names we use for these concepts, there's something ironic that functions behave better on varying data than variables. Oh well. As an advanced aside: the "equations" that you're writing into Python, unfortunately, aren't treated as real math equations, but as separate, independent assignment statements. I think I know what you want, but Python doesn't provide it out of the box. What I think you want is called "constraint" programming. Such systems do exist. For example: http://www.logilab.org/projects/constraint I can't vouch for the maturity of logilab's "constraint" module; I haven't played with it yet. But if you're interested, you may want to look at the treatment of simple constraint systems in the classic textbook "Structure and Interpretation of Computer Programs": http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_sec_3.3.5 It should be very possible to adapt the material there into Python, although it might take a fair bit of work if you're not familiar with Scheme. Good luck to you! From bgailer at alum.rpi.edu Sat Apr 8 02:09:41 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 07 Apr 2006 17:09:41 -0700 Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: References: Message-ID: <4436FF45.5010303@alum.rpi.edu> Jesse wrote: > Why is it that when one variable is assigned a value in terms of > another variable, assigning a new value to the first doesn't change > the value of the second? This is giving me a huge headache, since I > have a bunch of variables defined in terms of one another, and I want > to be able to dynamically update them (I did not include the > definitions of the functions overstock and roundup, but they work): > > stock = float(raw_input("Enter stock (in terms of portions: ")) > container = float(raw_input("Enter portions per container: ")) > price_per_container = float(raw_input("Enter price per container: ")) > weekly_quota = float(raw_input("Enter quota (in terms of portions): ")) > extra = overstock(stock, weekly_quota) # overstock returns 0 if the > first argument is less than the second; otherwise it returns the > > difference between the first argument and the second. > need = weekly_quota - extra > buy_containers = roundup(need/container) # roundup rounds a > non-integer to the next highest integer > buy_portions = buy_containers * container > leftover = buy_portions - need > cost = price_per_container * buy_containers > > I would like to write a function that will update the values of the > above variables given an increase in only the stock variable. > Otherwise I'd have to repeat a bunch of code...:( def recalculate(): global extra, need, buy_containers, buy_portions, leftover, cost extra = overstock(stock, weekly_quota) need = weekly_quota - extra buy_containers = roundup(need/container) buy_portions = buy_containers * container leftover = buy_portions - need cost = price_per_container * buy_containers That's all there is to it. From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 02:09:41 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 17:09:41 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) In-Reply-To: Message-ID: > > buy_containers = roundup(need/container) > > > Yeah, rather than code these as explicit variables, I'd strongly recommend > rewriting each of these as functions. Concretely: > > def buy_containers(stock, weekly_quota, container): > return roundup(need(stock, weekly_quota) - extra(stock, weekly_quota)) Gaaa. I don't know where the heck that function came from. *grin* Let me try that again: ######################################################### def buy_containers(stock, weekly_quota, container): return roundup(need(stock, weekly_quota) / container) ######################################################### Sorry; my eyes must have been wandering when I was writing that code. From Barry.Carroll at psc.com Sat Apr 8 02:23:45 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 7 Apr 2006 17:23:45 -0700 Subject: [Tutor] Unittest not running all test cases Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3649@eugsrv400.psc.pscnet.com> Kent: > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Friday, April 07, 2006 3:59 PM > To: Carroll, Barry > Subject: Re: [Tutor] Unittest not running all test cases > > Carroll, Barry wrote: > > Kent: > > > > I just rechecked my class names, and there are no duplicates. I was > > careful to preface all of the classes in testsymc39 with 'C39...', and > > used 'S25...' in testsym25. Likewise, the classes in each module have > > names that describe the type of data being tested, so names are unique > > within each module as well. > > > > Is there a maximum length for class names? Some of my class names are > > pretty long, and only differ in the last few characters. I'd be > > surprised if that were the case in Python, but I'm short on other ideas. > > I don't know of any limits on class names. They are just strings in > dictionaries after all. > > Try running your tests in verbose mode, you should at least be able to > figure out which ones aren't running. Try > > unittest.main(argv=['', '-v']) > > Kent > I tried your suggestion. Lo and behold, all the test cases ran! So I tried the terse mode again. All the test cases STILL ran! So the problem has vanished without a trace. Or a good reason. Having a problem just disappear like that bothers me almost more than the original problem. (It's also a little embarrassing.) =8^( Anyway, thanks for your help. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From billburns at pennswoods.net Sat Apr 8 04:49:14 2006 From: billburns at pennswoods.net (Bill Burns) Date: Fri, 07 Apr 2006 22:49:14 -0400 Subject: [Tutor] Watch and control access to an executable Message-ID: <443724AA.90802@pennswoods.net> Hi Tutors! I have a problem that I've solved using Python, and I want to know if I've done a good job :-) Here's the problem: At my work we have a Windows network. On a network drive lives a program that a couple people need to access (there's a shortcut on each user's Desktop to the executable). The problem is, only *one* person at a time should run the program. For various reasons, it's possible for information to get corrupted if two people are using the program at the same time. Here's the old solution to the problem: Pick-up the phone. Dial Dave's extension. Dave this is Bill, I'm going to use the program. Use the program. Call Dave again and tell him I'm done using the program. And Dave does the same for me. Putting it mildly - this is a less than ideal way to run software ;-) Now here's my solution: 1. Create a program let's call it 'myProg' that spawns 'otherProg'. 2. 'myProg' will utilize a config file. 3. When 'myProg' is started it looks in the config file to see if 'otherProg' is running. 4. If 'otherProg' is not running, start it and write to the config file that 'otherProg' is running (also write who is running it). 5. 'myProg' continues to run on the user's computer, continuously checking the PID (of 'otherProg') to see if the process is still alive. 6. When we don't find the PID anymore, write to the config file that 'otherProg' isn't running. 7. Shutdown 'myProg'. Now in step #3 above - if 'myProg' reads the config file and finds that the 'otherProg' is currently running, the user is warned that 'The program is currently in use by !' And 'otherProg' is not started. Couple of other things..... 1. I'm taking 'myProg' and creating a single-file executable using py2exe. 2. 'myProg.exe' and the config file live on the network in the same directory as 'otherProg'. 3. User's have a shortcut on the Desktop to 'myProg.exe' instead of 'otherProg'. BTW, I've never stopped to consider if there was a simple 'Windows networking / permissions' type solution to the problem. I just went straight to Python :-) Here's my code. I'd appreciate any critiques! Thanks, Bill import time import os import sys import getpass from ConfigParser import ConfigParser import win32pdhutil import win32con import win32api CONFIG_FILE = 'WatchProc.ini' # Is there a better way to deal with this # default config file data? defaultConfigData = \ """ [Process] proc = [Current User] user = [Executable] exe = [Process Status] running = [Shutdown Status] ok = """ class WatchProc: def __init__(self): self.config = Config() self.user = getpass.getuser() self.checkConfig() def checkConfig(self): """ Check the config file and see if a process is listed. If nothing is listed throw an error, else do checkStatus(). """ proc = self.config.getConfig('Process', 'proc') if proc == '': self.configFileError() else: self.checkStatus() def checkStatus(self): """ Check the config file to see if the process is running or not. If running throw an error, else start the app. """ status = self.config.getConfig('Process Status', 'running') if status == 'True': # App is in use. self.usageError() elif status == 'False': # App not in use. self.startApp() else: # Config file is not setup properly. self.configFileError() def startApp(self): """ Write the user's name to the config file. Start the executable. Then monitor the process. """ self.config.setConfig('Current User', 'user', self.user) self.startExe() time.sleep(1) self.monitorProcess() def monitorProcess(self): """ Get the process name from the config file then continuously check to see if the process is running. When the process dies, call cleanup(). """ procname = self.config.getConfig('Process', 'proc') self.config.setConfig('Shutdown Status', 'ok', False) CHECK = True while CHECK: try: pid = \ win32pdhutil.FindPerformanceAttributesByName(procname) time.sleep(.5) except: # App has stopped running. CHECK = False self.cleanup() def startExe(self): """ Grab the name of the executable to start. Write to the config file that we're running. Spawn. """ exe = self.config.getConfig('Executable', 'exe') self.config.setConfig('Process Status', 'running', True) os.spawnv(os.P_NOWAIT, exe, []) def cleanup(self): """ Set the config file to the proper values (for a clean shutdown) and then exit. """ self.config.setConfig('Shutdown Status', 'ok', True) self.config.setConfig('Process Status', 'running', False) self.config.setConfig('Current User', 'user', '') sys.exit() def configFileError(self): """ Error message that gets called when a value in the config file is missing. """ errMsg = 'The configuration file is not setup properly!' win32api.MessageBox(0, errMsg, 'Config File Error', win32con.MB_ICONEXCLAMATION) def usageError(self): """ Error message that gets called when somebody else is currently running the "watched" program. """ user = self.config.getConfig('Current User', 'user') errMsg = 'The program is currently in use by %s!' % (user) win32api.MessageBox(0, errMsg, 'Start Program Error', win32con.MB_ICONEXCLAMATION) class Config: def __init__(self): # Check to see if the config file exists, # if not create one. if not os.path.exists(CONFIG_FILE): self.writeDefaultConfig() self.cp = ConfigParser() self.cp.read(CONFIG_FILE) def setConfig(self, section, option, value): """ Method used to set config options and values in the ini file. """ self.cp.set(section, option, value) f = open(CONFIG_FILE, 'w') self.cp.write(f) f.close() def getConfig(self, section, option): """ Returns a value from the config file. """ return self.cp.get(section, option) def writeDefaultConfig(self): """ Writes the 'default' config file. Will only get called if one does not exist. """ f = open(CONFIG_FILE, "w") f.write(defaultConfigData) f.close() if __name__ == '__main__': watcher = WatchProc() From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 05:09:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 7 Apr 2006 20:09:18 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 7 Apr 2006 21:05:33 -0600 From: Jesse To: Danny Yoo Subject: Re: [Tutor] Beginner question (variables, namespaces...) I tried redefining the "higher-order" variables as functions, but it didn't quite work. Here's a simplified example: var1 = 2 def timestwo(x): return x*2 var2 = timestwo(var1) print var1, var2 var1 = 3 print var1, var2 This results in the output: 2, 4 3,4 ..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice and just store all of the variable assignments in a function, and then call the function every time I change one of the variables (based on user input). I could still leave the higher-order variables as functions as per your advice, but that alone doesn't seem to do the trick. Unless I've missed something. Jesse From alan.gauld at freenet.co.uk Sat Apr 8 09:52:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 08:52:47 +0100 Subject: [Tutor] Beginner question (variables, namespaces...) References: Message-ID: <001801c65ae1$6db09bb0$0b01a8c0@xp> Others have provided workarounds I'll attempt to answer the rationale part... > Why is it that when one variable is assigned a value in terms of another > variable, assigning a new value to the first doesn't change the value of > the > second? Python variables are just names that refer to a value. The value can be any kind of object that python recognises but it is a single value. When you assign an expression to a variable Python evaluates the current value of the expression before assigning it, it does not understand the concept of an expression as a value in its own right. The only way to store an expression is to place it in a function as the others have shown. The function can then be cxalled as needed, but it must be called explicitly, you cannot call it by implication when one of the terms of the expression changes. There is a way to fake this a little using properties of a class. If you create a class that has all your variables as properties, then you can write get/set methods for those properties such that when changed they automatically update the other properties, thus rippling the changes through your system. But using properties like this is a slightly esoteric technique in Python. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Apr 8 13:51:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 08 Apr 2006 07:51:33 -0400 Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: References: Message-ID: <4437A3C5.1020200@tds.net> > From: Jesse > > I tried redefining the "higher-order" variables as functions, but it didn't > quite work. Here's a simplified example: > > > var1 = 2 > > def timestwo(x): > return x*2 > > > var2 = timestwo(var1) > print var1, var2 > var1 = 3 > print var1, var2 > > This results in the output: > 2, 4 > 3,4 You still have to call the function whenever you need the value. print var1, timestwo(var1) var1 = 3 print var1, timestwo(var1) > > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's advice > and just store all of the variable assignments in a function, and then call > the function every time I change one of the variables (based on user input). > I could still leave the higher-order variables as functions as per your > advice, but that alone doesn't seem to do the trick. Unless I've missed > something. Danny's suggestion of using class properties is a good one, it allows you to automate the recalculation of the variables, and also protect against directly assigning one of the calculated values. Here is a class that has two attributes, val and val2. val can be assigned normally. val2 is read-only and always equal to twice val. Whenever a new value is assigned to val, the internal _recalculate() method is called. This is slightly more complex than needed for this example (_set_val()) could calculate val2 directly) but it extends easily to multiple settable and calculated values. The only problem with this approach is that it is not really beginner material, you need some understanding of classes and properties. I don't know of any beginner references for properties but you could try this: http://users.rcn.com/python/download/Descriptor.htm#properties Anyway here is the code: ##################### class AutoCompute(object): def __init__(self, val): self.val = val # Create a property named val # Setting val triggers recomputation def _set_val(self, val): self._val = val self._recompute() def _get_val(self): return self._val val = property(_get_val, _set_val) # Create a read-only property named val2 def _get_val2(self): return self._val2 val2 = property(_get_val2) def _recompute(self): self._val2 = self._val * 2 ac = AutoCompute(3) print ac.val, ac.val2 # Assigning to ac.val changes ac.val2 also ac.val = 4 print ac.val, ac.val2 # This raises AttributeError, val2 is read-only ac.val2 = 5 ################################### When run, the output is 3 6 4 8 Traceback (most recent call last): File "F:\Tutor\ComputedProperty.py", line 33, in ? ac.val2 = 5 AttributeError: can't set attribute From bgibson at us.ibm.com Sat Apr 8 14:01:47 2006 From: bgibson at us.ibm.com (Bob Gibson) Date: Sat, 8 Apr 2006 06:01:47 -0600 Subject: [Tutor] Bob Gibson is out of the office. Message-ID: I will be out of the office starting 03/31/2006 and will not return until 04/10/2006. I will respond to your message when I return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060408/494af4c3/attachment.html From alan.gauld at freenet.co.uk Sat Apr 8 15:10:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 14:10:31 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> Message-ID: <002d01c65b0d$d0cf8040$0b01a8c0@xp> > Desktop to the executable). The problem is, only *one* person at a time > should run the program. > Now here's my solution: > 1. Create a program let's call it 'myProg' that spawns 'otherProg'. > 2. 'myProg' will utilize a config file. > 3. When 'myProg' is started it looks in the config file to see if > 'otherProg' is running. The usual way of doing this is simply to create an empty file when the program starts and delete it when the program closes In python: ############## # File : exRun.py ''' usage python exRun.py foo.exe prevents more than one copy of the guarded program running ''' import os, sys if len(sys.argv) != 2: print "Usage: python exRun.py " sys.exit() prog = sys.argv[1] fname = prog+'running.dat' try: open(fname,'w').close() # create an empty file. os.system(prog) os.remove(fname) except IOError: print prog, 'is already running, try again later' sys.exit() ################ > 4. If 'otherProg' is not running, start it and write to the config file > that 'otherProg' is running (also write who is running it). > 5. 'myProg' continues to run on the user's computer, continuously > checking the PID (of 'otherProg') to see if the process is still alive. > 6. When we don't find the PID anymore, write to the config file that > 'otherProg' isn't running. > 7. Shutdown 'myProg'. The design above will work too of course but uses more CPU cycles and may be slightly harder to fix if the machine crashes while the app is running sincve the open config file could be corrupted. > Now in step #3 above - if 'myProg' reads the config file and finds that > the 'otherProg' is currently running, the user is warned that 'The > program is currently in use by !' And > 'otherProg' is not started. The current user name can be obtained from getpass.getuser() if you need it. > Couple of other things..... > 1. I'm taking 'myProg' and creating a single-file executable using py2exe. Thats fair enough > 2. 'myProg.exe' and the config file live on the network in the same > directory as 'otherProg'. There's no real need for that. My version usually lives in a common area since it can be used to control multiple apps, and it usually writes its file into a semi-hidden folder to avoid unscrupulous users deleting the file!. > 3. User's have a shortcut on the Desktop to 'myProg.exe' instead of > 'otherProg'. Yes, or in my case several shortcuts with the app names hard coded in the shortcut. > BTW, I've never stopped to consider if there was a simple 'Windows > networking / permissions' type solution to the problem. I just went > straight to Python :-) You can do it all using DOS style BAT files if you use my approach. > Here's my code. I'd appreciate any critiques! Its longer than mine :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From andre.roberge at gmail.com Sat Apr 8 15:33:25 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Sat, 8 Apr 2006 10:33:25 -0300 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <002d01c65b0d$d0cf8040$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> Message-ID: <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> On 4/8/06, Alan Gauld wrote: > > Desktop to the executable). The problem is, only *one* person at a time > > should run the program. [snip] > > The usual way of doing this is simply to create an empty file > when the program starts and delete it when the program closes > In python: > Couldn't this approach cause problems if the Python program crashes, leaving behind the empty file? However, there is a Cookbook solution that does, I believe, that what the original poster asked: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 It is actually so short that I can even reproduce it below. ========= from win32event import CreateMutex from win32api import GetLastError from winerror import ERROR_ALREADY_EXISTS from sys import exit handle = CreateMutex ( None, 1, 'A unique mutex name' ) if GetLastError ( ) == ERROR_ALREADY_EXISTS: # take appropriate action if this is the second # instance of this script; for example, print 'Oh! dear, I exist already.' exit ( 1 ) ============ A detailed explanation (of a slightly modified version) can be found in the second edition of the Python Cookbook [Recipe 9.9]. Andr? From alan.gauld at freenet.co.uk Sat Apr 8 16:51:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 15:51:53 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> Message-ID: <003101c65b1b$f9dc5950$0b01a8c0@xp> > > The usual way of doing this is simply to create an empty file > > when the program starts and delete it when the program closes > Couldn't this approach cause problems if the Python program crashes, > leaving behind the empty file? Yes, but its very easy for the administrator to delete the rogue file. This is how most Unix tools do it, using /tmp as the storage folder - /tmp can be purged at each reboot so ensuring a clean startup. This is simple to manage and better than writing entries to files which can get corrupted - that's much more difficult to manage. (This technique is also a mainstay of Mainframe computing and has been for over 40 years! :-) > However, there is a Cookbook solution that does, > I believe, that what the original poster asked: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 The Mutex version is nice, I haven't seen that before. Although it will only work on Windows but since that's what the OP uses, it's not a problem. Alan G. From billburns at pennswoods.net Sat Apr 8 18:02:41 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 12:02:41 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <002d01c65b0d$d0cf8040$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> Message-ID: <4437DEA1.4000707@pennswoods.net> [Bill] >> Desktop to the executable). The problem is, only *one* person at a time >> should run the program. > [Alan] > The usual way of doing this is simply to create an empty file > when the program starts and delete it when the program closes > In python: > > ############## > # File : exRun.py > ''' usage python exRun.py foo.exe > > prevents more than one copy of the guarded program running > ''' > > import os, sys > > if len(sys.argv) != 2: > print "Usage: python exRun.py " > sys.exit() > > prog = sys.argv[1] > fname = prog+'running.dat' > try: > open(fname,'w').close() # create an empty file. > os.system(prog) > os.remove(fname) > except IOError: > print prog, 'is already running, try again later' > sys.exit() > ################ Alan, Thank you for the code above . I'll take a look at it. Much shorter than my approach :-) [Bill] >> 4. If 'otherProg' is not running, start it and write to the config file >> that 'otherProg' is running (also write who is running it). >> 5. 'myProg' continues to run on the user's computer, continuously >> checking the PID (of 'otherProg') to see if the process is still alive. >> 6. When we don't find the PID anymore, write to the config file that >> 'otherProg' isn't running. >> 7. Shutdown 'myProg'. [Alan] > The design above will work too of course but uses more CPU cycles > and may be slightly harder to fix if the machine crashes while the app > is running sincve the open config file could be corrupted. My first attempt at continuously checking the PID was using a lot of CPU time. Then I added a sleep(.5) in my loop and the CPU % dropped to about 0% (at least according to Task Manager). [Bill] >> Now in step #3 above - if 'myProg' reads the config file and finds that >> the 'otherProg' is currently running, the user is warned that 'The >> program is currently in use by !' And >> 'otherProg' is not started. [Alan] > The current user name can be obtained from getpass.getuser() if you need > it. Yeah, my code uses that too. [Bill] >> 2. 'myProg.exe' and the config file live on the network in the same >> directory as 'otherProg'. [Alan] > There's no real need for that. My version usually lives in a common > area since it can be used to control multiple apps, and it usually writes > its file into a semi-hidden folder to avoid unscrupulous users deleting > the file!. I think I was just trying to make it easy for my program to find the program to start (since it'll look in the current directory first). I didn't want to hard-code any paths. But it looks like with your approach, I just issue the path to the executable on the command line and be done with it. Regarding the config file deletion - I've set the permissions on the .ini so that users can read & write to the file, but not delete it. But certainly a user with Admin privs could still delete it. Also , if my program doesn't find the .ini file - it creates a new one (although it must be setup again). [Bill] >> BTW, I've never stopped to consider if there was a simple 'Windows >> networking / permissions' type solution to the problem. I just went >> straight to Python :-) [Alan] > You can do it all using DOS style BAT files if you use my approach. I just knew someone would come up with an easier way :-) Thanks again, Alan! I'll play around with the code you posted. Bill From billburns at pennswoods.net Sat Apr 8 18:08:42 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 12:08:42 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> Message-ID: <4437E00A.2080005@pennswoods.net> [Bill] >>>Desktop to the executable). The problem is, only *one* person at a time >>>should run the program. > [Snip some good advise about file problems (that I'll look in to)] [Andr?] > However, there is a Cookbook solution that does, I believe, that what > the original poster asked: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67663 > > It is actually so short that I can even reproduce it below. > ========= > from win32event import CreateMutex > from win32api import GetLastError > from winerror import ERROR_ALREADY_EXISTS > from sys import exit > > handle = CreateMutex ( None, 1, 'A unique mutex name' ) > > if GetLastError ( ) == ERROR_ALREADY_EXISTS: > # take appropriate action if this is the second > # instance of this script; for example, > print 'Oh! dear, I exist already.' > exit ( 1 ) > ============ > A detailed explanation (of a slightly modified version) can be found > in the second edition of the Python Cookbook [Recipe 9.9]. Andr?, Thanks for the pointer to this recipe! If I'm not mistaken (and I certainly could be) I believe this recipe is used to control instances of an already running *script*. While I'm trying to control a completely different executable (program) written by someone else. Maybe I'm reading the recipe wrong?? I'll take a better look at it and see if it will work for my situation. Thanks for the reply!! Bill From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 18:14:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Apr 2006 09:14:02 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: Message-ID: > I tried redefining the "higher-order" variables as functions, but it > didn't quite work. Here's a simplified example: > > > var1 = 2 > > def timestwo(x): > return x*2 > > var2 = timestwo(var1) > print var1, var2 > var1 = 3 > print var1, var2 Try: ###### print 2, timestwo(2) print 3, timestwo(3) ###### Alternatively, try: ###### var1 = 2 print var1, timestwo(var1) var1 = 3 print var1, timestwo(var1) ###### What do you expect to see? > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's > advice and just store all of the variable assignments in a function, and > then call the function every time I change one of the variables (based > on user input). I could still leave the higher-order variables as > functions as per your advice, but that alone doesn't seem to do the > trick. Unless I've missed something. You're missing something. *wink* Play with this a little more. It's something basic in Python, and you'll want to get this squared away so it doesn't cause you grief later. The model you have about how variables behave in Python is slightly off still: I think you're still thinking of them like math equations. But Python's model for assigning variable names to values don't work like equality: it's more of a "this box now contains the value described by the right hand side at this particular time." So if we see: a = 3 b = 4 a = a + b we can model this as: [a : 3] (after stmt: a = 3) [a : 3, b : 4] (after stmt: b = 4) [a : 7, b : 4] (after stmt: a = a + b) where we keep a list of names and their current values. (I'm just using an ad-hoc notation for the stuff in the brackets.) Assignment erases the old value and replaces it with a new one as we flow through our program. From dyoo at hkn.eecs.berkeley.edu Sat Apr 8 18:21:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Apr 2006 09:21:00 -0700 (PDT) Subject: [Tutor] Beginner question (variables, namespaces...) (fwd) In-Reply-To: <4437A3C5.1020200@tds.net> Message-ID: > > ..which is not what I'm aiming for. Maybe I'll have to follow Bob's > > advice and just store all of the variable assignments in a function, > > and then call the function every time I change one of the variables > > (based on user input). I could still leave the higher-order variables > > as functions as per your advice, but that alone doesn't seem to do the > > trick. Unless I've missed something. > > Danny's suggestion of using class properties is a good one, it allows > you to automate the recalculation of the variables, and also protect > against directly assigning one of the calculated values. Just wanted to clarify that this is not my suggestion: Alan proposed this. But I think we should steer away a little away from full-fledged classes at the moment. The "professional" solution would be to do this, but I'm not sure how appropriate it is for Jesse to do this yet. Jesse is still confused about how variables work. In which case, suggesting him to look at classes will just make things worse. *grin* From alan.gauld at freenet.co.uk Sat Apr 8 18:44:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 8 Apr 2006 17:44:48 +0100 Subject: [Tutor] Watch and control access to an executable References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> <4437E00A.2080005@pennswoods.net> Message-ID: <003701c65b2b$c0352eb0$0b01a8c0@xp> > If I'm not mistaken (and I certainly could be) I believe this recipe is > used to control instances of an already running *script*. While I'm > trying to control a completely different executable (program) written by > someone else. Nope, its si8mply creating an arbitrary Mutex, which is like a flag in the OS itself. If the flag gets set OK - no errors - then you can go ahead and launch your app, if theres an error the most likely reason is that the app is already running. Its exactly the same principle as using a blank file but tidier since theres no file to delete(*) if things go wrong - although you might need to reboot since I',m not sure how to delete a Mutex created by another process, in fact I've only used a Mutex within a single multi-threading app, but in principle theres no reason not to use it this way too... (*) Having the file has advantages since the administrator can easily check with explorer to see if the app is in use, or manually create one to block access to the app temporarily, but its a minimal advantage I suspect. Alan g. From billburns at pennswoods.net Sat Apr 8 19:02:42 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 08 Apr 2006 13:02:42 -0400 Subject: [Tutor] Watch and control access to an executable In-Reply-To: <003701c65b2b$c0352eb0$0b01a8c0@xp> References: <443724AA.90802@pennswoods.net> <002d01c65b0d$d0cf8040$0b01a8c0@xp> <7528bcdd0604080633t63f3f6e8gbb832f496b4be352@mail.gmail.com> <4437E00A.2080005@pennswoods.net> <003701c65b2b$c0352eb0$0b01a8c0@xp> Message-ID: <4437ECB2.5050900@pennswoods.net> [Bill] >> If I'm not mistaken (and I certainly could be) I believe this recipe >> is used to control instances of an already running *script*. While I'm >> trying to control a completely different executable (program) written >> by someone else. [Alan] > Nope, its si8mply creating an arbitrary Mutex, which is like a flag in > the OS itself. If the flag gets set OK - no errors - then you can go > ahead and launch your app, if theres an error the most likely reason is > that the app is already running. > > Its exactly the same principle as using a blank file but tidier since > theres no file to delete(*) if things go wrong - although you might need > to reboot since I',m not sure how to delete a Mutex created by another > process, in fact I've only used a Mutex within a single multi-threading > app, but in principle theres no reason not to use it this way too... > > (*) Having the file has advantages since the administrator can easily > check with explorer to see if the app is in use, or manually create one > to block access to the app temporarily, but its a minimal advantage I > suspect. OK. I understand a little better and will definitely look into this!! The description of the recipe states: "A script can use this code to determine whether another instance of itself is already in execution. 32-bit MSW only." So I assumed it meant - you could use the recipe in your own scripts to determine if the user was trying to start multiple instances of your program. My apologies to Andr?!!! Thanks for the explanation! Bill From payal-python at scriptkitchen.com Mon Apr 10 15:33:42 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 10 Apr 2006 09:33:42 -0400 Subject: [Tutor] failing to learn python Message-ID: <20060410133342.GA7045@tranquility.scriptkitchen.com> Hi, I am trying to learn Python seriously for almost 2 months but have not gotten far at all. Infact, it seems I have not understood even the basic concepts itself. I know some shell, sed and awk programming. I have tried reading Learning Python - Mark Lutz Think C Spy A byte of Python Non-Programmers Tutorial For Python etc. But I have not got anything from them. I am feeling that they are superficial and do not touch real life problems. Also, not enough examples are provided which can help newbies like me. Can anyone help me, it is pretty pretty frustating thing for last couple of months? With warm regards, -Payal From kent37 at tds.net Mon Apr 10 16:05:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 10:05:45 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060410133342.GA7045@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> Message-ID: <443A6639.1050703@tds.net> Payal Rathod wrote: > Hi, > I am trying to learn Python seriously for almost 2 months but have not > gotten far at all. Infact, it seems I have not understood even the basic > concepts itself. I know some shell, sed and awk programming. > I have tried reading Learning Python - Mark Lutz > Think C Spy > A byte of Python > Non-Programmers Tutorial For Python > etc. > But I have not got anything from them. I am feeling that they are > superficial and do not touch real life problems. Also, not enough > examples are provided which can help newbies like me. Hi Payal, Beginner's material teaches the basics of the language. These are the building blocks you will use to solve your problems. You need to understand the basics like loops, functions, lists and dictionaries to solve most real-world problems. When you have questions about basic concepts you can ask for help on this list. You might like to look at "Python Programming for the absolute beginner". It is oriented to beginners and has many examples and exercises. http://premierpressbooks.com/ptr_detail.cfm?group=Programming&subcat=Other%20Programming&isbn=1%2D59863%2D112%2D8 What kind of real life problems are you interested in? You might like "Beginning Python", it has several real-life projects. http://apress.com/book/bookDisplay.html?bID=10013 When you have questions about basic concepts you can ask for help on this list. We do best with questions that are very specific. From payal-python at scriptkitchen.com Mon Apr 10 18:52:00 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 10 Apr 2006 12:52:00 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <443A6639.1050703@tds.net> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> Message-ID: <20060410165200.GA15376@tranquility.scriptkitchen.com> On Mon, Apr 10, 2006 at 10:05:45AM -0400, Kent Johnson wrote: > You might like to look at "Python Programming for the absolute > beginner". It is oriented to beginners and has many examples and > exercises. I might not be able to afford another book, due to high dollar-to-ruppee rate. > What kind of real life problems are you interested in? You might like I am a parttime sys admin so I want system admin problem which usually I do through shell scripts like parsing logs, generating reports, greping with regexes etc. The only thing I don't want is silly problems like generate fibonnacci series, add numbers frm 0-n etc. non required silly stuff. With warm regards, -Payal From bgailer at alum.rpi.edu Mon Apr 10 19:20:57 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 10 Apr 2006 10:20:57 -0700 Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <443A93F9.8050103@alum.rpi.edu> Payal Rathod wrote: > On Mon, Apr 10, 2006 at 10:05:45AM -0400, Kent Johnson wrote: > >> You might like to look at "Python Programming for the absolute >> beginner". It is oriented to beginners and has many examples and >> exercises. >> > > I might not be able to afford another book, due to high dollar-to-ruppee > rate. > > >> What kind of real life problems are you interested in? You might like >> > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. When I hear the word "silly" I assume that you are comfortable with programming in Python, and do not need the examples that are useful to beginners, and want access to libraries of code for doing the tasks you described. So I suggest you look at Python's remarkable set of modules. In the docs you'll find Global Module Index. Start with re for regular expressions, glob & shutil for some file management, os for more file and process management. Some of these have some example code. Select ONE task of interest to you, make your best stab at writing a Python program using the module, then come back with the program and tell us how we can help you with it. If my assumption is inaccurate, and you do need help with the fundamentals of Python, then I suggest you tackle some of the assignments in the references you have *as a way of becoming comfortable with Python*, then tackle the modules I mentioned. Someone else on this list may point you to online learning resources that will meet your need for more information at low-to-no cost. HTH From kent37 at tds.net Mon Apr 10 19:22:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 13:22:19 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <443A944B.1070304@tds.net> Payal Rathod wrote: >> What kind of real life problems are you interested in? You might like > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. Take a look at the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python Dive into Python is not targeted at beginners but it is available online and does have real-world examples: http://diveintopython.org/ Kent From gslindstrom at gmail.com Mon Apr 10 21:19:08 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 10 Apr 2006 14:19:08 -0500 Subject: [Tutor] Decorators Message-ID: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Hello- For some reason I have decided to learn about decorators; I heard them talked up at Pycon the past two years and want to know what all the fuss is about. I might even use them in my code :-) My problem, and this is after reading PEP 318 and other items found when I "Googled" for decorators, is that I can't figure out the practical use for them. This surely means that I do not understand the concept because Python does not waste my time or energy. Can any of you gurus either explain what all the excitement is about or point me to examples of how/why I would want to use decorators? Thanks for your attention... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060410/39ee66c1/attachment.htm From kent37 at tds.net Mon Apr 10 21:44:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Apr 2006 15:44:21 -0400 Subject: [Tutor] Decorators In-Reply-To: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Message-ID: <443AB595.8090804@tds.net> Greg Lindstrom wrote: > Hello- > > For some reason I have decided to learn about decorators; I heard them > talked up at Pycon the past two years and want to know what all the > fuss is about. I might even use them in my code :-) > > My problem, and this is after reading PEP 318 and other items found when > I "Googled" for decorators, is that I can't figure out the practical use > for them. This surely means that I do not understand the concept > because Python does not waste my time or energy. Can any of you gurus > either explain what all the excitement is about or point me to examples > of how/why I would want to use decorators? http://wiki.python.org/moin/PythonDecoratorLibrary From oasf2004 at yahoo.com Tue Apr 11 00:29:23 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:29:23 -0700 (PDT) Subject: [Tutor] Question about list Message-ID: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Hello, I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] and I wrote the script below: i = 0 while i < len(list1): print list1[i] i += 1 Ok. This script will generate as the output each element of the original list, one per line: spam! 2 ['Ted', 'Rock'] I also would like to print the length of each element of that list: spam! = 1 element 2 = 1 element ['Ted', 'Rock'] = 2 elements Could anyone, please, give me some hints? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Tue Apr 11 00:42:42 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Apr 2006 10:42:42 +1200 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: <5e58f2e40604101542t4483c642q46fe41af5f7fd9@mail.gmail.com> Hi Hoffmann, On 11/04/06, Hoffmann wrote: > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 Have you read about "for" loops? The pythonic way of looping through a list is to do something like this: for item in list1: print item This will produce the same output as your code above, but is much nicer to read :-) > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements The challenge here is that your list contains a mixture of different types. For example, the len() function will tell us that ['Ted', 'Rock'] has two elements. But it would also tell us that 'spam!' has five elements, and it would raise an exception if we tried to find the length of 2. So you will need to ask python about the type of element you're looking at. One possibility that might work for you is this: for item in list1: if isinstance(item, (tuple, list)): print len(item) else: print 1 May I ask why you're doing this? This feels like a situation where you need to think clearly what your goals are before you go diving towards a solution :-) -- John. From adam.jtm30 at gmail.com Tue Apr 11 00:42:54 2006 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 10 Apr 2006 23:42:54 +0100 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On 10/04/06, Hoffmann wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? > Thanks, > Hoffmann instead of just print list1[i] you could use print list1[i], len(list1[i]). I'd like to point out that the usual way to iterate through objects in a list like that would be using a for loop like so. for item in list1: print item, len(item) as you can see this is much easier to understand and is also a lot shorter. HTH. From oasf2004 at yahoo.com Tue Apr 11 00:48:01 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:48:01 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: Message-ID: <20060410224801.54752.qmail@web60021.mail.yahoo.com> --- Adam wrote: > On 10/04/06, Hoffmann wrote: > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > > > Could anyone, please, give me some hints? > > Thanks, > > Hoffmann > > instead of just print list1[i] you could use print > list1[i], len(list1[i]). > I'd like to point out that the usual way to iterate > through objects in > a list like that would be using a for loop like so. > > for item in list1: > print item, len(item) > > as you can see this is much easier to understand and > is also a lot shorter. > HTH. > Hi Adam, In the previous email, I forgot to mention that I have already tried: i = 0 while i < len(list1): print list1[i], len(list1[i]) i += 1 However, I got: soam! 5 1 Traceback (most recent call last): File "list1.py", line 11, in ? print list1[i], len(list1[i]) TypeError: len() of unsized object Could I hear from you again? Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From mwhite3 at ttsd.k12.or.us Tue Apr 11 00:49:45 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Mon, 10 Apr 2006 15:49:45 -0700 Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: <20060410224945.GB16865@ttsd.k12.or.us> Hi Hoffman, It is often useful to use the "for" construct to process items in a list. e.g.: >>> list1 = [ 'spam!', 2, ['Ted', 'Rock']] >>> for item in list: ... print item spam! 2 ['Ted', 'Rock'] If you pass a list to the len() function, it will return the number of elenents in the list. e.g.: >>> x = ['a', 'b', 'c'] >>> len(x) 3 Now if you pass len() a string it will return the length of a string: >>> y = 'hello' >>> len(y) 5 Given your list below, len() will return what you're looking for when it encounters the third element of the list, but won't for the first and second elements. One way to solve this problem is to use the type() function to figure out if your item is a string or list and use len() as appropriate. I hope this provides enough of a hint. -mtw On Mon, Apr 10, 2006 at 03:29:23PM -0700, Hoffmann (oasf2004 at yahoo.com) wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? > Thanks, > Hoffmann > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From oasf2004 at yahoo.com Tue Apr 11 00:52:22 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 15:52:22 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <5e58f2e40604101542t4483c642q46fe41af5f7fd9@mail.gmail.com> Message-ID: <20060410225222.98520.qmail@web60022.mail.yahoo.com> --- John Fouhy wrote: > Hi Hoffmann, > > On 11/04/06, Hoffmann wrote: > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > Have you read about "for" loops? The pythonic way > of looping through > a list is to do something like this: > > for item in list1: > print item > > This will produce the same output as your code > above, but is much > nicer to read :-) > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > The challenge here is that your list contains a > mixture of different types. > > For example, the len() function will tell us that > ['Ted', 'Rock'] has > two elements. But it would also tell us that > 'spam!' has five > elements, and it would raise an exception if we > tried to find the > length of 2. > > So you will need to ask python about the type of > element you're > looking at. One possibility that might work for you > is this: > > for item in list1: > if isinstance(item, (tuple, list)): > print len(item) > else: > print 1 > > May I ask why you're doing this? This feels like a > situation where > you need to think clearly what your goals are before > you go diving > towards a solution :-) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi John, This is just a version of a book exercise (How to think like a computer scientist - learning with python, by Downey, Elkner, and Meyers), page 84. Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From carroll at tjc.com Tue Apr 11 00:58:05 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 10 Apr 2006 15:58:05 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On Mon, 10 Apr 2006, Hoffmann wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements Well, the length of "spam!" is 5. Lengths of strings express the number of characters. You could check to see if it's a grouping-type of element -- i.e., a list, tuple or set -- but I think your better approach is that, if this is something you need, make all of the elements lists, some of which are single-item lists; for example, instead of: list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] use: list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] >>> list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] >>> for item in list1: ... print item, len(item) ... ['spam!'] 1 [2] 1 ['Ted', 'Rock'] 2 If your heart is set on the other approach, though, it can be done: >>> list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] >>> for item in list1: ... if isinstance(item,(list, tuple, set)): ... print item, len(item) ... else: ... print item, 1 ... spam! 1 2 1 ['Ted', 'Rock'] 2 >>> From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 00:44:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 15:44:09 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410222923.4535.qmail@web60020.mail.yahoo.com> References: <20060410222923.4535.qmail@web60020.mail.yahoo.com> Message-ID: On Mon, 10 Apr 2006, Hoffmann wrote: > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? The problem is slightly weird, just because you need to clarify what it means to take the length of a non-list. From the examples above, it sounds like we'd like to define the "length" of a non-list to be one. Is that right? Can you write a function called length() that takes a thing and returns the "length" of that thing? ###### def length(something): ... ## fill me in ###### For example, we'd like to see: length("spam!") ==> 1 length(2) ==> 1 length(['Ted', 'Rock']) ==> 2 If you can define this you should be able to use this to solve your problem. When you're defining length(), you may find the built-in function "type()" useful. For example: ###### >>> type(5) >>> type([1, 2, 3]) ###### Good luck! From oasf2004 at yahoo.com Tue Apr 11 01:10:41 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 16:10:41 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: Message-ID: <20060410231041.93988.qmail@web60014.mail.yahoo.com> --- Terry Carroll wrote: > On Mon, 10 Apr 2006, Hoffmann wrote: > > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > Well, the length of "spam!" is 5. Lengths of > strings express the number > of characters. > > You could check to see if it's a grouping-type of > element -- i.e., a list, > tuple or set -- but I think your better approach is > that, if this is > something you need, make all of the elements lists, > some of which are > single-item lists; for example, instead of: > > list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > > use: > list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > > >>> list1 = [ ['spam!'], [2], ['Ted', 'Rock'] ] > >>> for item in list1: > ... print item, len(item) > ... > ['spam!'] 1 > [2] 1 > ['Ted', 'Rock'] 2 > > If your heart is set on the other approach, though, > it can be done: > > >>> list1 = [ 'spam!', 2, ['Ted', 'Rock'] ] > >>> for item in list1: > ... if isinstance(item,(list, tuple, set)): > ... print item, len(item) > ... else: > ... print item, 1 > ... > spam! 1 > 2 1 > ['Ted', 'Rock'] 2 > >>> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Terry, Your aproaches (mainly the last one!) answered my question. After following your last approach, I got what I was looking for. Up to the page I am (page 84 of "How to think like a computer scientist - learning with Python"), I didn't see that nice approach. Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From oasf2004 at yahoo.com Tue Apr 11 01:17:08 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Mon, 10 Apr 2006 16:17:08 -0700 (PDT) Subject: [Tutor] Question about list In-Reply-To: <20060410224945.GB16865@ttsd.k12.or.us> Message-ID: <20060410231708.65281.qmail@web60021.mail.yahoo.com> --- Matthew White wrote: > Hi Hoffman, > > It is often useful to use the "for" construct to > process items in a list. > e.g.: > > >>> list1 = [ 'spam!', 2, ['Ted', 'Rock']] > >>> for item in list: > ... print item > spam! > 2 > ['Ted', 'Rock'] > > If you pass a list to the len() function, it will > return the number of > elenents in the list. e.g.: > > >>> x = ['a', 'b', 'c'] > >>> len(x) > 3 > > Now if you pass len() a string it will return the > length of a string: > >>> y = 'hello' > >>> len(y) > 5 > > Given your list below, len() will return what you're > looking for when it > encounters the third element of the list, but won't > for the first and > second elements. One way to solve this problem is > to use the type() > function to figure out if your item is a string or > list and use len() > as appropriate. I hope this provides enough of a > hint. > > -mtw > > > On Mon, Apr 10, 2006 at 03:29:23PM -0700, Hoffmann > (oasf2004 at yahoo.com) wrote: > > Hello, > > > > I have a list: list1 = [ 'spam!', 2, ['Ted', > 'Rock'] > > ] > > and I wrote the script below: > > > > i = 0 > > while i < len(list1): > > print list1[i] > > i += 1 > > > > Ok. This script will generate as the output each > > element of the original list, one per line: > > > > spam! > > 2 > > ['Ted', 'Rock'] > > > > I also would like to print the length of each > element > > of that list: > > > > spam! = 1 element > > 2 = 1 element > > ['Ted', 'Rock'] = 2 elements > > > > Could anyone, please, give me some hints? > > Thanks, > > Hoffmann > > > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Matthew White - District Systems Administrator > Tigard/Tualatin School District > 503.431.4128 > > "The greatest thing in this world is not so much > where we are, but in > what direction we are moving." -Oliver Wendell > Holmes > > Hi Matthew, Thanks for the nice information! I am learning a lot with all of the hints you guys are sending to me. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 01:20:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 16:20:37 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <20060410165200.GA15376@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. Hi Payal, You might also find David Mertz's book "Text Processing With Python" to be useful for you: http://gnosis.cx/TPiP/ I agree with the other recommendation on "Dive into Python": it provides a lot of good practical programming knowledge. http://diveintopython.org/ > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers from 0-n etc. non required silly stuff. Just as a counterpoint: some of those silly things aren't useful in their own right, but they're finger exercises to help one really get mastery over the language. Recursion is one of those things that are core concepts, and most Python tutorials try to cover it by talking about factorials. It's very unfortunate that fibonacci numbers are one of the "classical" examples of recursion, since they are useless to most people. But don't discount recursion altogether. We can look at concrete example of recursion that might be more applicable. One common system administration question that pops up every once in a while is: "How do I do [some_action] to every file in my directory?" We can either know magically that os.walk() will do the hard work for us, or we can use a combination of os.listdir() and os.path.isdir(): ############################################# ### pseudocode def my_walk(some_action, dir_or_file): if os.path.isfile(dir_or_file): some_action(dir_or_file) else: for thing in os.listdir(dir_or_file): my_walk(some_action, thing) ############################################# in which there's a specific "base" case for handling regular files, and an "inductive" case for handling directories. Another example of this kind of processing involves things like XML or HTML processing. If we wanted to get all the anchor link elements in an HTML document, how would we do this? We again break it into two cases: one to handle anchor elements, and another to handle anything else: ############################################## ## Pseudocode def get_anchors(element): if element is an anchor: return [element] else: anchors = [] for child in element.children: anchors.extend(get_anchors(child)) return anchors ############################################## We're in a slightly different domain, but if we look at this with a critical eye, we should see that the code structure is similar to the directory-walking example. There's a case for handling really simple problems, and another case for handling slightly harder problems. That's the key insight you should have been getting. If the tutorials that you're reading haven't been delving into this, that means that those tutorials aren't doing a good job. The fact that factorial() looks like: ################################ def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) ################################ is pretty darn worthless in itself. But the idea that we can break things down into two categories (simple cases, slightly complex cases) and handle them in some structured way is a valuable concept. If you see something that's looks trivially un-useful when you're reading a tutorial, bring it up on this list. They're bound to be some kind of real application for it. *grin* And if you have any other questions, feel free to ask. Good luck! From Barry.Carroll at psc.com Tue Apr 11 02:00:03 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 10 Apr 2006 17:00:03 -0700 Subject: [Tutor] Python for sysadmins (Was: failing to learn python) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C364A@eugsrv400.psc.pscnet.com> Payal: I agree with Kent: the Python Cookbook is an excellent resource. And, it has a whole section on System Administration. try this URL: http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=System You can also try Google. I entered 'Python sysadmin'. Here are just a few potentially interesting sites that came back: http://www.samag.com/documents/s=8964/sam0312a/0312a.htm http://www.unixreview.com/documents/s=8989/sam0401d/ http://www.linuxdevcenter.com/pub/a/linux/2002/05/09/sysadminguide.html Look through these and other resources, choose an example function that relates to one of your tasks and try it out. Post questions and problems here. Good luck Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > Message: 5 > Date: Mon, 10 Apr 2006 13:22:19 -0400 > From: Kent Johnson > Subject: Re: [Tutor] failing to learn python > Cc: tutor at python.org > Message-ID: <443A944B.1070304 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Payal Rathod wrote: > >> What kind of real life problems are you interested in? You might like > > > > I am a parttime sys admin so I want system admin problem which usually I > > do through shell scripts like parsing logs, generating reports, greping > > with regexes etc. > > The only thing I don't want is silly problems like generate fibonnacci > > series, add numbers frm 0-n etc. non required silly stuff. > > Take a look at the Python Cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python > > Dive into Python is not targeted at beginners but it is available online > and does have real-world examples: > http://diveintopython.org/ > > Kent From gslindstrom at gmail.com Tue Apr 11 05:04:51 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 10 Apr 2006 22:04:51 -0500 Subject: [Tutor] failing to learn python Message-ID: <57aa55060604102004o27ccf8e6ibdd27dca31f83536@mail.gmail.com> Paypal- I do a lot of system admin type work with Python. If you'd like, drop me a line and let me know what you're interested in learning...perhaps I could help you work through a project or two. Greg Lindstrom gslindstrom at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060410/7513e9cc/attachment.html From keosophon at khmeros.info Tue Apr 11 06:44:34 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Tue, 11 Apr 2006 11:44:34 +0700 Subject: [Tutor] input with default value option Message-ID: <200604111144.34644.keosophon@khmeros.info> Hi, With raw_input(), it allows to input value. Can it be used to input value with default value option? Phon From bgailer at alum.rpi.edu Tue Apr 11 07:03:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 10 Apr 2006 22:03:20 -0700 Subject: [Tutor] input with default value option In-Reply-To: <200604111144.34644.keosophon@khmeros.info> References: <200604111144.34644.keosophon@khmeros.info> Message-ID: <443B3898.3030909@alum.rpi.edu> Keo Sophon wrote: > Hi, > > With raw_input(), it allows to input value. Can it be used to input value with default value option? > response = raw_input("Enter some data:") if not response: response = "default value" From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 08:38:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Apr 2006 23:38:20 -0700 (PDT) Subject: [Tutor] input with default value option In-Reply-To: <200604111144.34644.keosophon@khmeros.info> References: <200604111144.34644.keosophon@khmeros.info> Message-ID: > With raw_input(), it allows to input value. Can it be used to input > value with default value option? Hi Phon, We can build your own function to do this. Bob showed how to set up code so that the default's taken if the user just presses enter in his reply. Let's take a look at it again: ########################################### response = raw_input("Enter some data:") if not response: response = "default value" ########################################### We can capture this as a function that takes in a question and a default answer: ################################## def ask(question, default): response = raw_input(question) if not response: response = default return response ################################## And now we have something that acts like raw_input(), but also gives the user the ability to get a default: ###### >>> ask("favorite color?", "Blue. No yellow -- aaaugh!") favorite color?red 'red' >>> ask("favorite color?", "Blue. No yellow -- aaaugh!") favorite color? 'Blue. No yellow -- aaaugh!' >>> ###### (In the second call to ask(), I just pressed enter.) Does this make sense? From alan.gauld at freenet.co.uk Tue Apr 11 09:33:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 08:33:07 +0100 Subject: [Tutor] failing to learn python References: <20060410133342.GA7045@tranquility.scriptkitchen.com><443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <009e01c65d3a$2d916ef0$0a01a8c0@xp> >> What kind of real life problems are you interested in? You might like > > I am a parttime sys admin so I want system admin problem which usually I > do through shell scripts like parsing logs, generating reports, greping > with regexes etc. My tutor is specifdically targetted at computer power users invcluding sys admins. It has examples of parsing files and creating reports (albeit very simple ones since its for beginners) and using regex. It also has side bars on topics like using WSH on Windows and other OS specific topics. There are also specific topics on using the OS and IPC comms etc being written. > The only thing I don't want is silly problems like generate fibonnacci > series, add numbers frm 0-n etc. non required silly stuff. None of the above are silly stuff, they are all needed in various real world computing and scientific problems. However I do agree that they are not what most beginners will be doing and I try to avoid any math type exercises. (I do use factorials as an example of recursion alongside another more practical example) I don't think my tutor was in your list so you might like to give it a go... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Apr 11 09:36:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 08:36:42 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> Message-ID: <00a801c65d3a$ad6b3b10$0a01a8c0@xp> > My problem, and this is after reading PEP 318 and other items found when I > "Googled" for decorators, is that I can't figure out the practical use for There is no practical use for decorators IMHO They are syntactic sugar added to the language to make some things that were already possible a little tidier looking (things like class/static methods etc) I don;t think there is anything that you need decorators to achieve that you can'tdo without them. In that respect they are like python's support for lambdas - nice to have but not essential to the language. Others may feel differently! :-) Alan G. From kaushalshriyan at gmail.com Tue Apr 11 11:19:37 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 14:49:37 +0530 Subject: [Tutor] Tuple Message-ID: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm >>> tuple = ('a', 'b', 'c', 'd', 'e') >>> tuple[0] 'a' And the slice operator selects a range of elements. >>> tuple[1:3] ('b', 'c') But if we try to modify one of the elements of the tuple, we get a error: >>> tuple[0] = 'A' TypeError: object doesn't support item assignment Of course, even if we can't modify the elements of a tuple, we can replace it with a different tuple: >>> tuple = ('A',) + tuple[1:] >>> tuple ('A', 'b', 'c', 'd', 'e') How does tuple = ('A',) + tuple[1:] this work ???? Please explain me with an example Thanks Regards Kaushal From noufal at nibrahim.net.in Tue Apr 11 11:38:53 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Tue, 11 Apr 2006 15:08:53 +0530 (IST) Subject: [Tutor] Tuple In-Reply-To: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Message-ID: <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> On Tue, April 11, 2006 2:49 pm, Kaushal Shriyan wrote: > Hi All > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > >>>> tuple = ('a', 'b', 'c', 'd', 'e') >>>> tuple[0] > 'a' > > > And the slice operator selects a range of elements. > >>>> tuple[1:3] > ('b', 'c') > > > But if we try to modify one of the elements of the tuple, we get a error: > >>>> tuple[0] = 'A' > TypeError: object doesn't support item assignment > > > Of course, even if we can't modify the elements of a tuple, we can > replace it with a different tuple: > >>>> tuple = ('A',) + tuple[1:] >>>> tuple > ('A', 'b', 'c', 'd', 'e') > > How does tuple = ('A',) + tuple[1:] this work ???? One question mark is enough. ;) ('A',) creates a tuple with a single element. The comma at the end is to differentiate between a tuple and just grouping brackets. tuple[1:] returns all elements of the tuple except the first. So what do you have? A tuple ('A') and another tuple ('b', 'c', 'd', 'e'). Now, the + operator concatenates these two into a new tuple. What do you get? ('A','b','c','d','e'). This is returned by the expression on the right hand side. And it's assigned to the variable "tuple". When you print it, you get the value. I think you're getting confused between changing a tuple itself and creating a new one with pieces of others. On a side note, it's not a good idea to call a variable "tuple" since there is a python builtin by the same name. -- -NI From kaushalshriyan at gmail.com Tue Apr 11 11:45:35 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:15:35 +0530 Subject: [Tutor] Tuple In-Reply-To: <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> <18135.203.145.176.76.1144748333.squirrel@members.hcoop.net> Message-ID: <6b16fb4c0604110245l56eca033q2a22a05a8c70fce7@mail.gmail.com> On 4/11/06, Noufal Ibrahim wrote: > > On Tue, April 11, 2006 2:49 pm, Kaushal Shriyan wrote: > > Hi All > > > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > > > >>>> tuple = ('a', 'b', 'c', 'd', 'e') > >>>> tuple[0] > > 'a' > > > > > > And the slice operator selects a range of elements. > > > >>>> tuple[1:3] > > ('b', 'c') > > > > > > But if we try to modify one of the elements of the tuple, we get a error: > > > >>>> tuple[0] = 'A' > > TypeError: object doesn't support item assignment > > > > > > Of course, even if we can't modify the elements of a tuple, we can > > replace it with a different tuple: > > > >>>> tuple = ('A',) + tuple[1:] > >>>> tuple > > ('A', 'b', 'c', 'd', 'e') > > > > How does tuple = ('A',) + tuple[1:] this work ???? > > One question mark is enough. ;) > > ('A',) creates a tuple with a single element. The comma at the end is to > differentiate between a tuple and just grouping brackets. > tuple[1:] returns all elements of the tuple except the first. > So what do you have? > A tuple ('A') and another tuple ('b', 'c', 'd', 'e'). > > Now, the + operator concatenates these two into a new tuple. What do you get? > ('A','b','c','d','e'). > > This is returned by the expression on the right hand side. And it's > assigned to the variable "tuple". When you print it, you get the value. > > I think you're getting confused between changing a tuple itself and > creating a new one with pieces of others. > > On a side note, it's not a good idea to call a variable "tuple" since > there is a python builtin by the same name. > -- > -NI > > Thanks Noufal for the explanation Appreciate it Kaushal From singletoned at gmail.com Tue Apr 11 12:10:16 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 11:10:16 +0100 Subject: [Tutor] failing to learn python In-Reply-To: <20060410133342.GA7045@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> Message-ID: <34bb7f5b0604110310k38bc5a6bm85c2b38407aa0982@mail.gmail.com> On 10/04/06, Payal Rathod wrote: > Hi, > I am trying to learn Python seriously for almost 2 months but have not > gotten far at all. Infact, it seems I have not understood even the basic > concepts itself. I know some shell, sed and awk programming. > I have tried reading Learning Python - Mark Lutz > Think C Spy > A byte of Python > Non-Programmers Tutorial For Python > etc. > But I have not got anything from them. I am feeling that they are > superficial and do not touch real life problems. Also, not enough > examples are provided which can help newbies like me. > > Can anyone help me, it is pretty pretty frustating thing for last couple > of months? > > With warm regards, > -Payal You might find reading real code to be more useful than a tutorial: Fredrik Lundh's Guide to the Standard Library contains thousands of examples: http://effbot.org/zone/librarybook-index.htm PLEAC contains loads of examples to show how to do things: http://pleac.sourceforge.net/pleac_python/index.html It all depends what kind of learner you are: Learn by being taught (read the tutorials) Learn by doing (think of a project, start trying to do it, then ask here when you get stuck) Learn by example (read lots of examples of other people's code to see how they do it) I'm very much the kind of person who likes to learn to swim by jumping as far into the water as he can, then trying to get back to the side. It's amazing how well you can do something when you don't have any choice. ;-) Ed From kent37 at tds.net Tue Apr 11 12:15:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 06:15:54 -0400 Subject: [Tutor] Decorators In-Reply-To: <00a801c65d3a$ad6b3b10$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <00a801c65d3a$ad6b3b10$0a01a8c0@xp> Message-ID: <443B81DA.90709@tds.net> Alan Gauld wrote: >> My problem, and this is after reading PEP 318 and other items found when I >> "Googled" for decorators, is that I can't figure out the practical use for > > There is no practical use for decorators IMHO > They are syntactic sugar added to the language to make some things > that were already possible a little tidier looking (things like class/static > methods etc) It's true that decorators are syntactic sugar and don't add any new functional capabilities to the language. @foo def bar(): pass is equivalent to def bar(): pass bar = foo(bar) However this doesn't mean that there is no practical use for decorators. After all, list comprehension is mostly syntactic sugar too! Decorators add expressiveness and clarity to Python rather than functionality. If you read the PEP you see this is the primary motivation. Decorators are used widely so apparently many people agree that they add to the expressiveness of the language. Here is another example - decorators are used in the implementation of a proposal for dynamic function overloading: http://www.artima.com/weblogs/viewpost.jsp?thread=155514 Kent From kaushalshriyan at gmail.com Tue Apr 11 12:17:20 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:47:20 +0530 Subject: [Tutor] Emailid Message-ID: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> Hi All I am a ardent fan of python can I have email address for me I mean For example for me it would be kaushal at python.org Regards Kaushal From kaushalshriyan at gmail.com Tue Apr 11 12:26:16 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 15:56:16 +0530 Subject: [Tutor] Tuple (Section 9.3) Message-ID: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Hi All I am reading this http://www.ibiblio.org/obp/thinkCSpy/chap09.htm and did not understood the Section 9.3 at all, Please explain me with an example so the idea become clear and understood #################################################################### 9.3 Tuples as return values Functions can return tuples as return values. For example, we could write a function that swaps two parameters: def swap(x, y): return y, x Then we can assign the return value to a tuple with two variables: a, b = swap(a, b) In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake: def swap(x, y): # incorrect version x, y = y, x If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing xinside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error. As an exercise, draw a state diagram for this function so that you can see why it doesn't work. #################################################################### Thanks in Advance Regards Kaushal From alan.gauld at freenet.co.uk Tue Apr 11 13:27:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 12:27:17 +0100 Subject: [Tutor] input with default value option References: <200604111144.34644.keosophon@khmeros.info> <443B3898.3030909@alum.rpi.edu> Message-ID: <00f301c65d5a$e5a6ee00$0a01a8c0@xp> >> With raw_input(), it allows to input value. Can it be used to input value >> with default value option? >> > response = raw_input("Enter some data:") > if not response: response = "default value" This is one of the few places where I do use the short-circuit evaluation trick: val = raw_input('> ') or myDefault I reads well (IMHO) and works pretty much safely. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Apr 11 13:36:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 12:36:29 +0100 Subject: [Tutor] Tuple References: <6b16fb4c0604110219ua5dce4cva483482a6cbd318a@mail.gmail.com> Message-ID: <00fb01c65d5c$2dc22370$0a01a8c0@xp> >>> tuple = ('A',) + tuple[1:] >>> tuple >('A', 'b', 'c', 'd', 'e') > > How does tuple = ('A',) + tuple[1:] this work ???? > > Please explain me with an example OK, we will use the example you gave us! tuple is a bad name since Python has an internal type called tuple usd for converting a list etc to a tuple so I'll use t1: >>> t1 = ('a','b','c','d','e') >>> t2 = ('A',) + t1[1:] We construct a new tuple by creating a single element tuple ('A',) and adding to it the contents of the original tuple starting with the second element (t1[1:]). We can add tuples together quite easily: >>> t3 = (1,2,3) + (4,5,6) >>> t3 (1,2,3,4,5,6) The result is a new tuple. The only difference in your example is that instead of using a new name (t2) you replaced the original tuple with the new one in t1. This is just the same as when you do x = x +1 Now which specific bit of that did you not understand and we can expand on it if necessary? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kaushalshriyan at gmail.com Tue Apr 11 13:48:06 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 17:18:06 +0530 Subject: [Tutor] comp.lang.python newsgroup Message-ID: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Hi All I went to a http://www.python.org/community/lists.html and found the below newsgroup How do i use this news group and access the information I need comp.lang.python newsgroup Thanks in Advance Regards Kaushal From kent37 at tds.net Tue Apr 11 14:22:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 08:22:28 -0400 Subject: [Tutor] comp.lang.python newsgroup In-Reply-To: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> References: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Message-ID: <443B9F84.6060909@tds.net> Kaushal Shriyan wrote: > Hi All > > I went to a http://www.python.org/community/lists.html and found the > below newsgroup > > How do i use this news group and access the information I need > > comp.lang.python newsgroup You can use Google groups http://groups.google.com/groups?group=comp.lang.python You can subscribe to the email version: http://www.python.org/mailman/listinfo/python-list Both of these and a few more options are listed in the web page you referenced! Kent From kent37 at tds.net Tue Apr 11 14:24:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 08:24:20 -0400 Subject: [Tutor] Emailid In-Reply-To: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> References: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> Message-ID: <443B9FF4.2070605@tds.net> Kaushal Shriyan wrote: > Hi All > > I am a ardent fan of python can I have email address for me > I mean For example for me it would be > > kaushal at python.org I don't know how you get a python.org mailing address but I'm sure it's not by asking here! Kent From singletoned at gmail.com Tue Apr 11 15:19:57 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 14:19:57 +0100 Subject: [Tutor] Emailid In-Reply-To: <443B9FF4.2070605@tds.net> References: <6b16fb4c0604110317n2fc75f2bt3164517a0b590946@mail.gmail.com> <443B9FF4.2070605@tds.net> Message-ID: <34bb7f5b0604110619i547cbb4aq3f5d6667f8e961a8@mail.gmail.com> On 11/04/06, Kent Johnson wrote: > Kaushal Shriyan wrote: > > Hi All > > > > I am a ardent fan of python can I have email address for me > > I mean For example for me it would be > > > > kaushal at python.org > > I don't know how you get a python.org mailing address but I'm sure it's > not by asking here! Actually, I can probably help. If you give your bank details to my friend in Nigeria, he can get you one. Ed From doug.shawhan at gmail.com Tue Apr 11 16:33:12 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 09:33:12 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? Message-ID: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> The difficulty I have may or may not be something that may be easily handled with pyserial and some other mystery module. I am attempting to screen scrape SuperDOS, an extremely closed system that uses wyse 60 terminals to communicate with a dos machine. I have not been able to communicate properly with superdos until trying the handy miniterm.py example from the pyserial package in conjunction with Markus Gutschke's wy60 emulator which translates input through an xterm into wyse 60 commands. These programs together allow me to interact with superdos pretty well ... with the exception of the arrow keys: for those I must fall back to the old cntl-letter combos to get the cursor to behave (actually cntl-letter x 2.. for some reason it likes an extra prod). This is fine, as now I have a way to debug my eventual script. My big problem is, I am completely unable to get SuperDos to respond to my carriage returns from within the script! I can watch the script work via miniterm.py. I have sent the return and newline characters in various combinations starting with "\n,\r", "\x0a\x0d", but they respond weirdly, putting the cursor *above* the existing command line, changing the cursor to an outline and generally letting me know that I am on the wrong track. Has some clever human alread created a handy module to handle wyse60 and other terminal emulation from within a python program? I have looked over the curses module, but it seems to be aimed at drawing proper screens for the user, not translation. PySerial's ability to suck up the output via readlines() is awesome, and I can see how I *think* it should all be done, but the weirdness has got me stymied! I am going to look at Mr. Gutscheke's source to see how he does it, but I am barely conversant in python and fear that exposure to that much C code may cause dizziness! Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/54068229/attachment-0001.htm From pkraus at pelsupply.com Tue Apr 11 16:29:25 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 11 Apr 2006 10:29:25 -0400 Subject: [Tutor] unpack/regexp Message-ID: <200604111029.25408.pkraus@pelsupply.com> Ok sorry for the perl refernce but I can't figure out how to do this. I have a fixed width text file i need to parse. so lets say I want an array to containt the pieces i need. if the fields I want are lengths from left to right. 10 10 13 12345678901234567890123456789012 I want to turn this into an array that has these elements. 1234567890 1234567890 123456789012 <--notice white space In Perl its a simple my @array = unpack ( "A10 A10 A13" , $line ) this extracts it and removes the whitespace after doing so. or if i wanted i could do my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) -- Paul Kraus =-=-=-=-=-=-=-=-=-=-= PEL Supply Company Network Administrator 216.267.5775 Voice 216.267.6176 Fax www.pelsupply.com =-=-=-=-=-=-=-=-=-=-= From kaushalshriyan at gmail.com Tue Apr 11 16:50:19 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Tue, 11 Apr 2006 20:20:19 +0530 Subject: [Tutor] Database Connectivity Message-ID: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Hi ALL How do i connect my python program to MySQL DB or Oracle DB or can you please specify the URL which gives a detailed explanation on this. Thanks in Advance Regards Kaushal From singletoned at gmail.com Tue Apr 11 17:01:02 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 11 Apr 2006 16:01:02 +0100 Subject: [Tutor] Database Connectivity In-Reply-To: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> References: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Message-ID: <34bb7f5b0604110801q48511c8ana120d54ee16e0044@mail.gmail.com> On 11/04/06, Kaushal Shriyan wrote: > Hi ALL > > How do i connect my python program to MySQL DB or Oracle DB or can you > please specify the URL which gives a detailed explanation on this. SQLObject is your best bet: http://www.sqlobject.org/ If you're using MySQL, you will need MySQLdb as well: http://sourceforge.net/projects/mysql-python Any questions, just ask. Ed From kent37 at tds.net Tue Apr 11 17:08:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 11:08:44 -0400 Subject: [Tutor] unpack/regexp In-Reply-To: <200604111029.25408.pkraus@pelsupply.com> References: <200604111029.25408.pkraus@pelsupply.com> Message-ID: <443BC67C.7010004@tds.net> Paul Kraus wrote: > Ok sorry for the perl refernce but I can't figure out how to do this. > I have a fixed width text file i need to parse. > > so lets say I want an array to containt the pieces i need. > if the fields I want are lengths from left to right. > 10 10 13 > 12345678901234567890123456789012 > I want to turn this into an array that has these elements. > 1234567890 > 1234567890 > 123456789012 <--notice white space > > In Perl its a simple > my @array = unpack ( "A10 A10 A13" , $line ) > this extracts it and removes the whitespace after doing so. struct.unpack() is a direct analog: In [10]: line = "12345678901234567890123456789012 " In [16]: struct.unpack('10s10s13s', line) Out[16]: ('1234567890', '1234567890', '123456789012 ') You can also use string slicing: In [14]: line[:10], line[10:20], line[20:] Out[14]: ('1234567890', '1234567890', '123456789012 ') > > or if i wanted i could do > my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) Python regex is a bit more verbose than Perl but you can do the same thing: In [2]: import re In [11]: m=re.match("(.{10})(.{10})(.{13})", line) In [13]: m.group(1, 2, 3) Out[13]: ('1234567890', '1234567890', '123456789012 ') Kent From kent37 at tds.net Tue Apr 11 17:11:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 11:11:00 -0400 Subject: [Tutor] Database Connectivity In-Reply-To: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> References: <6b16fb4c0604110750g2fc01fcal44dc1a4c398690e4@mail.gmail.com> Message-ID: <443BC704.5010203@tds.net> Kaushal Shriyan wrote: > Hi ALL > > How do i connect my python program to MySQL DB or Oracle DB or can you > please specify the URL which gives a detailed explanation on this. Basic connectivity is through modules that implement the DB-API standard. Read the spec and find implementations here: http://www.python.org/doc/topics/database/ There are several popular packages that layer on top of this basic functionality such as SQLObject and SQLAlchemy. Kent From pkraus at pelsupply.com Tue Apr 11 17:17:31 2006 From: pkraus at pelsupply.com (Paul Kraus) Date: Tue, 11 Apr 2006 11:17:31 -0400 Subject: [Tutor] unpack/regexp In-Reply-To: <443BC67C.7010004@tds.net> References: <200604111029.25408.pkraus@pelsupply.com> <443BC67C.7010004@tds.net> Message-ID: <200604111117.32127.pkraus@pelsupply.com> > Python regex is a bit more verbose than Perl but you can do the same thing: > > In [2]: import re > > In [11]: m=re.match("(.{10})(.{10})(.{13})", line) > > In [13]: m.group(1, 2, 3) > Out[13]: ('1234567890', '1234567890', '123456789012 ') That work great. Regex tend to be "expensive" is there a "better" way to do it? From doug.shawhan at gmail.com Tue Apr 11 17:32:41 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 10:32:41 -0500 Subject: [Tutor] unpack/regexp In-Reply-To: <200604111029.25408.pkraus@pelsupply.com> References: <200604111029.25408.pkraus@pelsupply.com> Message-ID: <5e1ceb8a0604110832p3d59a675q5b746654cf761af@mail.gmail.com> I always slice the string in this sort of situation: s = "12345678901234567890123456789012 " t = s[:10],s[10:20],s[20:-1] print t ('1234567890', '1234567890', '123456789012') One could always bracket it to make a list or whatever. Hope this helps! On 4/11/06, Paul Kraus wrote: > > Ok sorry for the perl refernce but I can't figure out how to do this. > I have a fixed width text file i need to parse. > > so lets say I want an array to containt the pieces i need. > if the fields I want are lengths from left to right. > 10 10 13 > 12345678901234567890123456789012 > I want to turn this into an array that has these elements. > 1234567890 > 1234567890 > 123456789012 <--notice white space > > In Perl its a simple > my @array = unpack ( "A10 A10 A13" , $line ) > this extracts it and removes the whitespace after doing so. > > or if i wanted i could do > my @array = ( $1, $2, $3 ) if ( $line =~ m/^(.{10})(.{10})(.{13}) ) > > > -- > Paul Kraus > =-=-=-=-=-=-=-=-=-=-= > PEL Supply Company > Network Administrator > 216.267.5775 Voice > 216.267.6176 Fax > www.pelsupply.com > =-=-=-=-=-=-=-=-=-=-= > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/6fd722a7/attachment.html From payal-python at scriptkitchen.com Tue Apr 11 18:06:45 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 11 Apr 2006 12:06:45 -0400 Subject: [Tutor] failing to learn python In-Reply-To: References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> Message-ID: <20060411160645.GB5242@tranquility.scriptkitchen.com> On Mon, Apr 10, 2006 at 04:20:37PM -0700, Danny Yoo wrote: > http://gnosis.cx/TPiP/ I will read that and Alan's tutorial too (isn't that MS-Windows specific ???) The reason I am disgrunted with Python is because lack of good documentation. Shell programming has great text and so do sed and awk but Python texts are rather boring and just hooting that Python is cool without proving it at all. All the examples I wanted were done better in shell/sed/awk. But anyways thanks for the support I will dive into it again with fresh vigour. I will get back with any stupid queries I have. With warm regards, -Payal From hugonz at h-lab.net Tue Apr 11 18:08:46 2006 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 11 Apr 2006 10:08:46 -0600 Subject: [Tutor] Tuple (Section 9.3) In-Reply-To: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> References: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Message-ID: <443BD48E.5040004@h-lab.net> Hi Kaushal, I might have to do a little guessing and see what is not clear from the explanation. The whole point of returning a tuple as opposed to, say, returning a list, is the fact that tuples are NON mutable. That is, *apparently* you would not be returning a reference, but the values themselves. There is no better example I can think of, than the one you already read. If you want a function tu return multiple parameters so that you can do. ret1, ret2 = func() then have func return a tuple. That's the whole point of the chapter you read. Maybe there is too much information in the discussion that does not look useful to you if you have not run into a problem where you need it. I hope this is not some kind of homework :) Hugo From josipl2000 at yahoo.com Tue Apr 11 18:13:40 2006 From: josipl2000 at yahoo.com (josip) Date: Tue, 11 Apr 2006 09:13:40 -0700 (PDT) Subject: [Tutor] for loops Message-ID: <20060411161340.72598.qmail@web60819.mail.yahoo.com> I have problem with this question. Can someone show me the code and than explain it? >>Write a Python program to print out the following shape. You are expected to use two for loops (these must be nested) to solve this problem. output: * * * * * * * * * * * * * * Thanks --------------------------------- Love cheap thrills? Enjoy PC-to-Phone calls to 30+ countries for just 2?/min with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/bc549895/attachment.htm From python at kapitalisten.no Tue Apr 11 18:31:41 2006 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue, 11 Apr 2006 18:31:41 +0200 (CEST) Subject: [Tutor] Webbrowser Message-ID: <4760.193.71.156.197.1144773101.squirrel@mail.sporck.net> Hello. I have recently discovered the Webbrowser module, and have started using it instead of just using IE thru win32com. But, have a few questions: 1) Is it possible to give it an adress, and if the browser gets a redirect to a different adress, I can override it? For example, I tell the browser to open a site. The browser tries, but gets redirected to a spam-site. I would therefore like to send the user somewhere else. Is it possible? 2) It doesn't seem like open(url[, new=0][, autoraise=1]) new and autoraise work with Firefox. I have tried all possible comboes, but the site is opened in a new tab in Firefox regardless. Any suggestions? Thanks in advance, ?yvind -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From alan.gauld at freenet.co.uk Tue Apr 11 18:33:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 17:33:34 +0100 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> Message-ID: <012f01c65d85$ad781740$0a01a8c0@xp> Hi Doug, > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > I must fall back to the old cntl-letter combos to get the cursor to behave Sounds like you need to find a tech spec for the Wyse 60. That should give you all of the Ctrl character combos to control the screen. If you have access to a Unix box you might find the info you need in the termcap or terminfo databases. But Wyse should have the spec sheet on their web site somewhere... Alan G. From alan.gauld at freenet.co.uk Tue Apr 11 18:43:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 17:43:10 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp> <443B81DA.90709@tds.net> Message-ID: <013301c65d87$0603d380$0a01a8c0@xp> >> There is no practical use for decorators IMHO > It's true that decorators are syntactic sugar and don't add any new > functional capabilities to the language. Which is all I intended to imply. > However this doesn't mean that there is no practical use for decorators. Nor did I mean that, after all I am a big advocate of lambdas and they too are sugar. They have no practical use but are nice for conveying certain concepts in code. Similarly with decorators (although I do hate the syntax!) > After all, list comprehension is mostly syntactic sugar too! Absolutely and also add no practical functionality they are just shorthand, albeit with a small performance advantage in many cases - which is not true of decorators or lambdas! > proposal for dynamic function overloading: > http://www.artima.com/weblogs/viewpost.jsp?thread=155514 I really don't like this proposal nor many of the others that currently exist to seemingly turn Python into Java and C++! If people want to code in the Java porridge let them use Java not try to turn Python into the same sludge. (And yes, I do realise that it's Guido who's doing the work in this case! :-) Alan G. From doug.shawhan at gmail.com Tue Apr 11 19:14:13 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 12:14:13 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? In-Reply-To: <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> <012f01c65d85$ad781740$0a01a8c0@xp> <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> Message-ID: <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> Oho! http://www.wyse.com/service/support/kbase/Keydetl1.asp?Q=7&R=6 has the hex codes! Thanks! Perhaps this will fix what ails me. On 4/11/06, doug shawhan wrote: > > Yeah, termca was were I looked first. > > The OpenBSD 3.8 termcap shows: > :cr=^M:ct=\E0:dc=\EW:dl=\ER:do=^J:ds=\EF\r:ei=\Er:fs=^M:\ for the carriage > return, but then I can't find the hex code for ^M! :-) At that point I > thought I'd ask if there was some sort of termcapesque module available. > > I will scope the wyse website again, perhaps I can locate it this time! > > Thanks > > > On 4/11/06, Alan Gauld wrote: > > > > Hi Doug, > > > > > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > > > I must fall back to the old cntl-letter combos to get the cursor to > > behave > > > > Sounds like you need to find a tech spec for the Wyse 60. That should > > give you all of the Ctrl character combos to control the screen. > > If you have access to a Unix box you might find the info you need > > in the termcap or terminfo databases. But Wyse should have the > > spec sheet on their web site somewhere... > > > > Alan G. > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/7c561fc9/attachment.htm From david at graniteweb.com Tue Apr 11 19:47:11 2006 From: david at graniteweb.com (David Rock) Date: Tue, 11 Apr 2006 12:47:11 -0500 Subject: [Tutor] for loops In-Reply-To: <20060411161340.72598.qmail@web60819.mail.yahoo.com> References: <20060411161340.72598.qmail@web60819.mail.yahoo.com> Message-ID: <20060411174711.GB2865@wdfs.graniteweb.com> * josip [2006-04-11 09:13]: > I have problem with this question. > Can someone show me the code and than explain it? > > >>Write a Python program to print out the following shape. You are expected to use two for loops (these must be nested) to solve this problem. > > output: > * * * * * > * * > * * > * * * * * That looks a lot like homework. If you have a specific question about a _part_ of code _you_ have written, we'll be glad to help out explaining those specifics. We generally try to stay away from doing the work for you :-) -- David Rock david at graniteweb.com From ms at cerenity.org Tue Apr 11 20:03:15 2006 From: ms at cerenity.org (Michael) Date: Tue, 11 Apr 2006 19:03:15 +0100 Subject: [Tutor] Decorators In-Reply-To: <013301c65d87$0603d380$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> Message-ID: <200604111903.15240.ms@cerenity.org> On Tuesday 11 April 2006 17:43, Alan Gauld wrote: > >> There is no practical use for decorators IMHO > > > > It's true that decorators are syntactic sugar and don't add any new > > functional capabilities to the language. > > Which is all I intended to imply. You have a different meaning of "practical use" from common usage then. Something that makes it easier to: * Understand that a function has been modified * Make it clear that a function is a staticmethod/classmethod/etc *right at the beginning of a function* without having to read the entire body. * Reduce typing * Allow hinting of types for integration with tools like PyObjC * Make it clear when reading the definition of a method/function is memoised, traced etc * Simplifying augmentation of generators with arbitrary extra communications attributes. ... are all practical benefits. That means they have practical use in my book :-) Syntactic sugar *IS* a practical benefit. After all, every language above assember is syntactic sugar, and by your definition of no practical use. Michael. From dyoo at hkn.eecs.berkeley.edu Tue Apr 11 20:04:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Apr 2006 11:04:15 -0700 (PDT) Subject: [Tutor] comp.lang.python newsgroup In-Reply-To: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> References: <6b16fb4c0604110448k477f3f58t3904d043d7f1e70@mail.gmail.com> Message-ID: [taking help at python.org out of CC] Hi Kaushal, Please do not crosspost between help at python.org and tutor at python.org. They are different mailing lists. > I went to a http://www.python.org/community/lists.html and found the > below newsgroup > > How do i use this news group and access the information I need Did you really read the page? I don't mean to be facetious, but the content is all right there from your link. What part about that page is confusing to you? I'm baffled, so if you can explain what difficulty you had in reading it, that may help us better understand. Also, I've noticed you're asking a lot of rapid-fire questions. You may want to take a look at: http://www.catb.org/~esr/faqs/smart-questions.html so that you get a better idea of asking questions that have a good chance of getting answered well. From python at venix.com Tue Apr 11 20:03:40 2006 From: python at venix.com (Python) Date: Tue, 11 Apr 2006 14:03:40 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060411160645.GB5242@tranquility.scriptkitchen.com> References: <20060410133342.GA7045@tranquility.scriptkitchen.com> <443A6639.1050703@tds.net> <20060410165200.GA15376@tranquility.scriptkitchen.com> <20060411160645.GB5242@tranquility.scriptkitchen.com> Message-ID: <1144778620.25186.36.camel@www.venix.com> On Tue, 2006-04-11 at 12:06 -0400, Payal Rathod wrote: > The reason I am disgrunted with Python is because lack of good > documentation. http://www.python.org/doc/ The Python Docs - possibly you missed this because of the plethora of links. The Library Reference used to have the tag line: (keep this under your pillow) The Module Index is the other key starting point. http://rgruet.free.fr/PQR24/PQR2.4.html A very handy quick reference. I think Python has incredibly good documentation. Fred Drake and the other folks who write, edit and maintain the documentation do a wonderful job of keeping it fresh and current as the language changes. There are very few rough spots within the thousands of pages of text. It's been a while since I looked at the Tutorial. Is that where you felt let down? I felt compelled to respond to your post. I think the quality and quantity of Python documentation is hard to beat. -- Lloyd Kvam Venix Corp From kent37 at tds.net Tue Apr 11 20:21:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 14:21:22 -0400 Subject: [Tutor] Decorators In-Reply-To: <013301c65d87$0603d380$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp> <443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> Message-ID: <443BF3A2.9070107@tds.net> Alan Gauld wrote: >> proposal for dynamic function overloading: >> http://www.artima.com/weblogs/viewpost.jsp?thread=155514 > > I really don't like this proposal nor many of the others that currently > exist to seemingly turn Python into Java and C++! If people want to > code in the Java porridge let them use Java not try to turn Python > into the same sludge. FWIW there is enough perceived need for this (and adapters or protocols) that it has been invented already two or three times, in PEAK (by Philip J Eby, author of a popular "Python is not Java" rant*), Zope and twisted IIRC. The PEAK version has been adopted by TurboGears. I think twisted has abandoned its own effort and adopted Zope's. So I don't think it is necessarily people who want to turn Python into Java, but meeting a need that comes up in large projects. Kent * http://dirtsimple.org/2004/12/python-is-not-java.html From alan.gauld at freenet.co.uk Tue Apr 11 20:35:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 19:35:15 +0100 Subject: [Tutor] failing to learn python References: <20060410133342.GA7045@tranquility.scriptkitchen.com><443A6639.1050703@tds.net><20060410165200.GA15376@tranquility.scriptkitchen.com> <20060411160645.GB5242@tranquility.scriptkitchen.com> Message-ID: <015201c65d96$ad311370$0a01a8c0@xp> > On Mon, Apr 10, 2006 at 04:20:37PM -0700, Danny Yoo wrote: >> http://gnosis.cx/TPiP/ > > I will read that and Alan's tutorial too (isn't that MS-Windows specific > ???) Nope, it usually mentions *nix workarounds etc Most of it is OS neutral. The OS and IPC topic are mainly Unix centric. > without proving it at all. All the examples I wanted were done better in > shell/sed/awk. I use Python a lot but I still use sed and awk for what they are good at. Using the Right Tool for the Job is still a sound maxim. Python is a general programmjing language great for bigger jobs. If you just want to run a sequience of unix commands shell is better. If you want simple but bulk text manipulation awk or sed are best. Alan G. From doug.shawhan at gmail.com Tue Apr 11 20:56:04 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Tue, 11 Apr 2006 13:56:04 -0500 Subject: [Tutor] Scan Codes, Character Sets: Any Modules? In-Reply-To: <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> References: <5e1ceb8a0604110733n4341d0b9s3c86da0275a39cea@mail.gmail.com> <012f01c65d85$ad781740$0a01a8c0@xp> <5e1ceb8a0604111001u7a87f60ax65257cc22afb35d8@mail.gmail.com> <5e1ceb8a0604111014ldf51cccw36e4cb854d74727d@mail.gmail.com> Message-ID: <5e1ceb8a0604111156m21242e77gb44a8191bdf8260d@mail.gmail.com> No luck. I think I am missing something utterly basic, and completely unrelated to python. :-) I'll quit filling everyone's mailbox with cheese and move on to a terminal newsgroup for my future pesterances. Thanks for the help folks! On 4/11/06, doug shawhan wrote: > > Oho! http://www.wyse.com/service/support/kbase/Keydetl1.asp?Q=7&R=6 has > the hex codes! > > Thanks! Perhaps this will fix what ails me. > > > On 4/11/06, doug shawhan wrote: > > > > Yeah, termca was were I looked first. > > > > The OpenBSD 3.8 termcap shows: > > :cr=^M:ct=\E0:dc=\EW:dl=\ER:do=^J:ds=\EF\r:ei=\Er:fs=^M:\ for the carriage > > return, but then I can't find the hex code for ^M! :-) At that point I > > thought I'd ask if there was some sort of termcapesque module available. > > > > I will scope the wyse website again, perhaps I can locate it this time! > > > > Thanks > > > > > > On 4/11/06, Alan Gauld < alan.gauld at freenet.co.uk> wrote: > > > > > > Hi Doug, > > > > > > > I am attempting to screen scrape SuperDOS, uses wyse 60 terminals > > > > I must fall back to the old cntl-letter combos to get the cursor to > > > behave > > > > > > Sounds like you need to find a tech spec for the Wyse 60. That should > > > give you all of the Ctrl character combos to control the screen. > > > If you have access to a Unix box you might find the info you need > > > in the termcap or terminfo databases. But Wyse should have the > > > spec sheet on their web site somewhere... > > > > > > Alan G. > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/b6cbd965/attachment-0001.htm From mhansen at cso.atmel.com Tue Apr 11 21:19:40 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 11 Apr 2006 13:19:40 -0600 Subject: [Tutor] Database Connectivity In-Reply-To: <443BC704.5010203@tds.net> Message-ID: <002601c65d9c$e19d94c0$28645f0a@mikehansen> > Kaushal Shriyan wrote: > > Hi ALL > > > > How do i connect my python program to MySQL DB or Oracle DB > or can you > > please specify the URL which gives a detailed explanation on this. > > Basic connectivity is through modules that implement the > DB-API standard. Read the spec and find implementations here: > http://www.python.org/doc/topics/database/ > > There are several popular packages that layer on top of this > basic functionality such as SQLObject and SQLAlchemy. > > Kent The DB-API spec would go a long way if it had a couple of examples. Poking around the database topics, I came across an article in Linux Journal that seems to help http://www.linuxjournal.com/article/2605 Also, the MySQLdb module has some examples http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307#som e-examples The module for Postgre called psycopg has a nice PDF about the DB-API http://initd.org/pub/software/psycopg/dbapi20programming.pdf Mike From alan.gauld at freenet.co.uk Tue Apr 11 21:58:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 20:58:10 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> Message-ID: <017e01c65da2$42ac96d0$0a01a8c0@xp> > Syntactic sugar *IS* a practical benefit. After all, every language above > assember is syntactic sugar, and by your definition of no practical use. Ah, but by that standard even assembler is syntactic sugar, now where are those hex codes and my keypunch? :-) By practical use I mean adding function to the language. I agree decorators add a modicum of readability, but they also remove a large slice of Python's readability by introducing more line noise characters to the language, and that's a really bad feature from my perspective. As to your list of benefits: * Understand that a function has been modified I'm not sure I see how decorators do that? Can you give an example to explain what you mean? * Make it clear that a function is a staticmethod/classmethod/etc *right at the beginning of a function* without having to read the entire body. Not been an issue, I found the previous explicit statement to be just as useful. * Reduce typing Never a good reason for introducing features if the feature introduces line noise in my book! I'd rather type a few more characters than contend with $@% type crud. * Allow hinting of types for integration with tools like PyObjC Too esoteric for mainstream, if I want to program in ObjC (and I do!) I'll use ObjC. Its never worth corrupting one language just to integrate with another (The only exception I've ever been happy with in that regard is the asm/endasm directives in C/Pascal/Cobol/Fortran etc) * Make it clear when reading the definition of a method/function is memoised, traced etc I use a debugger for that kind of thing. * Simplifying augmentation of generators with arbitrary extra communications attributes. Never ventured into this area yet so can't comment. Alan G From alan.gauld at freenet.co.uk Tue Apr 11 22:08:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 21:08:12 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><00a801c65d3a$ad6b3b10$0a01a8c0@xp><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <443BF3A2.9070107@tds.net> Message-ID: <018401c65da3$a9b34b70$0a01a8c0@xp> >> I really don't like this proposal nor many of the others that currently >> exist to seemingly turn Python into Java and C++! If people want to > > FWIW there is enough perceived need for this (and adapters or protocols) > that it has been invented already two or three times, in PEAK (by Philip > ... > So I don't think it is necessarily people who want to turn Python into > Java, but meeting a need that comes up in large projects. Just because there is a perceived need doesn't make it good. C++ started out as a neat elegant extension to C that enabled it to do things that vanilla C couldn't. Then 'perceived need' added features to support just about every OOP concept and flavour going, plus adding a few new ones. The end result is a nightmare language with so many holes gaping that it is almost impossible to use effectively. The result of that was the brain-dead Java v1 language which is now being frantically patched and is rapidly turning into another rotting pile of syntax. Unfortunately there is a real danger of Python going the same way.What was an easy to learn and use, ideal language for medium sized to fairly large scripting projects is trying to turn into an all encompassing general purpose language which will be increasingly difficult to use without falling down some new syntax hole. I would hate for that to happen to Python simply because people are trying to stretch it beyond its natural envelope. Sadly Lisp appears to be the only language so far that has succeeded in extending without losing its inherent simplicity of structure and syntax. Unfortunately Lisp's simplicity is only apparent to mathemeticians! :-) Alan G From alan.gauld at freenet.co.uk Tue Apr 11 22:15:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 21:15:30 +0100 Subject: [Tutor] for loops References: <20060411161340.72598.qmail@web60819.mail.yahoo.com> <20060411174711.GB2865@wdfs.graniteweb.com> Message-ID: <018e01c65da4$ae381ad0$0a01a8c0@xp> >> >>Write a Python program to print out the following shape. >> >>You are expected to use two for loops (these must be nested) to solve >> this problem. >> >> output: >> * * * * * >> * * >> * * >> * * * * * > > That looks a lot like homework. I agree and very poor homework too. I certainly wouldn't expect to use two for loops, I'd only use one. (And that assumes the more general problem of drawing an arbitrary sized square, for the specific case I'd use a single print statement and triple quoted string!) Any homework which implies that only one design is acceptable is a bad assignment in my book! > We generally try to stay away from doing the work for you :-) But the advice stays good. Tell us how far you got and what's sticking you and we will try to help... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Tue Apr 11 22:42:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 11 Apr 2006 13:42:20 -0700 Subject: [Tutor] Decorators In-Reply-To: <017e01c65da2$42ac96d0$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> Message-ID: <443C14AC.5020302@alum.rpi.edu> Alan Gauld wrote: >> Syntactic sugar *IS* a practical benefit. After all, every language above >> assember is syntactic sugar, and by your definition of no practical use. >> > > Ah, but by that standard even assembler is syntactic sugar, now > where are those hex codes and my keypunch? :-) Only those of us who keyed the bin loader into a PDP-8 by toggling switches, each representing one bit, can claim to be the most free of syntactic sugar. "Real programmers eschew languages. They do it on the bare metal." From hugonz-lists at h-lab.net Tue Apr 11 22:44:00 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 11 Apr 2006 14:44:00 -0600 Subject: [Tutor] Tuple (Section 9.3) In-Reply-To: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> References: <6b16fb4c0604110326q7059fb31rcc4f6f267498a8e9@mail.gmail.com> Message-ID: <443C1510.2000308@h-lab.net> Hi Kaushal, I might have to do a little guessing and see what is not clear from the explanation. The whole point of returning a tuple as opposed to, say, returning a list, is the fact that tuples are NON mutable. That is, *apparently* you would not be returning a reference, but the values themselves. There is no better example I can think of, than the one you already read. If you want a function tu return multiple parameters so that you can do. ret1, ret2 = func() then have func return a tuple. That's the whole point of the chapter you read. Maybe there is too much information in the discussion that does not look useful to you if you have not run into a problem where you need it. I hope this is not some kind of homework :) Hugo From fant at pobox.com Tue Apr 11 23:24:32 2006 From: fant at pobox.com (Andrew D. Fant) Date: Tue, 11 Apr 2006 17:24:32 -0400 Subject: [Tutor] Decorators In-Reply-To: <017e01c65da2$42ac96d0$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> Message-ID: <443C1E90.7020105@pobox.com> Alan Gauld wrote: >>Syntactic sugar *IS* a practical benefit. After all, every language above >>assember is syntactic sugar, and by your definition of no practical use. > > > Ah, but by that standard even assembler is syntactic sugar, now > where are those hex codes and my keypunch? :-) > > By practical use I mean adding function to the language. > I agree decorators add a modicum of readability, but > they also remove a large slice of Python's readability > by introducing more line noise characters to the language, > and that's a really bad feature from my perspective. > *chomp* (sorry for introducing perl constructs here 8) > Alan G Alan, May I just say AMEN? One of the reasons I started using python is that it was the first programming language I had seen since Fortran that didn't make my eyes cross from line noise characters stuck in among the text. Has anyone ever studied the effect of decorators on code readability? Personally, I think that if we want to add a bunch of unpronounceable characters to our code, we should go back to using APL. (for those who miss it, A+ is a fairly decent modern update of the concept) Now if you REALLY want to get funky. try crossing lisp with APL for a mathematically pure language that nobody can ever read. Andy -- Andrew Fant | And when the night is cloudy | This space to let Molecular Geek | There is still a light |---------------------- fant at pobox.com | That shines on me | Disclaimer: I don't Boston, MA | Shine until tomorrow, Let it be | even speak for myself From bgailer at alum.rpi.edu Wed Apr 12 00:10:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 11 Apr 2006 15:10:20 -0700 Subject: [Tutor] Decorators In-Reply-To: <443C1E90.7020105@pobox.com> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org> <017e01c65da2$42ac96d0$0a01a8c0@xp> <443C1E90.7020105@pobox.com> Message-ID: <443C294C.1050205@alum.rpi.edu> Andrew D. Fant wrote: > [snip] try crossing lisp > with APL for a mathematically pure language that nobody can ever read. > One problem is that APL allowed unbalanced parentheses (as in )SAVE), whereas LISP does not. And of course there is the right-to-left vs left-to-right issue... I do miss the incredible succinctness of APL. One "line noise" character was worth (say) 10 lines of (say) Fortran. I'd like to see some APL-ness added to Python, as I struggle to write a comprehension equivalent to one APL character. From victor at grupocdm.com Wed Apr 12 00:15:58 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 17:15:58 -0500 Subject: [Tutor] Extending a list within a list comprehension Message-ID: <1144793758.6561.108.camel@elrond> Hi all, I have solved my problem, but would like to know if what I accomplished can be done with different data using list comprehensions. the list I want to sort has the following format: elements = [ (codigo, [ cant, importe, porc]), (codigo, [ cant, importe, porc]), ... ] Actual data is: In [129]: elements[0:5] Out[129]: [('2712', [22.0, 3618.8099999999999, 0.0032389476163069883]), ('2713', [19.0, 6551.8100000000004, 0.0058640739309320719]), ('2710', [21.0, 2553.5799999999999, 0.0022855336019435113]), ('2716', [19.0, 8215.2700000000004, 0.0073529224203034461]), ('4305', [4.0, 348.37, 0.00031180199598565978])] And I want to sort descending on 'importe', which is x[1][1] for x in elements. What I did was the following, following the Schwarzian Transform: temporal = [] temporal = [ [x[1][1], (x[0], description[x[0]], x[1][0], x[1][1], x[1][2] ) ] for x in elements ] temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] If the second element in each array passed as x is of variable length (that is, it has a different element count than three, in this case), the program needs to extend the list instead. Without list comprehensions, and the added capability to utilize and sized list as a second element, my code ended up looking like the following: temporal = [] for x in elements: lst = [x[0], description[x[0]]] lst.extend(x[1]) temporal.append([x[1][1], lst]) temporal.sort() temporal.reverse() # sort descending elements = [ x[1] for x in temporal ] Is there a way to use list comprehensions to append or extend the array as needed by the second code listing? Thanks. Victor From john at fouhy.net Wed Apr 12 00:29:55 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 12 Apr 2006 10:29:55 +1200 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144793758.6561.108.camel@elrond> References: <1144793758.6561.108.camel@elrond> Message-ID: <5e58f2e40604111529m5849bc6o1f2ba0fd27e5d6a0@mail.gmail.com> On 12/04/06, Victor Bouffier wrote: > elements = [ > (codigo, [ cant, importe, porc]), > (codigo, [ cant, importe, porc]), > ... > ] > > And I want to sort descending on 'importe', which is x[1][1] for x in > elements. In python 2.4, you could achieve this by saying: elements.sort(key=lambda x: x[1][1]) In earlier versions of python, you can do: elements.sort(lambda x, y: cmp(x[1][1], y[1][1])) (but this is less efficient than key= in 2.4) There's also the decorate-sort-undecorate idiom: dec = [(x[1][1], x) for x in elements] dec.sort() elements = [x[1] for x in dec] -- John. From alan.gauld at freenet.co.uk Wed Apr 12 00:34:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 23:34:51 +0100 Subject: [Tutor] Decorators References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <200604111903.15240.ms@cerenity.org><017e01c65da2$42ac96d0$0a01a8c0@xp> <443C14AC.5020302@alum.rpi.edu> Message-ID: <01a401c65db8$2704cef0$0a01a8c0@xp> >> Ah, but by that standard even assembler is syntactic sugar, now >> where are those hex codes and my keypunch? :-) > Only those of us who keyed the bin loader into a PDP-8 by toggling > switches, each representing one bit, can claim to be the most free of > syntactic sugar. Never used a PDP 8 (but I did use a PDP 11), but I have keyed binary boot sequences into a Data General machine in the late '70s using the front panel DIP switches Alan G. From alan.gauld at freenet.co.uk Wed Apr 12 00:42:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 11 Apr 2006 23:42:29 +0100 Subject: [Tutor] Extending a list within a list comprehension References: <1144793758.6561.108.camel@elrond> Message-ID: <01ae01c65db9$385a6920$0a01a8c0@xp> Hi Victor, I've gotta say that I much prefer the second version here. > temporal = [] > temporal = [ [x[1][1], (x[0], description[x[0]], > x[1][0], x[1][1], x[1][2] ) ] for x in elements ] > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > > > temporal = [] > for x in elements: > lst = [x[0], description[x[0]]] > lst.extend(x[1]) > temporal.append([x[1][1], lst]) > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > That looks a lot easier to rtead (and debug) and will I suspect be easier to maintain. Copmprehensions are great but unfortunately can rapidly become incomprehensible! > Is there a way to use list comprehensions to append or extend the array > as needed by the second code listing? There may be but I wouldn't try. I might however look at using a simple list or dictionary of objects based on a class... It might be easier. Alan G From victor at grupocdm.com Wed Apr 12 01:14:41 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:14:41 -0500 Subject: [Tutor] [Fwd: Re: Extending a list within a list comprehension] Message-ID: <1144797282.6561.126.camel@elrond> I sent this to John directly. Posting to the list. -------- Forwarded Message -------- From: Victor Bouffier To: John Fouhy Subject: Re: [Tutor] Extending a list within a list comprehension Date: Tue, 11 Apr 2006 18:03:41 -0500 On Wed, 2006-04-12 at 10:29 +1200, John Fouhy wrote: > On 12/04/06, Victor Bouffier wrote: > > elements = [ > > (codigo, [ cant, importe, porc]), > > (codigo, [ cant, importe, porc]), > > ... > > ] > > > > And I want to sort descending on 'importe', which is x[1][1] for x in > > elements. > > In python 2.4, you could achieve this by saying: > > elements.sort(key=lambda x: x[1][1]) > > In earlier versions of python, you can do: > > elements.sort(lambda x, y: cmp(x[1][1], y[1][1])) > > (but this is less efficient than key= in 2.4) > > There's also the decorate-sort-undecorate idiom: > > dec = [(x[1][1], x) for x in elements] > dec.sort() > elements = [x[1] for x in dec] Hi John, Thanks for your help. This is very nice and I will definitely use it when sorting a fixed list. However, I forgot to point out I am including an extra element: item description from a dict, where its key=codigo (x[0]). This is why I write the whole list as a single element. Still I could follow your suggestion and do: dec = [(x[1][1], x, description[x[0]]) for x in elements] dec.sort() elements = [x[1], x[2] for x in dec] It is still better, but not quite there. Any feedback will be gladly taken. Victor From victor at grupocdm.com Wed Apr 12 01:18:03 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:18:03 -0500 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <01ae01c65db9$385a6920$0a01a8c0@xp> References: <1144793758.6561.108.camel@elrond> <01ae01c65db9$385a6920$0a01a8c0@xp> Message-ID: <1144797483.6561.131.camel@elrond> On Tue, 2006-04-11 at 23:42 +0100, Alan Gauld wrote: > Hi Victor, > > I've gotta say that I much prefer the second version here. > > > temporal = [] > > temporal = [ [x[1][1], (x[0], description[x[0]], > > x[1][0], x[1][1], x[1][2] ) ] for x in elements ] > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > > > temporal = [] > > for x in elements: > > lst = [x[0], description[x[0]]] > > lst.extend(x[1]) > > temporal.append([x[1][1], lst]) > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > That looks a lot easier to rtead (and debug) and will I suspect be > easier to maintain. Copmprehensions are great but unfortunately > can rapidly become incomprehensible! > > > Is there a way to use list comprehensions to append or extend the array > > as needed by the second code listing? > > There may be but I wouldn't try. > I might however look at using a simple list or dictionary of objects based > on a class... It might be easier. > > Alan G > > Hi Alan, I believe you are right. The most pythonic way is not always the most "perlish" way ;-) (no offense intended to Perl-comers, but Perl does tend to promote nesting of expressions). It is much easier to read and maintain, which is what I will need to do eventually. Thanks for the feedback. Victor From victor at grupocdm.com Wed Apr 12 01:35:11 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Tue, 11 Apr 2006 18:35:11 -0500 Subject: [Tutor] Decorators In-Reply-To: <018401c65da3$a9b34b70$0a01a8c0@xp> References: <57aa55060604101219t242c9fe9p142eecb0e9829502@mail.gmail.com> <00a801c65d3a$ad6b3b10$0a01a8c0@xp><443B81DA.90709@tds.net> <013301c65d87$0603d380$0a01a8c0@xp> <443BF3A2.9070107@tds.net> <018401c65da3$a9b34b70$0a01a8c0@xp> Message-ID: <1144798511.6561.141.camel@elrond> On Tue, 2006-04-11 at 21:08 +0100, Alan Gauld wrote: > What was an easy to learn and use, ideal language > for medium sized to fairly large scripting projects is trying to turn > into > an all encompassing general purpose language which will be > increasingly difficult to use without falling down some new syntax > hole. Alan, I could not agree more. Python's has both simplicity in its syntax and very powerful constructs like generators and object orientation included. I would hate to eventually need a Python reference book by my side for even the simplest of projects because I could not remember $#& meant a returned value from a function when the value was a particular type (I used to work with Perl and you can get into that pretty quickly). From rfquerin at gmail.com Wed Apr 12 03:47:05 2006 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 11 Apr 2006 21:47:05 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results Message-ID: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> I'm a relative newbie writing a function that carries out a bunch of calculations. The function requires about 4 or 5 numeric arguments as input but the data returned from the function call is about a dozen numbers in addition to a list of strings and a fairly long list of numbers (200+). My question is whether to create an class object beforehand and pass this into and out of the function, or to just keep things simple and pass in the 4 arguments and return a simple list object containing the numbers and lists of strings and numbers. Is there any benefit to using an class object for this? I don't want to limit what I can do with the returned data later. I want to be able to display the results of this function in different ways later on. I'm going to have a lot of functions of this type and I know I will have to keep the format of the results list object well documented in order to keep track of what is returned when I look at the code 6 months from now. Is a simple list the best way? or a class object? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/5a70883f/attachment.htm From hokkakada at khmeros.info Wed Apr 12 03:51:03 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 08:51:03 +0700 Subject: [Tutor] encoding Message-ID: <443C5D07.90607@khmeros.info> Hi all, Does anybody know how to decode to Windows Latin ("ANSI") I know how to decode to utf-8: stringinput = stringinput.decode('utf-8') but while I use stringinput = stringinput.decode('ANSI') LookupError: unknown encoding: ANSI so what is the correct way to do it? Thanks and !Happy Khmer New Year! kakada From kent37 at tds.net Wed Apr 12 04:17:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 22:17:50 -0400 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144793758.6561.108.camel@elrond> References: <1144793758.6561.108.camel@elrond> Message-ID: <443C634E.2050804@tds.net> Victor Bouffier wrote: > If the second element in each array passed as x is of variable length > (that is, it has a different element count than three, in this case), > the program needs to extend the list instead. Without list > comprehensions, and the added capability to utilize and sized list as a > second element, my code ended up looking like the following: > > temporal = [] > for x in elements: > lst = [x[0], description[x[0]]] > lst.extend(x[1]) > temporal.append([x[1][1], lst]) > temporal.sort() > temporal.reverse() # sort descending > elements = [ x[1] for x in temporal ] > > Is there a way to use list comprehensions to append or extend the array > as needed by the second code listing? I think you are looking for temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] but I would make two steps, one for the sort using just [ (x[0], x) for x in elements ] then when you pick the data back out you can format it how you like. Kent PS to John: the original solution is using DSU, aka Schwarzian Transform From rfquerin at gmail.com Wed Apr 12 04:27:26 2006 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 11 Apr 2006 22:27:26 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results In-Reply-To: <443C63D5.9060406@tds.net> References: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> <443C63D5.9060406@tds.net> Message-ID: <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> On 4/11/06, Kent Johnson wrote: > > There is no need to pass the class object in to the function, you can > create it in the function and return it. A class might be nice because > it gives names to the various values. A dict can also be used for this. > Do what feels right :-) To be more specific, I'm going to have probably 6 functions that do similar things. They all take slightly different arguments, they all do slightly different calculations, but the results of all the functions are the same format. So I guess it makes sense to use a class. Now, when you say 'create it in the function', you mean create the class instance inside the function and return that instance? The class itself is defined somewhere else in the module containing the functions so that all the functions have access to it. (Total newb to python and classes so sorry if that's a stupid question). -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/349c4c84/attachment.htm From kent37 at tds.net Wed Apr 12 04:32:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Apr 2006 22:32:35 -0400 Subject: [Tutor] Question About Function Arguments and Returned Results In-Reply-To: <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> References: <7d81675b0604111847p4e407104h27638c53d1e97547@mail.gmail.com> <443C63D5.9060406@tds.net> <7d81675b0604111927r133ad3ebvf2c9b49b375efd29@mail.gmail.com> Message-ID: <443C66C3.40101@tds.net> Richard Querin wrote: > > > On 4/11/06, *Kent Johnson* > wrote: > > > There is no need to pass the class object in to the function, you can > create it in the function and return it. A class might be nice because > it gives names to the various values. A dict can also be used for this. > Do what feels right :-) > > > To be more specific, I'm going to have probably 6 functions that do > similar things. They all take slightly different arguments, they all do > slightly different calculations, but the results of all the functions > are the same format. So I guess it makes sense to use a class. Now, when Yes, that's a good argument for a class. > you say 'create it in the function', you mean create the class instance > inside the function and return that instance? The class itself is > defined somewhere else in the module containing the functions so that > all the functions have access to it. (Total newb to python and classes > so sorry if that's a stupid question). Right, create the class instance in the function. class ReturnedValue(object): def __init__(self, value): self.value = value def myFunction(x, y, z, w): return ReturnedValue(x+y+z+w) Season to taste ;) Kent From hokkakada at khmeros.info Wed Apr 12 05:19:22 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 10:19:22 +0700 Subject: [Tutor] dictionary datatype Message-ID: <443C71BA.3040608@khmeros.info> Hello all, For example, I have a dictionary: dict1 = { 0x2018:u'k', 0x2019:u'd'} I assign: n = 0x2018 print dict1[n] Then: KeyError: '0x2018' But I can call directly: print dict1[0x2018] So, what is wrong with this? How can I solve it? Thx kakada From jason.massey at gmail.com Wed Apr 12 05:37:59 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 11 Apr 2006 22:37:59 -0500 Subject: [Tutor] dictionary datatype In-Reply-To: <443C71BA.3040608@khmeros.info> References: <443C71BA.3040608@khmeros.info> Message-ID: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Works for me: >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} >>> n = 0x2018 >>> print dict1[n] k >>> On 4/11/06, kakada wrote: > > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060411/2a70a60e/attachment.htm From victor at grupocdm.com Wed Apr 12 07:17:35 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 12 Apr 2006 00:17:35 -0500 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <443C634E.2050804@tds.net> References: <1144793758.6561.108.camel@elrond> <443C634E.2050804@tds.net> Message-ID: <1144819055.12108.15.camel@elrond> On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote: > Victor Bouffier wrote: > > > If the second element in each array passed as x is of variable length > > (that is, it has a different element count than three, in this case), > > the program needs to extend the list instead. Without list > > comprehensions, and the added capability to utilize and sized list as a > > second element, my code ended up looking like the following: > > > > temporal = [] > > for x in elements: > > lst = [x[0], description[x[0]]] > > lst.extend(x[1]) > > temporal.append([x[1][1], lst]) > > temporal.sort() > > temporal.reverse() # sort descending > > elements = [ x[1] for x in temporal ] > > > > Is there a way to use list comprehensions to append or extend the array > > as needed by the second code listing? > > I think you are looking for > temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] > Hi Kent, I try this one and get the following error: TypeError: list objects are unhashable I figured it is because of the x[0] element being used as a dict key. Can you explain further where this error comes from? Are you getting it too? > but I would make two steps, one for the sort using just > [ (x[0], x) for x in elements ] > You are right. This is cleaner and not a big deal to do in two steps. However for the issue at hand, it still keeps x as a two element list: [codigo, [ cant, importe, porc]], which I would like to have extended: [codigo, cant, importe, porc] It is not a big deal. That is why I finally went with the longer version Alan suggested. Before the sort I get a two element list, the second element being the list I finally want as output. > then when you pick the data back out you can format it how you like. > Right. After the sort I just get that second element in another list comprehension lines = [ x[1] for x in temp ] Thanks for your help. Victor > > Kent > > PS to John: the original solution is using DSU, aka Schwarzian Transform > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From victor at grupocdm.com Wed Apr 12 07:30:56 2006 From: victor at grupocdm.com (Victor Bouffier) Date: Wed, 12 Apr 2006 00:30:56 -0500 Subject: [Tutor] dictionary datatype In-Reply-To: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> References: <443C71BA.3040608@khmeros.info> <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Message-ID: <1144819856.12108.26.camel@elrond> On Tue, 2006-04-11 at 22:37 -0500, Jason Massey wrote: > Works for me: > > >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} > >>> n = 0x2018 > >>> print dict1[n] > k > >>> > > On 4/11/06, kakada wrote: > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > 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 Look into the value of n after assignment: In [285]: n = 0x2018 In [286]: n Out[286]: 8216 n is taken as an integer containing the decimal number 8216, which in hex is represented as 0x2018. Try again to see if you did not mistakenly typed dict1['0x2018'] or else defined n as such. If you try dict1[n], dict1[0x2018], or dict1[8216] you get a correct result, since the integer variable 'n' contains that value. Trying dict1['0x2016'] gives you the error because the key does not exist. define dict1 as: dict1 = { 0x2018:u'k', 0x2019:u'd'} and then display it whole: In [299]: print dict1 {8216: u'k', 8217: u'd'} Can you see your '0x2018' key anywhere? HTH Victor From kaushalshriyan at gmail.com Wed Apr 12 07:46:50 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Apr 2006 11:16:50 +0530 Subject: [Tutor] Tuples Message-ID: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm I did not understood the below Section at all :( 9.3 Tuples as return values Functions can return tuples as return values. For example, we could write a function that swaps two parameters: def swap(x, y): return y, x Then we can assign the return value to a tuple with two variables: a, b = swap(a, b) In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake: def swap(x, y): # incorrect version x, y = y, x If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing xinside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error. As an exercise, draw a state diagram for this function so that you can see why it doesn't work. Thanks in Advance Regards Kaushal From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 10:44:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 01:44:07 -0700 (PDT) Subject: [Tutor] Tuples / Critique of How to Think like a Computer Scientist [Was: Re: Tuples] In-Reply-To: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> References: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Message-ID: On Wed, 12 Apr 2006, Kaushal Shriyan wrote: > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm > I did not understood the below Section at all :( Hi Kaushal, Ok, let's trying starting somewhere else and see at what point you get stuck. It'll also give you a chance to practice what you do understand so far. Are you comfortable about being able to return things besides numbers or strings from a function? In particular, do you have any experience writing functions that return tuples? For example, could you write a function that takes two elements, and wraps its input in a tuple? Let's call this function something, like wrap(). We'd expect wrap() to do something like this: wrap(5, 6) --> (5, 6) wrap("hello", "world") --> ("hello", "world") Would you be able to write a definition of wrap()? Let's start from there and see if we can isolate where you're getting stuck. Also, if you are having trouble with How to Think Like a Computer Scientist, I wouldn't be ashamed; I'm not such a big fan of it myself anymore. You might want to take a look at the other tutorials on: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers --- I'm going to rant, but not at you, but at that particular tutorial you're reading. To the others on the list: frankly, I really do not like the approach that "How to Think like a Computer Scientist" uses in marching through all the concepts it tries to teach; in a critical eye, I would say that it's doesn't do such a good job in integrating concepts, nor does it have natural flow. Am I alone in thinking this? Chapter Nine seems especially problematic in terms of flow. It's as if they say: "Here are tuples, a data structure. You should learn them. Ok, next up: here's something else you have to learn called random numbers. They have nothing to do with those tuple things what we just talked about, but we have to hurry if we're going to finish covering all the things in the glossary." Maybe I'm just reading too pessimistically into it, but the tutorial just seems to go out of its way to avoid flowing one concept into another, but instead jolting the student across the landscape. When I read part of that section you pointed out, there's one particular thing I strongly disagree with, that is, when they throw a rocky curveball with the introduction of the "broken" swap() function: ######################################## def swap(x, y): # broken x, y = y, x ######################################## The issue they try to tackle here really has nothing to do with tuples. The same "bug" occurs with: ###### def broken_swap(x, y): t = x x = y y = t ###### or, for that matter: ###### def broken_double(x): x = x * 2 ###### So I'm actually not quite sure why the tutorial is trying to make a point about this. It's an issue that should have been touched on much earlier in Chapter Five or Six, when functions and "multiple assignment" were introduced, so mixing it in with the tuple stuff just seems off-track and deliberately bewildering. And mixing it in haphazardly here risks the student thinking: "does the issue here have anything to do with this 'immutability' thing I just read about a few paragraphs ago?" From kaushalshriyan at gmail.com Wed Apr 12 11:12:15 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 12 Apr 2006 14:42:15 +0530 Subject: [Tutor] Explanation of Lists data Type Message-ID: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Hi All I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm 8.7 List slices -------------------------------------------- >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] >>> list[1:3] ['b', 'c'] -----> I understood this >>> list[:4] --> Does this mean its list[0:4] ['a', 'b', 'c', 'd'] ----> I didnot understood this >>> list[3:] --> Does this mean its list[3:0] ['d', 'e', 'f'] ----> I didnot understood this >>> list[:] --> Does this mean its list[0:0] ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this Please explain me Thanks in Advance Regards Kaushal From ajikoe at gmail.com Wed Apr 12 11:32:10 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 12 Apr 2006 11:32:10 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: Hello, On 4/12/06, Kaushal Shriyan wrote: > > Hi All > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm > > 8.7 List slices > -------------------------------------------- > >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] > >>> list[1:3] > ['b', 'c'] -----> I understood this >>> list[:4] --> Does this mean its list[0:4] ':' here means --> from the first element to element index 4 > ['a', 'b', 'c', 'd'] ----> I didnot understood this >>> list[3:] --> Does this mean its list[3:0] ':' here means --> from element index 3 to the last element ['d', 'e', 'f'] ----> I didnot understood this >>> list[:] --> Does this mean its list[0:0] ':' here means --> from the first element to the last element > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this Please explain me > > Thanks in Advance > > Regards > > Kaushal Hope, this helps pujo _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/10110cd1/attachment.html From ajikoe at gmail.com Wed Apr 12 11:34:31 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 12 Apr 2006 11:34:31 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: Sorry for the last explanations....there is a correction! On 4/12/06, Pujo Aji wrote: > > Hello, > > > On 4/12/06, Kaushal Shriyan wrote: > > > > Hi All > > > > I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm > > > > 8.7 List slices > > -------------------------------------------- > > >>> list = ['a', 'b', 'c', 'd', 'e', 'f'] > > >>> list[1:3] > > ['b', 'c'] -----> I understood this > > > > > >>> list[:4] --> Does this mean its list[0:4] > > ':' here means --> from the first element to element index 3 # > corrected > > > ['a', 'b', 'c', 'd'] ----> I didnot understood this > > > > > >>> list[3:] --> Does this mean its list[3:0] > > ':' here means --> from element index 3 to the last element > ['d', 'e', 'f'] ----> I didnot understood this > > > > >>> list[:] --> Does this mean its list[0:0] > > ':' here means --> from the first element to the last element > > > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this > > > > > Please explain me > > > > Thanks in Advance > > > > Regards > > > > Kaushal > > > > > Hope, this helps > pujo > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/25042de8/attachment.htm From noufal at nibrahim.net.in Wed Apr 12 11:43:11 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 12 Apr 2006 15:13:11 +0530 (IST) Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: <38291.203.145.176.76.1144834991.squirrel@members.hcoop.net> On Wed, April 12, 2006 2:42 pm, Kaushal Shriyan wrote: >>>> list[:] --> Does this mean its list[0:0] > ['a', 'b', 'c', 'd', 'e', 'f'] ----> I didnot understood this I remember you once asked another question related to sequence slices and I mentioned the effects of slicing with no indices. You sure you're reading the replies? ;) When you leave an index in the slice argument, it will assume that you meant the maximum (or minimum as the case may be) possible. For example. >>> foo = ['a','b','c','d','e'] >>> foo[2] #Element at index 2 'c' >>> foo[2:] #Elements from index two till the end ['c', 'd', 'e'] >>> foo[:2] #Elements from the beginning till index 2. ['a', 'b'] >>> Now, when you give a [:] to the slice operator, you get a copy of the original list. This is shown below >>> bar = foo[:] #bar contains a copy of foo >>> baz = foo #baz is an alias for foo (not a copy) >>> baz is foo #Are baz and foo the same? True #Yes they are >>> bar is foo #Are bar and foo the same? False #No they're not. It's a copy remember? >>> bar[2]="test" #Change element at index 2 of bar to "test" >>> bar # Print it ['a', 'b', 'test', 'd', 'e'] # It's changed >>> foo # Has foo changed as well? ['a', 'b', 'c', 'd', 'e'] # Nope. Because bar is a copy of foo. >>> baz[2]="test" # Now we change element at index 2 of baz. >>> baz # Has baz changed? ['a', 'b', 'test', 'd', 'e'] # Of course. :) >>> foo # Has foo changed? ['a', 'b', 'test', 'd', 'e'] # Yes. Since baz was an alias of foo. >>> I trust this clears things up. Also, try not to use "list" as a variable name since it's a builtin. -- -NI From kent37 at tds.net Wed Apr 12 12:08:12 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 06:08:12 -0400 Subject: [Tutor] Extending a list within a list comprehension In-Reply-To: <1144819055.12108.15.camel@elrond> References: <1144793758.6561.108.camel@elrond> <443C634E.2050804@tds.net> <1144819055.12108.15.camel@elrond> Message-ID: <443CD18C.2030802@tds.net> Victor Bouffier wrote: > On Tue, 2006-04-11 at 22:17 -0400, Kent Johnson wrote: >> Victor Bouffier wrote: >> >>> If the second element in each array passed as x is of variable length >>> (that is, it has a different element count than three, in this case), >>> the program needs to extend the list instead. Without list >>> comprehensions, and the added capability to utilize and sized list as a >>> second element, my code ended up looking like the following: >>> >>> temporal = [] >>> for x in elements: >>> lst = [x[0], description[x[0]]] >>> lst.extend(x[1]) >>> temporal.append([x[1][1], lst]) >>> temporal.sort() >>> temporal.reverse() # sort descending >>> elements = [ x[1] for x in temporal ] >>> >>> Is there a way to use list comprehensions to append or extend the array >>> as needed by the second code listing? >> I think you are looking for >> temporal = [ [x[0], description[x[0]]] + x[1] for x in elements ] >> > > Hi Kent, > I try this one and get the following error: > > TypeError: list objects are unhashable It's helpful if you show the traceback as well as the error message. > > I figured it is because of the x[0] element being used as a dict key. > Can you explain further where this error comes from? Are you getting it > too? No, I don't know what is causing it. Isn't x[0] a string? What is description? I didn't run the code myself. Kent From hokkakada at khmeros.info Wed Apr 12 12:20:18 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 12 Apr 2006 17:20:18 +0700 Subject: [Tutor] dictionary datatype In-Reply-To: <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> References: <443C71BA.3040608@khmeros.info> <7e3eab2c0604112037m4e00810ck7f3d526a9dafa8cc@mail.gmail.com> Message-ID: <443CD462.7010103@khmeros.info> It also works for me now:) First i tried it with Konsole in Kate and it's not working. It sometimes happen with assignment statement: i += 1 (not working) i+= 1(working) but later on I tested it again and both are working. Thanks for your help, though. da Jason Massey wrote: > Works for me: > > >>> dict1 = { 0x2018:u'k', 0x2019:u'd'} > >>> n = 0x2018 > >>> print dict1[n] > k > >>> > > On 4/11/06, * kakada* > wrote: > > Hello all, > > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > > But I can call directly: > print dict1[0x2018] > > So, what is wrong with this? How can I solve it? > > Thx > > kakada > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From payal-python at scriptkitchen.com Wed Apr 12 16:02:01 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Wed, 12 Apr 2006 10:02:01 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <015201c65d96$ad311370$0a01a8c0@xp> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> Message-ID: <20060412140201.GA8795@tranquility.scriptkitchen.com> On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote: > Python is a general programmjing language great for bigger jobs. If But what does Python excel at. That si my main question. Whatevfer I think of I can already do or know a way to do in shell. I am not getting where would I need Python. e.g. for parsing log files with regex I rather use egrep than Python. For counting the number of mails received for a user I use awk, where can I use Python. Everyone says it is a "general programming language", but what in the world is a "general programming language"? The Python video said that one can take this language to good level in 1 afternoon, for me it has been 2 months and more. What is wrong? With warm regards, -Payal From kent37 at tds.net Wed Apr 12 16:23:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 10:23:16 -0400 Subject: [Tutor] failing to learn python In-Reply-To: <20060412140201.GA8795@tranquility.scriptkitchen.com> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: <443D0D54.7090105@tds.net> Payal Rathod wrote: > On Tue, Apr 11, 2006 at 07:35:15PM +0100, Alan Gauld wrote: >> Python is a general programmjing language great for bigger jobs. If > > But what does Python excel at. That si my main question. Whatevfer I > think of I can already do or know a way to do in shell. I am not getting > where would I need Python. > e.g. for parsing log files with regex I rather use egrep than Python. > For counting the number of mails received for a user I use awk, where It's possible that for the jobs you need to do, you are already using the best tools. If you know shell, egrep and awk, they are probably better than Python at doing the things they do. For me, I don't know those specialized tools and I have chosen not to learn them because I don't often need their capabilities and Python can do what they do. Maybe not as easily to one fluent in both, but I would rather learn one tool that is widely useful than several narrow ones that I would use rarely. > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? A programming language that can be used for a wide variety of tasks, rather than being specialized to a particular domain. Some things that Python can be used for that might be hard with the tools you know: mailing list manager (Mailman) spam filter (SpamBayes) distributed file sharing (BitTorrent) dynamic web site (Django, TurboGears, etc, etc) web scraping (urllib, BeautifulSoup) XML processing (ElementTree, etc) GUIs (Tkinter, wxPython, etc) Also take a look at some of the case studies here: http://www.python.org/about/success/ or search sourceforge.net for Python projects. Kent From hugonz-lists at h-lab.net Wed Apr 12 16:57:13 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 12 Apr 2006 08:57:13 -0600 Subject: [Tutor] encoding In-Reply-To: <443C5D07.90607@khmeros.info> References: <443C5D07.90607@khmeros.info> Message-ID: <443D1549.6010802@h-lab.net> kakada wrote: > LookupError: unknown encoding: ANSI > > so what is the correct way to do it? > stringinput.encode('latin_1') works for me. Do a Google search for Python encodings, and you will find what the right names for the encodings are. http://docs.python.org/lib/standard-encodings.html Hugo From hugonz-lists at h-lab.net Wed Apr 12 17:00:27 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 12 Apr 2006 09:00:27 -0600 Subject: [Tutor] dictionary datatype In-Reply-To: <443C71BA.3040608@khmeros.info> References: <443C71BA.3040608@khmeros.info> Message-ID: <443D160B.4040403@h-lab.net> kakada wrote: > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' > Notice the error menstions a *string*. You probably mistyped it, not in the email, but in your actual program. Hugo From alan.gauld at freenet.co.uk Wed Apr 12 19:01:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:01:15 +0100 Subject: [Tutor] dictionary datatype References: <443C71BA.3040608@khmeros.info> Message-ID: <01fc01c65e52$b5fc0700$0a01a8c0@xp> > For example, I have a dictionary: > dict1 = { 0x2018:u'k', 0x2019:u'd'} > > I assign: > n = 0x2018 > print dict1[n] > > Then: > KeyError: '0x2018' The error is complaining that you are using a string as a key. Are you sure you aren't assigning n = '0x2018' Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 19:07:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:07:59 +0100 Subject: [Tutor] Tuples / Critique of How to Think like a Computer Scientist[Was: Re: Tuples] References: <6b16fb4c0604112246m745f4e03ya59d6fe45eb6fe8f@mail.gmail.com> Message-ID: <020601c65e53$a6d5e510$0a01a8c0@xp> > I'm going to rant, but not at you, but at that particular tutorial you're > reading. To the others on the list: frankly, I really do not like the > approach that "How to Think like a Computer Scientist" uses in marching > through all the concepts it tries to teach; in a critical eye, I would say > that it's doesn't do such a good job in integrating concepts, nor does it > have natural flow. Am I alone in thinking this? I shouldn't comment at all I suppose but I personally think CSpy is a reasonable CS text if you were using it with a (human) tutor to provide context. That is, it teaches the CS concepts well enough but doesn't provide much context. But living in a glass house as I do, I don't like to throw stones at other tutorials so I'll leave it at that! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 19:17:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 18:17:17 +0100 Subject: [Tutor] Explanation of Lists data Type References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> Message-ID: <020a01c65e54$f31a51d0$0a01a8c0@xp> Kaushal, > 8.7 List slices You might find it worth going through the official tutor section on slicing, it explains the various forms quite well. >>> list[:4] --> Does this mean its list[0:4] Sort of, it means from *the beginning* to 4. >>> list[3:] --> Does this mean its list[3:0] No it means from 3 to *the end* >>> list[:] --> Does this mean its list[0:0] No, it means from *the beginning* to *the end* These are all just shortcut conventions that you need to learn. Another one that can be confusing is negative slices: list[-3:] means from the -3 position(ie 3 from the end) to the end list[3:-3] means from the 3rd position to the -3 position I find it helps to thingk of the collection organised as a ring with the counter sitting between the items. Thus zero sits between the first and last items. Unfortunately this breaks down if you do list [-3:3] which is an error but is not reported as such, rathger it returns an empty list! Basically, play with them a lot and you will get used to their little oddities, the huge benefits outweigh the occasional confusion. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 21:23:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 12:23:01 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <20060412140201.GA8795@tranquility.scriptkitchen.com> References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: On Wed, 12 Apr 2006, Payal Rathod wrote: > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? One idea behind a "general purpose programming language" is that it's not specialized toward anything in particular. It's meant to be malliable and a bit formless. A programmer makes what one can with it. > e.g. for parsing log files with regex I rather use egrep than Python. > For counting the number of mails received for a user I use awk And for text parsing and processing, I think that's perfectly right, and you're using the best tools for that application. (Actually, you might want to look into Perl, which integrates regexes very deeply into its language.) You're more effective with those tools because awk and sed are domain-specific: they are specifically designed to do text processing very well. You can think of Python as a tool-maker. If you already are working in solely in one domain, where there are already plenty of tools already written for you, then you may not get so much out of a general-purpose language. This point is made in an amusing way in Literate Programming: http://www-cs-faculty.stanford.edu/~uno/lp.html The story goes that Knuth, when given the common-words problem, wrote up beautiful algorithm, designed a cool data structure to support it, and wrote it all in literate programming style. Bentley, on the other hand, used awk and other shell utilities, and in a few minutes, got a more correct solution. *grin* > But what does Python excel at. That si my main question. Whatevfer I > think of I can already do or know a way to do in shell. I am not getting > where would I need Python. But _someone_ had to write awk and sed: they didn't come fully-formed from the head of Zeus. That's what a general-purpose language like Python is for. You wouldn't write a web application in sed or awk because those two languages have limitations on what they're allowed to touch. > The Python video said that one can take this language to good level in 1 > afternoon, for me it has been 2 months and more. What is wrong? No, you're not wrong. Anyone who says that programming can be learned in an afternoon is selling something. *grin* From intermezzoooh at gmail.com Wed Apr 12 22:17:46 2006 From: intermezzoooh at gmail.com (Jesse) Date: Wed, 12 Apr 2006 14:17:46 -0600 Subject: [Tutor] n00b question: dictionaries and functions. Message-ID: Hey, this should be an easy question for you guys. I'm writing my first program (which Bob, Alan, and Danny have already helped me with--thanks, guys!), and I'm trying to create a simple command-line interface. I have a good portion of the program's "core functions" already written, and I want to create a dictionary of functions. When the program starts up, a global variable named command will be assigned the value of whatever the user types: command = raw_input("Cmd > ") If command is equivalent to a key in the dictionary of functions, that key's function will be called. Here's an example that I wrote for the sake of isolating the problem: def add(): x = float(raw_input("Enter a number: ")) y = float(raw_input("And a second number: ")) print x + y def subtract(): x = float(raw_input("Enter a number: ")) y = float(raw_input("And a second number: ")) print x - y commands = {"add": add(), "subtract": subtract()} Now, before I could even get to writing the while loop that would take a command and call the function associated with that command in the commands dictionary, I ran this bit of code and, to my dismay, both add() and subtract() were called. So I tried the following: def add(x, y): x = float(raw_input("Enter a numer: ")) y = float(raw_input("And a second number: ")) add = add() When I ran this, add() was called. I don't understand why, though. Surely I didn't call add(), I merely stored the function call in the name add. I would expect the following code to call add: def add(x, y): x = float(raw_input("Enter a numer: ")) y = float(raw_input("And a second number: ")) add = add() add Can someone clear up my misunderstanding here? I don't want to end up writing a long while loop of conditional statements just to effect a command-line interface. -Jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060412/d91a79de/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Apr 12 22:37:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Apr 2006 13:37:13 -0700 (PDT) Subject: [Tutor] n00b question: dictionaries and functions. In-Reply-To: References: Message-ID: On Wed, 12 Apr 2006, Jesse wrote: > def add(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x + y > def subtract(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x - y > > > commands = {"add": add(), "subtract": subtract()} > > > Now, before I could even get to writing the while loop that would take a > command and call the function associated with that command in the > commands dictionary, I ran this bit of code and, to my dismay, both > add() and subtract() were called. Hi Jesse, Ah! Yes, that's happening because there are parens in there that are causing the functions to fire off prematurely. For example, let's say we have defined a function: ###### >>> def test_function(x): ... return x * x ... ###### (I should give it a better name like square(), but let's ignore that for the moment.) If we just name the function, we'll get back a function value: ###### >>> test_function ###### This is a value that can be stored in containers, just like any other Python value. But as soon as we do use parentheses, Python will try to call the function: ###### >>> test_function() Traceback (most recent call last): File "", line 1, in TypeError: test_function() takes exactly 1 argument (0 given) ###### If we go back to the place where the commands dictionary is being built: commands = {"add": add(), "subtract": subtract()} do you see what needs to be fixed to associate those strings to function values? Best of wishes! From bgailer at alum.rpi.edu Wed Apr 12 22:40:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 12 Apr 2006 13:40:56 -0700 Subject: [Tutor] n00b question: dictionaries and functions. In-Reply-To: References: Message-ID: <443D65D8.5030104@alum.rpi.edu> Jesse wrote: > Hey, this should be an easy question for you guys. I'm writing my > first program (which Bob, Alan, and Danny have already helped me > with--thanks, guys!), and I'm trying to create a simple command-line > interface. I have a good portion of the program's "core functions" > already written, and I want to create a dictionary of functions. When > the program starts up, a global variable named command will be > assigned the value of whatever the user types: > > command = raw_input("Cmd > ") > > If command is equivalent to a key in the dictionary of functions, that > key's function will be called. Here's an example that I wrote for the > sake of isolating the problem: > > > def add(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x + y > def subtract(): > x = float(raw_input("Enter a number: ")) > y = float(raw_input("And a second number: ")) > print x - y > > > commands = {"add": add(), "subtract": subtract()} > > > > Now, before I could even get to writing the while loop that would take > a command and call the function associated with that command in the > commands dictionary, I ran this bit of code and, to my dismay, both > add() and subtract() were called. So I tried the following: > > def add(x, y): > x = float(raw_input("Enter a numer: ")) > y = float(raw_input("And a second number: ")) > add = add() > > When I ran this, add() was called. I don't understand why, though. > Surely I didn't call add(), I merely stored the function call in the > name add. I would expect the following code to call add: > > def add(x, y): > x = float(raw_input("Enter a numer: ")) > y = float(raw_input("And a second number: ")) > add = add() > add > > Can someone clear up my misunderstanding here? I don't want to end up > writing a long while loop of conditional statements just to effect a > command-line interface. "stored the function call" NO - this mixing 2 things. What you want is to store a reference to the function, then call the function thru its reference in response to user input. add is a reference to the function. add() calls (runs) the function. commands = {"add": add, "subtract": subtract} # stores function references command = raw_input("Cmd > ") if command in commands: commands[command]() # retrieve a function reference and calls it. From patriciap.gu at gmail.com Wed Apr 12 22:56:12 2006 From: patriciap.gu at gmail.com (Patricia) Date: Wed, 12 Apr 2006 20:56:12 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers Message-ID: Hi, This is my code: conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "", db ="mydb") cursor = conn.cursor() cursor.execute("""SELECT h, k, l, m, s, t FROM targets WHERE target_name = %s""", (target)) result = cursor.fetchone() alist = helperfunc.calc_numbers(list(result)) # read below cursor.close() conn.close() for li in alist: if li == '': s = s + "" else: s = s + "%s" % li # problem here calc_numbers is a method in helperfunc.py that takes the list of values that I retrieved from the database and then does some calculations (addition & division) and also replaces a specific number with ''. When I display the results, most of the times everything looks right, BUT sometimes I get i.e. 15%% instead of 15. I don't understand why %% is added to some of the numbers being displayed. I've noticed that the numbers that show %% are the ones that have been modified in the calc_numbers method. The numbers that are not touched in that method, don't show it. When I printed the list obatined from the calc_numbers method, the numbers that have not been touched have an L at the end (i'm assuming it stands for long). As I said these numbers are displayed correctly all the time. I'm really hoping someone can point me to the right direction because I've tried different things and nothing seems to work. Another quick question, my page shows several drop down boxes with pre-selected values. When I submit the form or open the page, the preselected values appear, but when I press the reload button, they don't. (Mozilla) Thanks, Patricia From alan.gauld at freenet.co.uk Wed Apr 12 23:15:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 22:15:59 +0100 Subject: [Tutor] failing to learn python References: <20060411160645.GB5242@tranquility.scriptkitchen.com><015201c65d96$ad311370$0a01a8c0@xp> <20060412140201.GA8795@tranquility.scriptkitchen.com> Message-ID: <024401c65e76$4c013fe0$0a01a8c0@xp> > can I use Python. Everyone says it is a "general programming language", > but what in the world is a "general programming language"? Others have already answered this. I'll add a few other comments. A general purpose language is one that in theory means you don't need any others. It can do anything. It may not do everything as well as special purppose tools like sed but it can do anything. Where sys admins typically use tools like Python is in producing well formatted reports, particularly nowadays on web pages. Or maybe you have to do a lot of SQL admin on a database and python's database links will allow you to write a single script which is easier to maintain than lots of separate ones. Where python is likely to be more useful to you is where you have long shell scripts rather than long awk/sed scripts. Shell scripts are fine as application launchers but if you need to process the output of commands and have long multi way if/else chains the Python may offer better facilities. But if you are working exclusively on Unix and you know the 400+ Unix commands well you may very well have little use for Python. I certainly don;t use it for much sys admin stuff, I tend to use it to write GUI front ends for the tools, or for writing networking applications or testing new protocols. One example where a tool like Python may be of use to you would be in building an interactive diff tool. The standard diff tools in Unix only allow comparison of 3 files, but if you have 6 or 8 versions you need to compare then using python you can build your own diff tool to compare 8 files if needed. And with the low cost of disk space file management of concurrent versions is becoming an issue for many admins... > The Python video said that one can take this language to good level in 1 > afternoon, for me it has been 2 months and more. What is wrong? Probably nothing. That claim refers to someone who is already fluent in another general purpose language like C or Java. Such a programmer can indeed get to the point where they can write a reasonable program in Python after a few hours with the official tutorial. A beginner will take more like 4-6 months to get really comfortable. You probably fit somewhere in the middle depending on your awk or shell skill level. If your awk action clauses run to 10s of lines then you probably do know enough to learn Python quickly but if you typically only write 3 or 4 lines in an action clause then Python will be more challenging. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Apr 12 23:52:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 12 Apr 2006 22:52:09 +0100 Subject: [Tutor] failing to learn python References: <20060411160645.GB5242@tranquility.scriptkitchen.com> <015201c65d96$ad311370$0a01a8c0@xp><20060412140201.GA8795@tranquility.scriptkitchen.com> <443D0D54.7090105@tds.net> Message-ID: <024a01c65e7b$59452590$0a01a8c0@xp> > the best tools. If you know shell, egrep and awk, they are probably better > than Python at doing the things they do. > > For me, I don't know those specialized tools and I have chosen not to > learn them because I don't often need their capabilities and Python can do > what they do. I must admit I use a myriad of tools, including several text editors. Its one of the few areas where I disagree with Hunt & Thomas in "the Pragmatic Programmer", they advocate choosing one editor and using it exclusively, I use emacs, vim, xedit and even ed on a daily basis (OK ed only once a month or so!) But I also use awk and sed weekly. I've also don't think I've ever worked on a production project that used less than 5 languages and some have used 12 or more. Awk in particular is one that I think every programmer should know, at least at a basic level, in the same way as everyone should learn a little Tcl and a little Lisp(*). These languages are sufficiently different to mainstream in structure that we can learn a lot about how to create programs by looking at their approach. It's fair to say that we probably wouldn't have ElementTree, BeautifulSoup, SAX or any other event driven parsers today if it weren't for awk and its elegant approach to working with text files. (*)For those building business apps I'd add COBOL to the list. It's not just history that makes it still the most widely used language on the planet according to Infoweek. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carlos at carlosbenevides.com Thu Apr 13 01:45:47 2006 From: carlos at carlosbenevides.com (Carlos Benevides) Date: Wed, 12 Apr 2006 16:45:47 -0700 Subject: [Tutor] String question. In-Reply-To: <44367CCC.6010309@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> Message-ID: <443D912B.7060108@carlosbenevides.com> All, I have a problem/question I'd like to pose to you guys on how best to accomplish the following. I have a string that will vary in size, what I would like to do is split into n size chunks. I am also not sure how best to represent the chunks. For example, say I have a len(s) = 200 chars. I'd like to get one chunk with 160 of those chars and the remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like two chunks of 160 and a 3rd with the remainder. I don't know what it would best way to accomplish this. I have the idea of converting the string to a list of chars loop through it until size is met, create a new string with s=s[:160], then start again, and so on. Is this the only way to accomplish this? Or is there a more elegant/clever way? Thank you :) From kent37 at tds.net Thu Apr 13 03:06:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 21:06:19 -0400 Subject: [Tutor] String question. In-Reply-To: <443D912B.7060108@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> <443D912B.7060108@carlosbenevides.com> Message-ID: <443DA40B.8020004@tds.net> Carlos Benevides wrote: > All, > > I have a problem/question I'd like to pose to you guys on how best to > accomplish the following. I have a string that will vary in size, what > I would like to do is split into n size chunks. I am also not sure how > best to represent the chunks. For example, say I have a len(s) = 200 > chars. I'd like to get one chunk with 160 of those chars and the > remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like > two chunks of 160 and a 3rd with the remainder. > > I don't know what it would best way to accomplish this. I have the idea > of converting the string to a list of chars loop through it until size > is met, create a new string with s=s[:160], then start again, and so > on. Is this the only way to accomplish this? Or is there a more > elegant/clever way? Here is a good way and links to more ideas: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 Kent From wescpy at gmail.com Thu Apr 13 05:24:20 2006 From: wescpy at gmail.com (w chun) Date: Wed, 12 Apr 2006 20:24:20 -0700 Subject: [Tutor] Problems when displaying numbers In-Reply-To: References: Message-ID: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> hi patricia, it would be really helpful to see an example of 'result' before and after the call to calc_numbers() as well as the code for calc_numbers if possible. this will likely reveal the problem that you are having. thanks, -wesley On 4/12/06, Patricia wrote: > Hi, > > This is my code: > > conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "", > db ="mydb") > cursor = conn.cursor() > cursor.execute("""SELECT h, k, l, m, s, t > FROM targets WHERE target_name = %s""", (target)) > result = cursor.fetchone() > > alist = helperfunc.calc_numbers(list(result)) # read below > > cursor.close() > conn.close() > > for li in alist: > if li == '': > s = s + "" > else: > s = s + "%s" % li # problem here > > > calc_numbers is a method in helperfunc.py that takes the list of values > that I retrieved from the database and then does some calculations > (addition & division) and also replaces a specific number with ''. > > When I display the results, most of the times everything looks right, BUT > sometimes I get i.e. 15%% instead of 15. I don't understand why %% is > added to some of the numbers being displayed. I've noticed that the numbers > that show %% are the ones that have been modified in the calc_numbers > method. The numbers that are not touched in that method, don't show it. > When I printed the list obatined from the calc_numbers method, the > numbers that have not been touched have an L at the end (i'm assuming > it stands for long). As I said these numbers are displayed correctly > all the time. I'm really hoping someone can point me to the right direction > because I've tried different things and nothing seems to work. > > Another quick question, my page shows several drop down boxes with > pre-selected values. When I submit the form or open the page, the > preselected values appear, but when I press the reload button, > they don't. (Mozilla) > > Thanks, > Patricia > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "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 oasf2004 at yahoo.com Thu Apr 13 05:28:39 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Wed, 12 Apr 2006 20:28:39 -0700 (PDT) Subject: [Tutor] Python video? Message-ID: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Hi, I read this week on this forum about a kind of Python video in its website. Which view is that, and where could I find it? I search in Python website, but I didn't find it. Is it a 'demo' of the language? Thanks, Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From samrobertsmith at gmail.com Thu Apr 13 09:07:20 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 13 Apr 2006 00:07:20 -0700 Subject: [Tutor] underscore function Message-ID: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> I got a sample code and found some function definition looks like def _abc There is one underscore before the function name "abc", what does it mean? From sean.x.lee at gmail.com Thu Apr 13 09:15:30 2006 From: sean.x.lee at gmail.com (Sean Lee) Date: Thu, 13 Apr 2006 02:15:30 -0500 Subject: [Tutor] Meaning of %g ? Message-ID: What is the exact meaning of %g in Python ? >From Python ducumentation: %g: Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. But if %.mg is used, I don't see the rules. See the following example: So here it follows the above rule: >>> print "%.16g" % 0.00010481234567890 0.0001048123456789 >>> print "%.16g" % 0.000010481234567890 1.048123456789e-005 But I do not know the rules below: >>> print "%.g" % 111111111110.000010481234567890 1e+011 >>> print "%.15g" % 111111111110.000010481234567890 111111111110 >>> print "%.16g" % 111111111110.000010481234567890 111111111110 >>> print "%.17g" % 111111111110.000010481234567890 111111111110.00002 >>> print "%.32g" % 111111111110.000010481234567890 111111111110.00002 What is the difference for each %g ? >>> print "%.f" % 111111111110.000010481234567890 111111111110 >>> print "%.15f" % 111111111110.000010481234567890 111111111110.000020000000000 >>> print "%.16f" % 111111111110.000010481234567890 111111111110.0000200000000000 >>> print "%.17f" % 111111111110.000010481234567890 111111111110.00002000000000000 Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/5e17404f/attachment.html From tim.golden at viacom-outdoor.co.uk Thu Apr 13 09:36:15 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 13 Apr 2006 08:36:15 +0100 Subject: [Tutor] underscore function Message-ID: [linda.s] | I got a sample code and found some | function definition looks like def _abc | There is one underscore before the function name "abc", | what does it mean? It's a convention which indicates to any user of the code (including the original developer) that the function is not intended to be used externally to the module (or class, or whatever) in which it is defined. Note that this is a convention only: there's absolutely nothing to stop you calling _abc (args) within your code. But the original developer intended that this function be an implementation detail that might change, or be refactored, or which assumes a particular state of data which might not obtain when called from elsewhere, etc. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajikoe at gmail.com Thu Apr 13 09:36:56 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 13 Apr 2006 09:36:56 +0200 Subject: [Tutor] underscore function In-Reply-To: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> References: <1d987df30604130007r723dee14ge146ee917c976a03@mail.gmail.com> Message-ID: Python programmers prefer to use name convention to make method of class "looks" private. Usually they use of '_' before the private method or private attribute name. This private method like the one you mentioned def _abc is not intentionaly used outside the class other then it is used among other class methods privately. Example: class A: def __init__(self, myvar): self._myvar = myvar def _makedouble(self): '''this method is private''' self._myvar = self._myvar * 2 def printvarADouble(self): self._makedouble() print self._myvar def main(): o = A(2) o.printvarADouble() # 4 You may use def abc instead of def _abc, again it is only a convention. Hope this helps, pujo On 4/13/06, linda.s wrote: > > I got a sample code and found some > function definition looks like def _abc > There is one underscore before the function name "abc", > what does it mean? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/132989e2/attachment.htm From john.brokaw at gmail.com Thu Apr 13 07:06:33 2006 From: john.brokaw at gmail.com (John Brokaw) Date: Thu, 13 Apr 2006 01:06:33 -0400 Subject: [Tutor] Can anyone help me plz Message-ID: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> I'am very new to pygame, and python and any help would help me so much thx. I have no idea whats wrong the chimp.py ex. works perfect, but when I get to http://rene.f0o.com/mywiki/*LECTURETHREE* *, *I get so stuck becuz the call window = pygame.display.set_mode((468, 60)) makes a window like it should be its always not responding. Can someone please tell my why this is happending. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/b4f89d69/attachment.htm From adam.jtm30 at gmail.com Thu Apr 13 12:24:52 2006 From: adam.jtm30 at gmail.com (Adam) Date: Thu, 13 Apr 2006 11:24:52 +0100 Subject: [Tutor] String question. In-Reply-To: <443D912B.7060108@carlosbenevides.com> References: <44367CCC.6010309@carlosbenevides.com> <443D912B.7060108@carlosbenevides.com> Message-ID: How's this?: >>> s = """All, ... ... I have a problem/question I'd like to pose to you guys on how best to ... accomplish the following. I have a string that will vary in size, what ... I would like to do is split into n size chunks. I am also not sure how ... best to represent the chunks. For example, say I have a len(s) = 200 ... chars. I'd like to get one chunk with 160 of those chars and the ... remaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like ... two chunks of 160 and a 3rd with the remainder. ... ... I don't know what it would best way to accomplish this. I have the idea ... of converting the string to a list of chars loop through it until size ... is met, create a new string with s=s[:160], then start again, and so ... on. Is this the only way to accomplish this? Or is there a more ... elegant/clever way? ... ... Thank you :)""" >>> l = [] >>> start = 0 >>> for i in range(160, len(s)+160, 160): ... l.append(s[start:i]) ... start = i ... >>>l ["All,\n\nI have a problem/question I'd like to pose to you guys on how best to\naccomplish the following. I have a string that will vary in size, what\nI would like", " to do is split into n size chunks. I am also not sure how\nbest to represent the chunks. For example, say I have a len(s) = 200\nchars. I'd like to get one ch", "unk with 160 of those chars and the\nremaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like\ntwo chunks of 160 and a 3rd with the remainder.\n\nI d", "on't know what it would best way to accomplish this. I have the idea\nof converting the string to a list of chars loop through it until size\nis met, create a ne", '', " to do is split into n size chunks. I am also not sure how\nbest to represent the chunks. For example, say I have a len(s) = 200\nchars. I'd like to get one ch", "unk with 160 of those chars and the\nremaining 40 in a second. Likewise, if I have a len(s) = 350, I'd like\ntwo chunks of 160 and a 3rd with the remainder.\n\nI d", "on't know what it would best way to accomplish this. I have the idea\nof converting the string to a list of chars loop through it until size\nis met, create a ne", 'w string with s=s[:160], then start again, and so\non. Is this the only way to accomplish this? Or is there a more\nelegant/clever way?\n\nThank you :)'] From rschroev_nospam_ml at fastmail.fm Thu Apr 13 12:29:02 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Apr 2006 12:29:02 +0200 Subject: [Tutor] Explanation of Lists data Type In-Reply-To: <020a01c65e54$f31a51d0$0a01a8c0@xp> References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com> <020a01c65e54$f31a51d0$0a01a8c0@xp> Message-ID: Alan Gauld schreef: > list [-3:3] > > which is an error but is not reported as such, rathger it returns > an empty list! I don't think this is an error, and whether it returns an empty list or not depends on the length of the list: >>> for i in range(10): print i, range(i)[-3:3] 0 [] 1 [0] 2 [0, 1] 3 [0, 1, 2] 4 [1, 2] 5 [2] 6 [] 7 [] 8 [] 9 [] -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From singletoned at gmail.com Thu Apr 13 13:51:51 2006 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 13 Apr 2006 12:51:51 +0100 Subject: [Tutor] Force a value to int Message-ID: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> Is there a particular way to force a value to be an int by either converting it with int() or returning a default value. I've ended up writing my own function to do it, but it seems like the kind of thing that would be built-in somewhere. Ed From patriciap.gu at gmail.com Thu Apr 13 13:56:36 2006 From: patriciap.gu at gmail.com (Patty) Date: Thu, 13 Apr 2006 11:56:36 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers References: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> Message-ID: Hi: >it would be really helpful to see an example of 'result' before and >after the call to calc_numbers() as well as the code for calc_numbers if >possible. An example of result before the call to calc_numbers is: [50L, -1, 1, -1] an example after the call is: [50L, 25, ' ', 25] the code: def calc_numbers(alist): sum = 0 count = 0 for li in alist: # in the database, -1 is unspecified and 1 is null if li >= 0 and li != 1: sum = sum + int(li) if li == -1: count = count + 1 temp = 100 - sum if count != 0: number = temp/count else: number = temp for li, pos in enumerate(alist): if pos == -1: alist[li] = number elif pos == 1: alist[li] = '' return alist Thanks, Patricia From kent37 at tds.net Thu Apr 13 14:01:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Apr 2006 08:01:25 -0400 Subject: [Tutor] Can anyone help me plz In-Reply-To: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> References: <3e31560604122206u15c1b8eau9b16ebdf0192401b@mail.gmail.com> Message-ID: <443E3D95.50402@tds.net> John Brokaw wrote: > I'am very new to pygame, and python and any help would help me so much thx. > I have no idea whats wrong the chimp.py ex. works perfect, but when I > get to http://rene.f0o.com/mywiki/*LECTURETHREE* > *, *I get so stuck becuz the > call window = pygame.display.set_mode((468, 60)) makes a window like it > should be its always not responding. Can someone please tell my why this > is happending. You will increase your chance of getting an answer by doing some or all of these: - post the code you are using - post a working URL to the lecture - post on the pygame mailing list (http://www.pygame.org/wiki/info) Kent From kent37 at tds.net Thu Apr 13 14:06:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Apr 2006 08:06:34 -0400 Subject: [Tutor] Force a value to int In-Reply-To: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> References: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> Message-ID: <443E3ECA.2060108@tds.net> Ed Singleton wrote: > Is there a particular way to force a value to be an int by either > converting it with int() or returning a default value. > > I've ended up writing my own function to do it, but it seems like the > kind of thing that would be built-in somewhere. No, there is no built-in for this but it's easy to write your own: def my_int(value, default): try: return int(value) except ValueError: return default Kent From alan.gauld at freenet.co.uk Thu Apr 13 14:28:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Apr 2006 13:28:54 +0100 Subject: [Tutor] Meaning of %g ? References: Message-ID: <029001c65ef5$d4640140$0a01a8c0@xp> > What is the exact meaning of %g in Python ? Same as in C. Its the shorter of the Scientific notation (%e) or Floating Point(%f) representations. In 20 years of using C I've never needed it, I wouldn't worry too much! :-) >From Python ducumentation: > %g: Same as "e" if exponent is greater than -4 or less than > precision, "f" otherwise. Yeah, thats not very clear. > Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ? Why? Because Kernighan & Ritchie made them different in C. Why? Because they did a lot of sacientific calculations and wanted the subtle variations I suspect. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From patriciap.gu at gmail.com Thu Apr 13 15:38:09 2006 From: patriciap.gu at gmail.com (Patricia) Date: Thu, 13 Apr 2006 13:38:09 +0000 (UTC) Subject: [Tutor] Problems when displaying numbers References: <78b3a9580604122024o2a16627fu8fae0d2fe32c13a1@mail.gmail.com> Message-ID: > An example of result before the call to calc_numbers is: [50L, -1, 1, -1] An example of result before the call is: [50L, -1L, 1L, -1L] Sorry about that. Thanks, Patricia From davholla2002 at yahoo.co.uk Thu Apr 13 18:53:20 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 13 Apr 2006 17:53:20 +0100 (BST) Subject: [Tutor] Show us some code Message-ID: <20060413165320.39006.qmail@web25911.mail.ukl.yahoo.com> John, Can you please post your code and the exact error message. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/59716233/attachment.html From Barry.Carroll at psc.com Thu Apr 13 18:55:35 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 13 Apr 2006 09:55:35 -0700 Subject: [Tutor] failing to learn python Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3651@eugsrv400.psc.pscnet.com> Greetings: The discussion surrounding this topic (by Payal, Kent, Alan and others) has been very interesting. It illustrates the fact that software engineering remains very much a craft. As with all crafts, is heavily influenced by the preferences (style if you will) of the individual artisan. There are very few 'right or wrong' answers here. The tool that works well and feels comfortable when used is the one that should be used. When a new tool comes along, try it out. If it makes the work easier or faster, or the product better, then use it. If not, forget it. The product is the goal, not the tool. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- <> > > For me, I don't know those specialized tools and I have chosen not to > > learn them because I don't often need their capabilities and Python can > do > > what they do. > > I must admit I use a myriad of tools, including several text editors. > Its one of the few areas where I disagree with Hunt & Thomas > in "the Pragmatic Programmer", they advocate choosing one editor > and using it exclusively, I use emacs, vim, xedit and even ed on > a daily basis (OK ed only once a month or so!) But I also use > awk and sed weekly. <> > From dyoo at hkn.eecs.berkeley.edu Thu Apr 13 20:18:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Apr 2006 11:18:51 -0700 (PDT) Subject: [Tutor] Python video? In-Reply-To: <20060413032839.86688.qmail@web60012.mail.yahoo.com> References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: On Wed, 12 Apr 2006, Hoffmann wrote: > I read this week on this forum about a kind of Python video in its > website. Which view is that, and where could I find it? I search in > Python website, but I didn't find it. Is it a 'demo' of the language? It's a video with gushing praise over Python, made in the style of a Monty Python skit. There's a link to it from here: http://wiki.python.org/moin/PythonCdFun From oasf2004 at yahoo.com Thu Apr 13 20:53:10 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Thu, 13 Apr 2006 11:53:10 -0700 (PDT) Subject: [Tutor] failing to learn python In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3651@eugsrv400.psc.pscnet.com> Message-ID: <20060413185310.16849.qmail@web60014.mail.yahoo.com> --- "Carroll, Barry" wrote: > Greetings: > > The discussion surrounding this topic (by Payal, > Kent, Alan and others) > has been very interesting. It illustrates the fact > that software > engineering remains very much a craft. As with all > crafts, is heavily > influenced by the preferences (style if you will) of > the individual > artisan. There are very few 'right or wrong' > answers here. > > The tool that works well and feels comfortable when > used is the one that > should be used. When a new tool comes along, try it > out. If it makes > the work easier or faster, or the product better, > then use it. If not, > forget it. The product is the goal, not the tool. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning > cathedrals. > > -Quarry worker's creed > > > > -----Original Message----- > > <> > > > > For me, I don't know those specialized tools and > I have chosen not > to > > > learn them because I don't often need their > capabilities and Python > can > > do > > > what they do. > > > > I must admit I use a myriad of tools, including > several text editors. > > Its one of the few areas where I disagree with > Hunt & Thomas > > in "the Pragmatic Programmer", they advocate > choosing one editor > > and using it exclusively, I use emacs, vim, xedit > and even ed on > > a daily basis (OK ed only once a month or so!) But > I also use > > awk and sed weekly. > > <> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Barry, I do agree with you. I also would add the Linux/Windows 'dispute'. I am a BIG FAN of linux. Even at home I use linux 90% of the time. However, in some cases I use Windows, as well (to watch DVDs (movies), for example). Due to the stability of Windows in this (multimidia) case, I do prefer using it for watching movies. So. There is no reason to use just one programming language. I am a BIG FAN of Python, but I am studying Python, Shell programming, and MATLAB in paralell. Moreover, I am very interested in both Fortran and C. Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From matt.singletary at gmail.com Thu Apr 13 21:16:33 2006 From: matt.singletary at gmail.com (Matthew Singletary) Date: Thu, 13 Apr 2006 15:16:33 -0400 Subject: [Tutor] checking diagonals on a chessboard Message-ID: first, A disclaimer: This isn't directly homework but is related to an assignment of mine I'm building a genetic algorithm to solve the queen placement problem, the complicated stuff I can do on my own, but I'm not getting one part. suppose the queen is on a square, I can check that it is in the same row or same col but the diagonals, are less straight-forward. I know I could solve this by just smashing away at it, but I was wondering if anyone could suggest some tips on directions to work I'm NOT looking for any answers, just some tips to an _elegant_ method to solve this. The reason I started teaching myself python was it seemed a little more concise, and it seems there should be an elegant way to do this but I guess I'm not used to thinking the pythonic way thanks for any help matt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/e4efe037/attachment.html From python at venix.com Thu Apr 13 21:34:13 2006 From: python at venix.com (Python) Date: Thu, 13 Apr 2006 15:34:13 -0400 Subject: [Tutor] checking diagonals on a chessboard In-Reply-To: References: Message-ID: <1144956853.20218.53.camel@www.venix.com> On Thu, 2006-04-13 at 15:16 -0400, Matthew Singletary wrote: > I'm building a genetic algorithm to solve the queen placement problem, > the complicated stuff I can do on my own, but I'm not getting one > part. > suppose the queen is on a square, I can check that it is in the same > row or same col but the diagonals, are less straight-forward. > I know I could solve this by just smashing away at it, but I was > wondering if anyone could suggest some tips on directions to work > > I'm NOT looking for any answers, just some tips to an _elegant_ method > to solve this. > This problem is discussed in "The ICON Programming Language" by Ralph and Madge Griswold around page 150. The basic approach they take is to number diagonals, just like you number rows and columns. So every queen's position involves a row #, col #, and diag #. Scratching your head over how to number the diagonals I'll leave to you. They counted 30 diagonals, so if you come up with a different count, you either have an original approach or have blundered somewhere. (Hopefully that was the kind of pointer you were looking for. Tim Peters (I think) has written about this problem in a Python context, but citing Icon.) -- Lloyd Kvam Venix Corp From andre.roberge at gmail.com Thu Apr 13 21:35:58 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 13 Apr 2006 16:35:58 -0300 Subject: [Tutor] checking diagonals on a chessboard In-Reply-To: References: Message-ID: <7528bcdd0604131235i11b74243i91c782ef8c7a5355@mail.gmail.com> On 4/13/06, Matthew Singletary wrote: > > first, A disclaimer: > This isn't directly homework but is related to an assignment of mine > > I'm building a genetic algorithm to solve the queen placement problem, the > complicated stuff I can do on my own, but I'm not getting one part. > suppose the queen is on a square, I can check that it is in the same row or > same col but the diagonals, are less straight-forward. > I know I could solve this by just smashing away at it, but I was wondering > if anyone could suggest some tips on directions to work > > I'm NOT looking for any answers, just some tips to an _elegant_ method to > solve this. The answer you are looking for most likely depends on how you represent your chessboard (i.e. single list, list of list, etc.). Not an answer to your question directly, but a Python solution using recursion can be found at: http://en.wikipedia.org/wiki/Eight_queens_puzzle Of course, it has to include how to check for diagonals, which you can use for what you are looking for. I don't know if it can be considered to be "elegant". [As an aside, I used this solution to write an undocumented "visual" solution of this problem using rur-ple (rur-ple.sourceforge.net), where 8 "queens" move on a screen to illustrate one such solution, with colored lines showing which square is attacked by each queen. For those that have downloaded rur-ple, you can find this solution under rur_programs/temp/queen.rur] Andr? > > The reason I started teaching myself python was it seemed a little more > concise, and it seems there should be an elegant way to do this but I guess > I'm not used to thinking the pythonic way > > thanks for any help > matt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From tim.peters at gmail.com Thu Apr 13 21:47:52 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 13 Apr 2006 15:47:52 -0400 Subject: [Tutor] checking diagonals on a chessboard In-Reply-To: <1144956853.20218.53.camel@www.venix.com> References: <1144956853.20218.53.camel@www.venix.com> Message-ID: <1f7befae0604131247y258502c7i24fc6d9f035113e0@mail.gmail.com> [Matthew Singletary] >> I'm building a genetic algorithm to solve the queen placement problem, >> the complicated stuff I can do on my own, but I'm not getting one >> part. >> suppose the queen is on a square, I can check that it is in the same >> row or same col but the diagonals, are less straight-forward. >> I know I could solve this by just smashing away at it, but I was >> wondering if anyone could suggest some tips on directions to work >> >> I'm NOT looking for any answers, just some tips to an _elegant_ method >> to solve this. [Lloyd Kvam] > This problem is discussed in "The ICON Programming Language" by Ralph > and Madge Griswold around page 150. The basic approach they take is to > number diagonals, just like you number rows and columns. So every > queen's position involves a row #, col #, and diag #. > > Scratching your head over how to number the diagonals I'll leave to you. > They counted 30 diagonals, so if you come up with a different count, you > either have an original approach or have blundered somewhere. > > (Hopefully that was the kind of pointer you were looking for. Tim > Peters (I think) has written about this problem in a Python context, but > citing Icon.) There's a short and sweet Queens solver in Python's test_generators.py, part of Python's standard test suite. The comments explain one way to uniquely number the diagonals in the general (NxN board) case, as linear functions of the row and column indices. It's easy but tedious :-) From dyoo at hkn.eecs.berkeley.edu Thu Apr 13 22:07:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Apr 2006 13:07:29 -0700 (PDT) Subject: [Tutor] checking diagonals on a chessboard Message-ID: > I'm building a genetic algorithm to solve the queen placement problem, > the complicated stuff I can do on my own, but I'm not getting one part. > suppose the queen is on a square, I can check that it is in the same row > or same col but the diagonals, are less straight-forward. I know I could > solve this by just smashing away at it, but I was wondering if anyone > could suggest some tips on directions to work Hi Matt, This is sensitive to the way that you're encoding the position of a queen. If you're using chess's algebraic notation, like "e2" or "f7", although it's familiar, this may not be be the most convenient representation for doing positional calculations. A slightly more convenient representation may be as cartesian coordinates. i.e.: "e2" <==> (5, 2) "f7" <==> (6, 7) That is, treat the chessboard as if it were a piece of graph paper. The reason that this particular encoding of position as 2-tuples is nice is this: like the algebraic notation, it's easy to check rows and columns for similarity. But furthermore, given two positions, it isn't too bad to see if those positions lie on the same diagonal. (Think back to algebra and slopes.) So our choice of how we represent knowledge can matter. Math would suck if we had to stick with Roman numerals. >From my layman's understanding of genetic algorithms, I remember that an effective choice in representation is also a big deal in evolving new solutions, so it's always something to keep in mind. Are you reading something like Melanie Mitchell's "An Introduction to Genetic Algorithms"? This is an area I'd like to know more about too, so if you have any book pointers, I'll put them on my wishlist. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Thu Apr 13 23:22:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Apr 2006 22:22:34 +0100 Subject: [Tutor] Explanation of Lists data Type References: <6b16fb4c0604120212j75c03d54vc5e93fa576951c09@mail.gmail.com><020a01c65e54$f31a51d0$0a01a8c0@xp> Message-ID: <02c201c65f40$61a66bc0$0a01a8c0@xp> >> list [-3:3] >> which is an error but is not reported as such, rathger it returns an >> empty list! > > I don't think this is an error, and whether it returns an empty list or > not depends on the length of the list: I stand corrected, and yes when you think about it, it makes sense. > print i, range(i)[-3:3] > 0 [] > 1 [0] > 2 [0, 1] > 3 [0, 1, 2] > 4 [1, 2] > 5 [2] > 6 [] [-3:3] is not an error as such it just doesn't make sense for longer lists since -3 is after 3. But for short lists -3 sits before 3 so the slice between them is valid. Interesting, and shows the danger of relying on inaccurate analagies like my circular list. It works in many cases but not all! Thanks Roel. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Apr 13 23:30:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Apr 2006 22:30:28 +0100 Subject: [Tutor] Force a value to int References: <34bb7f5b0604130451y1bb00d92p43cb591f905d1899@mail.gmail.com> Message-ID: <02ca01c65f41$7c708660$0a01a8c0@xp> > Is there a particular way to force a value to be an int by either > converting it with int() or returning a default value. I don't think it exists. I think that would be a difficult thing to do in a generic way. The potential for inadvertant data loss is very high. > I've ended up writing my own function to do it, I assume you mean something like: def forceInt(v, default=42): try: result = int(v) except: result = default return result but if you do class C: # lots of stuff in here pass c = C() v=forceInt(c) You could lose all the data in C. I suppose that if you make the default non defaulted - so you have to provide a default - that would be better, the default could then be the object itself v = forceInt(c,c) Is that what you mean? Alan G From alan.gauld at freenet.co.uk Thu Apr 13 23:46:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 13 Apr 2006 22:46:06 +0100 Subject: [Tutor] failing to learn python References: <2BBAEE949D384D40A2B851287ADB6A432C3651@eugsrv400.psc.pscnet.com> Message-ID: <02d401c65f43$ab788e10$0a01a8c0@xp> > has been very interesting. It illustrates the fact that software > engineering remains very much a craft. As with all crafts, is heavily > influenced by the preferences (style if you will) of the individual > artisan. There are very few 'right or wrong' answers here. Oops, you hit a hot button there. :-) I don't think the multitude of styles or tools is any different to any other engineering discipline and cerainly doesn't indicate any more craft status than the fact that different electrical engineers have different preferences of AVO meter type (analogue, digital, electronic, magnetic etc - and most use several). Chosing the right tool for the job is just as much part of the skill of the engineer as much as the artisan. Where there may be a difference is that the engineer may specify the tools (and definitely the materials) during the design process, the artisan may choose the tools and materials in an ad-hoc manner as the work progresses. The engineer's goals are consistency and economy whereas the artisans goals are "quality(*)" and individuality. (*)Engineers strive for quality too, but a pre-determined measure of quality not the abstract concept of 'fine-ness' that craftsmen generally aim for. Software engineering, when practiced as engineering, is very little different to other branches of engineering, unfortunately it is, for various reasons, not often practiced as an enginering disipline but as a craft. But the SE label is applied regardless! As in other engineering disciplines it will take a large disaster wiith huge loss of human life(*) due to badly designed software to force the industry to adopt the kind of rigour demanded oin other fields. It is entirely possible now, it's just not practiced! (*)And even then only when that loss of life is accompanied by correspondingly large insurance claims - or is that too cynical? We'll find out fairly soon I'm sure... Alan G. From john.corry at ntlworld.com Thu Apr 13 23:58:27 2006 From: john.corry at ntlworld.com (John Corry) Date: Thu, 13 Apr 2006 22:58:27 +0100 Subject: [Tutor] Databases Message-ID: Hi, I have some database files that are written in visual foxpro. I want to be able to access them, read them and amend them. Can I do this with python? Are there any good links or websites that would specifically deal with interrogating visual foxpro databases with Python? I have limited knowledge with databses. I have created and modified some gadfly databases but on a very simple level. Any help would be greatly appreciated. Thanks, John. From mhansen at cso.atmel.com Fri Apr 14 00:10:07 2006 From: mhansen at cso.atmel.com (mhansen at cso.atmel.com) Date: Thu, 13 Apr 2006 16:10:07 -0600 Subject: [Tutor] Databases Message-ID: I just googled "foxpro python" and this link will probably help. http://mail.python.org/pipermail/db-sig/2001-May/001782.html I also posted a link a couple of days ago that has a nice PDF of the Python DB-API which I hope the ODBC driver mentioned in the mail message above uses. Mike ----- Original Message ----- From: John Corry Date: Thursday, April 13, 2006 3:58 pm Subject: [Tutor] Databases > Hi, > > I have some database files that are written in visual foxpro. I > want to be > able to access them, read them and amend them. Can I do this with > python? > Are there any good links or websites that would specifically deal with > interrogating visual foxpro databases with Python? > > I have limited knowledge with databses. I have created and > modified some > gadfly databases but on a very simple level. > > Any help would be greatly appreciated. > > Thanks, > > John. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From matt.singletary at gmail.com Fri Apr 14 00:14:53 2006 From: matt.singletary at gmail.com (Matthew Singletary) Date: Thu, 13 Apr 2006 18:14:53 -0400 Subject: [Tutor] checking diagonals on a chessboard In-Reply-To: References: Message-ID: Thanks for the input from everyone, I had been working with a flat array and checking the horizontals and verticals with slices and mod math but I think the tuple approach would be pretty easy to change to use. I can't ever recall being interested in a test from a test suite but my interest is piqued. I get to spend this weekend working on this and some simulated annealling so I will get to polish my python skills some more. Thanks again, matt -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060413/c5a9dbbd/attachment.htm From sanelson at gmail.com Fri Apr 14 00:31:06 2006 From: sanelson at gmail.com (Steve Nelson) Date: Thu, 13 Apr 2006 23:31:06 +0100 Subject: [Tutor] Python video? In-Reply-To: References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: On 4/13/06, Danny Yoo wrote: > > > On Wed, 12 Apr 2006, Hoffmann wrote: > > > I read this week on this forum about a kind of Python video in its > > website. Which view is that, and where could I find it? I search in > > Python website, but I didn't find it. Is it a 'demo' of the language? > > It's a video with gushing praise over Python, made in the style of a Monty > Python skit. On a similar line, I've recently discovered "podcasts". I spend a lot of time driving, and have been listening through the "Security Now" broadcasts, and the last few days some stuff on Evolutionary Theory. Does anyone know of some good sources for programming-type discussions - talks or lectures I could download and listen to? S. From wescpy at gmail.com Fri Apr 14 00:41:13 2006 From: wescpy at gmail.com (w chun) Date: Thu, 13 Apr 2006 15:41:13 -0700 Subject: [Tutor] Python video? In-Reply-To: References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: <78b3a9580604131541k6be6fc89ub526e5c18f249e5b@mail.gmail.com> > > > I read this week on this forum about a kind of Python video in its > > > website. Which view is that, and where could I find it? > > > > It's a video with gushing praise over Python, made in the style of a Monty > > Python skit. > > On a similar line, I've recently discovered "podcasts". > : > Does anyone know of some good sources for programming-type discussions > - talks or lectures I could download and listen to? also, if you haven't seen them already, here are two other great video/audio clips you should watch (or at least listen to): 1. Python and Ruby http://snakesandrubies.com/ this is a talk given by two of the folks heading Ruby's Ruby on Rails and Python's Django web app frameworks a few months ago in Chicago 2. Guido's 'State of the Python Universe' Keynote http://video.google.com/videoplay?docid=60331183357868340 he gave this talk at Google in NY and PyCon 2006 in Dallas... it highlights the 2.5 release coming this fall. enjoy! -- 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 Barry.Carroll at psc.com Fri Apr 14 00:43:44 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 13 Apr 2006 15:43:44 -0700 Subject: [Tutor] failing to learn python Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3653@eugsrv400.psc.pscnet.com> Alan: As always, you make excellent points. Actually, there isn't much on which we disagree here, I think. I did not mean that other engineering disciplines necessarily employ less craftsmanship than does software. On the contrary, excellent craftsmanship can be found in all branches of engineering. One example will suffice: automotive engineering. Manufacturer _____ [insert your favorite here] produces vehicles which are among the most finely crafted objects in the world. On the other hand, ______ [again, take your pick) makes cars that exhibit horrible craftsmanship. Both are the products of automotive engineering, but the differences in reliability, safety, performance and economy, not to mention beauty, individuality and 'fine-ness' (a great term, IMHO), are obvious. I could cite examples from any other discipline, though I might have to spend some time in research; I'm a programmer, not an engineering historian. =8^) Anyway, my point was that no programming language is best in all cases or for all people. The preference of the engineer (craftsman, if you will) matters. Best Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] > Sent: Thursday, April 13, 2006 2:46 PM > To: Carroll, Barry; tutor at python.org > Subject: Re: [Tutor] failing to learn python > > > has been very interesting. It illustrates the fact that software > > engineering remains very much a craft. As with all crafts, is heavily > > influenced by the preferences (style if you will) of the individual > > artisan. There are very few 'right or wrong' answers here. > > Oops, you hit a hot button there. :-) > > > I don't think the multitude of styles or tools is any different to any > other engineering discipline and certainly doesn't indicate any more > craft status than the fact that different electrical engineers have > different > preferences of AVO meter type (analogue, digital, electronic, magnetic > etc - and most use several). Choosing the right tool for the job is just > as much part of the skill of the engineer as much as the artisan. > > Where there may be a difference is that the engineer may specify the > tools (and definitely the materials) during the design process, the > artisan may choose the tools and materials in an ad-hoc manner > as the work progresses. The engineer's goals are consistency and > economy whereas the artisans goals are "quality(*)" and individuality. > > (*)Engineers strive for quality too, but a pre-determined measure > of quality not the abstract concept of 'fine-ness' that craftsmen > generally > aim for. > > Software engineering, when practiced as engineering, is very little > different to other branches of engineering, unfortunately it is, for > various reasons, not often practiced as an engineering discipline > but as a craft. But the SE label is applied regardless! As in other > engineering disciplines it will take a large disaster with huge loss > of human life(*) due to badly designed software to force the industry > to adopt the kind of rigour demanded in other fields. It is entirely > possible now, it's just not practiced! > > (*)And even then only when that loss of life is accompanied by > correspondingly large insurance claims - or is that too cynical? > We'll find out fairly soon I'm sure... > > > > Alan G. > From francois.schnell at gmail.com Fri Apr 14 00:47:27 2006 From: francois.schnell at gmail.com (francois schnell) Date: Fri, 14 Apr 2006 00:47:27 +0200 Subject: [Tutor] Python video? In-Reply-To: References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: <13a83ca10604131547h27c66998oceb9e5c96fd29e77@mail.gmail.com> Hello, I find Python411 an excellent podcast about Python: http://www.awaretek.com/python/index.html and on general topics about IT: http://www.itconversations.com/ francois On 14/04/06, Steve Nelson wrote: > > On 4/13/06, Danny Yoo wrote: > > > > > > On Wed, 12 Apr 2006, Hoffmann wrote: > > > > > I read this week on this forum about a kind of Python video in its > > > website. Which view is that, and where could I find it? I search in > > > Python website, but I didn't find it. Is it a 'demo' of the language? > > > > It's a video with gushing praise over Python, made in the style of a > Monty > > Python skit. > > On a similar line, I've recently discovered "podcasts". I spend a lot > of time driving, and have been listening through the "Security Now" > broadcasts, and the last few days some stuff on Evolutionary Theory. > Does anyone know of some good sources for programming-type discussions > - talks or lectures I could download and listen to? > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060414/c4be006c/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Fri Apr 14 01:24:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Apr 2006 16:24:37 -0700 (PDT) Subject: [Tutor] Python video? In-Reply-To: <13a83ca10604131547h27c66998oceb9e5c96fd29e77@mail.gmail.com> References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> <13a83ca10604131547h27c66998oceb9e5c96fd29e77@mail.gmail.com> Message-ID: > I find Python411 an excellent podcast about Python: > http://www.awaretek.com/python/index.html > > and on general topics about IT: > http://www.itconversations.com/ Before its untimely demise, Dr Dobbs Journal used to do a lot with Technetcast: http://technetcast.ddj.com/ The site still works (for the most part) but it's unmaintained and doesn't have new content. The streaming "PLAY" links are the ones you'll want to visit, as the "SAVE" links are broken. From tiagosaboga at terra.com.br Fri Apr 14 02:40:00 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 13 Apr 2006 21:40:00 -0300 Subject: [Tutor] sqlobject behavior Message-ID: <200604132140.00562.tiagosaboga@terra.com.br> Hi! I don't understand why sqlobject's ForeignKey attribute has to have the same name of the linked class. The following example doesn't work (the traceback is just after) unless I rename the 'p' attribute of 'Address' class as 'person'. Thanks, Tiago. class Person(SQLObject): name = StringCol() add = MultipleJoin('Address') class Address(SQLObject): street = StringCol() p = ForeignKey('Person') def initdb(): connection_string = 'mysql://tiago at localhost/test' connection = connectionForURI(connection_string) sqlhub.processConnection = connection def main(): initdb() createandfeedTables() search(raw_input('Search? ')) def createandfeedTables(): try: Person.createTable() Address.createTable() for i, j in (('tiago', 'rua ceara'), ('lucas', 'rua sergipe')): nam = Person(name=i) Address(street=j, p=nam) except: print 'Assuming tables are created and fed.' def search(searchexp): gr = Person.select(CONTAINSSTRING(Person.q.name, searchexp)) for l in gr: print l.add if __name__=='__main__': main() ------------------------------------ $ ./searchjoin2.py Search? uc Traceback (most recent call last): File "./searchjoin2.py", line 47, in ? main() File "./searchjoin2.py", line 29, in main search(raw_input('Search? ')) File "./searchjoin2.py", line 44, in search print l.add File "", line 1, in File "/usr/lib/python2.3/site-packages/sqlobject/joins.py", line 131, in performJoin inst.id) File "/usr/lib/python2.3/site-packages/sqlobject/dbconnection.py", line 592, in _SO_selectJoin return self.queryAll("SELECT %s FROM %s WHERE %s = %s" % File "/usr/lib/python2.3/site-packages/sqlobject/dbconnection.py", line 316, in queryAll return self._runWithConnection(self._queryAll, s) File "/usr/lib/python2.3/site-packages/sqlobject/dbconnection.py", line 217, in _runWithConnection val = meth(conn, *args) File "/usr/lib/python2.3/site-packages/sqlobject/dbconnection.py", line 309, in _queryAll self._executeRetry(conn, c, s) File "/usr/lib/python2.3/site-packages/sqlobject/mysql/mysqlconnection.py", line 60, in _executeRetry return cursor.execute(query) File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 137, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (1054, "Unknown column 'person_id' in 'where clause'") From sanelson at gmail.com Fri Apr 14 07:59:42 2006 From: sanelson at gmail.com (Steve Nelson) Date: Fri, 14 Apr 2006 06:59:42 +0100 Subject: [Tutor] checking diagonals on a chessboard In-Reply-To: References: Message-ID: On 4/13/06, Matthew Singletary wrote: > I'm NOT looking for any answers, just some tips to an _elegant_ method to > solve this. My tutor/mentor and I wrote a chess program a while back - diaganols were the hardest bit to get working! Essentially diagonals are treated as though they were ranks and files on a board rotated through 45 degrees. Doing bitboard lookups then becomes fairly simple. A bitboard solution to the n-queens problem would actually be rather neat for a genetic algorithm, as the genes could correspond directly to the bitboards. Both are just large integers. If you haven't already, take a look at Bob Hyatt's bitboard paper. In this case, though, it is probably simple enough to work out if two pieces are on the same diagonal: 1. Find the difference in their ranks 2. Find the difference in their files 3. If the answer is the same (regardless of sign) then the pieces share a diagonal. S. From pythontut at pusspaws.net Fri Apr 14 08:43:43 2006 From: pythontut at pusspaws.net (Dave S) Date: Fri, 14 Apr 2006 07:43:43 +0100 Subject: [Tutor] Looking for an open source project Message-ID: <200604140743.45759.pythontut@pusspaws.net> Hi all, I have been playing around with Python for a while now and am looking for open source KDE projects written in Python that I can help with / learn from. Something relatively simple that uses Qt. (I am still a bit green) Any idea where I can get a list of projects. I checked out sourceforge but could not work out how to filter for Python. Dave From alan.gauld at freenet.co.uk Fri Apr 14 09:37:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Apr 2006 08:37:20 +0100 Subject: [Tutor] Meaning of %g ? References: <029001c65ef5$d4640140$0a01a8c0@xp> Message-ID: <02fd01c65f96$43adbaf0$0a01a8c0@xp> >> > %g: Same as "e" if exponent is greater than -4 or less than >> > precision, "f" otherwise. >> >> Yeah, thats not very clear. > >So what is the exact meaning ? I am still not clear. The exact meaning is that it will use the shorter of %e and %f. It's as simple as that., In some cases Scientific notation will be shorter than floating point notation. In other cases it will be the other way round. %g will always display the shorter one. > Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ? > > Why? Because Kernighan & Ritchie made them different in C. > > So what is the exact rules of %.g? As above, the shorter of %e and %f >>> bignum = 1234567898.2345678945 >>> print "%g\n%e\n%f" % (bignum,bignum,bignum) 1.23457e+009 1.234568e+009 1234567898.234568 Hmm, that's interesting, %g is actually slightly shorter than the shortest! One less digit. interesting... >>> smallnum = 1234.456789 >>> print "%g\n%e\n%f" % (smallnum,smallnum,smallnum) 1234.46 1.234457e+003 1234.456789 >>> Hopefully you can see that in the bignum case %g used the same style as %e because it's shorter. In the smallnum case it used the same style as %f because that was shorter. In both cases it truncated to 6 digits, which I didn't expect!! > In doing scientific calculations, what format do I trust? You can trust all of them, they are all correct. None of them change the underlying value they simply display them differently. In practice you rarely use any of them on their own, you will normally add length and precision modifiers as in: >>> print "%14.3g\n%14.3e\n%14.3f" % (bignum,bignum,bignum) 1.23e+009 1.235e+009 1234567898.235 Hopefully those examples show whats happening. I have no idea why %g is dropping a digit, it may even be a bug! Alan G. From alan.gauld at freenet.co.uk Fri Apr 14 09:39:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Apr 2006 08:39:11 +0100 Subject: [Tutor] Databases References: Message-ID: <030d01c65f96$85a4a1d0$0a01a8c0@xp> > I have some database files that are written in visual foxpro. I want to > be > able to access them, read them and amend them. Can I do this with python? I think you will need to use the OCDB adapter. Although there may be a Fox adapter out there somewhere, but I haven't seen any references to it. > Are there any good links or websites that would specifically deal with > interrogating visual foxpro databases with Python? Not that I know of, only the standard Python DBI pages. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Apr 14 11:58:32 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Apr 2006 05:58:32 -0400 Subject: [Tutor] Meaning of %g ? In-Reply-To: <02fd01c65f96$43adbaf0$0a01a8c0@xp> References: <029001c65ef5$d4640140$0a01a8c0@xp> <02fd01c65f96$43adbaf0$0a01a8c0@xp> Message-ID: <443F7248.5040407@tds.net> Alan Gauld wrote: >>>> print "%14.3g\n%14.3e\n%14.3f" % (bignum,bignum,bignum) > 1.23e+009 > 1.235e+009 > 1234567898.235 > > Hopefully those examples show whats happening. > I have no idea why %g is dropping a digit, it may even be a bug! It looks to me like either a documentation error or a bug. It might be worth asking on c.l.py. Kent From kent37 at tds.net Fri Apr 14 12:07:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Apr 2006 06:07:59 -0400 Subject: [Tutor] Looking for an open source project In-Reply-To: <200604140743.45759.pythontut@pusspaws.net> References: <200604140743.45759.pythontut@pusspaws.net> Message-ID: <443F747F.8010501@tds.net> Dave S wrote: > Hi all, > > I have been playing around with Python for a while now and am looking for > open source KDE projects written in Python that I can help with / learn from. > > Something relatively simple that uses Qt. (I am still a bit green) > > Any idea where I can get a list of projects. I checked out sourceforge but > could not work out how to filter for Python. Go to the SF software map and click on a category, then you will be able to filter for language. Kent From patriciap.gu at gmail.com Fri Apr 14 15:32:39 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 14 Apr 2006 13:32:39 +0000 (UTC) Subject: [Tutor] MySQLdb question Message-ID: Hi, I have a data structure in a python file that looks something like this: my_map= { "host1": {"target1", "target2", "target3" }, "host2": {"target4", "target5", "target6" }, } I have a method that has two parameteres (ahost, atarget), which I want to use to retrieve data from the database. In my database each host has a column and each target has a row. The way I have it now is something like this: cursor.execute("""SELECT host1, host2, host3, host4, host5, host6 FROM targets WHERE target_name = %s """, (target)) This is very inefficient because I'm retrieving data that I don't need. Instead, I want to use the parameters in my method, but I'm not sure how to do it cursor.execute("""SELECT %s FROM targets WHERE target_name = %s """, (ahost, target)) # I tried this, but it didn't work. I also tried this, but got a error: cursor.execute("""SELECT %s FROM targets WHERE target_name = %s """ % (ahost, target)) Can anybody show me the right way to do it? Thanks, Patty From ajschmidt at fredericksburg.com Fri Apr 14 16:10:20 2006 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Fri, 14 Apr 2006 10:10:20 -0400 Subject: [Tutor] MySQLdb question In-Reply-To: References: Message-ID: <443FAD4C.9060004@fredericksburg.com> Patty wrote: >I have a data structure in a python file that looks something like this: > >my_map= { "host1": {"target1", "target2", "target3" }, > "host2": {"target4", "target5", "target6" }, > } > >cursor.execute("""SELECT %s FROM targets > WHERE target_name = %s """ % (ahost, target)) > >Can anybody show me the right way to do it? > > Hi Patty, I don't know if this is the right way, but here is basically how I would do it. First of all, I will assume that you are looping over the items in the dictionary to get the variables ahost and target. for ahost,target in my_map: cursor.execute("""SELECT %s FROM targets WHERE target_name in (%s) """ % (ahost, ",".join(target))) This would generate a list that MySQL will look through to find target_name. It is the same as one would do in Python to find an item in a list: if target_name in ("target1", "target2", "target3") Hope that helps! Allen J. Schmidt, Jr. From ajikoe at gmail.com Fri Apr 14 16:29:23 2006 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 14 Apr 2006 16:29:23 +0200 Subject: [Tutor] MySQLdb question In-Reply-To: References: Message-ID: I think you can wrap the select sql command with a function which return a string. this function receive a particular hostname in a string format and return the whole 'SELECT ... FROM.. WHERE' style including the hostname from the function argument. Cheers, pujo On 4/14/06, Patty wrote: > > Hi, > > I have a data structure in a python file that looks something like this: > > my_map= { "host1": {"target1", "target2", "target3" }, > "host2": {"target4", "target5", "target6" }, > } > > I have a method that has two parameteres (ahost, atarget), which I want to > use > to retrieve data from the database. In my database each host has a column > and > each target has a row. The way I have it now is something like this: > > cursor.execute("""SELECT host1, host2, host3, host4, host5, host6 FROM > targets > WHERE target_name = %s """, (target)) > > This is very inefficient because I'm retrieving data that I don't need. > Instead, > I want to use the parameters in my method, but I'm not sure how to do it > > cursor.execute("""SELECT %s FROM targets > WHERE target_name = %s """, (ahost, target)) # I tried this, but > it > didn't work. > > > I also tried this, but got a error: > > cursor.execute("""SELECT %s FROM targets > WHERE target_name = %s """ % (ahost, target)) > > Can anybody show me the right way to do it? > > Thanks, > Patty > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060414/8b685577/attachment.htm From pythontut at pusspaws.net Fri Apr 14 16:52:40 2006 From: pythontut at pusspaws.net (Dave S) Date: Fri, 14 Apr 2006 15:52:40 +0100 Subject: [Tutor] Looking for an open source project In-Reply-To: <443F747F.8010501@tds.net> References: <200604140743.45759.pythontut@pusspaws.net> <443F747F.8010501@tds.net> Message-ID: <200604141552.40188.pythontut@pusspaws.net> On Friday 14 April 2006 11:07, Kent Johnson wrote: > Dave S wrote: > > Hi all, > > > > I have been playing around with Python for a while now and am looking > > for open source KDE projects written in Python that I can help with / > > learn from. > > > > Something relatively simple that uses Qt. (I am still a bit green) > > > > Any idea where I can get a list of projects. I checked out sourceforge > > but could not work out how to filter for Python. > > Go to the SF software map and click on a category, then you will be able > to filter for language. > Thanks for that :) Dave From kent37 at tds.net Fri Apr 14 17:29:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Apr 2006 11:29:27 -0400 Subject: [Tutor] Meaning of %g ? In-Reply-To: <443F7248.5040407@tds.net> References: <029001c65ef5$d4640140$0a01a8c0@xp> <02fd01c65f96$43adbaf0$0a01a8c0@xp> <443F7248.5040407@tds.net> Message-ID: <443FBFD7.4070105@tds.net> Kent Johnson wrote: > Alan Gauld wrote: >>>>> print "%14.3g\n%14.3e\n%14.3f" % (bignum,bignum,bignum) >> 1.23e+009 >> 1.235e+009 >> 1234567898.235 >> >> Hopefully those examples show whats happening. >> I have no idea why %g is dropping a digit, it may even be a bug! > > It looks to me like either a documentation error or a bug. It might be > worth asking on c.l.py. Which I did; see here for Fredrik Lundh's answer: http://groups.google.com/group/comp.lang.python/msg/f8dca0d28c426d48?hl=en& Kent From patriciap.gu at gmail.com Fri Apr 14 19:31:41 2006 From: patriciap.gu at gmail.com (Patty) Date: Fri, 14 Apr 2006 17:31:41 +0000 (UTC) Subject: [Tutor] MySQLdb question References: <443FAD4C.9060004@fredericksburg.com> Message-ID: > > for ahost,target in my_map: > cursor.execute("""SELECT %s FROM targets > WHERE target_name in (%s) """ % (ahost, ",".join(target))) > Hi again, I'm confused :-( I'm using an old version of python (2.3.4). In my database, target_name is the name of a column, not the name of a target. Patty From davholla2002 at yahoo.co.uk Fri Apr 14 20:20:16 2006 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri, 14 Apr 2006 19:20:16 +0100 (BST) Subject: [Tutor] plz help Message-ID: <20060414182016.38863.qmail@web25911.mail.ukl.yahoo.com> John, Sorry I have been away since then. You should always include the tutor in any replies in case anyone else can help or if the original person has a problem and is away from the pc. I will look at this tomorrow unless someone else helps before. John Brokaw wrote: Date: Thu, 13 Apr 2006 13:07:23 -0400 From: "John Brokaw" To: "David Holland" Subject: Re: Show us some code Sure... >>> import pygame, sys,os >>> from pygame.locals import * >>> pygame.init() (6,0) >>>window = pygame.display.set_mode((468, 60)) I have also did it in real-time and attached pics of the proccess hope this helps. On 4/13/06, David Holland wrote: John, Can you please post your code and the exact error message. ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail ------------------------------------------------------------------------------------------------------------------------------------ First they came for the Danes, but I did not speak out because I am not a Dane. --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PC calling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060414/efaa0b73/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: Code.jpg Type: image/jpeg Size: 143625 bytes Desc: pat869519609 Url : http://mail.python.org/pipermail/tutor/attachments/20060414/efaa0b73/attachment-0003.jpg -------------- next part -------------- A non-text attachment was scrubbed... Name: notrespon.jpg Type: image/jpeg Size: 142833 bytes Desc: pat1179996618 Url : http://mail.python.org/pipermail/tutor/attachments/20060414/efaa0b73/attachment-0004.jpg -------------- next part -------------- A non-text attachment was scrubbed... Name: errors.jpg Type: image/jpeg Size: 173119 bytes Desc: pat1909106184 Url : http://mail.python.org/pipermail/tutor/attachments/20060414/efaa0b73/attachment-0005.jpg From alan.gauld at freenet.co.uk Fri Apr 14 21:03:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 14 Apr 2006 20:03:24 +0100 Subject: [Tutor] Meaning of %g ? References: <029001c65ef5$d4640140$0a01a8c0@xp> <02fd01c65f96$43adbaf0$0a01a8c0@xp><443F7248.5040407@tds.net> <443FBFD7.4070105@tds.net> Message-ID: <034601c65ff6$1b1bd440$0a01a8c0@xp> >>> Hopefully those examples show whats happening. >>> I have no idea why %g is dropping a digit, it may even be a bug! >> >> It looks to me like either a documentation error or a bug. It might be >> worth asking on c.l.py. > > Which I did; see here for Fredrik Lundh's answer: > http://groups.google.com/group/comp.lang.python/msg/f8dca0d28c426d48?hl=en& Hmm, that says there is allowed to be a difference but not why there is a difference. The quote from the C standard would allow both e,f and g to have the same precision. In the original K&R(pre ANSI) it simply says %g is the shorter of %f and %e with no hint of any other modification. Given that the logical implementation for %g would be to use %e/%f format as required but for some odd reason its been implemented differently. So its not really a bug, since the spac allows for it, but is still strange behaviour Thanks for asking the question Kent, I was going to get around to it sometime! :-) IMHO. Alan G. From adam.jtm30 at gmail.com Fri Apr 14 21:56:32 2006 From: adam.jtm30 at gmail.com (Adam) Date: Fri, 14 Apr 2006 20:56:32 +0100 Subject: [Tutor] plz help In-Reply-To: <20060414182016.38863.qmail@web25911.mail.ukl.yahoo.com> References: <20060414182016.38863.qmail@web25911.mail.ukl.yahoo.com> Message-ID: > John Brokaw wrote: > Date: Thu, 13 Apr 2006 13:07:23 -0400 > From: "John Brokaw" > To: "David Holland" > Subject: Re: Show us some code > > > Sure... > >>> import pygame, sys,os > >>> from pygame.locals import * > >>> pygame.init() > (6,0) > >>>window = pygame.display.set_mode((468, 60)) > I have also did it in real-time and attached pics of the proccess hope this > helps. Have you tried pygame.display.quit()? It looks to me like it is working ok because idle has displayed another >>>. Try that command to shut down the pygame window. From srini_iyyer_bio at yahoo.com Fri Apr 14 23:46:32 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 14 Apr 2006 14:46:32 -0700 (PDT) Subject: [Tutor] changing 2x3 matrix to 3x2 matrix - using lists In-Reply-To: Message-ID: <20060414214632.77590.qmail@web38107.mail.mud.yahoo.com> Dear group, I have a huge list of data. This was obtained using R through Rpy. the data resembles a 10K (row) x 30 (column) matrix. I processed the data column wise( obtained median values for duplicated rows). Now I am left with 500 rows and 30 columns. I want to print the same way. A snippet: >>> a = """apple\tboy\tcat\ndog\tegg\tfox\n""" >>> ab = a.split('\n') >>> for m in ab: cols = m.split('\t') print cols ['apple', 'boy', 'cat'] ['dog', 'egg', 'fox'] ######################################## # Here I processed the data and assuming nothing changed in the snippet, I want to print : ## apple dog boy egg cat fox How can I do that? I tries a different way below. If there are two lists, I could use 'zip' method. However, since script is running over a loop of 30 columns, I have no clue how can I use zip dynamically. ################################### >>> for m in result: for i in range(len(m)): print m[i]+'\t'+m[i+1] apple dog Traceback (most recent call last): File "", line 3, in -toplevel- print m[i]+'\t'+m[i+1] IndexError: list index out of range __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From adam.jtm30 at gmail.com Sat Apr 15 00:01:22 2006 From: adam.jtm30 at gmail.com (Adam) Date: Fri, 14 Apr 2006 23:01:22 +0100 Subject: [Tutor] plz help In-Reply-To: <3e31560604141339s673d3bb9h9be7c9cf59ee7da3@mail.gmail.com> References: <20060414182016.38863.qmail@web25911.mail.ukl.yahoo.com> <3e31560604141339s673d3bb9h9be7c9cf59ee7da3@mail.gmail.com> Message-ID: On 14/04/06, John Brokaw wrote: > Adam, Yes i have and thanks for trying to help. I guess I need to be more > specific with my question. I need to know why this is happening and will it > happend if a put together a complete game. I can close the window with the > display.quit command and or the ctrl+alt+del method, but I want to know why > its not repsonding in the first place. What do you mean not responding? If you mean when you click on the window manager X thing that usually shuts down windows, and nothing happens, it doesn't until you bind the event of it being clicked to pygame.display.quit() From kent37 at tds.net Sat Apr 15 00:14:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Apr 2006 18:14:43 -0400 Subject: [Tutor] changing 2x3 matrix to 3x2 matrix - using lists In-Reply-To: <20060414214632.77590.qmail@web38107.mail.mud.yahoo.com> References: <20060414214632.77590.qmail@web38107.mail.mud.yahoo.com> Message-ID: <44401ED3.10108@tds.net> Srinivas Iyyer wrote: > Dear group, > I have a huge list of data. This was obtained using R > through Rpy. > > the data resembles a 10K (row) x 30 (column) matrix. > > I processed the data column wise( obtained median > values for duplicated rows). > > Now I am left with 500 rows and 30 columns. > > I want to print the same way. > > > A snippet: > >>>> a = """apple\tboy\tcat\ndog\tegg\tfox\n""" >>>> ab = a.split('\n') >>>> for m in ab: > cols = m.split('\t') > print cols > > > ['apple', 'boy', 'cat'] > ['dog', 'egg', 'fox'] > ######################################## > # Here I processed the data and assuming nothing > changed in the snippet, I want to print : > ## > apple dog > boy egg > cat fox > > How can I do that? > I tries a different way below. If there are two lists, > I could use 'zip' method. However, since script is > running over a loop of 30 columns, I have no clue how > can I use zip dynamically. For working with arrays that big you should probably look at numpy, but someone else will have to help you with that. If you have a list of lists, you can use zip(*lists) to transpose it: In [1]: data = [ ...: ['apple', 'boy', 'cat'], ...: ['dog', 'egg', 'fox'], ...: ['spam', 'cheese', 'ni'] ...: ] In [3]: data Out[3]: [['apple', 'boy', 'cat'], ['dog', 'egg', 'fox'], ['spam', 'cheese', 'ni']] In [4]: zip(*data) Out[4]: [('apple', 'dog', 'spam'), ('boy', 'egg', 'cheese'), ('cat', 'fox', 'ni')] zip(*data) is like saying zip(data[0], data[1], ..., data[-1]) but you don't have to know how big data is. Kent From ml.cyresse at gmail.com Sat Apr 15 02:27:49 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 15 Apr 2006 12:27:49 +1200 Subject: [Tutor] MySQLdb question In-Reply-To: References: Message-ID: On 4/15/06, Patty wrote: > Hi, > > I have a data structure in a python file that looks something like this: > > my_map= { "host1": {"target1", "target2", "target3" }, > "host2": {"target4", "target5", "target6" }, > } > > I have a method that has two parameteres (ahost, atarget), which I want to use > to retrieve data from the database. In my database each host has a column and > each target has a row. The way I have it now is something like this: > > cursor.execute("""SELECT host1, host2, host3, host4, host5, host6 FROM targets > WHERE target_name = %s """, (target)) > > This is very inefficient because I'm retrieving data that I don't need. Instead, > I want to use the parameters in my method, but I'm not sure how to do it > > cursor.execute("""SELECT %s FROM targets > WHERE target_name = %s """, (ahost, target)) # I tried this, but it > didn't work. > > > I also tried this, but got a error: > > cursor.execute("""SELECT %s FROM targets > WHERE target_name = %s """ % (ahost, target)) > > Can anybody show me the right way to do it? > > Thanks, > Patty > >> >> for ahost,target in my_map: >> cursor.execute("""SELECT %s FROM targets >> WHERE target_name in (%s) """ % (ahost, ",".join(target))) >> >Hi again, >I'm confused :-( >I'm using an old version of python (2.3.4). In my database, target_name is the >name of a column, not the name of a target. I'm confused also. Can you show us in SQL what you're trying to do? i.e. What's your desired SQL statement? From prabhu.chinnee at gmail.com Sat Apr 15 13:34:27 2006 From: prabhu.chinnee at gmail.com (Prabhakar K) Date: Sat, 15 Apr 2006 17:04:27 +0530 Subject: [Tutor] PHP Functions in Python Message-ID: <3ae549770604150434t400b5d7fr6970e3bf863f58f3@mail.gmail.com> Hi, I want to call php function in Python... is there any way to call. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/a727f43b/attachment.htm From john.corry at ntlworld.com Sat Apr 15 15:20:46 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 15 Apr 2006 14:20:46 +0100 Subject: [Tutor] Difficulty connecting with odbc drivers Message-ID: <000501c6608f$6c1122d0$4a3ea8c0@JOHNC> Hi, I have downloaded the mxodbc product. I am using windows xp, python 2.4 and I am trying to log onto a visual foxpro database file. I have downloaded the visual foxpro driver. I use the following code: import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') c = db.cursor() and I get the following error: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\databasemanager.py", line 4, in ? db = mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified', 6044) What am I doing wrong and what do I need to do? Any help would be greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/a86087ac/attachment.htm From john.corry at ntlworld.com Sat Apr 15 15:21:31 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 15 Apr 2006 14:21:31 +0100 Subject: [Tutor] Difficulty connecting with odbc drivers Message-ID: <000a01c6608f$874a2150$4a3ea8c0@JOHNC> Hi, I have downloaded the mxodbc product. I am using windows xp, python 2.4 and I am trying to log onto a visual foxpro database file. I have downloaded the visual foxpro driver. I use the following code: import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') c = db.cursor() and I get the following error: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\databasemanager.py", line 4, in ? db = mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified', 6044) What am I doing wrong and what do I need to do? Any help would be greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/fa9c4d72/attachment.html From ml.cyresse at gmail.com Sat Apr 15 15:59:15 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 16 Apr 2006 01:59:15 +1200 Subject: [Tutor] PHP Functions in Python In-Reply-To: <3ae549770604150434t400b5d7fr6970e3bf863f58f3@mail.gmail.com> References: <3ae549770604150434t400b5d7fr6970e3bf863f58f3@mail.gmail.com> Message-ID: Um. I suppose you could, but what are you trying to do? I'm fairly certain Python has similar functionality to PHP, and is a lot more straightforward than interfacing with a forked process. (Assuming you're using the PHP CLI and not talking PHP in Apache, etc.) On 4/15/06, Prabhakar K wrote: > > Hi, > > I want to call php function in Python... is there any way to call. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Sat Apr 15 16:02:25 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 16 Apr 2006 02:02:25 +1200 Subject: [Tutor] Difficulty connecting with odbc drivers In-Reply-To: <000a01c6608f$874a2150$4a3ea8c0@JOHNC> References: <000a01c6608f$874a2150$4a3ea8c0@JOHNC> Message-ID: According to the eGenix docs: Please refer to the ODBC manuals of your ODBC manager and database for the exact syntax of the DSN_string. It typically has these entries: 'DSN=datasource_name;UID=userid;PWD=password;' (case is important !). So, you've got DSN lowercase... On 4/16/06, John CORRY wrote: > > > > Hi, > > > > I have downloaded the mxodbc product. I am using windows xp, python 2.4 and > I am trying to log onto a visual foxpro database file. I have downloaded > the visual foxpro driver. I use the following code: > > > > import mx.ODBC > > import mx.ODBC.Windows > > db = > mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') > > c = db.cursor() > > > > and I get the following error: > > > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\databasemanager.py", > line 4, in ? > > db = > mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') > > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data source > name not found and no default driver specified', 6044) > > > > What am I doing wrong and what do I need to do? Any help would be greatly > appreciated. > > > > Thanks, > > > > John. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From john.corry at ntlworld.com Sat Apr 15 16:30:14 2006 From: john.corry at ntlworld.com (John Corry) Date: Sat, 15 Apr 2006 15:30:14 +0100 Subject: [Tutor] Difficulty connecting with odbc drivers In-Reply-To: Message-ID: Liam, Thanks for the quick response. I have changed the code so that dsn is now DSN. However I get the same error. Any other thoughts? Regards, John. -----Original Message----- From: Liam Clarke [mailto:ml.cyresse at gmail.com] Sent: 15 April 2006 15:02 To: john.corry at ntlworld.com Cc: tutor at python.org Subject: Re: [Tutor] Difficulty connecting with odbc drivers According to the eGenix docs: Please refer to the ODBC manuals of your ODBC manager and database for the exact syntax of the DSN_string. It typically has these entries: 'DSN=datasource_name;UID=userid;PWD=password;' (case is important !). So, you've got DSN lowercase... On 4/16/06, John CORRY wrote: > > > > Hi, > > > > I have downloaded the mxodbc product. I am using windows xp, python 2.4 and > I am trying to log onto a visual foxpro database file. I have downloaded > the visual foxpro driver. I use the following code: > > > > import mx.ODBC > > import mx.ODBC.Windows > > db = > mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') > > c = db.cursor() > > > > and I get the following error: > > > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\databasemanager.py", > line 4, in ? > > db = > mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') > > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data source > name not found and no default driver specified', 6044) > > > > What am I doing wrong and what do I need to do? Any help would be greatly > appreciated. > > > > Thanks, > > > > John. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From john.corry at ntlworld.com Sat Apr 15 16:24:38 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 15 Apr 2006 15:24:38 +0100 Subject: [Tutor] odbc Message-ID: <000001c66098$58a5e380$4a3ea8c0@JOHNC> Hi, I have just run the test package within mxODBC. I get the following result. ======================================================================== mx.ODBC Test Suite ------------------------------------------------------------------------ Subpackage Name [Windows]: Available Datasources: ------------------------------------------------------------------------ Excel Files - Microsoft Excel Driver (*.xls) MS Access Database - Microsoft Access Driver (*.mdb) Visual FoxPro Database - Microsoft Visual FoxPro Driver Visual FoxPro Tables - Microsoft Visual FoxPro Driver dBASE Files - Microsoft dBase Driver (*.dbf) DriverConnect arguments [DSN=test;UID=test;PWD=test]: Clear AUTOCOMMIT ? (1/0) [1] Run tests continuously to check for leaks ? (y/n) [n] Use direct execution of SQL statements ? (y/n) [n] Run long benchmark ? (y/n) [n] Show driver type information ? (y/n) [n] Output file [stdout]: Testing package mx.ODBC.Windows version: 2.0.5 compiled with Unicode support using Python version: 2.4 Test suite: Connecting to the database. Traceback (most recent call last): File "C:\Python24\Lib\site-packages\mx\ODBC\Misc\test.py", line 2346, in ? rc = main(packagename) File "C:\Python24\Lib\site-packages\mx\ODBC\Misc\test.py", line 2278, in main connection = apply(connectapi,connectargs) OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified', 6044) It gives me the same error that I am experiencing when I run my code. Does this mean that I have not installed something that I need or have not installed something properly. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/b6b4163b/attachment.html From kent37 at tds.net Sat Apr 15 16:39:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Apr 2006 10:39:35 -0400 Subject: [Tutor] odbc In-Reply-To: <000001c66098$58a5e380$4a3ea8c0@JOHNC> References: <000001c66098$58a5e380$4a3ea8c0@JOHNC> Message-ID: <444105A7.6030800@tds.net> John CORRY wrote: > I have just run the test package within mxODBC. I get the following result. > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data > source name not found and no default driver specified', 6044) > > It gives me the same error that I am experiencing when I run my code. > Does this mean that I have not installed something that I need or have > not installed something properly. Have you configured an ODBC data source for the database you are trying to access? I don't remember how to do this but I know it was a necessary step for accessing MS-Access databases from ODBC. Kent From john.corry at ntlworld.com Sat Apr 15 17:03:38 2006 From: john.corry at ntlworld.com (John Corry) Date: Sat, 15 Apr 2006 16:03:38 +0100 Subject: [Tutor] odbc In-Reply-To: <444105A7.6030800@tds.net> Message-ID: Kent, I am not sure what you mean. I am feeling about in the dark on this subject. Do you have an example? Among my visual foxpro database files I have a file called tng.dbc. When I acces the database files through excel, I select the tng.dbc before I can see the fields in the databases. Is this what I need to log onto with python first before I access the database file? Regards, John. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Kent Johnson Sent: 15 April 2006 15:40 Cc: tutor at python.org Subject: Re: [Tutor] odbc John CORRY wrote: > I have just run the test package within mxODBC. I get the following result. > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data > source name not found and no default driver specified', 6044) > > It gives me the same error that I am experiencing when I run my code. > Does this mean that I have not installed something that I need or have > not installed something properly. Have you configured an ODBC data source for the database you are trying to access? I don't remember how to do this but I know it was a necessary step for accessing MS-Access databases from ODBC. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat Apr 15 16:56:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 15 Apr 2006 15:56:08 +0100 Subject: [Tutor] Difficulty connecting with odbc drivers References: <000501c6608f$6c1122d0$4a3ea8c0@JOHNC> Message-ID: <002301c6609c$baca90c0$0a01a8c0@xp> > I have downloaded the mxodbc product. I am using windows xp, python 2.4 > mx.ODBC.Windows.DriverConnect('dsn=c:/test/m2m/data/cost_grid.dbf') > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data > source name not found and no default driver specified', 6044) > What am I doing wrong and what do I need to do? Any help would be > greatly appreciated. You need to set up the driver using the ODBC management applet from Control Panel->Admin Tools. You don't mention doing that so it may be you need an extra step. Otherwise I dunno, sorry. Alan G. From john.corry at ntlworld.com Sat Apr 15 18:58:02 2006 From: john.corry at ntlworld.com (John Corry) Date: Sat, 15 Apr 2006 17:58:02 +0100 Subject: [Tutor] Good Hustle Hit the Showers! In-Reply-To: <1145113437.22297.67.camel@www.venix.com> Message-ID: Hi, Good advice. I configured the ODBC data sources as advised and I am now able to query my database files. Thanks, John. -----Original Message----- From: Lloyd Kvam [mailto:lkvam at venix.com] Sent: 15 April 2006 16:04 To: john.corry at ntlworld.com Cc: Kent Johnson; Tutor Python Subject: Re: [Tutor] odbc On Sat, 2006-04-15 at 16:03 +0100, John Corry wrote: > Kent, > > I am not sure what you mean. I am feeling about in the dark on this > subject. > > Do you have an example? You should have a Control Panel Application for configuring ODBC data sources. The program using an ODBC driver is separated from the actual file. Instead the DSN name is matched against a registry entry to find the actual file or database. So you won't get anywhere until you get the ODBC registry stuff straight. That's also why the unit tests fail. (This is from a Linux guy, so the exact details could be off a little bit, but hopefully it points you in the right direction.) > Among my visual foxpro database files I have a file > called tng.dbc. When I acces the database files through excel, I select the > tng.dbc before I can see the fields in the databases. Is this what I need > to log onto with python first before I access the database file? > > Regards, > > John. > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Kent Johnson > Sent: 15 April 2006 15:40 > Cc: tutor at python.org > Subject: Re: [Tutor] odbc > > > John CORRY wrote: > > I have just run the test package within mxODBC. I get the following > result. > > OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Data > > source name not found and no default driver specified', 6044) > > > > It gives me the same error that I am experiencing when I run my code. > > Does this mean that I have not installed something that I need or have > > not installed something properly. > > Have you configured an ODBC data source for the database you are trying > to access? I don't remember how to do this but I know it was a necessary > step for accessing MS-Access databases from ODBC. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 From bgailer at alum.rpi.edu Sat Apr 15 18:53:55 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 15 Apr 2006 09:53:55 -0700 Subject: [Tutor] Difficulty connecting with odbc drivers In-Reply-To: References: Message-ID: <44412523.2050607@alum.rpi.edu> John Corry wrote: > Liam, > > Thanks for the quick response. I have changed the code so that dsn is now > DSN. However I get the same error. I agree with Alan.the dsn should point to a data source rather than a file. To be more precise Start -> Settings -> Control Panel -> Administrative Tools -> Data Sources If you can't figure out what to do there let us know. From oasf2004 at yahoo.com Sat Apr 15 19:50:29 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Sat, 15 Apr 2006 10:50:29 -0700 (PDT) Subject: [Tutor] Is this correct? Message-ID: <20060415175029.46196.qmail@web60016.mail.yahoo.com> Hello: This question is regarding the first exercise of the book "How to think Like a Computer Scientist: Learning with Python", by Downey, Elkner, and Meyers, Chapter 13, page 137. The goal is to write a function printTime that takes a Time object as an argument and prints it in the form hours:minutes:seconds. So, I wrote the script below: class Time: pass hour = int( raw_input('Enter the hour: ') ) min = int( raw_input('Enter the minute: ') ) sec = int( raw_input('Enter the sec: ') ) time = Time() time.hours = hour time.minutes = min time.seconds = sec def printTime(time): print 'The time is %dh:%dmin:%dsec' % (hour, min, sec) printTime(time) That seems to work, but I would like to hear from you. Please, let me know if I am in the right way. Thanks! Hoffmann __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From xray_2003 at hotmail.com Sat Apr 15 19:35:50 2006 From: xray_2003 at hotmail.com (x-ray ubeenstung) Date: Sat, 15 Apr 2006 18:35:50 +0100 Subject: [Tutor] (no subject) Message-ID: STOP SENDING ME MESSAGES I NEVER SIGNED UP TO YOUR MAILING LIST From dyoo at hkn.eecs.berkeley.edu Sat Apr 15 21:06:19 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Apr 2006 12:06:19 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: > STOP SENDING ME MESSAGES I NEVER SIGNED UP TO YOUR MAILING LIST Followup --- unsubscribed. In the future --- and just so that others know --- if anyone has any administrative messages or "unsubscribe me" messages, send them to the administrators at: The administrative email address is: tutor-owner at python.org Try to avoid sending admin stuff to the main tutor mailing list, since only the admins have the access to handle list management issues. From john.corry at ntlworld.com Sat Apr 15 23:26:34 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 15 Apr 2006 22:26:34 +0100 Subject: [Tutor] Didn't take long to hit my next wall! Message-ID: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> Hi, I am having problems amending records in my database. If I use the following code my database is updated fine. c = '"PF1"' b = 91.4 a = 85.00 import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = "PF1" and finish_dro = ?', ( a, b,)) db.commit() c.close() However if I use the following code:- Where the only difference is I use the c variable instead of the actual "PF1". The database does not get updated. I have also tried C = "PF1" but this does not work either. c = '"PF1"' b = 91.4 a = 85.00 import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? and finish_dro = ?', ( a, c,b,)) db.commit() c.close() Any suggestions would be greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/d2ef578c/attachment.htm From john.corry at ntlworld.com Sun Apr 16 00:48:36 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 15 Apr 2006 23:48:36 +0100 Subject: [Tutor] School Boy Error Message-ID: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> Thanks Brian for the help on the last one. I couldn't see the wood for the trees. I have a tougher one for you. I am reading in a CSV file. Each line represents a line that I want to upload into my database. I am trying to upload the first line in the file to get myself started. The code is below:- import string, re path = "c:/test/import.csv" listy = [] input = file(path, "r") for line in input.readlines(): line = line.split(",") listy.append(line) print listy[-1] stat = """Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" t = 5000 d = "PF2" b = 91.4 a = 95.00 import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute(stat, listy[-1]) db.commit() c.close() I get the following error: TypeError: parameters must be a list of tuples Any suggestions would be greatly appreciated. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/e0e08247/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Apr 16 00:50:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Apr 2006 15:50:20 -0700 (PDT) Subject: [Tutor] Didn't take long to hit my next wall! In-Reply-To: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> Message-ID: > I am having problems amending records in my database. Hi John, The root of this problem is a matter of choosing variable names that are way too terse. In particular, note that you're using the variable 'c' as: c = 'PF1' but at the same time, you're also using: c = db.cursor() Do you notice anything bad that might happen here? From alan.gauld at freenet.co.uk Sun Apr 16 01:08:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 16 Apr 2006 00:08:28 +0100 Subject: [Tutor] Didn't take long to hit my next wall! References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> Message-ID: <006101c660e1$8207dfa0$0a01a8c0@xp> Hi John, I've no idea why its not working but this illustrates why I prefer to create the sql string outside the execute - its a lot easier to debug when you can print the string exactly as passed to execute. I know many others like to leave execute to do the escaping stuff but I prefer to see what I'm doing and put in a little extra effort. So I would write it as: query = '''UPDATE cost_grid SET cost_1 = %s WHERE cost_grid_id = %s AND finish_dro = %s'''' % ( a,c,b) c.execute(query) Dunno if that helps but its my experience FWIW, Alan G. ----- Original Message ----- From: "John CORRY" To: Sent: Saturday, April 15, 2006 10:26 PM Subject: [Tutor] Didn't take long to hit my next wall! > Hi, > > I am having problems amending records in my database. > > If I use the following code my database is updated fine. > > c = '"PF1"' > b = 91.4 > a = 85.00 > import mx.ODBC > import mx.ODBC.Windows > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > c = db.cursor() > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = "PF1" > and finish_dro = ?', ( a, b,)) > > db.commit() > c.close() > > However if I use the following code:- > Where the only difference is I use the c variable instead of the actual > "PF1". The database does not get updated. I have also tried > C = "PF1" but this does not work either. > > c = '"PF1"' > b = 91.4 > a = 85.00 > import mx.ODBC > import mx.ODBC.Windows > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > c = db.cursor() > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? and > finish_dro = ?', ( a, c,b,)) > > db.commit() > c.close() > > Any suggestions would be greatly appreciated. > > Thanks, > > John. > From alan.gauld at freenet.co.uk Sun Apr 16 01:12:16 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 16 Apr 2006 00:12:16 +0100 Subject: [Tutor] Is this correct? References: <20060415175029.46196.qmail@web60016.mail.yahoo.com> Message-ID: <006701c660e2$09d53180$0a01a8c0@xp> Hi, > The goal is to write a function printTime that takes a > Time object as an argument and prints it in the form > hours:minutes:seconds. > > So, I wrote the script below: > > class Time: > pass > > hour = int( raw_input('Enter the hour: ') ) > min = int( raw_input('Enter the minute: ') ) > sec = int( raw_input('Enter the sec: ') ) > > time = Time() > time.hours = hour > time.minutes = min > time.seconds = sec Personally I prefer to put the initialisation intomnan __init__() method, but otherwise it looks ok to me. Also I'd probably not use a class here but a simple tuple or similar, but your exercise seems to want an object and implies a class should be used. > def printTime(time): > print 'The time is %dh:%dmin:%dsec' % (hour, min, > sec) > > printTime(time) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From oasf2004 at yahoo.com Sun Apr 16 01:39:43 2006 From: oasf2004 at yahoo.com (Hoffmann) Date: Sat, 15 Apr 2006 16:39:43 -0700 (PDT) Subject: [Tutor] Is this correct? In-Reply-To: <006701c660e2$09d53180$0a01a8c0@xp> Message-ID: <20060415233943.58592.qmail@web60016.mail.yahoo.com> --- Alan Gauld wrote: > Hi, > > > The goal is to write a function printTime that > takes a > > Time object as an argument and prints it in the > form > > hours:minutes:seconds. > > > > So, I wrote the script below: > > > > class Time: > > pass > > > > hour = int( raw_input('Enter the hour: ') ) > > min = int( raw_input('Enter the minute: ') ) > > sec = int( raw_input('Enter the sec: ') ) > > > > time = Time() > > time.hours = hour > > time.minutes = min > > time.seconds = sec > > Personally I prefer to put the initialisation > intomnan __init__() > method, but otherwise it looks ok to me. Also I'd > probably > not use a class here but a simple tuple or similar, > but your > exercise seems to want an object and implies a class > should be used. > > > def printTime(time): > > print 'The time is %dh:%dmin:%dsec' % (hour, min, > > sec) > > > > printTime(time) > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > Hi Alan, Thanks for your comments. Please, see below a new version of that exercise. What do you think? Thanks, Hoffmann ps: the new version: hour = int( raw_input('Enter the hour: ') ) min = int( raw_input('Enter the minute: ') ) sec = int( raw_input('Enter the sec: ') ) class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self.hours = hours self.minutes = minutes self.seconds = seconds def printTime(self): # By convention, the first parameter of a method is called self. '''printTime: Prints the time.''' print str(self.hours) + ":" + str(self.minutes) + ":" + str(self.seconds) def convertToSeconds(t): ''' convertToSeconds: Converts a Time object into an integer.''' minutes = t.hours * 60 + t.minutes seconds = t.minutes * 60 + t.seconds return seconds def makeTime(seconds): ''' makeTime: Converts from an integer to a Time object.''' time = Time() time.hours = seconds/3600 seconds = seconds - time.hours * 3600 time.minutes = seconds/60 seconds = seconds - time.minutes * 60 time.seconds = seconds return time def addTime(t1, t2): ''' addTime function: Calculates the sum of two times.''' seconds = convertToSeconds(t1) + convertToSeconds(t2) return makeTime(seconds) currentTime = Time() currentTime.hours = hour currentTime.minutes = min currentTime.seconds = sec currentTime.printTime() __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tiagosaboga at terra.com.br Sun Apr 16 02:40:19 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Sat, 15 Apr 2006 21:40:19 -0300 Subject: [Tutor] string formatting (%s) Message-ID: <200604152140.20156.tiagosaboga@terra.com.br> Can I use string formatting in my own functions, or is it stuck with builtins? It doesn't make much sense for me, but I don't understand the following error: In [1]: var = 456 In [2]: def printd(arg): ...: print('>>> %s') % arg ...: In [3]: printd(var) >>> 456 In [4]: printd('Variable is %s') % var >>> Variable is %s --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/tiago/ TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' Thanks, Tiago. From brian at daviesinc.com Sun Apr 16 03:33:45 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 15 Apr 2006 21:33:45 -0400 Subject: [Tutor] School Boy Error In-Reply-To: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> References: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> Message-ID: <44419EF9.5050205@daviesinc.com> would be helpful to paste the entire error information that python gives .. including the lines before and after. When pytho sets an error , it will tell you *exactly* where the error is at (or it should) I do all my development work on Linux, havent worked with ODBC databases, but the reference to a list of tuples , almost makes me thing the SQL needs to be a full insert: (insert into tablename (field1,field2.....) values (value1,value2....) ) John CORRY wrote: > Thanks Brian for the help on the last one. I couldn?t see the wood for > the trees. I have a tougher one for you. > > > > I am reading in a CSV file. Each line represents a line that I want to > upload into my database. I am trying to upload the first line in the > file to get myself started. The code is below:- > > > > import string, re > > path = "c:/test/import.csv" > > listy = [] > > input = file(path, "r") > > for line in input.readlines(): > > line = line.split(",") > > listy.append(line) > > > > print listy[-1] > > > > stat = """Insert into cost_grid values > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" > > t = 5000 > > d = "PF2" > > b = 91.4 > > a = 95.00 > > > > import mx.ODBC > > import mx.ODBC.Windows > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute(stat, listy[-1]) > > > > db.commit() > > c.close() > > > > I get the following error: > > > > TypeError: parameters must be a list of tuples > > > > Any suggestions would be greatly appreciated. > > > > Thanks, > > > > John. > > !DSPAM:444178de174651249418164! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:444178de174651249418164! From ml.cyresse at gmail.com Sun Apr 16 03:39:15 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 16 Apr 2006 13:39:15 +1200 Subject: [Tutor] School Boy Error In-Reply-To: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> References: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> Message-ID: Hi John, Listy will be a list of lists, and the DBAPI specifies tuples. So either change this - listy.append(line) to listy.append(tuple(line)) or stick a list comprehension at the end if you need to mung anything in listy before passing it in: listy = [ tuple(item) for item in listy] Regards, Liam Clarke On 4/16/06, John CORRY wrote: > > > > Thanks Brian for the help on the last one. I couldn't see the wood for the > trees. I have a tougher one for you. > > > > I am reading in a CSV file. Each line represents a line that I want to > upload into my database. I am trying to upload the first line in the file > to get myself started. The code is below:- > > > > import string, re > > path = "c:/test/import.csv" > > listy = [] > > input = file(path, "r") > > for line in input.readlines(): > > line = line.split(",") > > listy.append(line) > > > > print listy[-1] > > > > stat = """Insert into cost_grid values > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" > > t = 5000 > > d = "PF2" > > b = 91.4 > > a = 95.00 > > > > import mx.ODBC > > import mx.ODBC.Windows > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute(stat, listy[-1]) > > > > db.commit() > > c.close() > > > > I get the following error: > > > > TypeError: parameters must be a list of tuples > > > > Any suggestions would be greatly appreciated. > > > > Thanks, > > > > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Sun Apr 16 03:45:27 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 16 Apr 2006 13:45:27 +1200 Subject: [Tutor] School Boy Error In-Reply-To: References: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> Message-ID: Wait, I have put you wrong there. Can you please copy and paste here the output of print liney[-1] Thanks, Liam On 4/16/06, Liam Clarke wrote: > Hi John, > > Listy will be a list of lists, and the DBAPI specifies tuples. So > either change this - > > listy.append(line) > > to > > listy.append(tuple(line)) > > or stick a list comprehension at the end if you need to mung anything > in listy before passing it in: > > listy = [ tuple(item) for item in listy] > > Regards, > > Liam Clarke > > On 4/16/06, John CORRY wrote: > > > > > > > > Thanks Brian for the help on the last one. I couldn't see the wood for the > > trees. I have a tougher one for you. > > > > > > > > I am reading in a CSV file. Each line represents a line that I want to > > upload into my database. I am trying to upload the first line in the file > > to get myself started. The code is below:- > > > > > > > > import string, re > > > > path = "c:/test/import.csv" > > > > listy = [] > > > > input = file(path, "r") > > > > for line in input.readlines(): > > > > line = line.split(",") > > > > listy.append(line) > > > > > > > > print listy[-1] > > > > > > > > stat = """Insert into cost_grid values > > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" > > > > t = 5000 > > > > d = "PF2" > > > > b = 91.4 > > > > a = 95.00 > > > > > > > > import mx.ODBC > > > > import mx.ODBC.Windows > > > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > > > c = db.cursor() > > > > c.execute(stat, listy[-1]) > > > > > > > > db.commit() > > > > c.close() > > > > > > > > I get the following error: > > > > > > > > TypeError: parameters must be a list of tuples > > > > > > > > Any suggestions would be greatly appreciated. > > > > > > > > Thanks, > > > > > > > > John. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From david at graniteweb.com Sun Apr 16 04:31:17 2006 From: david at graniteweb.com (David Rock) Date: Sat, 15 Apr 2006 21:31:17 -0500 Subject: [Tutor] School Boy Error In-Reply-To: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> References: <000001c660de$bce1aaf0$4a3ea8c0@JOHNC> Message-ID: <20060416023117.GA2309@wdfs.graniteweb.com> * John CORRY [2006-04-15 23:48]: > Thanks Brian for the help on the last one. I couldn't see the wood for > the trees. I have a tougher one for you. > > I am reading in a CSV file. Each line represents a line that I want to > upload into my database. I am trying to upload the first line in the > file to get myself started. The code is below:- You may want to check out the csv module to aid in any odd data input, too. http://docs.python.org/lib/module-csv.html -- David Rock david at graniteweb.com From rfquerin at gmail.com Sun Apr 16 05:20:23 2006 From: rfquerin at gmail.com (Richard Querin) Date: Sat, 15 Apr 2006 23:20:23 -0400 Subject: [Tutor] Python video? In-Reply-To: References: <20060413032839.86688.qmail@web60012.mail.yahoo.com> Message-ID: <7d81675b0604152020v75ebec1ck325aab6011a006e3@mail.gmail.com> On 4/13/06, Steve Nelson wrote: > > > On a similar line, I've recently discovered "podcasts". I spend a lot > of time driving, and have been listening through the "Security Now" > broadcasts, and the last few days some stuff on Evolutionary Theory. > Does anyone know of some good sources for programming-type discussions > - talks or lectures I could download and listen to? I've found some neat stuff at http://itconversations.com. They publish quite a few podcasts per week, some interest me, some don't, but they cover quite a large range of topics. Here's a link to part 1 of a 2-part podcast interview with Guido Von Rossum: http://www.itconversations.com/shows/detail545.html Also, Leo Laport has started (finally!) a podcast on open source called Floss. He does several podcasts these days. You can find them (and the Floss podcast) here: http://twit.tv You can also do a search on 'programming' or 'python' at http://podcastalley.com and sometimes find some good podcasts. One other way that's kind of neat, is to use http://podzinger.com which does searches via speech recognition on podcasts. There's quite a lot of potential sources for good programming related podcasts, however finding them is the tough part. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060415/2ec500f2/attachment-0001.htm From carroll at tjc.com Sun Apr 16 07:40:34 2006 From: carroll at tjc.com (Terry Carroll) Date: Sat, 15 Apr 2006 22:40:34 -0700 (PDT) Subject: [Tutor] In[nnn], Out[nnn] (was: dictionary datatype In-Reply-To: <1144819856.12108.26.camel@elrond> Message-ID: On Wed, 12 Apr 2006, Victor Bouffier wrote: > In [285]: n = 0x2018 > > In [286]: n > Out[286]: 8216 Victor -- I've seen this notation 00 e.g., In [286], Out[286] -- in a few people's postings. What variety of Python does this? From dyoo at hkn.eecs.berkeley.edu Sun Apr 16 07:46:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Apr 2006 22:46:51 -0700 (PDT) Subject: [Tutor] string formatting (%s) In-Reply-To: <200604152140.20156.tiagosaboga@terra.com.br> References: <200604152140.20156.tiagosaboga@terra.com.br> Message-ID: On Sat, 15 Apr 2006, Tiago Saboga wrote: > Can I use string formatting in my own functions, or is it stuck with builtins? > It doesn't make much sense for me, but I don't understand the following > error: > > In [1]: var = 456 > > In [2]: def printd(arg): > ...: print('>>> %s') % arg > ...: Hi Tiago, Ah! printd() is not doing what you think it's doing. Try: ######################### def printd(arg): print ('>>> %s' % arg) ######################### The parenthesization you had earlier forced Python into printing out your template before it had an opportunity to plug arg into it. You need to do the interpolation first. From dyoo at hkn.eecs.berkeley.edu Sun Apr 16 07:53:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 15 Apr 2006 22:53:46 -0700 (PDT) Subject: [Tutor] string formatting (%s) In-Reply-To: References: <200604152140.20156.tiagosaboga@terra.com.br> Message-ID: > The parenthesization you had earlier forced Python into printing out > your template before it had an opportunity to plug arg into it. You > need to do the interpolation first. Gaaah. Brain freeze. I was pointing at the wrong code. *grin* I meant to look at the other statement that you had, the one that raised the error: ############################## var = 456 def printd(arg): print(">>> %s") % arg printd(var) printd('Variable is %s') % var ############################## There might be two possibilities to fix this code. One will do the interpolation first: ############################## var = 456 def printd(arg): print(">>> %s") % arg printd(var) printd('Variable is %s' % var) ############################## But the other possible fix is to change printd() from being a side-effect function to something that actually returns something: ################################### var = 456 def arrow(arg): return (">>> %s" % arg) print arrow(var) print arrow('Variable is %s') % var ################################### This second approach is better: functions that return values are more reusable than ones that are fixated on printing things to the screen. From alan.gauld at freenet.co.uk Sun Apr 16 09:39:50 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 16 Apr 2006 08:39:50 +0100 Subject: [Tutor] Is this correct? References: <20060415233943.58592.qmail@web60016.mail.yahoo.com> Message-ID: <008101c66128$f18b9280$0a01a8c0@xp> >> Personally I prefer to put the initialisation >> into an __init__() method, > Thanks for your comments. Please, see below a new > version of that exercise. What do you think? > hour = int( raw_input('Enter the hour: ') ) > min = int( raw_input('Enter the minute: ') ) > sec = int( raw_input('Enter the sec: ') ) > > > class Time: > def __init__(self, hours = 0, minutes = 0, seconds = > 0): > self.hours = hours > self.minutes = minutes > self.seconds = seconds > > def printTime(self): # By convention, the first > parameter of a method is called self. > '''printTime: > > Prints the time.''' > print str(self.hours) + ":" + str(self.minutes) + > ":" + str(self.seconds) > > > def convertToSeconds(t): > ''' convertToSeconds: > > Converts a Time object into an integer.''' > minutes = t.hours * 60 + t.minutes > seconds = t.minutes * 60 + t.seconds > return seconds So far so good. > def makeTime(seconds): > ''' makeTime: > Converts from an integer to a Time object.''' > time = Time() > time.hours = seconds/3600 > seconds = seconds - time.hours * 3600 > time.minutes = seconds/60 > seconds = seconds - time.minutes * 60 > time.seconds = seconds > return time I'd rework this bit to: hours = seconds/3600 seconds = seconds % 3600 # use % to get remainder minutes = seconds/60 seconds = seconds % 60 #and again time = Time(hours,minutes,seconds) return time And by using divmod() you can combine two lines into one: hours,seconds = divmod(seconds,3600) minutes,seconds = divmod(seconds,60) time = Time(hours,minutes,seconds) return time > def addTime(t1, t2): > ''' addTime function: > > Calculates the sum of two times.''' > seconds = convertToSeconds(t1) + convertToSeconds(t2) > return makeTime(seconds) > currentTime = Time() > currentTime.hours = hour > currentTime.minutes = min > currentTime.seconds = sec > currentTime.printTime() I'd move the raw_input lines from the top to here so that the logical connection between them and this is clearer. And you don't use your init method here. Do this instead: currentTime = Time(hour,min,sec) currentTime.printTime() One of the principles of OOP is that you should try not to access the data members of the class directly, use methods to do all the work. [The reason for this is that we can overrride the methods in subclasses but we can't override the data so using data directly limits the effectiveness of subclassing as a mechanism, for changing the behaviour of your code without modifying it. (In Computer Science speak this is known as the Open/Closed principle - open for extension, closed for modification) ] HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Apr 16 09:42:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 16 Apr 2006 08:42:39 +0100 Subject: [Tutor] string formatting (%s) References: <200604152140.20156.tiagosaboga@terra.com.br> Message-ID: <008501c66129$567242c0$0a01a8c0@xp> > Can I use string formatting in my own functions, or is it stuck with > builtins? No, you can use it too. > It doesn't make much sense for me, but I don't understand the following > error: > In [2]: def printd(arg): > ...: print('>>> %s') % arg The format operator needs to be with the string, inside the parentheses: def printd(arg): print('>>> %s' % arg) > TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' The NoneType it refers to is the None returned by the function. In your code the function gets called then Python tries to apply string formatting to the result, which is None. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From john.corry at ntlworld.com Sun Apr 16 11:42:01 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 16 Apr 2006 10:42:01 +0100 Subject: [Tutor] School Boy error Message-ID: <000001c6613a$06ad83b0$4a3ea8c0@JOHNC> Hi, I couldn't sleep last night with all the code running though my head. Counting sheep didn't work as I kept wanting to turn them into a loop! listy[-1] Outputs the following:- ['432', 'TM BLIND', 'RO', 'PF1', 'Plain Finish Range One', '304.8', '', '45.7', '80', '90', '0', '39', '61', '15.03', '33', '0', '46', '81.3', '19.38', '42', '0', '60', '101.6', '22.39', '49', '0', '69', '121.9', '26.39', '58', '0', '81', '142.2', '30.4', '67', '0', '93', '162.6', '34.41', '75', '0', '105', '182.9', '38.08', '83', '0', '117', '198.1', '41.42', '90', '0', '127', '223.5', '48.77', '106', '0', '149', '243.8', '53.12', '117', '0', '163', '274.3', '60.8', '133', '0', '186', '304.8', '66.14', '145', '0', '202', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0\n'] The full error is Traceback (most recent call last): File "C:\Python24\Lib\site-packages\databasemanager.py", line 30, in ? c.execute(stat, listy[-1]) TypeError: parameters must be a list of tuples Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060416/0e132185/attachment.html From brian at daviesinc.com Sun Apr 16 12:16:06 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 16 Apr 2006 06:16:06 -0400 Subject: [Tutor] School Boy error In-Reply-To: <000001c6613a$06ad83b0$4a3ea8c0@JOHNC> References: <000001c6613a$06ad83b0$4a3ea8c0@JOHNC> Message-ID: <44421966.5010808@daviesinc.com> instead of c.execute(stat, listy[-1]) try sql_list = listy[-1] c.execute(stat, sql_list) Also what does print stat give you? maybe one of those two would tell us .. Bri! John CORRY wrote: > Hi, > > > > I couldn?t sleep last night with all the code running though my head. > Counting sheep didn?t work as I kept wanting to turn them into a loop! > > > > listy[-1] > > > > Outputs the following:- > > > > ['432', 'TM BLIND', 'RO', 'PF1', 'Plain Finish Range One', '304.8', '', > '45.7', '80', '90', '0', '39', '61', '15.03', '33', '0', '46', '81.3', > '19.38', '42', '0', '60', '101.6', '22.39', '49', '0', '69', '121.9', > '26.39', '58', '0', '81', '142.2', '30.4', '67', '0', '93', '162.6', > '34.41', '75', '0', '105', '182.9', '38.08', '83', '0', '117', '198.1', > '41.42', '90', '0', '127', '223.5', '48.77', '106', '0', '149', '243.8', > '53.12', '117', '0', '163', '274.3', '60.8', '133', '0', '186', '304.8', > '66.14', '145', '0', '202', '0', '0', '0', '0', '0', '0', '0', '0', '0', > '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', > '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0\n'] > > > > The full error is > > > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\databasemanager.py", line 30, in ? > > c.execute(stat, listy[-1]) > > TypeError: parameters must be a list of tuples > > > > Thanks, > > > > John. > > !DSPAM:444211df223121389011208! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:444211df223121389011208! From john.corry at ntlworld.com Sun Apr 16 12:40:15 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 16 Apr 2006 11:40:15 +0100 Subject: [Tutor] School Boy Error Message-ID: <000001c66142$2a42bb30$4a3ea8c0@JOHNC> Bri, Print stat gives Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,) Traceback (most recent call last): File "C:\Python24\Lib\site-packages\databasemanager.py", line 31, in ? c.execute(stat, sql_list) TypeError: parameters must be a list of tuples Unfortunately sql_list gives the same error. Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060416/4303956f/attachment.htm From kent37 at tds.net Sun Apr 16 13:28:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Apr 2006 07:28:34 -0400 Subject: [Tutor] Is this correct? In-Reply-To: <20060415233943.58592.qmail@web60016.mail.yahoo.com> References: <20060415233943.58592.qmail@web60016.mail.yahoo.com> Message-ID: <44422A62.3060502@tds.net> Hoffmann wrote: > class Time: > def __init__(self, hours = 0, minutes = 0, seconds = > 0): > self.hours = hours > self.minutes = minutes > self.seconds = seconds > > def printTime(self): # By convention, the first > parameter of a method is called self. > '''printTime: > > Prints the time.''' > print str(self.hours) + ":" + str(self.minutes) + > ":" + str(self.seconds) Instead of writing a method that prints the Time, a more flexible approach is to write a method that returns a string representation of the Time. If you call the method __str__(), it is recognized by Python and used automatically by print statements. For example: In [1]: class Test(object): ...: def __init__(self, value): ...: self.value = value ...: def __str__(self): ...: return 'Test(%s)' % self.value ...: ...: In [2]: t1=Test(3) In [3]: print t1 Test(3) Writing a __str__() method gives the caller the flexibility to format the result further, such as printing two Tests on one line: In [4]: t2 = Test(4) In [5]: print t1, t2 Test(3) Test(4) By the way, __str__ is an example of a "special method" - a method that is recognized by the Python runtime and used to implement bits of Python functionality. When you write print x this becomes print str(x) which is implemented as print x.__str__() You can learn more about special methods here: http://docs.python.org/ref/specialnames.html Kent From kent37 at tds.net Sun Apr 16 13:30:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Apr 2006 07:30:16 -0400 Subject: [Tutor] Is this correct? In-Reply-To: <20060415175029.46196.qmail@web60016.mail.yahoo.com> References: <20060415175029.46196.qmail@web60016.mail.yahoo.com> Message-ID: <44422AC8.8040307@tds.net> Hoffmann wrote: > So, I wrote the script below: > > class Time: > pass > > hour = int( raw_input('Enter the hour: ') ) > min = int( raw_input('Enter the minute: ') ) > sec = int( raw_input('Enter the sec: ') ) > > time = Time() > time.hours = hour > time.minutes = min > time.seconds = sec > > def printTime(time): > print 'The time is %dh:%dmin:%dsec' % (hour, min, > sec) You fixed this in your later version, but here you are not using the hour, min, sec attributes from time, you are using the global hour, min, sec from the raw_input() calls. It should be time.hour, etc. Kent From john.corry at ntlworld.com Sun Apr 16 13:32:29 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 16 Apr 2006 12:32:29 +0100 Subject: [Tutor] School Boy Error - Update Message-ID: <000001c66149$7642e440$4a3ea8c0@JOHNC> Hi, I have taken on board the advice in relation to the cvs module and setting the list to a tuple. I am now using the following code and getting a different error. I think it is a small step forward? import string, re path = "c:/test/import.csv" listy = [] import csv reader = csv.reader(open(path,"rb")) for row in reader: listy.append(tuple(row)) sql_list = listy[0] stat = """Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" t = 5000 d = "PF2" b = 91.4 a = 95.00 print stat print sql_list import mx.ODBC import mx.ODBC.Windows db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute(stat, sql_list) db.commit() c.close() I now get the following ouput + error: Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,) ('961', 'TM BLIND', 'RO', 'PF1', 'Plain Finish Range One', '91.4', '', '45.7', '10', '20', '0', '24', '61', '8.69', '20', '0', '27', '81.3', '11.03', '25', '0', '34', '101.6', '12.36', '28', '0', '38', '121.9', '14.36', '32', '0', '44', '142.2', '16.7', '37', '0', '51', '162.6', '18.71', '41', '0', '58', '182.9', '20.72', '45', '0', '64', '198.1', '22.71', '49', '0', '70', '223.5', '27.39', '60', '0', '84', '243.8', '30.07', '66', '0', '92', '274.3', '34.41', '76', '0', '105', '304.8', '37.42', '82', '0', '115', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0') Traceback (most recent call last): File "C:\Python24\Lib\site-packages\databasemanager.py", line 35, in ? c.execute(stat, sql_list) ProgrammingError: ('37000', 200, '[Microsoft][ODBC Visual FoxPro Driver]Syntax error.', 4347) I assume this error is telling me that the database does not like the syntax of the data I am importing. The data that I am importing is actually data that I exported, so I know that it is in the right order and the right amount. The only thing that I can think of is that, the database requires floats for the numbers instead of strings. I assume that the numbers in listy[0] are now strings. Am I now going to have to throw listy[0] through a function to make the numbers into floats or is there another way to do this? Am I on the right track? Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060416/3339b04b/attachment.html From kent37 at tds.net Sun Apr 16 13:35:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Apr 2006 07:35:26 -0400 Subject: [Tutor] Didn't take long to hit my next wall! In-Reply-To: <006101c660e1$8207dfa0$0a01a8c0@xp> References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> <006101c660e1$8207dfa0$0a01a8c0@xp> Message-ID: <44422BFE.60505@tds.net> Alan Gauld wrote: > Hi John, > > I've no idea why its not working but this illustrates why I prefer to create > the sql string outside the execute - its a lot easier to debug when you can > print the string exactly as passed to execute. I know many others like to > leave execute to do the escaping stuff but I prefer to see what I'm doing > and put in a little extra effort. > > So I would write it as: > > query = '''UPDATE cost_grid > SET cost_1 = %s > WHERE cost_grid_id = %s > AND finish_dro = %s'''' % ( a,c,b) > c.execute(query) Yikes! Alan! Certainly you know what an SQL injection attack is? And what if the data contains special characters? For those who don't know, imagine what happens in the above if b = '91.4; drop table cost_grid;' or even b = 'a;b;"c"update' Kent From kent37 at tds.net Sun Apr 16 13:40:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Apr 2006 07:40:35 -0400 Subject: [Tutor] In[nnn], Out[nnn] In-Reply-To: References: Message-ID: <44422D33.7010000@tds.net> Terry Carroll wrote: > On Wed, 12 Apr 2006, Victor Bouffier wrote: > >> In [285]: n = 0x2018 >> >> In [286]: n >> Out[286]: 8216 > > Victor -- > > I've seen this notation 00 e.g., In [286], Out[286] -- in a few people's > postings. What variety of Python does this? IPython http://ipython.scipy.org/ Kent From brian at daviesinc.com Sun Apr 16 16:00:09 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 16 Apr 2006 10:00:09 -0400 Subject: [Tutor] School Boy Error In-Reply-To: <000001c66142$2a42bb30$4a3ea8c0@JOHNC> References: <000001c66142$2a42bb30$4a3ea8c0@JOHNC> Message-ID: <44424DE9.7040005@daviesinc.com> I wonder if it could not be the extra comma (,) at the end of your sql ? thus: ......?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)<--- see trailing comma, and no matching ? could be a value count != column count mis-match make sure you have the correct number of values to each column :) On the other hand, it is also possible, if ODBC is strict about taking strings and ints, that you need to run a function to convert list items to integer values where an integer is required.. John CORRY wrote: > Bri, > > > > Print stat gives > > > > Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,) > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\databasemanager.py", line 31, in ? > > c.execute(stat, sql_list) > > TypeError: parameters must be a list of tuples > > > > Unfortunately sql_list gives the same error. > > > > Thanks, > > > > John. > > !DSPAM:44421f56263591105852714! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:44421f56263591105852714! From brian at daviesinc.com Sun Apr 16 16:07:54 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 16 Apr 2006 10:07:54 -0400 Subject: [Tutor] Didn't take long to hit my next wall! In-Reply-To: <44422BFE.60505@tds.net> References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> <006101c660e1$8207dfa0$0a01a8c0@xp> <44422BFE.60505@tds.net> Message-ID: <44424FBA.3070108@daviesinc.com> python in this form uses BIND variables.. >>query = '''UPDATE cost_grid >> SET cost_1 = %s <--- %s = the bind variable placeholder/formatter >> WHERE cost_grid_id = %s >> AND finish_dro = %s'''' % ( a,c,b) <--- the raw tuple That is, what is provided to python in the tuple following , is formatted as specified by the %s , and as such, is a formatted string (special characters are properly esscaped), and as far as sql query is concerned, it is escaped safely.. I tested this before, when I first started working with python - Not a problem at all. In fact, I also wrote a custom database class in PHP that mimics this exact same functionality.. and in all my testing, not a single SQL injection has succeeded :) Basically whatever the value may be is formatted to a string, and escaped if necessary for special chars. Kent Johnson wrote: > Alan Gauld wrote: > >>Hi John, >> >>I've no idea why its not working but this illustrates why I prefer to create >>the sql string outside the execute - its a lot easier to debug when you can >>print the string exactly as passed to execute. I know many others like to >>leave execute to do the escaping stuff but I prefer to see what I'm doing >>and put in a little extra effort. >> >>So I would write it as: >> >>query = '''UPDATE cost_grid >> SET cost_1 = %s >> WHERE cost_grid_id = %s >> AND finish_dro = %s'''' % ( a,c,b) >>c.execute(query) > > > Yikes! Alan! Certainly you know what an SQL injection attack is? And > what if the data contains special characters? > > For those who don't know, imagine what happens in the above if > b = '91.4; drop table cost_grid;' > > or even > b = 'a;b;"c"update' > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:44422c98294101990911452! > > From kent37 at tds.net Sun Apr 16 18:15:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Apr 2006 12:15:51 -0400 Subject: [Tutor] Didn't take long to hit my next wall! In-Reply-To: <44424FBA.3070108@daviesinc.com> References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> <006101c660e1$8207dfa0$0a01a8c0@xp> <44422BFE.60505@tds.net> <44424FBA.3070108@daviesinc.com> Message-ID: <44426DB7.7050203@tds.net> Brian Gustin wrote: > python in this form uses BIND variables.. > >>query = '''UPDATE cost_grid > >> SET cost_1 = %s <--- %s = the bind variable > placeholder/formatter > >> WHERE cost_grid_id = %s > >> AND finish_dro = %s'''' % ( a,c,b) <--- the raw tuple > > > That is, what is provided to python in the tuple following , is > formatted as specified by the %s , and as such, is a formatted string > (special characters are properly esscaped), and as far as sql query is > concerned, it is escaped safely.. No. There are two ways to write this that look very similar but act very differently. To simplify the example a bit, suppose the query is query = '''update cost_grid set cost_1 = %s where cost_grid_id = %s''' and the values for cost_1 and cost_grid_id are in variables a and b. If you write cursor.execute(query % (a, b)) then you are using string formatting to put the values into the query. This is problematic when a or b needs to be escaped in any way, and is open to SQL injection attacks. On the other hand, if you write cursor.execute(query, (a, b)) then the values are passed as a separate parameter to execute(). In this case the DB wrapper will properly escape the values. Kent From brian at daviesinc.com Sun Apr 16 19:12:05 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sun, 16 Apr 2006 13:12:05 -0400 Subject: [Tutor] Didn't take long to hit my next wall! In-Reply-To: <44426DB7.7050203@tds.net> References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC> <006101c660e1$8207dfa0$0a01a8c0@xp> <44422BFE.60505@tds.net> <44424FBA.3070108@daviesinc.com> <44426DB7.7050203@tds.net> Message-ID: <44427AE5.2090405@daviesinc.com> Interesting.. I'll have to dig out my unit test scripts that I wrote to test the situation to my satisfaction... The way I had it , I wrote the query exactly as was done in this case, but I wrote it directly in the cursor.execute() function as in: cursor.execute('''insert into tablea (id,name,number) values (%s,%s,%s)'''%(clean_number,injected_text,injected_number)) and the sql injection attacks I had set as testing, were inserted to the database properly escaped, and never broke. However, I did not test it as a separate string to be inserted as cursor.execute(sql_string,%(tuplea,tupleb)), etc. thanks for the heads up. Bri! Kent Johnson wrote: > Brian Gustin wrote: > >>python in this form uses BIND variables.. >> >>query = '''UPDATE cost_grid >> >> SET cost_1 = %s <--- %s = the bind variable >>placeholder/formatter >> >> WHERE cost_grid_id = %s >> >> AND finish_dro = %s'''' % ( a,c,b) <--- the raw tuple >> >> >> That is, what is provided to python in the tuple following , is >>formatted as specified by the %s , and as such, is a formatted string >>(special characters are properly esscaped), and as far as sql query is >>concerned, it is escaped safely.. > > > No. There are two ways to write this that look very similar but act very > differently. To simplify the example a bit, suppose the query is > query = '''update cost_grid set cost_1 = %s where cost_grid_id = %s''' > and the values for cost_1 and cost_grid_id are in variables a and b. > > If you write > cursor.execute(query % (a, b)) > > then you are using string formatting to put the values into the query. > This is problematic when a or b needs to be escaped in any way, and is > open to SQL injection attacks. > > On the other hand, if you write > cursor.execute(query, (a, b)) > > then the values are passed as a separate parameter to execute(). In this > case the DB wrapper will properly escape the values. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:44426e80136686683119212! > > From ml.cyresse at gmail.com Mon Apr 17 09:21:35 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 17 Apr 2006 19:21:35 +1200 Subject: [Tutor] School Boy Error - Update In-Reply-To: <000001c66149$7642e440$4a3ea8c0@JOHNC> References: <000001c66149$7642e440$4a3ea8c0@JOHNC> Message-ID: Dude, you've still got your trailing comma in stat. Get rid of it. If I jump into MySQL, here's an example - create table a (a int, b int); OK insert into a values (5, 4); OK insert into a values(5, 4,); Syntax error ---- Try something like this - it's more scalable too. def generateSQL(data): stat = "Insert into cost_grid values (" num_of_q = len(data) qs = list(num_of_q * "?") string_qs = ", ".join(qs) final_string = stat + string_qs + ")" return final_string And you can generate parameterised statements with - stat = generateSQL(listy[0]) But yeah. Apologies for the caps, but DROP THE TRAILING COMMA. May I also recommend downloading SQLite http://www.sqlite.org/download.html and playing in that to confirm your SQL, because that comma is the problem. i.e. stat should be "Insert into cost_grid values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" On 4/16/06, John CORRY wrote: > > > > Hi, > > > > I have taken on board the advice in relation to the cvs module and setting > the list to a tuple. I am now using the following code and getting a > different error. I think it is a small step forward? > > > > import string, re > > path = "c:/test/import.csv" > > listy = [] > > import csv > > reader = csv.reader(open(path,"rb")) > > for row in reader: > > listy.append(tuple(row)) > > > > sql_list = listy[0] > > > > > > stat = """Insert into cost_grid values > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)""" > > t = 5000 > > d = "PF2" > > b = 91.4 > > a = 95.00 > > print stat > > print sql_list > > import mx.ODBC > > import mx.ODBC.Windows > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute(stat, sql_list) > > > > db.commit() > > c.close() > > > > > > I now get the following ouput + error: > > > > Insert into cost_grid values > (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, > > ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,) > > ('961', 'TM BLIND', 'RO', 'PF1', 'Plain Finish Range One', '91.4', '', > '45.7', '10', '20', '0', '24', '61', '8.69', '20', '0', '27', '81.3', > '11.03', '25', '0', '34', '101.6', '12.36', '28', '0', '38', '121.9', > '14.36', '32', '0', '44', '142.2', '16.7', '37', '0', '51', '162.6', > '18.71', '41', '0', '58', '182.9', '20.72', '45', '0', '64', '198.1', > '22.71', '49', '0', '70', '223.5', '27.39', '60', '0', '84', '243.8', > '30.07', '66', '0', '92', '274.3', '34.41', '76', '0', '105', '304.8', > '37.42', '82', '0', '115', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', > '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', > '0', '0', '0', '0', '0', '0', '0', '0', '0', '0') > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\databasemanager.py", > line 35, in ? > > c.execute(stat, sql_list) > > ProgrammingError: ('37000', 200, '[Microsoft][ODBC Visual FoxPro > Driver]Syntax error.', 4347) > > > > I assume this error is telling me that the database does not like the syntax > of the data I am importing. The data that I am importing is actually data > that I exported, so I know that it is in the right order and the right > amount. The only thing that I can think of is that, the database requires > floats for the numbers instead of strings. I assume that the numbers in > listy[0] are now strings. Am I now going to have to throw listy[0] through > a function to make the numbers into floats or is there another way to do > this? > > > > Am I on the right track? > > > > Thanks, > > > > John. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kaushalshriyan at gmail.com Mon Apr 17 10:16:34 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Mon, 17 Apr 2006 13:46:34 +0530 Subject: [Tutor] Stack Diagrams Message-ID: <6b16fb4c0604170116s25e4955bxfcd28ec6f4708d47@mail.gmail.com> Hi All I am referring to Stack Diagrams from http://www.ibiblio.org/obp/thinkCSpy/chap03.htm#11 I did not understood this, please explain me with an example Thanks in Advance Regards Kaushal From sean.x.lee at gmail.com Mon Apr 17 10:28:40 2006 From: sean.x.lee at gmail.com (Sean Lee) Date: Mon, 17 Apr 2006 03:28:40 -0500 Subject: [Tutor] Meaning of %g ? In-Reply-To: References: <029001c65ef5$d4640140$0a01a8c0@xp> <02fd01c65f96$43adbaf0$0a01a8c0@xp> <033601c65fe2$96b48b60$0a01a8c0@xp> Message-ID: > > >>> print "%14.3g\n%14.3e\n%14.3f" % (bignum,bignum,bignum) > > 1.23e+009 > > 1.235e+009 > > 1234567898.235 > > > > But in practice, we do not know how big is the data in advance when > > doing scientific computation in a compiled program. > > That is irrelevant, the format you display the data in has > no bearing on its precision, the display format is purely to > make it more readable. Another interesting one: >>> a = 123456.78 >>> print "%g\n%e\n%f" % (a,a,a) 123457 1.234568e+005 123456.780000 >>> Float number loses digits and becomes integer in the output ? Can we override the %g in python, or adding in some other format identifier so that print statement with custom format string still works ? Here if I want to dynamically output floating data based on the number of significant digits (SD) from an input's: - If SD > m, truncate (or round it) in the output - If SD < m, just directly output the number (without padding 0 to the end). - In either of above cases, similar to %g, if %e is necessary, just output %e format as result (also truncate the data based on SD in the %e format if necessary). e.g, if SD = 3: - for input = 100.0, the output is just 100.0 (not 100.00000..), since 100.0 = 1.0 * 10e2 (2<3) - for input = 0.01, the output is just 0.01, since 0.01 = 1.0 * 10e-2 (2<3) - for input with SD > 3, truncate it to output. SD can be set to some number (e.g. 6) in the program. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060417/cd67759a/attachment-0001.html From alan.gauld at freenet.co.uk Mon Apr 17 11:00:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 17 Apr 2006 10:00:58 +0100 Subject: [Tutor] Didn't take long to hit my next wall! References: <000001c660d3$4a666bb0$4a3ea8c0@JOHNC><006101c660e1$8207dfa0$0a01a8c0@xp> <44422BFE.60505@tds.net> Message-ID: <013a01c661fd$71d6cac0$0a01a8c0@xp> >> query = '''UPDATE cost_grid >> SET cost_1 = %s >> WHERE cost_grid_id = %s >> AND finish_dro = %s'''' % ( a,c,b) >> c.execute(query) > > Yikes! Alan! Certainly you know what an SQL injection attack is? And what > if the data contains special characters? > > For those who don't know, imagine what happens in the above if > b = '91.4; drop table cost_grid;' Yes that's true and a very good point, you do need to do some validation if the inputs are coming from, for example a web site. Creating the string yourself means taking responsibility for checking the parameters. If thats an issue execute() is probably a better bet, in my work thats never an issue since the data normally comes to me well formatted. Alan G From alan.gauld at freenet.co.uk Mon Apr 17 11:15:35 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 17 Apr 2006 10:15:35 +0100 Subject: [Tutor] Meaning of %g ? References: <029001c65ef5$d4640140$0a01a8c0@xp><02fd01c65f96$43adbaf0$0a01a8c0@xp><033601c65fe2$96b48b60$0a01a8c0@xp> Message-ID: <016201c661ff$7c649880$0a01a8c0@xp> >>>> a = 123456.78 >>>> print "%g\n%e\n%f" % (a,a,a) > 123457 > 1.234568e+005 > 123456.780000 >Float number loses digits and becomes integer in the output ? Yep, I am rapidly coming to the comnclusion that %g is broken in Python. I must do some tests with gcc to see what it does with %g, it may be the wierd behaviour is coming from there. I've never used %g with gcc... > Can we override the %g in python, or adding in some other > format identifier so that print statement with custom format > string still works ? I don't think we can add new format specifiers. It would be an interesting feature to have though... The best we can do is create a class and define our own __str__ method. > Here if I want to dynamically output floating data based > on the number of significant digits (SD) from an input's: > - If SD > m, truncate (or round it) in the output > - If SD < m, just directly output the number > (without padding 0 to the end). > - In either of above cases, similar to %g, if %e is necessary, > just output %e format as result This lseems to be more about the number of SD input rather than the actual precision of the stored data. In other words this is a problem of string parsing. I'd write a function that calculated the SD of a given string and use the result to choose the output format. If you convert the string to a float the precision and the number of SD will be defined by Pythons internal binary representation which may only be an approximation to the input value. The output format can be defined by a set of parameters such as sign,length,precision,style. Theese can be used to create a format string: fmt = "%%s%s.%s%s" % sign,length,precision,style result = fmt % value HTH, Alan G. From alan.gauld at freenet.co.uk Mon Apr 17 11:39:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 17 Apr 2006 10:39:42 +0100 Subject: [Tutor] Stack Diagrams References: <6b16fb4c0604170116s25e4955bxfcd28ec6f4708d47@mail.gmail.com> Message-ID: <016901c66202$db2eeca0$0a01a8c0@xp> > I am referring to Stack Diagrams from > http://www.ibiblio.org/obp/thinkCSpy/chap03.htm#11 > > I did not understood this, please explain me with an example The diagram he goives is an example but I'll try to reiterate slightly differently. First the context: def printTwice(bruce): print bruce, bruce def catTwice(part1, part2): cat = part1 + part2 printTwice(cat) >>> chant1 = "Pie Jesu domine, " >>> chant2 = "Dona eis requiem." >>> catTwice(chant1, chant2) This is the code that he is discussing. The stuff that is outside a function is in the __main__ function, which is a conceptual idea for the top level of the program. Working from the bottom of the code up we see that in the main function we have two variables: chant1, chant 2 each with values assigned. Thats the top box or frame on the diagram. Main then calls catTwice which is the next function up. catTwice takes two arguments: part1, part2 These arguments take the values of chant1,chant2. It also has a local variable called cat which takes the value of part1+part2 This is what is shown in the second frame of the diagram. catTwice then calls printTwice, our top function. printtwice takes a single argument called(bizarrely!) bruce. bruce takes the value of cat This is shown in the third frame box of the diagram. The stack diagram is a debugging/diagnostic tool used in figuring out the state of the program at any given time. In practice they are rarely used, but the concept often is in the form of a variable table(you need fixed width font for this bit!): chant1 chant2 part1 part2 cat bruce 'blah' 'blah' - - - - 'blah' 'blah' 'blah' 'blah' - - 'blah' 'blah' 'blah' 'blah' 'blah blah' - 'blah' 'blah' 'blah' 'blah' 'blah blah' 'blah blah' Even this is cumbersome except for numeric values and I've only ever used it for really complex algorithms. A simpler form of the stack diagram is presented by Python when it gfenerates an error. The error message includes a *stack trace* which shows the sequence of functions. Thus if we introduce an error into printTwice, we get the following stack trace: >>> def printTwice(b): ... raise TypeError # create an error here ... >>> def catTwice(p1,p2): ... c = p1 + p2 ... printTwice(c) ... >>> c1 = 'busy' >>> c2 = 'bee' >>> catTwice(c1,c2) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in catTwice File "", line 2, in printTwice TypeError >>> Notice the three File lines are in fact the frames from stack diagram. You can use the Python debugger to examine the individual frame variables as needed, so in practice most folks use the debugger (or just insert print statements!) to examine the stack frames if needed rather than draw the diagram. But that only works if you know what you expect to see, thats where a stack diagram or variable table comes in useful - to figure out what you *expect* to see and compare it with what the debugger says *is* there. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060417/cd4c4f23/attachment.html From payal-python at scriptkitchen.com Mon Apr 17 17:42:13 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 17 Apr 2006 11:42:13 -0400 Subject: [Tutor] functions in Python Message-ID: <20060417154213.GA22488@tranquility.scriptkitchen.com> Hi, I am now reading Alan's tut on Python, before that I have read a few other tuts too. But I am not getting functions exactly. I mean what is the difference between, def func(): .... and def func(x): .... When to use which? (please do not say "returns a value" for I do not understand the meaning of the same) With warm regards, -Payal From adam.jtm30 at gmail.com Mon Apr 17 18:02:07 2006 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 17 Apr 2006 17:02:07 +0100 Subject: [Tutor] functions in Python In-Reply-To: <20060417154213.GA22488@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> Message-ID: On 17/04/06, Payal Rathod wrote: > Hi, > I am now reading Alan's tut on Python, before that I have read a few other tuts too. > But I am not getting functions exactly. I mean what is the difference between, > > def func(): > .... > > and > > def func(x): > .... > > When to use which? (please do not say "returns a value" for I do not understand the meaning > of the same) > > With warm regards, > -Payal The x is a name for a value that you pass in to the function. To call the first function you would do >>> func() and the second function: >>> func(5) # 5 is just an example it could be any value depending on the function. From sanelson at gmail.com Mon Apr 17 18:42:05 2006 From: sanelson at gmail.com (Steve Nelson) Date: Mon, 17 Apr 2006 17:42:05 +0100 Subject: [Tutor] functions in Python In-Reply-To: References: <20060417154213.GA22488@tranquility.scriptkitchen.com> Message-ID: Sorry - including list. On 4/17/06, Payal Rathod wrote: > what is the difference between, > > def func(): > .... > > and > > def func(x): > .... When you define a function, you are writing a block of code which you can ask to perform a task. The task may be simple, and not require any additional information, or it may be more complex and need information. Take a simple analogy. Let's suppose I gave you the instruction "Switch off the light" and there was only one light, you wouldn't need any more information. We could call that: def toggleLight(): Now let's take a more complicated examle - making tea. If I give you the instruction "Make me a cup of tea" you might ask questions like "Milk? Sugar? Kind of tea?" I need to give you this information before you can perform the task. Similarly in a function - you may need to pass information (arguments) to the function. Here's the tea example: def makeTea(sugar, milk, kind): We might call the function as follows: makeTea(2, "none", "darjeeling") The internals of the function would be able to parse the arguments you gave it, and carry out the task you've asked it to do. As to when to use which, I think you'll find that most of the functions you write will require information if they're to be of much use. Only a very simple function doesn't take any arguments. Hope that helps :o) S. > > When to use which? (please do not say "returns a value" for I do not understand the meaning > of the same) > > With warm regards, > -Payal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From robert at cantab.net Mon Apr 17 18:10:51 2006 From: robert at cantab.net (Robert Schumann) Date: Mon, 17 Apr 2006 17:10:51 +0100 Subject: [Tutor] functions in Python In-Reply-To: <20060417154213.GA22488@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> Message-ID: <4443BE0B.8000400@cantab.net> Payal Rathod wrote: > Hi, > I am now reading Alan's tut on Python, before that I have read a few other tuts too. > But I am not getting functions exactly. I mean what is the difference between, > > def func(): > .... > > and > > def func(x): > .... > > When to use which? (please do not say "returns a value" for I do not understand the meaning > of the same) > It's a bit like the grammar of regular language. You could say "I kick" (which is like func(), because you're not specifying an object to operate on) or your could say "I kick the ball" (in which case x = "the ball"). The grammar of functions is very specific. In a sentence you can string together quite a few "addons": I kick - the ball - hard - down the hill - to Peter. But in a function in most programming languages, you have to give the same number of objects that it is asking for e.g. def kick(what, how, where, ToWhom): If any of them are missing, the function is going to complain, although as you learn more about Python you'll find ways around this. If I had defined my function grammar as def kick(): you wouldn't be allowed to tell me *any* of that extra information when you call the function. The return value of the function is the effect it has - for example, assuming the sentence is true, "I kick the ball to Peter" has two effects: first, the ball is now with Peter and second, the listener knows this. OK, the analogy is not that great.... Robert. > With warm regards, > -Payal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From payal-python at scriptkitchen.com Mon Apr 17 19:01:00 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 17 Apr 2006 13:01:00 -0400 Subject: [Tutor] functions in Python In-Reply-To: References: <20060417154213.GA22488@tranquility.scriptkitchen.com> Message-ID: <20060417170100.GC23790@tranquility.scriptkitchen.com> On Mon, Apr 17, 2006 at 05:02:07PM +0100, Adam wrote: > The x is a name for a value that you pass in to the function. To call > the first function you would do > >>> func() > > and the second function: > >>> func(5) # 5 is just an example it could be any value depending on > the function. Sorry but it is very confusing, couldn't get it at all. With warm regards, -Payal From payal-python at scriptkitchen.com Mon Apr 17 19:03:41 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 17 Apr 2006 13:03:41 -0400 Subject: [Tutor] functions in Python In-Reply-To: <4443BE0B.8000400@cantab.net> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <4443BE0B.8000400@cantab.net> Message-ID: <20060417170341.GD23790@tranquility.scriptkitchen.com> On Mon, Apr 17, 2006 at 05:10:51PM +0100, Robert Schumann wrote: > You could say "I kick" (which is like func(), because you're not > specifying an object to operate on) or your could say "I kick the > ball" (in which case x = "the ball"). > Sorry, but you have confused me more ;) Can you give an simple example of just function() ? Where can it be useful? And when you say it returns a value, what do you mean by that? return to whom and what exactly? With warm regards, -Payal From payal-python at scriptkitchen.com Mon Apr 17 19:24:31 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 17 Apr 2006 13:24:31 -0400 Subject: [Tutor] functions in Python In-Reply-To: References: <20060417154213.GA22488@tranquility.scriptkitchen.com> Message-ID: <20060417172431.GA26463@tranquility.scriptkitchen.com> On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: > When you define a function, you are writing a block of code which you > can ask to perform a task. The task may be simple, and not require > any additional information, or it may be more complex and need > information. What is the difference between, >>> def f(x): ... return x ... >>> f(4) 4 >>> def f(x): ... print x ... >>> f(4) 4 Both give same results. So, why return statement is needed? With warm regards, -Payal From dyoo at hkn.eecs.berkeley.edu Mon Apr 17 19:31:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 17 Apr 2006 10:31:04 -0700 (PDT) Subject: [Tutor] functions in Python In-Reply-To: <20060417170341.GD23790@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <4443BE0B.8000400@cantab.net> <20060417170341.GD23790@tranquility.scriptkitchen.com> Message-ID: > Sorry, but you have confused me more ;) Can you give an simple example > of just function() ? Where can it be useful? > > And when you say it returns a value, what do you mean by that? return to > whom and what exactly? One view that's common is the idea that a function is a box that takes an input and returns an output: +----------+ input ----> | function | -----> output +----------+ The most direct equivalent you've experienced to this is a math function. For example, if we're traveling in a car at fifty miles an hour, for three hours, we know that we've traveled 150 miles. (Word problems... aagggh!) But let's write that as a function: ###### def miles_traveled_at_50_mph_for_3_hours(): return 50 * 3 ###### A function definition does not do anything by itself, but it can be "called" after it's defined. Try writing: ############################################# def miles_traveled_at_50_mph_for_3_hours(): return 50 * 3 print miles_traveled_at_50_mph_for_3_hours() ############################################# and run it, and see what you see. We are "defining" the function at the top, and "calling" the function at the bottom, (Forgive me for such a long function name: please bear with it for a moment.) One natural question we might have here is: how far do we travel if we go at the same speed, but for 4 and a half miles instead? We could just calculate it and write it out again: ###### def miles_traveled_at_50_mph_for_4_half_hours(): return 50 * 4.5 ###### But we can do a little better, by allowing our function to take "hours" as an parameter: ###### def miles_traveled_at_50_mph(hours): return 50 * hours ###### Now we can find out how long we've travelled by computing this function for the particular hours we'd like. (And we can shorten the function name. *grin*) For example, can you guess at what: print miles_traveled_at_50_mph(4) print miles_traveled_at_50_mph(3) print miles_traveled_at_50_mph(2) gives us? Try it! Functions let us define a relationship between inputs and outputs. The idea is that we've made our function take in an input, and it can vary its answer based on that input. Our miles_traveled function above changes its answer based on what length of time we drive. But a different function may define an entirely different relationship between its input and output. As another quick example: ###### def square(x): """Given x, returns the square of x.""" return x * x ###### or: ###### def height(h): """Given someone's height h in feet, tells us if that person is high or not.""" if h < 4: return "short" elif h < 6: return "medium" else: return "high" ###### We now have two other functions that also take in a single input, but they do different things, and even return different kinds of data. The square() example, like the miles_traveled example, takes a number and returns another number. But height() takes a number, and returns a string. In general, functions can take anything as an input, and return anything as an output --- I've been using numbers primarily because I'm trying to piggyback the knowledge you already should have about math and algebra. In my work, all the functions I write use more complex inputs --- and usually not numbers --- but the main ideas are the same. Do you have questions about this so far? From dyoo at hkn.eecs.berkeley.edu Mon Apr 17 19:37:53 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 17 Apr 2006 10:37:53 -0700 (PDT) Subject: [Tutor] functions in Python In-Reply-To: <20060417172431.GA26463@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <20060417172431.GA26463@tranquility.scriptkitchen.com> Message-ID: On Mon, 17 Apr 2006, Payal Rathod wrote: > What is the difference between, > >>>> def f(x): > ... return x > ... >>>> f(4) > 4 > >>>> def f(x): > ... print x > ... >>>> f(4) > 4 > > Both give same results. Clarification. Both "show" the same results from the interpreter. From what you see so far, there's no difference. One way to see the difference is to write functions that use functions. A elementary-school example might be to find the hypotenuse of a right triangle. Given two legs of lengths 'a' and 'b', we know that the hypotenuse has this relationship: hypotenuse = sqrt(square(a) + square(b)) Let's write this out as a set of functions: ################################################################### def hypo(a, b): """Given lengths of lengths a and b, returns the hypotenuse.""" return sqrt(square(a) + square(b)) def square(x): return x * x def sqrt(x): return x**(0.5) ################################################################### Experiment with this. See what happens if you replace a return statement with a print statement in square() or sqrt(). The key idea here is that print only shows us its output: it doesn't do anything else with it. It's what's called a "side-effect". And sometimes, we don't care about seeing something as much as we do getting the related value back. Above, hypo does not care what square looks like when it's printed to you, but it cares about getting the real value so it can do its computations. Does this make sense? From paul at benchline.org Mon Apr 17 19:30:31 2006 From: paul at benchline.org (Paul D. Eden) Date: Mon, 17 Apr 2006 10:30:31 -0700 Subject: [Tutor] functions in Python In-Reply-To: <20060417172431.GA26463@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <20060417172431.GA26463@tranquility.scriptkitchen.com> Message-ID: <4443D0B7.7060803@benchline.org> This only happens because the python interactive command-line (what you get when you just type 'python' in a terminal window) prints return values automatically for you. If you were executing f(4) in a program/script, the return value would be lost. Paul Payal Rathod wrote: > On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: > >>When you define a function, you are writing a block of code which you >>can ask to perform a task. The task may be simple, and not require >>any additional information, or it may be more complex and need >>information. > > > What is the difference between, > > >>>>def f(x): > > ... return x > ... > >>>>f(4) > > 4 > > >>>>def f(x): > > ... print x > ... > >>>>f(4) > > 4 > > Both give same results. So, why return statement is needed? > With warm regards, > -Payal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From paul.kraus at gmail.com Mon Apr 17 20:02:37 2006 From: paul.kraus at gmail.com (Paul D. Kraus) Date: Mon, 17 Apr 2006 14:02:37 -0400 Subject: [Tutor] Changing lists in place Message-ID: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> I have a list that I want to change in a for loop. It changes in the loop but the changes are not persistant outside of the loop. I thought lists were mutuable objects so I am a bit confused. Sample Code.... #!/usr/bin/env python """ Testing lists """ mylist = [ 'One ', ' two', ' three ' ] print mylist for element in mylist: element = element.strip() print "<>" + element + "<>" print mylist Sample Output.... ['One ', ' two', ' three '] <>One<> <>two<> <>three<> ['One ', ' two', ' three '] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060417/b1d0ae57/attachment.html From paul at benchline.org Mon Apr 17 20:11:44 2006 From: paul at benchline.org (Paul D. Eden) Date: Mon, 17 Apr 2006 11:11:44 -0700 Subject: [Tutor] Changing lists in place In-Reply-To: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> References: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> Message-ID: <4443DA60.2060509@benchline.org> Lists are mutable, you are right. But the code you gave does not change the list. It changes the variable element which is separate from the list myList. If you want to change the list try something like this: mylist = [ 'One ', ' two', ' three ' ] print mylist newlist = [] for element in mylist: element = element.strip() newlist.append(element) print "<>" + element + "<>" print newlist OR mylist = [ 'One ', ' two', ' three ' ] print mylist mylist = [element.strip() for element in mylist] for element in mylist: print "<>" + element + "<>" print mylist Paul Paul D. Kraus wrote: > I have a list that I want to change in a for loop. It changes in the > loop but the changes are not persistant outside of the loop. > I thought lists were mutuable objects so I am a bit confused. > > Sample Code.... > #!/usr/bin/env python > """ Testing lists """ > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > for element in mylist: > element = element.strip() > print "<>" + element + "<>" > print mylist > > > Sample Output.... > ['One ', ' two', ' three '] > <>One<> > <>two<> > <>three<> > ['One ', ' two', ' three '] > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Mon Apr 17 20:17:18 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 17 Apr 2006 11:17:18 -0700 Subject: [Tutor] Changing lists in place In-Reply-To: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> References: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> Message-ID: <4443DBAE.40003@alum.rpi.edu> Paul D. Kraus wrote: > I have a list that I want to change in a for loop. It changes in the > loop but the changes are not persistant outside of the loop. > I thought lists were mutuable objects They are. > so I am a bit confused. > > Sample Code.... > #!/usr/bin/env python > """ Testing lists """ > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > for element in mylist: element is a variable to which the successive items in mylist are assigned. element has no "magic" connection to the list. > element = element.strip() In order to change a list item you must do something like: mylist[itemIndex] = element.strip() So you need both the item's value and its position in the list. That's what enumerate is for: for itemIndex, element in enumerate(mylist): mylist[itemIndex] = element.strip() > [snip] From carroll at tjc.com Mon Apr 17 20:35:13 2006 From: carroll at tjc.com (Terry Carroll) Date: Mon, 17 Apr 2006 11:35:13 -0700 (PDT) Subject: [Tutor] Meaning of %g ? In-Reply-To: <016201c661ff$7c649880$0a01a8c0@xp> Message-ID: On Mon, 17 Apr 2006, Alan Gauld wrote: > >>>> a = 123456.78 > >>>> print "%g\n%e\n%f" % (a,a,a) > > 123457 > > 1.234568e+005 > > 123456.780000 > > >Float number loses digits and becomes integer in the output ? > > Yep, I am rapidly coming to the comnclusion that %g is broken > in Python. I must do some tests with gcc to see what it does > with %g, it may be the wierd behaviour is coming from there. > I've never used %g with gcc... FWIW, (Cygwin) Perl gives a similar result: > perl -e 'my $a = 123456.78;printf ("%g\n%e\n%f", $a, $a, $a);' 123457 1.234568e+05 123456.780000 The only difference being the two-digit vs. three-digit exponent on %e (Python's 1.234568e+005 vs. Perl's 1.234568e+05). Hmm.. Upon further review, Cygwin Perl gives 1.234568e+05; while Activestate Perl gives 1.234568e+005. (For reasons that elude me, Activestate Perl won't do the command-line version, but I don't care enough to track it down.) From kent37 at tds.net Mon Apr 17 21:01:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Apr 2006 15:01:59 -0400 Subject: [Tutor] Changing lists in place In-Reply-To: <4443DA60.2060509@benchline.org> References: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> <4443DA60.2060509@benchline.org> Message-ID: <4443E627.4030103@tds.net> Paul D. Eden wrote: > Lists are mutable, you are right. > > But the code you gave does not change the list. It changes the variable > element which is separate from the list myList. > > If you want to change the list try something like this: > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > newlist = [] > for element in mylist: > element = element.strip() > newlist.append(element) > print "<>" + element + "<>" > print newlist > > OR > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > mylist = [element.strip() for element in mylist] > for element in mylist: > print "<>" + element + "<>" > print mylist Neither of these changes the original list either. They both create new lists with the desired contents. The second example binds the new list to the old name, but it is still a new list. In many cases this is fine, but the distinction is important. For example if you are writing a function that modifies a list passed to it, these solutions won't work. Bob's solution using enumerate() is the simplest way to modify a list in place. Kent From Barry.Carroll at psc.com Mon Apr 17 20:48:08 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 17 Apr 2006 11:48:08 -0700 Subject: [Tutor] Tutor Digest, Vol 26, Issue 55 Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3658@eugsrv400.psc.pscnet.com> Payal: > -----Original Message----- > Date: Mon, 17 Apr 2006 13:24:31 -0400 > From: Payal Rathod > Subject: Re: [Tutor] functions in Python > To: Steve Nelson > Cc: "Python\[Tutor\]" > Message-ID: <20060417172431.GA26463 at tranquility.scriptkitchen.com> > Content-Type: text/plain; charset=us-ascii > > On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: > > When you define a function, you are writing a block of code which you > > can ask to perform a task. The task may be simple, and not require > > any additional information, or it may be more complex and need > > information. > > What is the difference between, > > >>> def f(x): > ... return x > ... > >>> f(4) > 4 > > >>> def f(x): > ... print x > ... > >>> f(4) > 4 > > Both give same results. So, why return statement is needed? > With warm regards, > -Payal Let's use your two functions named and see what we can do with them. In order to use both function definitions in the same interactive session, I will name the first 'f1' and the second 'f2'. >>>>>>>>>> >>> def f1(x): ... return x ... >>> def f2(x): ... print x ... >>>>>>>>>> Okay so far? Now, let's use each of these functions in a simple computation. To start, we'll just add two integers (called literals in programming jargon), >>>>>>>>>> >>> 4 + 4 8 >>>>>>>>>> The '+' operator takes two integers, adds them together and gives back (returns) the result. (Actually, the '+' operator can do more than this, but this is enough for this example.) Now, we'll do the same calculation using f1 instead of the literals. >>>>>>>>>> >>> f1(4) + f1(4) 8 >>>>>>>>>> This worked as expected: f1 sent back (returned) the value we gave it (the argument 4) and the '+' operator did the addition. Questions? Now, let's do the same calcuation once more, using f2 this time. >>>>>>>>>> >>> f2(4) + f2(4) 4 4 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' >>>>>>>>>> This time the operation failed. The f2 function did what we wrote it to do: it printed the argument to the Standard Output device (also called STDOUT), the interactive shell window in this case. But, as the error message indicates, it also RETURNED a value: in this case None, which has the type NoneType. The '+' operator then tried to add the two None values together and failed. The examples above show that, although the output of f1 and f2 look the same, it is actually different. The 'f2' function displays its argument for humans to read. The 'f1' function makes the argument available for other code to use. That is the purpose of the 'return' statement: to make the results of the function available to other code. It is important to remember that, in Python, EVERY function returns a value. If a 'return' statement is included in the function, the value the result of the expression associated with the statement (in your example, 4). If no 'return' statement is included, the function returns None. I hope this makes sense to you. If not, keep asking questions. Best Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From paul at benchline.org Mon Apr 17 21:04:57 2006 From: paul at benchline.org (Paul D. Eden) Date: Mon, 17 Apr 2006 12:04:57 -0700 Subject: [Tutor] Changing lists in place In-Reply-To: <4443E627.4030103@tds.net> References: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> <4443DA60.2060509@benchline.org> <4443E627.4030103@tds.net> Message-ID: <4443E6D9.5050101@benchline.org> Very true. Paul Kent Johnson wrote: > Paul D. Eden wrote: > >>Lists are mutable, you are right. >> >>But the code you gave does not change the list. It changes the variable >>element which is separate from the list myList. >> >>If you want to change the list try something like this: >> >>mylist = [ 'One ', ' two', ' three ' ] >>print mylist >>newlist = [] >>for element in mylist: >> element = element.strip() >> newlist.append(element) >> print "<>" + element + "<>" >>print newlist >> >>OR >> >>mylist = [ 'One ', ' two', ' three ' ] >>print mylist >>mylist = [element.strip() for element in mylist] >>for element in mylist: >> print "<>" + element + "<>" >>print mylist > > > Neither of these changes the original list either. They both create new > lists with the desired contents. The second example binds the new list > to the old name, but it is still a new list. In many cases this is fine, > but the distinction is important. For example if you are writing a > function that modifies a list passed to it, these solutions won't work. > Bob's solution using enumerate() is the simplest way to modify a list in > place. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Apr 17 22:05:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 17 Apr 2006 21:05:02 +0100 Subject: [Tutor] functions in Python References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <20060417172431.GA26463@tranquility.scriptkitchen.com> Message-ID: <01bd01c6625a$36ae0230$0a01a8c0@xp> Wow! I checked the list at lunchtime and there were only a few things here, then I check again now and lots of stuff from my tutor! Fortunately most of it has been answered already - thanks folks - but I feel honour bound to contribute something... > What is the difference between, > >>>> def f(x): > ... return x >>>> def f(x): > ... print x > ... >>>> f(4) > 4 > Both give same results. So, why return statement is needed? As has been stated the print displays on the output The return sends the value of the function back to the caller. If the caller is the interactive prompt(as here) the prompt prints the value so the effect is the same. If you need to save the result for later use then you must store it in a variable. You cannot do that if the function just prints the result - the value gets lost when the function ends. Try this: >>> def f(x): return x ... >>> def g(x): print x ... >>> fVal = f(4) >>> gVal = g(4) 4 Now notice that the two functoons behave differently f() doesn't display a value but g does because of the print statement. So far g seems to win. But... >>> print fVal 4 >>> print gVal None >>> Now f() wins because we have stored its value in fVal and can use it over and over again as we wish. The reason gVal has stored None is because any function that does not return an explicit value is treated as retiurning the special value None. Since g() only printed the parameter 4 but did not return it gVal stored a None value. If we return the value of f() we can display it any time we want by using print: >>> print f(4) 4 >>> So we do not lose anything by using return instead of print but we gain a lot by being able to store the returned value. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From doug.shawhan at gmail.com Mon Apr 17 23:40:45 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Mon, 17 Apr 2006 16:40:45 -0500 Subject: [Tutor] Raw Bits! (Control characters ahoy!) Message-ID: <5e1ceb8a0604171440r6b34dd57j4ab20a9061a831b3@mail.gmail.com> I am in the middle of a project that requires me to send and retrieve information from a machine connected to a serial port. My problems are these: 1. I cannot send control characters 2. I cannot read data streaming from the serial port I have been doing fine with: os.system("echo '5' >/dev/tty00") os.system("echo '8' >/dev/tty00") and the like to the remote machine, but I need to be able to send control characters the same way to scroll through menus. I have tried pyserial and pexpect with mixed (mostly horrible) results (not the fault of the module builders!), thus far the simple act of echoing the strings to the serial port is the only reliable method I have found. Reading from the serial port has also been problematic. I find that simply opening the port /dev/tty00 file and using readlines(), read() or whatever gives me empty strings or lists. Pbth. So first: how should I go about adding the hex escape sequences (\x0a and \x50) to the above strings in their raw form? second: what method should I use to read a raw stream from the serial port for a given period? I have looked carefully at the neat and tidy miniterm.py example in the pyserial examples directory, and see how one can continuously read via a thread from the port, but have not been able to replicate it thus far. Any help whatsoever would be great! I'm beginning to feel a little lightheaded. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060417/27ca42b3/attachment.html From alan.gauld at freenet.co.uk Tue Apr 18 00:32:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 17 Apr 2006 23:32:10 +0100 Subject: [Tutor] Changing lists in place References: <4e2aea430604171102y136f3d83x725d38aad66376a6@mail.gmail.com> Message-ID: <01de01c6626e$c6c3c080$0a01a8c0@xp> > I have a list that I want to change in a for loop. Thats nearly always a bad thing to do. Its like the old cartoon of the guy vcutting off the branch of the tree while sitting on it. Python can get very confused. Either make a copy and change the copy or use a while loop and an index. However, as others have pointed out: mylist = [ 'One ', ' two', ' three ' ] print mylist for element in mylist: element is a copy of the value in mylist, it is not a reference to mylist[n] element = element.strip() print "<>" + element + "<>" so changes to element are not changes to the list content. If you want to change the list content use a while loop: index = 0 while index < len(mylist): mylist[index] = '<> + mylist[index].strip() + '<>' index += 1 Or a list comprehension: mylist = ['<>' + n.strip() + '<>' for n in mylist] But notice that the comprehension builds a new list it does not actually change mylist directly in the way the while loop does. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From justin.mailinglists at gmail.com Tue Apr 18 05:08:39 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 18 Apr 2006 11:08:39 +0800 Subject: [Tutor] Python programmer needs to learn Java Message-ID: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> Greetings. I am seeking book recommendations or preferrably online tutorials to help me learn Java. Company under new management and most likely would be moving to Java and .NET I came from Visual Basic 6 to Python and had little problems which is why I love Python. From hugonz-lists at h-lab.net Tue Apr 18 07:02:59 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 17 Apr 2006 23:02:59 -0600 Subject: [Tutor] Raw Bits! (Control characters ahoy!) In-Reply-To: <5e1ceb8a0604171440r6b34dd57j4ab20a9061a831b3@mail.gmail.com> References: <5e1ceb8a0604171440r6b34dd57j4ab20a9061a831b3@mail.gmail.com> Message-ID: <44447303.3050900@h-lab.net> doug shawhan wrote: > I am in the middle of a project that requires me to send and retrieve > information from a machine connected to a serial port. My problems are > these: > > 1. I cannot send control characters > 2. I cannot read data streaming from the serial port > > > I have been doing fine with: > > os.system("echo '5' >/dev/tty00") > os.system("echo '8' >/dev/tty00") > Hi Doug, Echo just opens the file and writes to it, closing it afterwards. if you have used setserial correctly on the portt, then the equivalent Python commands should work. Note that the echo command adds a carriage return at the end. > Reading from the serial port has also been problematic. I find that > simply opening the port /dev/tty00 file and using readlines(), read() or > whatever gives me empty strings or lists. Pbth. If you use blocking, then reading should not give you anything empty, but data, no matter how long it has to wait. > > So first: how should I go about adding the hex escape sequences (\x0a > and \x50) to the above strings in their raw form? fileo = open('/dev/ttyS0', 'w') fileo.write('5' + '\x0a\x50') #\x0a is a linefeed (do you want to do that?) fileo.close() You may use fileo.flush() instead of close, for avoiding buffering and not having to close the file. > second: what method should I use to read a raw stream from the serial > port for a given period? > fileo = open('/dev/ttyS0') #read only data = fileo.read(1) #just one char fileo.close() #This waits forever. For a given period, use the select module (UN*X only) import select select([fileo.fileno()],[],[], 1.0) #This will wait for 1 second for output from the file. Then the return value will tell you if the filehandles have data. ([], [], []) means no data to read. > I have looked carefully at the neat and tidy miniterm.py example in the > pyserial examples directory, and see how one can continuously read via a > thread from the port, but have not been able to replicate it thus far. > I never use threads for that, I always use select(). Then again, I'm a unixhead. Hugo From alan.gauld at freenet.co.uk Tue Apr 18 09:30:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 08:30:56 +0100 Subject: [Tutor] Meaning of %g ? References: Message-ID: <001801c662ba$08653f50$0a01a8c0@xp> >> in Python. I must do some tests with gcc to see what it does >> with %g, it may be the wierd behaviour is coming from there. Tried it and get the same behaviour. Tried the Borland C++ compiler and got the same behaviour. Tried my MIX K&R compiler and - it didn't work! - it's a pure DOS application and XP barfed... Oh well! So it looks like Python is consistent with the norm for C compilers on PCs at least. I tried looking up the ANSI standard to see what it said but couldn't find a clear statement there either. And finally, the most precise statement seemed to come from the Linux printf man page: -------------- The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit. ------------- At this point I'll setytle for Python doing the "normal" thing with %g but for me not to use it because I can't see that behaviour being very useful! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Apr 18 09:45:37 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 08:45:37 +0100 Subject: [Tutor] Raw Bits! (Control characters ahoy!) References: <5e1ceb8a0604171440r6b34dd57j4ab20a9061a831b3@mail.gmail.com> Message-ID: <003101c662bc$155c6bf0$0a01a8c0@xp> Hi Doug, Have you looked at the struct module which provides tools for encoding binary values into byte streams and decoding byte streams into binary data. However if you only need to inject some hex codes into a string you can use the chr() function, this works even for unprintable characters like control sequences. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "doug shawhan" To: Sent: Monday, April 17, 2006 10:40 PM Subject: [Tutor] Raw Bits! (Control characters ahoy!) I am in the middle of a project that requires me to send and retrieve information from a machine connected to a serial port. My problems are these: 1. I cannot send control characters 2. I cannot read data streaming from the serial port I have been doing fine with: os.system("echo '5' >/dev/tty00") os.system("echo '8' >/dev/tty00") and the like to the remote machine, but I need to be able to send control characters the same way to scroll through menus. I have tried pyserial and pexpect with mixed (mostly horrible) results (not the fault of the module builders!), thus far the simple act of echoing the strings to the serial port is the only reliable method I have found. Reading from the serial port has also been problematic. I find that simply opening the port /dev/tty00 file and using readlines(), read() or whatever gives me empty strings or lists. Pbth. So first: how should I go about adding the hex escape sequences (\x0a and \x50) to the above strings in their raw form? second: what method should I use to read a raw stream from the serial port for a given period? I have looked carefully at the neat and tidy miniterm.py example in the pyserial examples directory, and see how one can continuously read via a thread from the port, but have not been able to replicate it thus far. Any help whatsoever would be great! I'm beginning to feel a little lightheaded. Thanks! From payal-python at scriptkitchen.com Tue Apr 18 10:19:20 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 18 Apr 2006 04:19:20 -0400 Subject: [Tutor] Alan Gauld Tutorial - OOP Message-ID: <20060418081920.GA18488@tranquility.scriptkitchen.com> Hi, I am reading Alan's tut and have stuck on the OOP chapter. What does he mean by, | Objects are collections of data and functions that operate on that |data. These are bound together so that you can pass an object from one |part of your program and they automatically get access to not only the |data attributes but the operations that are available too. What are exactly "data attributes" and what "operations" is he referring to? With warm regards, -Payal From payal-python at scriptkitchen.com Tue Apr 18 10:25:32 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 18 Apr 2006 04:25:32 -0400 Subject: [Tutor] functions in Python In-Reply-To: References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <4443BE0B.8000400@cantab.net> <20060417170341.GD23790@tranquility.scriptkitchen.com> Message-ID: <20060418082532.GA18613@tranquility.scriptkitchen.com> On Mon, Apr 17, 2006 at 10:31:04AM -0700, Danny Yoo wrote: > One view that's common is the idea that a function is a box that takes > an input and returns an output: Thanks a lot for the detailed help. Well, I have now got atleast basics of functions, will be doing some more reading on it in next few days. Thanks again. With warm regards, -Payal From john.corry at ntlworld.com Tue Apr 18 11:08:52 2006 From: john.corry at ntlworld.com (John CORRY) Date: Tue, 18 Apr 2006 10:08:52 +0100 Subject: [Tutor] My Name is John and I copy and paste Message-ID: <000501c662c7$b7af22c0$4a3ea8c0@JOHNC> Hi, Thanks for all the help so far on my database questions. I have now developed a program that reads in info from a csv file and updates already existing records in my database. I have enclosed the code below. The good news is that it is working. However, I used copy and paste and amended the text to write the code and it seems rather longwinded. Is there a quicker/better way to write the code below? path = "c:/test/import.csv" import mx.ODBC import mx.ODBC.Windows import csv reader = csv.reader(open(path,"rb")) for row in reader: db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[5]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[6]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[7]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[8]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[9]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[10]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[11]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[12]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[13]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[14]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[15]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[16]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[17]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[18]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[19]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[20]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[21]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[22]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[23]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[24]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[25]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[26]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[27]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[28]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[29]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[30]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[31]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[32]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_11 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[33]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_11 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[34]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_11 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[35]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_12 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[36]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_12 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[37]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_12 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[38]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_13 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[39]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_13 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[40]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_13 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[41]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_14 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[42]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_14 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[43]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_14 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[44]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_15 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[45]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_15 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[46]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_15 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[47]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_16 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[48]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_16 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[49]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_16 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[50]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_17 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[51]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_17 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[52]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_17 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[53]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_18 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[54]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_18 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[55]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_18 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[56]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_19 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[57]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_19 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[58]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_19 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[59]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_20 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[60]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_20 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[61]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_20 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[62]), row[0], float(row[2]))) db.commit() c.close() Thanks, John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060418/5391464b/attachment.htm From nywbon001 at mail.uct.ac.za Tue Apr 18 10:55:11 2006 From: nywbon001 at mail.uct.ac.za (nywbon001 at mail.uct.ac.za) Date: Tue, 18 Apr 2006 10:55:11 +0200 Subject: [Tutor] Tutor Digest, Vol 26, Issue 56 In-Reply-To: References: Message-ID: <1145350511.4444a96fc7cf2@webmail.uct.ac.za> Quoting tutor-request at python.org: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Changing lists in place (Paul D. Kraus) > 2. Re: Changing lists in place (Paul D. Eden) > 3. Re: Changing lists in place (Bob Gailer) > 4. Re: Meaning of %g ? (Terry Carroll) > 5. Re: Changing lists in place (Kent Johnson) > 6. Re: Tutor Digest, Vol 26, Issue 55 (Carroll, Barry) > 7. Re: Changing lists in place (Paul D. Eden) > 8. Re: functions in Python (Alan Gauld) > 9. Raw Bits! (Control characters ahoy!) (doug shawhan) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 17 Apr 2006 14:02:37 -0400 > From: "Paul D. Kraus" > Subject: [Tutor] Changing lists in place > To: tutor at python.org > Message-ID: > <4e2aea430604171102y136f3d83x725d38aad66376a6 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I have a list that I want to change in a for loop. It changes in the loop > but the changes are not persistant outside of the loop. > I thought lists were mutuable objects so I am a bit confused. > > Sample Code.... > #!/usr/bin/env python > """ Testing lists """ > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > for element in mylist: > element = element.strip() > print "<>" + element + "<>" > print mylist > > > Sample Output.... > ['One ', ' two', ' three '] > <>One<> > <>two<> > <>three<> > ['One ', ' two', ' three '] > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060417/b1d0ae57/attachment-0001.html > > ------------------------------ > > Message: 2 > Date: Mon, 17 Apr 2006 11:11:44 -0700 > From: "Paul D. Eden" > Subject: Re: [Tutor] Changing lists in place > To: pkraus at pelsupply.com > Cc: tutor at python.org > Message-ID: <4443DA60.2060509 at benchline.org> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Lists are mutable, you are right. > > But the code you gave does not change the list. It changes the variable > element which is separate from the list myList. > > If you want to change the list try something like this: > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > newlist = [] > for element in mylist: > element = element.strip() > newlist.append(element) > print "<>" + element + "<>" > print newlist > > OR > > mylist = [ 'One ', ' two', ' three ' ] > print mylist > mylist = [element.strip() for element in mylist] > for element in mylist: > print "<>" + element + "<>" > print mylist > > Paul > > Paul D. Kraus wrote: > > I have a list that I want to change in a for loop. It changes in the > > loop but the changes are not persistant outside of the loop. > > I thought lists were mutuable objects so I am a bit confused. > > > > Sample Code.... > > #!/usr/bin/env python > > """ Testing lists """ > > > > mylist = [ 'One ', ' two', ' three ' ] > > print mylist > > for element in mylist: > > element = element.strip() > > print "<>" + element + "<>" > > print mylist > > > > > > Sample Output.... > > ['One ', ' two', ' three '] > > <>One<> > > <>two<> > > <>three<> > > ['One ', ' two', ' three '] > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 3 > Date: Mon, 17 Apr 2006 11:17:18 -0700 > From: Bob Gailer > Subject: Re: [Tutor] Changing lists in place > To: pkraus at pelsupply.com > Cc: tutor at python.org > Message-ID: <4443DBAE.40003 at alum.rpi.edu> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Paul D. Kraus wrote: > > I have a list that I want to change in a for loop. It changes in the > > loop but the changes are not persistant outside of the loop. > > I thought lists were mutuable objects > They are. > > so I am a bit confused. > > > > Sample Code.... > > #!/usr/bin/env python > > """ Testing lists """ > > > > mylist = [ 'One ', ' two', ' three ' ] > > print mylist > > for element in mylist: > element is a variable to which the successive items in mylist are > assigned. element has no "magic" connection to the list. > > element = element.strip() > In order to change a list item you must do something like: > mylist[itemIndex] = element.strip() > > So you need both the item's value and its position in the list. That's > what enumerate is for: > > for itemIndex, element in enumerate(mylist): > mylist[itemIndex] = element.strip() > > [snip] > > > ------------------------------ > > Message: 4 > Date: Mon, 17 Apr 2006 11:35:13 -0700 (PDT) > From: Terry Carroll > Subject: Re: [Tutor] Meaning of %g ? > To: tutor at python.org > Message-ID: > Content-Type: TEXT/PLAIN; charset=US-ASCII > > On Mon, 17 Apr 2006, Alan Gauld wrote: > > > >>>> a = 123456.78 > > >>>> print "%g\n%e\n%f" % (a,a,a) > > > 123457 > > > 1.234568e+005 > > > 123456.780000 > > > > >Float number loses digits and becomes integer in the output ? > > > > Yep, I am rapidly coming to the comnclusion that %g is broken > > in Python. I must do some tests with gcc to see what it does > > with %g, it may be the wierd behaviour is coming from there. > > I've never used %g with gcc... > > FWIW, (Cygwin) Perl gives a similar result: > > > perl -e 'my $a = 123456.78;printf ("%g\n%e\n%f", $a, $a, $a);' > 123457 > 1.234568e+05 > 123456.780000 > > The only difference being the two-digit vs. three-digit exponent on %e > (Python's 1.234568e+005 vs. Perl's 1.234568e+05). > > Hmm.. Upon further review, Cygwin Perl gives 1.234568e+05; while > Activestate Perl gives 1.234568e+005. (For reasons that elude me, > Activestate Perl won't do the command-line version, but I don't care > enough to track it down.) > > > > ------------------------------ > > Message: 5 > Date: Mon, 17 Apr 2006 15:01:59 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Changing lists in place > Cc: tutor at python.org > Message-ID: <4443E627.4030103 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Paul D. Eden wrote: > > Lists are mutable, you are right. > > > > But the code you gave does not change the list. It changes the variable > > element which is separate from the list myList. > > > > If you want to change the list try something like this: > > > > mylist = [ 'One ', ' two', ' three ' ] > > print mylist > > newlist = [] > > for element in mylist: > > element = element.strip() > > newlist.append(element) > > print "<>" + element + "<>" > > print newlist > > > > OR > > > > mylist = [ 'One ', ' two', ' three ' ] > > print mylist > > mylist = [element.strip() for element in mylist] > > for element in mylist: > > print "<>" + element + "<>" > > print mylist > > Neither of these changes the original list either. They both create new > lists with the desired contents. The second example binds the new list > to the old name, but it is still a new list. In many cases this is fine, > but the distinction is important. For example if you are writing a > function that modifies a list passed to it, these solutions won't work. > Bob's solution using enumerate() is the simplest way to modify a list in > place. > > Kent > > > > ------------------------------ > > Message: 6 > Date: Mon, 17 Apr 2006 11:48:08 -0700 > From: "Carroll, Barry" > Subject: Re: [Tutor] Tutor Digest, Vol 26, Issue 55 > To: > Message-ID: > <2BBAEE949D384D40A2B851287ADB6A432C3658 at eugsrv400.psc.pscnet.com> > Content-Type: text/plain; charset="US-ASCII" > > Payal: > > > -----Original Message----- > > Date: Mon, 17 Apr 2006 13:24:31 -0400 > > From: Payal Rathod > > Subject: Re: [Tutor] functions in Python > > To: Steve Nelson > > Cc: "Python\[Tutor\]" > > Message-ID: <20060417172431.GA26463 at tranquility.scriptkitchen.com> > > Content-Type: text/plain; charset=us-ascii > > > > On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: > > > When you define a function, you are writing a block of code which > you > > > can ask to perform a task. The task may be simple, and not require > > > any additional information, or it may be more complex and need > > > information. > > > > What is the difference between, > > > > >>> def f(x): > > ... return x > > ... > > >>> f(4) > > 4 > > > > >>> def f(x): > > ... print x > > ... > > >>> f(4) > > 4 > > > > Both give same results. So, why return statement is needed? > > With warm regards, > > -Payal > > Let's use your two functions named and see what we can do with them. In > order to use both function definitions in the same interactive session, > I will name the first 'f1' and the second 'f2'. > > >>>>>>>>>> > >>> def f1(x): > ... return x > ... > >>> def f2(x): > ... print x > ... > >>>>>>>>>> > > Okay so far? > > Now, let's use each of these functions in a simple computation. To > start, we'll just add two integers (called literals in programming > jargon), > > >>>>>>>>>> > >>> 4 + 4 > 8 > >>>>>>>>>> > > The '+' operator takes two integers, adds them together and gives back > (returns) the result. (Actually, the '+' operator can do more than > this, but this is enough for this example.) > > Now, we'll do the same calculation using f1 instead of the literals. > > >>>>>>>>>> > >>> f1(4) + f1(4) > 8 > >>>>>>>>>> > > This worked as expected: f1 sent back (returned) the value we gave it > (the argument 4) and the '+' operator did the addition. > Questions? > > Now, let's do the same calcuation once more, using f2 this time. > > >>>>>>>>>> > >>> f2(4) + f2(4) > 4 > 4 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' > >>>>>>>>>> > > This time the operation failed. The f2 function did what we wrote it to > do: it printed the argument to the Standard Output device (also called > STDOUT), the interactive shell window in this case. But, as the error > message indicates, it also RETURNED a value: in this case None, which > has the type NoneType. The '+' operator then tried to add the two None > values together and failed. > > The examples above show that, although the output of f1 and f2 look the > same, it is actually different. The 'f2' function displays its argument > for humans to read. The 'f1' function makes the argument available for > other code to use. That is the purpose of the 'return' statement: to > make the results of the function available to other code. > > It is important to remember that, in Python, EVERY function returns a > value. If a 'return' statement is included in the function, the value > the result of the expression associated with the statement (in your > example, 4). If no 'return' statement is included, the function returns > None. > > I hope this makes sense to you. If not, keep asking questions. > > Best Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed > > > > > ------------------------------ > > Message: 7 > Date: Mon, 17 Apr 2006 12:04:57 -0700 > From: "Paul D. Eden" > Subject: Re: [Tutor] Changing lists in place > To: Kent Johnson > Cc: tutor at python.org > Message-ID: <4443E6D9.5050101 at benchline.org> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Very true. > > Paul > > Kent Johnson wrote: > > Paul D. Eden wrote: > > > >>Lists are mutable, you are right. > >> > >>But the code you gave does not change the list. It changes the variable > >>element which is separate from the list myList. > >> > >>If you want to change the list try something like this: > >> > >>mylist = [ 'One ', ' two', ' three ' ] > >>print mylist > >>newlist = [] > >>for element in mylist: > >> element = element.strip() > >> newlist.append(element) > >> print "<>" + element + "<>" > >>print newlist > >> > >>OR > >> > >>mylist = [ 'One ', ' two', ' three ' ] > >>print mylist > >>mylist = [element.strip() for element in mylist] > >>for element in mylist: > >> print "<>" + element + "<>" > >>print mylist > > > > > > Neither of these changes the original list either. They both create new > > lists with the desired contents. The second example binds the new list > > to the old name, but it is still a new list. In many cases this is fine, > > but the distinction is important. For example if you are writing a > > function that modifies a list passed to it, these solutions won't work. > > Bob's solution using enumerate() is the simplest way to modify a list in > > place. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 8 > Date: Mon, 17 Apr 2006 21:05:02 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] functions in Python > To: "Payal Rathod" , "Steve Nelson" > > Cc: "Python\[Tutor\]" > Message-ID: <01bd01c6625a$36ae0230$0a01a8c0 at xp> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > Wow! I checked the list at lunchtime and there were only a few things > here, then I check again now and lots of stuff from my tutor! Fortunately > most of it has been answered already - thanks folks - but I feel honour > bound to contribute something... > > > What is the difference between, > > > >>>> def f(x): > > ... return x > > >>>> def f(x): > > ... print x > > ... > >>>> f(4) > > 4 > > > Both give same results. So, why return statement is needed? > > As has been stated the print displays on the output > The return sends the value of the function back to the caller. > If the caller is the interactive prompt(as here) the prompt > prints the value so the effect is the same. > > If you need to save the result for later use then you must > store it in a variable. You cannot do that if the function > just prints the result - the value gets lost when the function > ends. > > Try this: > > >>> def f(x): return x > ... > >>> def g(x): print x > ... > >>> fVal = f(4) > >>> gVal = g(4) > 4 > > Now notice that the two functoons behave differently > f() doesn't display a value but g does because of the > print statement. So far g seems to win. But... > > >>> print fVal > 4 > >>> print gVal > None > >>> > > Now f() wins because we have stored its value in fVal > and can use it over and over again as we wish. > > The reason gVal has stored None is because any function that > does not return an explicit value is treated as retiurning the > special value None. Since g() only printed the parameter 4 > but did not return it gVal stored a None value. > > If we return the value of f() we can display it any time we > want by using print: > > >>> print f(4) > 4 > >>> > > So we do not lose anything by using return instead of print > but we gain a lot by being able to store the returned value. > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > ------------------------------ > > Message: 9 > Date: Mon, 17 Apr 2006 16:40:45 -0500 > From: "doug shawhan" > Subject: [Tutor] Raw Bits! (Control characters ahoy!) > To: tutor at python.org > Message-ID: > <5e1ceb8a0604171440r6b34dd57j4ab20a9061a831b3 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I am in the middle of a project that requires me to send and retrieve > information from a machine connected to a serial port. My problems are > these: > > 1. I cannot send control characters > 2. I cannot read data streaming from the serial port > > > I have been doing fine with: > > os.system("echo '5' >/dev/tty00") > os.system("echo '8' >/dev/tty00") > > > and the like to the remote machine, but I need to be able to send control > characters the same way to scroll through menus. I have tried pyserial and > pexpect with mixed (mostly horrible) results (not the fault of the module > builders!), thus far the simple act of echoing the strings to the serial > port is the only reliable method I have found. > > Reading from the serial port has also been problematic. I find that simply > opening the port /dev/tty00 file and using readlines(), read() or whatever > gives me empty strings or lists. Pbth. > > So first: how should I go about adding the hex escape sequences (\x0a and > \x50) to the above strings in their raw form? > second: what method should I use to read a raw stream from the serial port > for a given period? > > I have looked carefully at the neat and tidy miniterm.py example in the > pyserial examples directory, and see how one can continuously read via a > thread from the port, but have not been able to replicate it thus far. > > Any help whatsoever would be great! I'm beginning to feel a little > lightheaded. Thanks! > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060417/27ca42b3/attachment.htm > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 26, Issue 56 > ************************************* > I want to build a function which will reverse my input sentance.if i try to use the rervese it does not work here is my function: def reversor(): for i in string(a): l=[] if a==string: l.reversed(a) print l ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From alan.gauld at freenet.co.uk Tue Apr 18 12:11:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 11:11:46 +0100 Subject: [Tutor] Python programmer needs to learn Java References: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> Message-ID: <004501c662d0$804d0a50$0a01a8c0@xp> > I am seeking book recommendations or preferrably online tutorials > to help me learn Java. The only online resources I recommend for Java are: 1) Bruce Eckel's Thinking in Java and 2) The official Sun tutorial The only book I've found that I like is: O'Reilly Learning Java The Java in a Nutshell is a useful reference too. > I came from Visual Basic 6 to Python and had little problems > which is why I love Python. With that background you should have little difficulty with Java conceptually., except that Javba uses classes for everythjing and because of that relies hevily on class methods(statics) to mimic functions in VB/Python Otherwise the pain is mainly in the rigours of strict static typing and getting to know the huge class library. Have fun, Alan G. From alan.gauld at freenet.co.uk Tue Apr 18 12:19:32 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 11:19:32 +0100 Subject: [Tutor] Alan Gauld Tutorial - OOP References: <20060418081920.GA18488@tranquility.scriptkitchen.com> Message-ID: <004f01c662d1$95f69550$0a01a8c0@xp> > I am reading Alan's tut and have stuck on the OOP chapter. > What does he mean by, > > | Objects are collections of data and functions that operate on that > |data. These are bound together so that you can pass an object from one > |part of your program and they automatically get access to not only the > |data attributes but the operations that are available too. > > What are exactly "data attributes" and what "operations" is he referring > to? I mean the data and the functions that are used to create an object. As the definition above states, objects are collections of data and the functions that operate on the data. Another name for a function inside an object is "operation", and as you'll discover the most common name of all is "method" Any time you see a word in italics in my tutor it means I'm introducing a new technical term. Thus attributes and operations being italicised tells you that these are jargon terms for the data and functions just mentioned. You have already met objects back in the Raw Materials topic and also in strings and files. (Strings and Files are predefined objects in Python) . The OOP topic tells you how to create your own object types, or classes. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Tue Apr 18 12:21:46 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 18 Apr 2006 06:21:46 -0400 Subject: [Tutor] Python programmer needs to learn Java In-Reply-To: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> References: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> Message-ID: <115217002503.20060418062146@columbus.rr.com> > Greetings. > I am seeking book recommendations or preferrably online tutorials > to help me learn Java. _Head First Java_ Alan From alan.gauld at freenet.co.uk Tue Apr 18 12:52:25 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 11:52:25 +0100 Subject: [Tutor] Tutor Digest, Vol 26, Issue 56 References: <1145350511.4444a96fc7cf2@webmail.uct.ac.za> Message-ID: <005c01c662d6$2e1db4e0$0a01a8c0@xp> ----- Original Message ----- From: Subject: Re: [Tutor] Tutor Digest, Vol 26, Issue 56 Please don't reply to the digest message, we get all of the digest plus your question tagged on at the end! >> >> End of Tutor Digest, Vol 26, Issue 56 >> ************************************* >> > I want to build a function which will reverse my input sentance.if i try > to > use the rervese it does not work here is my function: > > def reversor(): > for i in string(a): What is string(a)? Indeed, what is a? string is not a built in function in Python. Do you mean str(a)? str(a) will attempt to convert a to a string. It would be better to pass a string into the function as a parameter. > l=[] This creates an empty list, l > if a==string: > l.reversed(a) This says that if 'a' equals string (which you show to be some kind of function object) then call l.reversed(a) There is no method of a list called reversed(), there is one called reverse() but it doesn't have a parameter. And it reverses the list which in this case is empty. > print l So you print an empty list. Did you try to run the code? What error did you get? What did you think the code was doing? What did you expect to happen? Armed with this information we might be able to help you solve your problem. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tinoloc at gmail.com Tue Apr 18 13:22:52 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 18 Apr 2006 07:22:52 -0400 Subject: [Tutor] Tutor projects Message-ID: Hi there, This list is great! I really like the aspect of mentor-mentee relationship. Ok, I have been programming in various languages for many many years, and here is my dilemna. I jump into a huge project such as Zope or Mambo (php side) and spend a couple of weeks on it, get frustrated, and give up. What I am requesting is an interesting project that is good for the intermediate level hacker, and somebody to assist me when I run into a problem. Any takers? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060418/e326d29a/attachment.html From kent37 at tds.net Tue Apr 18 13:32:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Apr 2006 07:32:56 -0400 Subject: [Tutor] My Name is John and I copy and paste In-Reply-To: <000501c662c7$b7af22c0$4a3ea8c0@JOHNC> References: <000501c662c7$b7af22c0$4a3ea8c0@JOHNC> Message-ID: <4444CE68.5040401@tds.net> John CORRY wrote: > Thanks for all the help so far on my database questions. I have now > developed a program that reads in info from a csv file and updates > already existing records in my database. I have enclosed the code > below. The good news is that it is working. However, I used copy and > paste and amended the text to write the code and it seems rather > longwinded. Is there a quicker/better way to write the code below? Hi John, What you need here is a loop. Have you learned about for loops? Here is a short example to get you started. Any Python tutorial will tell you more. In [1]: rows = [ ['row1', 0], ['row2', 55], ['row3', 23] ] In [2]: for row in rows: ...: print row[0], row[1] ...: ...: row1 0 row2 55 row3 23 Kent > path = "c:/test/import.csv" > > import mx.ODBC > > import mx.ODBC.Windows > > import csv > > reader = csv.reader(open(path,"rb")) > > for row in reader: > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? and > finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) From andreengels at gmail.com Tue Apr 18 14:11:18 2006 From: andreengels at gmail.com (Andre Engels) Date: Tue, 18 Apr 2006 14:11:18 +0200 Subject: [Tutor] pyexpat Message-ID: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> I am working for the Python Wikipediabot Framework (http://www.sourceforge.net/pywikipedia). A user noted me to an apparent deadlock in the XML parsing. I tried to get to the actual parsing code to see what went wrong. The furthest I get, however, is in the feed() method of the class ExpatParser in expatreader.py. There is a line there: self._parser.Parse(data, isFinal) self._parser, as I have found, is an object of the class pyexpat.xmlparser, but I have no idea about where to fine pyexpat. Can anyone help me further? -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From kent37 at tds.net Tue Apr 18 14:27:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Apr 2006 08:27:06 -0400 Subject: [Tutor] pyexpat In-Reply-To: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> References: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> Message-ID: <4444DB1A.5030108@tds.net> Andre Engels wrote: > I am working for the Python Wikipediabot Framework > (http://www.sourceforge.net/pywikipedia). A user noted me to an > apparent deadlock in the XML parsing. I tried to get to the actual That's pretty surprising, I wouldn't expect the parser to use any locks. Can you say more about the deadlock? > parsing code to see what went wrong. The furthest I get, however, is > in the feed() method of the class ExpatParser in expatreader.py. There > is a line there: > > self._parser.Parse(data, isFinal) > > self._parser, as I have found, is an object of the class > pyexpat.xmlparser, but I have no idea about where to fine pyexpat. Can > anyone help me further? pyexpat is written in C, you have to look at the Python source code. Download the source tarball or browse the Subversion repository online; pyexpat.c is here: http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=45449&view=auto pyexpat is itself a wrapper around expat which is here: http://svn.python.org/view/python/trunk/Modules/expat/ Kent From payal-python at scriptkitchen.com Tue Apr 18 14:45:12 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 18 Apr 2006 08:45:12 -0400 Subject: [Tutor] Alan Gauld Tutorial - OOP In-Reply-To: <004f01c662d1$95f69550$0a01a8c0@xp> References: <20060418081920.GA18488@tranquility.scriptkitchen.com> <004f01c662d1$95f69550$0a01a8c0@xp> Message-ID: <20060418124512.GA22902@tranquility.scriptkitchen.com> On Tue, Apr 18, 2006 at 11:19:32AM +0100, Alan Gauld wrote: > I mean the data and the functions that are used to create an object. > As the definition above states, objects are collections of data and > the functions that operate on the data. Another name for a function > inside an object is "operation", and as you'll discover the most > common name of all is "method" Thanks for the prompt response. My real problem is that there is no place inside a tutorial where all the terms like object, data, method, operation, attributes are explained on a single page *with* one small example of each. I am *really* confused when they occur now. I found this place a better help http://www.devshed.com/c/a/Python/Object-Orientation-in-Python/ I want something like this. e.g. Alan when I read your tut for OOP, I don't get what you mean by data, variable, and object and difference between them. Thanks again. With warm regards, -Payal From ewalker at micron.com Tue Apr 18 14:46:07 2006 From: ewalker at micron.com (Eric Walker) Date: Tue, 18 Apr 2006 06:46:07 -0600 Subject: [Tutor] functions in Python In-Reply-To: <20060417172431.GA26463@tranquility.scriptkitchen.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <20060417172431.GA26463@tranquility.scriptkitchen.com> Message-ID: <4444DF8F.5070505@micron.com> Payal Rathod wrote: >On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: > > >>When you define a function, you are writing a block of code which you >>can ask to perform a task. The task may be simple, and not require >>any additional information, or it may be more complex and need >>information. >> >> > >What is the difference between, > > > >>>>def f(x): >>>> >>>> >... return x >... > > >>>>f(4) >>>> >>>> >4 > > > >>>>def f(x): >>>> >>>> >... print x >... > > >>>>f(4) >>>> >>>> >4 > >Both give same results. So, why return statement is needed? >With warm regards, >-Payal >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > New at this but the f(x) with the return statement passes the value back to be used in something. The one with the print statement just prints it. Correct me if I am wrong experts def f(x): x = x + 1; return x def g(x): x=x + 1; print x; >>> bob = 5 + f(5) >>> print bob bob =Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' 5 + g(5) -------------- next part -------------- A non-text attachment was scrubbed... Name: ewalker.vcf Type: text/x-vcard Size: 176 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060418/a343e809/attachment-0001.vcf From andreengels at gmail.com Tue Apr 18 15:21:05 2006 From: andreengels at gmail.com (Andre Engels) Date: Tue, 18 Apr 2006 15:21:05 +0200 Subject: [Tutor] pyexpat In-Reply-To: <6faf39c90604180620h6f0c940av1b458e251edb5648@mail.gmail.com> References: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> <4444DB1A.5030108@tds.net> <6faf39c90604180620h6f0c940av1b458e251edb5648@mail.gmail.com> Message-ID: <6faf39c90604180621x312aaa73had52482e8a3a9da6@mail.gmail.com> 2006/4/18, Kent Johnson : > Andre Engels wrote: > > I am working for the Python Wikipediabot Framework > > (http://www.sourceforge.net/pywikipedia). A user noted me to an > > apparent deadlock in the XML parsing. I tried to get to the actual > > That's pretty surprising, I wouldn't expect the parser to use any locks. > Can you say more about the deadlock? I have found some more, and there is not a deadlock... Just the thing is going damn slow on this specific text, not sure why. Thanks anyway. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From janos.juhasz at VELUX.com Tue Apr 18 15:23:13 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 18 Apr 2006 15:23:13 +0200 Subject: [Tutor] Olle-Olla In-Reply-To: Message-ID: Hi All, Is it possible to replace the print statement with one of mine function ? Is it any extra reason why print isn't similar to the functions I can make with def ? >>> def olle(dummy): print 'olle:', dummy ... >>> def olla(dummy): print 'olla:', dummy ... >>> olle('Hopp') olle: Hopp >>> olla('Hopp') olla: Hopp >>> olle = olla >>> olle('Hopp') olla: Hopp >>> print = olle Traceback ( File "", line 1 print = olle ^ SyntaxError: invalid syntax In reality, I would like to replace the print in my PyCrust app with the log.write() function. janos juhasz From alan.gauld at freenet.co.uk Tue Apr 18 16:29:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 15:29:28 +0100 Subject: [Tutor] Alan Gauld Tutorial - OOP References: <20060418081920.GA18488@tranquility.scriptkitchen.com> <004f01c662d1$95f69550$0a01a8c0@xp> <20060418124512.GA22902@tranquility.scriptkitchen.com> Message-ID: <006001c662f4$804d2700$0a01a8c0@xp> > I want something like this. e.g. Alan when I read your tut for OOP, I > don't get what you mean by data, variable, and object and difference > between them. Those terms were all explained back in the Raw Materials section since they are fundamental building blocks of programming. Have you read through the basics section of the tutor or are you simply picking topics of intrest? You can do that with the advanced topics like OOP etc but only if you have already understood the basics section. Otherwise there will be a lot of jargon that is not explained. I dedicate a lot of the introductory topics to explaining and defining the fundamental building blocks. If you have not done so I really reconmmend you read the two topics: 1) What is Programming 2) The Raw Materials These are both fairly essential reading. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ewalker at micron.com Tue Apr 18 16:38:06 2006 From: ewalker at micron.com (Eric Walker) Date: Tue, 18 Apr 2006 08:38:06 -0600 Subject: [Tutor] GUI Message-ID: <4444F9CE.7060800@micron.com> All, I want to create a GUI, and I downloaded the pyQT stuff. Ok, now that I am reading my but off trying to figure out how to use this thing and learn python at the same time, I read some stuff about having to purchase licenses. For commercial development, who do I need to contact for licensing? Thanks Python Newbie.... From bgailer at alum.rpi.edu Tue Apr 18 17:19:08 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 18 Apr 2006 08:19:08 -0700 Subject: [Tutor] My Name is John and I copy and paste In-Reply-To: <000501c662c7$b7af22c0$4a3ea8c0@JOHNC> References: <000501c662c7$b7af22c0$4a3ea8c0@JOHNC> Message-ID: <4445036C.1040304@alum.rpi.edu> John CORRY wrote: > > Hi, > > > > Thanks for all the help so far on my database questions. I have now > developed a program that reads in info from a csv file and updates > already existing records in my database. I have enclosed the code > below. The good news is that it is working. However, I used copy and > paste and amended the text to write the code and it seems rather > longwinded. Is there a quicker/better way to write the code below? > > > > path = "c:/test/import.csv" > > import mx.ODBC > > import mx.ODBC.Windows > > import csv > > reader = csv.reader(open(path,"rb")) > > for row in reader: > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET ie_rrp_1 = ? where cost_grid_id = > ? and finish_dro = ?', ( float(row[5]), row[0], float(row[2]))) > When I see "repeated columns" I think the database is not fully normalized. If this were my database I'd have a table with columns named cost, rrp, ie_rrp, cost_grid_id, finish_dro, and a column to distingush the 20 cases. A little more work up front, but a lot easier to work with once it is set up. The recommendation to do this in a loop is the answer regardless of the data model. [snip] From tinoloc at gmail.com Tue Apr 18 17:24:21 2006 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 18 Apr 2006 11:24:21 -0400 Subject: [Tutor] Quick networking question Message-ID: Hi Everybody, I am writing a script to do some simple networking. When I do a close on the socket and exit the program, I getting a time wait on the port, and the port can''t be utilized again until the time wait disappears. How do I get port to shut down and be able to reuse that port? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060418/a355fdd8/attachment.htm From payal-python at scriptkitchen.com Tue Apr 18 17:41:41 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 18 Apr 2006 11:41:41 -0400 Subject: [Tutor] Alan Gauld Tutorial - OOP In-Reply-To: <006001c662f4$804d2700$0a01a8c0@xp> References: <20060418081920.GA18488@tranquility.scriptkitchen.com> <004f01c662d1$95f69550$0a01a8c0@xp> <20060418124512.GA22902@tranquility.scriptkitchen.com> <006001c662f4$804d2700$0a01a8c0@xp> Message-ID: <20060418154141.GA26816@tranquility.scriptkitchen.com> On Tue, Apr 18, 2006 at 03:29:28PM +0100, Alan Gauld wrote: > Have you read through the basics section of the tutor or are you > simply picking topics of intrest? You can do that with the advanced No, I read the tutorial from start. I am not understanding how data, objects, attributes etc. are related to each other. I am really curious, why didn't you make the whole tutorial Python only. As you Python people say - python is a language to teach programming, why unnecessary stuff about Vbscript or Javascript? Is there any page which tell me how do I read the tutorial, I mean I don't want to learn Vbscript or Javascript, what do I do then, am I supposed to skip those parts? With warm regards, -Payal From alan.gauld at freenet.co.uk Tue Apr 18 18:17:13 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 17:17:13 +0100 Subject: [Tutor] Alan Gauld Tutorial - OOP References: <20060418081920.GA18488@tranquility.scriptkitchen.com> <004f01c662d1$95f69550$0a01a8c0@xp> <20060418124512.GA22902@tranquility.scriptkitchen.com> <006001c662f4$804d2700$0a01a8c0@xp> <20060418154141.GA26816@tranquility.scriptkitchen.com> Message-ID: <008801c66303$8d7d2b00$0a01a8c0@xp> > No, I read the tutorial from start. I am not understanding how data, > objects, attributes etc. are related to each other. That is back in the Raw Materials section. And objects are then expanded in the OOP topic. > I am really curious, why didn't you make the whole tutorial Python only. Because learning only one programming language makes for more limited programmers in my experience. It is much better to understand the underlying concepts that apply in every language and thus become a "programmer" who can learn and use any language than to become a "Python Programmer" who is afraid to use other languages because it would take too long to learn them. It says pretty much the same on the intro page under the heading "Why Python?". That having been said I do not expect the reader to actually type in all the examples for all 3 languages. Pick one, type in the examples in that language and read the others for comparison. I thought I said that explicitly in the tutor but i can't find it anywhere so should probably add it! (Thanks for picking that up!) > Is there any page which tell me how do I read the tutorial, I mean I > don't want to learn Vbscript or Javascript, what do I do then, am I > supposed to skip those parts? There will soon be a paragraph on the Getting Started page to say what I did above... In fact its there now! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From payal-python at scriptkitchen.com Tue Apr 18 19:03:54 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 18 Apr 2006 13:03:54 -0400 Subject: [Tutor] wanted exercises in python Message-ID: <20060418170354.GA856@tranquility.scriptkitchen.com> Hi, As I mentioned I have been reading Python a lot in last 2 months but lack of examples and coding is not getting me anywhere. Can someone give me some exercises or I can try them myself (pythonchallenge.com please excuse). I am reading Alan's tut now and covered Basis set and regex from advanced set, so please give me exercises based on those topics i.e. don't tell me to code a http client or a GUI based program in Python :) With warm regards, -Payal From paul at benchline.org Tue Apr 18 19:08:27 2006 From: paul at benchline.org (Paul D. Eden) Date: Tue, 18 Apr 2006 10:08:27 -0700 Subject: [Tutor] wanted exercises in python In-Reply-To: <20060418170354.GA856@tranquility.scriptkitchen.com> References: <20060418170354.GA856@tranquility.scriptkitchen.com> Message-ID: <44451D0B.3080507@benchline.org> If you have some programming experience already in another language you may want to try the examples in http://www.diveintopython.org/toc/index.html Paul Payal Rathod wrote: > Hi, > As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself (pythonchallenge.com please > excuse). I am reading Alan's tut now and covered Basis set and regex > from advanced set, so please give me exercises based on those topics > i.e. don't tell me to code a http client or a GUI based program in > Python :) > > With warm regards, > -Payal > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Apr 18 19:13:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 10:13:30 -0700 (PDT) Subject: [Tutor] functions in Python In-Reply-To: <4444DF8F.5070505@micron.com> References: <20060417154213.GA22488@tranquility.scriptkitchen.com> <20060417172431.GA26463@tranquility.scriptkitchen.com> <4444DF8F.5070505@micron.com> Message-ID: > New at this but the f(x) with the return statement passes the value back > to be used in something. The one with the print statement just prints > it. Correct me if I am wrong experts > def f(x): > x = x + 1; > return x > > def g(x): > x=x + 1; > print x; Hi Eric, Yes, you've got it. Just as a side note: no semicolons needed. *wink* Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue Apr 18 19:15:54 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 10:15:54 -0700 (PDT) Subject: [Tutor] pyexpat In-Reply-To: <6faf39c90604180621x312aaa73had52482e8a3a9da6@mail.gmail.com> References: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> <4444DB1A.5030108@tds.net> <6faf39c90604180620h6f0c940av1b458e251edb5648@mail.gmail.com> <6faf39c90604180621x312aaa73had52482e8a3a9da6@mail.gmail.com> Message-ID: On Tue, 18 Apr 2006, Andre Engels wrote: > 2006/4/18, Kent Johnson : >> Andre Engels wrote: >>> I am working for the Python Wikipediabot Framework >>> (http://www.sourceforge.net/pywikipedia). A user noted me to an >>> apparent deadlock in the XML parsing. I tried to get to the actual >> >> That's pretty surprising, I wouldn't expect the parser to use any locks. >> Can you say more about the deadlock? > > I have found some more, and there is not a deadlock... Just the thing is > going damn slow on this specific text, not sure why. Thanks anyway. Hi Andre, Hmmmm.... Can you send a link to the text that's causing performance issues? It might be possible that someone here might isolate the performance problem. (Hey, it happened before with BeautifulSoup... *grin*) From dyoo at hkn.eecs.berkeley.edu Tue Apr 18 19:19:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 10:19:48 -0700 (PDT) Subject: [Tutor] Olle-Olla In-Reply-To: References: Message-ID: > Is it possible to replace the print statement with one of mine function ? Hi Janos, Yes; there are a set of reserved "keywords" that Python does not allow to be rebound as something else. It's a particular consequence of the way Python's language grammar is parsed. You'll want to watch out for keywords. Here they are: http://docs.python.org/ref/keywords.html If you avoid using them as variable names, you should be fine. Best of wishes! From agunnerson at gmail.com Tue Apr 18 19:23:15 2006 From: agunnerson at gmail.com (Andy) Date: Tue, 18 Apr 2006 11:23:15 -0600 Subject: [Tutor] wanted exercises in python In-Reply-To: <20060418170354.GA856@tranquility.scriptkitchen.com> References: <20060418170354.GA856@tranquility.scriptkitchen.com> Message-ID: <26e972870604181023g4124d28ct2b837d6ac18603e6@mail.gmail.com> Well, these are from a Ruby group but I don't see any reason why you couldn't do them in Python. http://www.rubyquiz.com Look through their quiz's, might find something fun to try. -Andy "Be who you are and be that well." - Saint Francis de Sales On 4/18/06, Payal Rathod wrote: > Hi, > As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself (pythonchallenge.com please > excuse). I am reading Alan's tut now and covered Basis set and regex > from advanced set, so please give me exercises based on those topics > i.e. don't tell me to code a http client or a GUI based program in > Python :) > > With warm regards, > -Payal > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Tue Apr 18 19:31:58 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 10:31:58 -0700 (PDT) Subject: [Tutor] Quick networking question In-Reply-To: References: Message-ID: On Tue, 18 Apr 2006, Tino Dai wrote: > I am writing a script to do some simple networking. When I do a > close on the socket and exit the program, I getting a time wait on the > port, and the port can''t be utilized again until the time wait > disappears. How do I get port to shut down and be able to reuse that > port? Hi Tino, Ah! You may want to take a look at some sample use of networking in the SocketServer: http://svn.python.org/view/python/trunk/Lib/SocketServer.py?rev=39194&view=markup In particular, take a look at: def server_bind(self): """Called by constructor to bind the socket. May be overridden. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) If we're using SocketServer class to build your socket servers, we set the allow_reuse_address attribute to True (See: http://www.python.org/doc/lib/node536.html) If we're building server sockets from scratch, we'll want to do that magic line: socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) right before binding the socket to the address. Best of wishes! From carroll at tjc.com Tue Apr 18 19:31:35 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 18 Apr 2006 10:31:35 -0700 (PDT) Subject: [Tutor] Tutorial on bitwise Python? Message-ID: Can anyone point me to a tutorial on bit manipulations (testing and setting) in Python? I'm very clear on the concepts (in a previous lifetime, I used to do systems programming in IBM System/3x0 assembler), but weak on how some things would be approached in Python, and need an orientation. From amonroe at columbus.rr.com Tue Apr 18 19:29:59 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 18 Apr 2006 13:29:59 -0400 Subject: [Tutor] Alan Gauld Tutorial - OOP In-Reply-To: <20060418124512.GA22902@tranquility.scriptkitchen.com> References: <20060418081920.GA18488@tranquility.scriptkitchen.com> <004f01c662d1$95f69550$0a01a8c0@xp> <20060418124512.GA22902@tranquility.scriptkitchen.com> Message-ID: <31242695197.20060418132959@columbus.rr.com> > Thanks for the prompt response. My real problem is that there is no > place inside a tutorial where all the terms like object, data, method, > operation, attributes are explained on a single page *with* one small > example of each. I am *really* confused when they occur now. I found The _Head First Java_ book explains it this way: Attributes are what an object KNOWS. Methods are what an object can DO. Alan From carroll at tjc.com Tue Apr 18 19:34:17 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 18 Apr 2006 10:34:17 -0700 (PDT) Subject: [Tutor] functions in Python In-Reply-To: Message-ID: On Tue, 18 Apr 2006, Danny Yoo wrote: > Just as a side note: no semicolons needed. *wink* Yesterday, I tested something with a two-line perl program. I could not for the life of me see why I was getting a syntax error. It was only after 15 minutes of looking up red herrings that it finally dawned on me that, back in Perlland, semicolons are required. From carroll at tjc.com Tue Apr 18 19:39:16 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 18 Apr 2006 10:39:16 -0700 (PDT) Subject: [Tutor] Python programmer needs to learn Java In-Reply-To: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> Message-ID: On Tue, 18 Apr 2006, Justin Ezequiel wrote: > I am seeking book recommendations or preferrably online tutorials > to help me learn Java. If you already know a language "Just Java" (now titled "Just Java 2") by Peter van der Linden is very good. It's intended for people who are moving from C to Java, but I think it would be very workable for Python-to-Java, too. From alan.gauld at freenet.co.uk Tue Apr 18 19:52:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 18:52:00 +0100 Subject: [Tutor] GUI References: <4444F9CE.7060800@micron.com> Message-ID: <00a201c66310$cb1a1ab0$0a01a8c0@xp> > I want to create a GUI, and I downloaded the pyQT stuff. Any reason why you must use PyQt? Not that it's a bad toolkit but there is less expertise in using it so unless you already use it from another language - like C++ - its going to be a lot harder to learn than Tkinter or wxPython which are the two most commonly used GUI tookits. Both Tkinter and wxPython are free, Tkinter comes with Python, wxPython is a searate download. wxPython tends to look nicer and has some fancier widgets. You pays yer money etc... > read some stuff about having to purchase licenses. > For commercial development, who do I need to contact for licensing? TrollTech own Qt, their licensing arrangements seem a tad complex to me. Try their web site. Alan G. From kent37 at tds.net Tue Apr 18 19:52:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Apr 2006 13:52:17 -0400 Subject: [Tutor] Olle-Olla In-Reply-To: References: Message-ID: <44452751.4000606@tds.net> J?nos Juh?sz wrote: > Hi All, > > Is it possible to replace the print statement with one of mine function ? > > In reality, I would like to replace the print in my PyCrust app with the > log.write() function. Best: Use a good editor to change your print statements to log.write() Not so good: Replace sys.stdout with something that intercepts write() calls and sends them to the log. Kent From alan.gauld at freenet.co.uk Tue Apr 18 19:58:17 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 18:58:17 +0100 Subject: [Tutor] wanted exercises in python References: <20060418170354.GA856@tranquility.scriptkitchen.com> Message-ID: <00ae01c66311$ac645c10$0a01a8c0@xp> > As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself There are a few suggestions in the last topic of my tutor - Refernces etc... But the best place to find stuff for beginners is the Useless Python web site. The new site didn't have much last time I looked buyt the old site (linked from the new one) has a lot of stuff, albeit slightly confusingly laid out. http://www.uselesspython.com/pythonchallenge.html Despite the URL this has nothing to do with the Python Challenge game web site. HTH, Alan G. From alan.gauld at freenet.co.uk Tue Apr 18 20:03:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 19:03:53 +0100 Subject: [Tutor] Olle-Olla References: Message-ID: <00b801c66312$74a74c00$0a01a8c0@xp> > Is it possible to replace the print statement with one of mine function ? No precisely because the print statement is a statement (or more accurately a command) not a function. But of course you can create your own print *function*, just call it a slightly different name - printit(), or display(), or logit(), or somesuch. > Is it any extra reason why print isn't similar to the functions I can make > with def ? Guido's call. Guido has intimated that he thinks this was one of his (few) mistakes in building Python. > In reality, I would like to replace the print in my PyCrust app with the > log.write() function. You will need to do a search/replace of all print statements with your new function, but its doable. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ewalker at micron.com Tue Apr 18 20:09:29 2006 From: ewalker at micron.com (Eric Walker) Date: Tue, 18 Apr 2006 12:09:29 -0600 Subject: [Tutor] GUI In-Reply-To: <00a201c66310$cb1a1ab0$0a01a8c0@xp> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> Message-ID: <44452B59.1000509@micron.com> Alan Gauld wrote: >> I want to create a GUI, and I downloaded the pyQT stuff. > > > Any reason why you must use PyQt? > > Not that it's a bad toolkit but there is less expertise in using it so > unless you already use it from another language - like C++ - its going > to be a lot harder to learn than Tkinter or wxPython which are the two > most commonly used GUI tookits. > > Both Tkinter and wxPython are free, Tkinter comes with Python, > wxPython is a searate download. wxPython tends to look nicer and has > some fancier widgets. You pays yer money etc... > >> read some stuff about having to purchase licenses. For commercial >> development, who do I need to contact for licensing? > > > TrollTech own Qt, their licensing arrangements seem a tad complex to me. > Try their web site. > > Alan G. > > Ok, If I can get it for free, I might as well go with say wxPython. Thanks From cdgarciaq at yahoo.com Tue Apr 18 20:14:03 2006 From: cdgarciaq at yahoo.com (Cesar Garcia) Date: Tue, 18 Apr 2006 11:14:03 -0700 (PDT) Subject: [Tutor] Help Entry !!! Message-ID: <20060418181403.20038.qmail@web51709.mail.yahoo.com> Hi !!! Friends, i nedd process Data Entry in python Example Entry = 20 Result = 20*10 This Result in Windows (Tkinter) How do you do Think !!!!!!! Regards Cesar Exmaple from Tkinter import * class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) Label(top, text="Valor").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk() root.update() d = MyDialog(root) root.wait_window(d.top) --------------------------------- New Yahoo! Messenger with Voice. Call regular phones from your PC and save big. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060418/0bb19d34/attachment.htm From srini_iyyer_bio at yahoo.com Tue Apr 18 20:53:58 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 18 Apr 2006 11:53:58 -0700 (PDT) Subject: [Tutor] creating a tab delim file In-Reply-To: <20060418181403.20038.qmail@web51709.mail.yahoo.com> Message-ID: <20060418185358.365.qmail@web38113.mail.mud.yahoo.com> Hi group, I asked similar questions in the past. I am unable to get to the crux of this problem so that I can solve on my own. apologies for my ignorance. The problem: I have 50 tab delim files. Each file has 500 rows and 50 columns. I have to read the first column of each file. Repeat the same for 50 files and write a tab delim text file containing 500 rows and 50 columns. code that works through half of the problem: import glob files = glob.glob('*.proc') for each in files: f = open(each,'r') da = f.read().split('\n') dat = da[:-1] for m in dat: mycol = m.split('\t')[0] .................. >From here I am blanked out. Although I can extract the first column from each file:I have no idea how to store each list. thought 1. Create an empty string and join each by a tab. ## mycol = '' for m in dat: mycol = m.split('\t')[0] mstr = '\t'.join(mycol) how can i append the data from second file to that string. could tutors help me with this situation. Thanks srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Tue Apr 18 20:59:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Apr 2006 14:59:38 -0400 Subject: [Tutor] Olle-Olla In-Reply-To: <6faf39c90604181145j71857feeg752c00f705abe4f@mail.gmail.com> References: <44452751.4000606@tds.net> <6faf39c90604181145j71857feeg752c00f705abe4f@mail.gmail.com> Message-ID: <4445371A.1000502@tds.net> Andre Engels wrote: > 2006/4/18, Kent Johnson : >> J?nos Juh?sz wrote: >>> Hi All, >>> >>> Is it possible to replace the print statement with one of mine function ? >>> >>> In reality, I would like to replace the print in my PyCrust app with the >>> log.write() function. >> Best: Use a good editor to change your print statements to log.write() > > Even better: Use a good editor to change your print statements to > myprint() and then def myprint() to be log.write(). This has the > advantage that if (for example) you want prints later to be "usually > log.write() but if redFlagHighestWarning is True, then both > log.write() and print()", you don't need to go through all this again, > but just have to change myprint(). Or use the logging module, which lets you make changes like this by editing a config file. I usually set it up so that INFO level and higher messages go to a console or GUI panel, and all messages go to a rollover file. Very handy. Kent From alan.gauld at freenet.co.uk Tue Apr 18 21:56:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 18 Apr 2006 20:56:01 +0100 Subject: [Tutor] Tutorial on bitwise Python? References: Message-ID: <00d401c66322$1ec8ecc0$0a01a8c0@xp> > Can anyone point me to a tutorial on bit manipulations (testing and > setting) in Python? Look at the sidebar in my OS topic. It covers using bitmasks to test the bits set by the file stat functions. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From khp at pflaesterer.de Tue Apr 18 23:55:18 2006 From: khp at pflaesterer.de (Karl Pfl?sterer) Date: Tue, 18 Apr 2006 23:55:18 +0200 Subject: [Tutor] creating a tab delim file In-Reply-To: <20060418185358.365.qmail@web38113.mail.mud.yahoo.com> (Srinivas Iyyer's message of "Tue, 18 Apr 2006 11:53:58 -0700 (PDT)") References: <20060418185358.365.qmail@web38113.mail.mud.yahoo.com> Message-ID: On 18 Apr 2006, srini_iyyer_bio at yahoo.com wrote: > The problem: > > I have 50 tab delim files. Each file has 500 rows and > 50 columns. > > I have to read the first column of each file. Repeat > the same for 50 files and write a tab delim text file > containing 500 rows and 50 columns. > > code that works through half of the problem: > > import glob > > files = glob.glob('*.proc') > > > for each in files: > f = open(each,'r') > da = f.read().split('\n') > dat = da[:-1] > for m in dat: > mycol = m.split('\t')[0] > .................. You don't need to read the whole file at once. You can read individual lines from a file with: f = open('name') for line in f: # do something with line I'll show you a different solution for your problem; if you don't understand it ask (I try to explain it). --8<---------------cut here---------------start------------->8--- import glob filehdls = [file(f) for f in glob.glob('*.proc')] out = open('reordered.prc', 'w') col_1 = [f.readline().split('\t')[0] for f in filehdls] while col_1[0]: out.write('\t'.join(col0)) out.write('\n') col_1 = [f.readline().split('\t')[0] for f in filehdls] out.close() for f in filehdls: f.close() --8<---------------cut here---------------end--------------->8--- filehdls is a list of file handles. col_1 is a list of the values of column 1 of each of the files. How does it work? f.readline().split('\t')[0] Read it from left to right. First we call readline() which reads the next line from file or returns the empty string if it reached the end of the file. Then we call split('\t') on the string returned from readline(). This returns a list of strings obtained from splitting the string at each tab. Then we take the first element from thew list (index 0) since we are only interested in column 1. We do this for every file in the list of file handles. The while loop runs as long as the first element in our list of columns is not false (at eof we get here an empty string which counts as false). We join the columns with a tab, write that string to our output file and write a newline to that file. Then we try to read the next line. The above will only work if all files have equal length. Karl -- Please do *not* send copies of replies to me. I read the list From nospamformeSVP at gmail.com Wed Apr 19 00:10:47 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 18 Apr 2006 18:10:47 -0400 Subject: [Tutor] Version of a .pyc file Message-ID: I want like to write a script to scan all of the .pyc on my pythonpath to find out if they were built with Python 2.3 or 2.4. How can I tell if a .pyc file was built with 2.3 or 2.4? Thanks, Don. From andre.roberge at gmail.com Wed Apr 19 00:34:48 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 18 Apr 2006 19:34:48 -0300 Subject: [Tutor] unit testing raw_input() Message-ID: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Hi all- Suppose I had a function like the following: def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer How could I go about to write an automated test for it? Andr? From carroll at tjc.com Wed Apr 19 01:01:28 2006 From: carroll at tjc.com (Terry Carroll) Date: Tue, 18 Apr 2006 16:01:28 -0700 (PDT) Subject: [Tutor] Version of a .pyc file In-Reply-To: Message-ID: On Tue, 18 Apr 2006, Don Taylor wrote: > How can I tell if a .pyc file was built with 2.3 or 2.4? There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether you consider the \r\n part of the MN). >>> f = open("pycfile.pyc", "rb") >>> magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"} >>> magic = f.read(4) >>> release = magictable.get(magic,"unknown") >>> print "Python release:", release Python release: 2.4 From ms at cerenity.org Wed Apr 19 01:15:51 2006 From: ms at cerenity.org (Michael) Date: Wed, 19 Apr 2006 00:15:51 +0100 Subject: [Tutor] unit testing raw_input() In-Reply-To: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: <200604190015.51904.ms@cerenity.org> On Tuesday 18 April 2006 23:34, Andre Roberge wrote: > Hi all- > > Suppose I had a function like the following: > > [ function that interacts with the outside world ] ... > How could I go about to write an automated test for it? You create a mock for raw_input, put the above code inside a module and rebind raw_input in the module before calling your function. ie: ------------(CONTENTS of y_n.py)------------ def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer ------------(END CONTENTS of y_n.py)------------ You can even create and test a mock in the command line interpreter, so here's a quick example: >>> import y_n # Import the module >>> def raw_input_mock(prompt): # create a mock ... return "y" ... >>> y_n.raw_input = raw_input_mock # rebind the name inside the module >>> y_n.y_n() # Run, this now calls our mock instead of the real raw_input You said yes! To my mind this is generally useful for testing error conditions with complex modules (select & socket spring to mind). To do this properly with your module, it makes more sense for your function to return strings, which would allow you to directly test the result. Alternatively you could wrap print in a function and then mock that instead. The key thing about a mock is that it simply provides the results you want. If it's important *how* the mock was called (eg you're testing correct use of a library), your mock could append parameters to a list for later comparision. Eg >>> mocktrace = [] >>> def raw_input_mock(prompt): # create a mock ... mocktrace.append((prompt,)) ... return "y" ... As I say though, this sort of thing is (IME) often more about testing the correct usage of something. Regards, Michael. From dyoo at hkn.eecs.berkeley.edu Wed Apr 19 03:39:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 18:39:29 -0700 (PDT) Subject: [Tutor] unit testing raw_input() In-Reply-To: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: On Tue, 18 Apr 2006, Andre Roberge wrote: > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? Hi Andre, One way to do this is to parameterize y_n() a little more to make it more amendable to unit testing. If we look at y_n(), we'd say that "raw_input()" is a free variable in here --- its meaning comes from the outside environment as part of builtins. We can change this by making it an explicit parameter: ######################################################## def y_n(prompt="Answer yes or no", raw_input=raw_input): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer ######################################################## Looks a little funny. *grin* But now we can hardcode particular inputs by sending y_n() a mock "raw_input" that returns precooked values. ########################### def yes1_raw_input(prompt): return "y" def yes2_raw_input(prompt): return "Y" def yes3_raw_input(prompt): return "yes" def yes4_raw_input(prompt): return "YES" ########################### And then we can use these as part of our test case: y_n(raw_input=yes1_raw_input) We can also parameterize output in the same way. Right now, the function is printing out the answer. Testing printed output is a little harder in Python without fiddling around with stdout, but we can also make this also a parameter of the function: ################################################### def y_n(prompt="Answer yes or no", raw_input=raw_input, output=sys.stdout): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print >>output, "You said yes!" break elif answer in ['n', 'N', 'no']: print >>output, "You said no!" break else: print >>output, "%s is an invalid answer."%answer ################################################### Now we can inject our own output string that we can use to test what has happened: ## pseudocode import StringIO test_output = StringIO.StringIO() y_n(raw_input = yes4_raw_input, output = test_output) assertEquals("You said yes!", test_output.getvalue()) Does this make sense so far? y_n() in its original form might not be in the right shape to make it easy to test, but we can turn it into a form that is more easily testable. Good luck! From justin.mailinglists at gmail.com Wed Apr 19 05:03:48 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 19 Apr 2006 11:03:48 +0800 Subject: [Tutor] Python programmer needs to learn Java In-Reply-To: <004501c662d0$804d0a50$0a01a8c0@xp> References: <3c6718980604172008v6c0f168fp92bf4388463ac415@mail.gmail.com> <004501c662d0$804d0a50$0a01a8c0@xp> Message-ID: <3c6718980604182003tc869e5u863fec95bf45dea8@mail.gmail.com> > The only online resources I recommend for Java are: > 1) Bruce Eckel's Thinking in Java and > 2) The official Sun tutorial > > The only book I've found that I like is: > O'Reilly Learning Java > > The Java in a Nutshell is a useful reference too. > Thanks Alan. Will check these out ASAP. From justin.mailinglists at gmail.com Wed Apr 19 05:06:56 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 19 Apr 2006 11:06:56 +0800 Subject: [Tutor] Python programmer needs to learn Java Message-ID: <3c6718980604182006s2927ac1ldec8793e1b71621a@mail.gmail.com> > If you already know a language "Just Java" (now titled "Just Java 2") by > Peter van der Linden is very good. Thanks Terry. Will surely check this out. From hokkakada at khmeros.info Wed Apr 19 05:10:40 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 19 Apr 2006 10:10:40 +0700 Subject: [Tutor] encode Message-ID: <4445AA30.5050507@khmeros.info> Hi again folks, I wonder if we can check the encoding of text in one text file. user is free to encode the file whether Latin1, utf-8, ANSI... Any ideas? Thx da From python at venix.com Wed Apr 19 05:41:55 2006 From: python at venix.com (Python) Date: Tue, 18 Apr 2006 23:41:55 -0400 Subject: [Tutor] encode In-Reply-To: <4445AA30.5050507@khmeros.info> References: <4445AA30.5050507@khmeros.info> Message-ID: <1145418115.6268.78.camel@www.venix.com> On Wed, 2006-04-19 at 10:10 +0700, kakada wrote: > Hi again folks, > > I wonder if we can check the encoding of text in one text file. > user is free to encode the file whether Latin1, utf-8, ANSI... > Any ideas? def decode_file(filepath): '''Order of codecs is important. ASCII is most restrictive to decode - no byte values > 127. UTF8 is next most restrictive. There are illegal byte values and illegal sequences. LATIN will accept anything since all 256 byte values are OK. The final decision still depends on human inspection. ''' buff = open(filepath,'rb').read() for charset in (ASCII,UTF8,LATIN,): try: unistr = buff.decode(charset,'strict') except UnicodeDecodeError: pass else: break else: unistr,charset = u'',None return unistr, charset Also note that the unicode character u'\ufffd' represents an error placeholder. It can be decoded from UTF8 inputs and reflects earlier processing problems. DO NOT USE THIS CODE BLINDLY. It simply offers a reasonable, first cut where those are the likely encodings. It is impossible to distinguish the various LATINx encodings by simply looking at bits. All 8 bit bytes are valid, but their meanings change based on the encoding used. > > Thx > > da > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Wed Apr 19 07:14:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Apr 2006 22:14:56 -0700 (PDT) Subject: [Tutor] encode In-Reply-To: <4445AA30.5050507@khmeros.info> References: <4445AA30.5050507@khmeros.info> Message-ID: On Wed, 19 Apr 2006, kakada wrote: > I wonder if we can check the encoding of text in one text file. user is > free to encode the file whether Latin1, utf-8, ANSI... In the general case, this is difficult, and "solving" it might be worse than not. See: http://www.joelonsoftware.com/articles/Unicode.html It is much better if you don't have to guess the file type: that's exactly the point of adding "document type" metadata to a document. If you can explain your situation more more --- why you're guessing document types --- we might be able to offer a different approach. Best of wishes to you! From alan.gauld at freenet.co.uk Wed Apr 19 08:01:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 19 Apr 2006 07:01:45 +0100 Subject: [Tutor] unit testing raw_input() References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: <010c01c66376$bd8e7b00$0a01a8c0@xp> > Suppose I had a function like the following: ############# def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer ################ > How could I go about to write an automated test for it? Create a data file with all of the inputs you need and use input redirection to run it. Assuming its called y_n.py: $ python y_n.py y_n.out This is the easiest way of testing interactive programs. This has limitations for unit testing if you have more than one function per module however, in that case you need to write a driver module that imports yours and takes as a first input the function you want to test... In Python the driver can sit inside the if __name__ == __main__ stanza Alan G From janos.juhasz at VELUX.com Wed Apr 19 08:45:52 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 19 Apr 2006 08:45:52 +0200 Subject: [Tutor] Olle-Olla In-Reply-To: <00b801c66312$74a74c00$0a01a8c0@xp> Message-ID: Dear All, Thanks your answers about why I can't redifne the print. I just wanted to play with Python dynamic possibilities. I wanted to replace function in a loaded module instead of create an inherited class and using that. It was easier to try it with print. Alan Gauld wrote: > Guido's call. Guido has intimated that he thinks this was one > of his (few) mistakes in building Python. It is funny, I tried to redefine the only function, that is not a function but a keyword :) Thanks for Alan, Danny, Gabriel, Kent J?nos Juh?sz From nywbon001 at mail.uct.ac.za Wed Apr 19 08:59:28 2006 From: nywbon001 at mail.uct.ac.za (nywbon001 at mail.uct.ac.za) Date: Wed, 19 Apr 2006 08:59:28 +0200 Subject: [Tutor] Tutor Digest, Vol 26, Issue 62 In-Reply-To: References: Message-ID: <1145429968.4445dfd061700@webmail.uct.ac.za> Quoting tutor-request at python.org: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Help Entry !!! (Cesar Garcia) > 2. creating a tab delim file (Srinivas Iyyer) > 3. Re: Olle-Olla (Kent Johnson) > 4. Re: Tutorial on bitwise Python? (Alan Gauld) > 5. Re: creating a tab delim file (Karl Pfl?sterer) > 6. Version of a .pyc file (Don Taylor) > 7. unit testing raw_input() (Andre Roberge) > 8. Re: Version of a .pyc file (Terry Carroll) > 9. Re: unit testing raw_input() (Michael) > 10. Re: unit testing raw_input() (Danny Yoo) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 18 Apr 2006 11:14:03 -0700 (PDT) > From: Cesar Garcia > Subject: [Tutor] Help Entry !!! > To: tutor at python.org > Message-ID: <20060418181403.20038.qmail at web51709.mail.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi !!! > Friends, i nedd process Data Entry in python > Example > > Entry = 20 > Result = 20*10 > > This Result in Windows (Tkinter) > How do you do Think !!!!!!! > > Regards > Cesar > Exmaple > from Tkinter import * > class MyDialog: > def __init__(self, parent): > top = self.top = Toplevel(parent) > Label(top, text="Valor").pack() > self.e = Entry(top) > self.e.pack(padx=5) > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > def ok(self): > print "value is", self.e.get() > self.top.destroy() > root = Tk() > root.update() > d = MyDialog(root) > root.wait_window(d.top) > > > --------------------------------- > New Yahoo! Messenger with Voice. Call regular phones from your PC and save > big. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060418/0bb19d34/attachment-0001.htm > > ------------------------------ > > Message: 2 > Date: Tue, 18 Apr 2006 11:53:58 -0700 (PDT) > From: Srinivas Iyyer > Subject: [Tutor] creating a tab delim file > To: tutor at python.org > Message-ID: <20060418185358.365.qmail at web38113.mail.mud.yahoo.com> > Content-Type: text/plain; charset=iso-8859-1 > > Hi group, > I asked similar questions in the past. I am unable to > get to the crux of this problem so that I can solve on > my own. apologies for my ignorance. > > > The problem: > > I have 50 tab delim files. Each file has 500 rows and > 50 columns. > > I have to read the first column of each file. Repeat > the same for 50 files and write a tab delim text file > containing 500 rows and 50 columns. > > code that works through half of the problem: > > import glob > > files = glob.glob('*.proc') > > > for each in files: > f = open(each,'r') > da = f.read().split('\n') > dat = da[:-1] > for m in dat: > mycol = m.split('\t')[0] > .................. > > >From here I am blanked out. Although I can extract the > first column from each file:I have no idea how to > store each list. > > thought 1. Create an empty string and join each by a > tab. > ## > mycol = '' > for m in dat: > mycol = m.split('\t')[0] > mstr = '\t'.join(mycol) > how can i append the data from second file to that > string. > > > could tutors help me with this situation. > > Thanks > srini > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > > ------------------------------ > > Message: 3 > Date: Tue, 18 Apr 2006 14:59:38 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Olle-Olla > To: Python Tutor > Message-ID: <4445371A.1000502 at tds.net> > Content-Type: text/plain; charset=UTF-8; format=flowed > > Andre Engels wrote: > > 2006/4/18, Kent Johnson : > >> J?nos Juh?sz wrote: > >>> Hi All, > >>> > >>> Is it possible to replace the print statement with one of mine function ? > >>> > >>> In reality, I would like to replace the print in my PyCrust app with the > >>> log.write() function. > >> Best: Use a good editor to change your print statements to log.write() > > > > Even better: Use a good editor to change your print statements to > > myprint() and then def myprint() to be log.write(). This has the > > advantage that if (for example) you want prints later to be "usually > > log.write() but if redFlagHighestWarning is True, then both > > log.write() and print()", you don't need to go through all this again, > > but just have to change myprint(). > > Or use the logging module, which lets you make changes like this by > editing a config file. I usually set it up so that INFO level and higher > messages go to a console or GUI panel, and all messages go to a rollover > file. Very handy. > > Kent > > > > ------------------------------ > > Message: 4 > Date: Tue, 18 Apr 2006 20:56:01 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Tutorial on bitwise Python? > To: "Terry Carroll" , > Message-ID: <00d401c66322$1ec8ecc0$0a01a8c0 at xp> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > > Can anyone point me to a tutorial on bit manipulations (testing and > > setting) in Python? > > Look at the sidebar in my OS topic. > It covers using bitmasks to test the bits set by the file stat functions. > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > ------------------------------ > > Message: 5 > Date: Tue, 18 Apr 2006 23:55:18 +0200 > From: Karl Pfl?sterer > Subject: Re: [Tutor] creating a tab delim file > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii > > On 18 Apr 2006, srini_iyyer_bio at yahoo.com wrote: > > > The problem: > > > > I have 50 tab delim files. Each file has 500 rows and > > 50 columns. > > > > I have to read the first column of each file. Repeat > > the same for 50 files and write a tab delim text file > > containing 500 rows and 50 columns. > > > > code that works through half of the problem: > > > > import glob > > > > files = glob.glob('*.proc') > > > > > > for each in files: > > f = open(each,'r') > > da = f.read().split('\n') > > dat = da[:-1] > > for m in dat: > > mycol = m.split('\t')[0] > > .................. > > You don't need to read the whole file at once. You can read individual > lines from a file with: > f = open('name') > for line in f: > # do something with line > > I'll show you a different solution for your problem; if you don't > understand it ask (I try to explain it). > > --8<---------------cut here---------------start------------->8--- > import glob > > filehdls = [file(f) for f in glob.glob('*.proc')] > out = open('reordered.prc', 'w') > > col_1 = [f.readline().split('\t')[0] for f in filehdls] > while col_1[0]: > out.write('\t'.join(col0)) > out.write('\n') > col_1 = [f.readline().split('\t')[0] for f in filehdls] > > > out.close() > for f in filehdls: f.close() > > --8<---------------cut here---------------end--------------->8--- > > filehdls is a list of file handles. > col_1 is a list of the values of column 1 of each of the files. > How does it work? > f.readline().split('\t')[0] > Read it from left to right. > First we call readline() which reads the next line from file or returns > the empty string if it reached the end of the file. > Then we call split('\t') on the string returned from readline(). This > returns a list of strings obtained from splitting the string at each > tab. > Then we take the first element from thew list (index 0) since we are > only interested in column 1. > We do this for every file in the list of file handles. > > The while loop runs as long as the first element in our list of > columns is not false (at eof we get here an empty string which counts as > false). We join the columns with a tab, write that string to our output > file and write a newline to that file. Then we try to read the next > line. > > The above will only work if all files have equal length. > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > ------------------------------ > > Message: 6 > Date: Tue, 18 Apr 2006 18:10:47 -0400 > From: Don Taylor > Subject: [Tutor] Version of a .pyc file > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > I want like to write a script to scan all of the .pyc on my pythonpath > to find out if they were built with Python 2.3 or 2.4. > > How can I tell if a .pyc file was built with 2.3 or 2.4? > > Thanks, > > Don. > > > > ------------------------------ > > Message: 7 > Date: Tue, 18 Apr 2006 19:34:48 -0300 > From: "Andre Roberge" > Subject: [Tutor] unit testing raw_input() > To: Tutor > Message-ID: > <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi all- > > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? > > Andr? > > > ------------------------------ > > Message: 8 > Date: Tue, 18 Apr 2006 16:01:28 -0700 (PDT) > From: Terry Carroll > Subject: Re: [Tutor] Version of a .pyc file > To: tutor at python.org > Message-ID: > > Content-Type: TEXT/PLAIN; charset=US-ASCII > > On Tue, 18 Apr 2006, Don Taylor wrote: > > > How can I tell if a .pyc file was built with 2.3 or 2.4? > > There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether > you consider the \r\n part of the MN). > > >>> f = open("pycfile.pyc", "rb") > >>> magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"} > >>> magic = f.read(4) > >>> release = magictable.get(magic,"unknown") > >>> print "Python release:", release > Python release: 2.4 > > > > ------------------------------ > > Message: 9 > Date: Wed, 19 Apr 2006 00:15:51 +0100 > From: Michael > Subject: Re: [Tutor] unit testing raw_input() > To: tutor at python.org > Message-ID: <200604190015.51904.ms at cerenity.org> > Content-Type: text/plain; charset="iso-8859-1" > > On Tuesday 18 April 2006 23:34, Andre Roberge wrote: > > Hi all- > > > > Suppose I had a function like the following: > > > > [ function that interacts with the outside world ] > ... > > How could I go about to write an automated test for it? > > You create a mock for raw_input, put the above code inside a module and > rebind > raw_input in the module before calling your function. > > ie: > ------------(CONTENTS of y_n.py)------------ > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > ------------(END CONTENTS of y_n.py)------------ > > You can even create and test a mock in the command line interpreter, so > here's > a quick example: > > >>> import y_n # Import the module > >>> def raw_input_mock(prompt): # create a mock > ... return "y" > ... > >>> y_n.raw_input = raw_input_mock # rebind the name inside the module > >>> y_n.y_n() # Run, this now calls our mock instead of the real raw_input > You said yes! > > To my mind this is generally useful for testing error conditions with complex > modules (select & socket spring to mind). > > To do this properly with your module, it makes more sense for your function > to return strings, which would allow you to directly test the result. > Alternatively you could wrap print in a function and then mock that instead. > > The key thing about a mock is that it simply provides the results you want. > If > it's important *how* the mock was called (eg you're testing correct use of a > library), your mock could append parameters to a list for later comparision. > > Eg > >>> mocktrace = [] > >>> def raw_input_mock(prompt): # create a mock > ... mocktrace.append((prompt,)) > ... return "y" > ... > > As I say though, this sort of thing is (IME) often more about testing the > correct usage of something. > > Regards, > > > Michael. > > > ------------------------------ > > Message: 10 > Date: Tue, 18 Apr 2006 18:39:29 -0700 (PDT) > From: Danny Yoo > Subject: Re: [Tutor] unit testing raw_input() > To: Andre Roberge > Cc: Tutor > Message-ID: > Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed > > > > On Tue, 18 Apr 2006, Andre Roberge wrote: > > > Suppose I had a function like the following: > > > > def y_n(prompt="Answer yes or no"): > > while True: > > answer = raw_input(prompt) > > if answer in ['y', 'Y', 'yes']: > > print "You said yes!" > > break > > elif answer in ['n', 'N', 'no']: > > print "You said no!" > > break > > else: > > print "%s is an invalid answer."%answer > > > > How could I go about to write an automated test for it? > > > Hi Andre, > > One way to do this is to parameterize y_n() a little more to make it more > amendable to unit testing. > > > If we look at y_n(), we'd say that "raw_input()" is a free variable in > here --- its meaning comes from the outside environment as part of > builtins. We can change this by making it an explicit parameter: > > ######################################################## > def y_n(prompt="Answer yes or no", raw_input=raw_input): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > ######################################################## > > Looks a little funny. *grin* > > > But now we can hardcode particular inputs by sending y_n() a mock > "raw_input" that returns precooked values. > > ########################### > def yes1_raw_input(prompt): > return "y" > > def yes2_raw_input(prompt): > return "Y" > > def yes3_raw_input(prompt): > return "yes" > > def yes4_raw_input(prompt): > return "YES" > ########################### > > And then we can use these as part of our test case: > > y_n(raw_input=yes1_raw_input) > > > > We can also parameterize output in the same way. Right now, the function > is printing out the answer. Testing printed output is a little harder in > Python without fiddling around with stdout, but we can also make this also > a parameter of the function: > > ################################################### > def y_n(prompt="Answer yes or no", > raw_input=raw_input, > output=sys.stdout): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print >>output, "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print >>output, "You said no!" > break > else: > print >>output, "%s is an invalid answer."%answer > ################################################### > > > Now we can inject our own output string that we can use to test what has > happened: > > ## pseudocode > > import StringIO > test_output = StringIO.StringIO() > y_n(raw_input = yes4_raw_input, > output = test_output) > > assertEquals("You said yes!", test_output.getvalue()) > > Does this make sense so far? y_n() in its original form might not be in > the right shape to make it easy to test, but we can turn it into a form > that is more easily testable. > > > Good luck! > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 26, Issue 62 > ************************************* > haai guys: i want to write a function which will sort the sentence by the length of each word in the sentece, short length first.please help. ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From andreengels at gmail.com Wed Apr 19 09:23:35 2006 From: andreengels at gmail.com (Andre Engels) Date: Wed, 19 Apr 2006 09:23:35 +0200 Subject: [Tutor] pyexpat In-Reply-To: References: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> <4444DB1A.5030108@tds.net> <6faf39c90604180620h6f0c940av1b458e251edb5648@mail.gmail.com> <6faf39c90604180621x312aaa73had52482e8a3a9da6@mail.gmail.com> Message-ID: <6faf39c90604190023g263c6209tdf70261df7cc1b48@mail.gmail.com> 2006/4/18, Danny Yoo : > Hmmmm.... Can you send a link to the text that's causing performance > issues? It might be possible that someone here might isolate the > performance problem. (Hey, it happened before with BeautifulSoup... > *grin*) I have sent the text (and another text that did not cause problems) to Danny; sending it to this list was disallowed because of length (about 1.5M for the 'slow' case and about half of that for the 'fast' one). -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From dyoo at hkn.eecs.berkeley.edu Wed Apr 19 09:27:01 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Apr 2006 00:27:01 -0700 (PDT) Subject: [Tutor] net ettiquette and sentence sorting/homework In-Reply-To: <1145429968.4445dfd061700@webmail.uct.ac.za> References: <1145429968.4445dfd061700@webmail.uct.ac.za> Message-ID: >> ************************************* > i want to write a function which will sort the sentence by the length of > each word in the sentece, short length first.please help. Hi Nywbon, First: please do not reply to the whole email digest. The point of a reply is to continue a previous conversation. Please be aware that not everyone has high-speed internet access: quoting the whole archive actually can strain some people's network bandwidth, if not their good humor and patience. Since you are starting a new question, start a new email to create a new "thread" of conversation. Second (and related to the first): please use a useful subject line. It helps when people try to learn from the mailing list archives at: http://mail.python.org/pipermail/tutor/ Finally, to get back to your question: > i want to write a function which will sort the sentence by the length of > each word in the sentece, short length first.please help. This looks very much like a homework question. We can not help you much with this. The only thing we can really do is try to guide you indirectly. Here are a few things you can do: 1. Write some concrete test examples of the problem statement and what you'd like to get out of it. 2. Show us some of the code that you've written so far, so we can at least point out areas of improvement. For point one, let's take a totally different problem and demonstrate. Let's say we wanted to write a function to turn a number from 0-9 to a string of the Esperanto rendition. If we wanted to write example cases, we'd imagine what calling this function for interesting inputs would look like. For example: translate(0) --> "nul" translate(1) --> "unu" translate(2) --> "du" ... translate(9) --> "nau" I use the arrow notation '-->' as an ad-hoc way of saying "I expect to get this value on the right hand side if everything is going well with my function". Can you write examples of your own for your problem? From dyoo at hkn.eecs.berkeley.edu Wed Apr 19 09:27:58 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Apr 2006 00:27:58 -0700 (PDT) Subject: [Tutor] pyexpat In-Reply-To: <6faf39c90604190023g263c6209tdf70261df7cc1b48@mail.gmail.com> References: <6faf39c90604180511p65927ac6l7b185abba4974f4c@mail.gmail.com> <4444DB1A.5030108@tds.net> <6faf39c90604180620h6f0c940av1b458e251edb5648@mail.gmail.com> <6faf39c90604180621x312aaa73had52482e8a3a9da6@mail.gmail.com> <6faf39c90604190023g263c6209tdf70261df7cc1b48@mail.gmail.com> Message-ID: On Wed, 19 Apr 2006, Andre Engels wrote: > 2006/4/18, Danny Yoo : > >> Hmmmm.... Can you send a link to the text that's causing performance >> issues? It might be possible that someone here might isolate the >> performance problem. (Hey, it happened before with BeautifulSoup... >> *grin*) > > I have sent the text (and another text that did not cause problems) to > Danny; sending it to this list was disallowed because of length (about > 1.5M for the 'slow' case and about half of that for the 'fast' one). Can you provide a web link somewhere? That will help solve the distribution problem by turning it from a "push" to a "pull". From kaushalshriyan at gmail.com Wed Apr 19 14:37:27 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 19 Apr 2006 18:07:27 +0530 Subject: [Tutor] OOPs Concept Message-ID: <6b16fb4c0604190537k413a9bb0ofda196b69ce8793@mail.gmail.com> Hi All I wanted to understand about OOPs Concept in Python in a easy way, Please explain me with an example I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm but at the moment still the concept is not clear Thanks in Advance Regards Kaushal From chris.lasher at gmail.com Wed Apr 19 16:00:32 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: Wed, 19 Apr 2006 10:00:32 -0400 Subject: [Tutor] GUI In-Reply-To: <00a201c66310$cb1a1ab0$0a01a8c0@xp> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> Message-ID: <128a885f0604190700q4a16918fj9a587ceecf8d52eb@mail.gmail.com> It's a dual license. If you use Qt in non-commercial software, the GPL applies and you pay no licensing fees. If you use Qt in commercial software, licensing fees are due to TrollTech. Chris On 4/18/06, Alan Gauld wrote: > [snip] > TrollTech own Qt, their licensing arrangements seem a tad complex to me. > Try their web site. > > Alan G. From lists at janeden.org Wed Apr 19 16:39:47 2006 From: lists at janeden.org (Jan Eden) Date: Wed, 19 Apr 2006 16:39:47 +0200 Subject: [Tutor] Re-instantiate within __init__ Message-ID: Hi, is it correct that an object cannot be re-instantiated within it's __init__ method? I tried: class Omega: def Display(self): print self class Alpha(Omega): def __init__(self): self = Beta() class Beta(Omega): def __init__(self): pass objectus = Alpha() objectus.Display() which prints <__main__.Alpha instance at 0x54d50> Background: I need to create a new object upon instantiation when a database query returns no records. The rest of the program should just use the new object. Is there any way to achieve this? I can always place the equivalent of 'self = Beta()' in the Display() function: def Display(self): if self.not_found: self = Beta() self.Display() return print self but this does not look very elegant. Thanks, Jan -- Any sufficiently advanced technology is insufficiently documented. From mwhite3 at ttsd.k12.or.us Wed Apr 19 17:32:54 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 19 Apr 2006 08:32:54 -0700 Subject: [Tutor] OOPs Concept In-Reply-To: <6b16fb4c0604190537k413a9bb0ofda196b69ce8793@mail.gmail.com> References: <6b16fb4c0604190537k413a9bb0ofda196b69ce8793@mail.gmail.com> Message-ID: <20060419153253.GJ16865@ttsd.k12.or.us> Even though I am still new to python, I've recently had an insight as to what makes OOP different from procedural programming. Let's take perl for example. A variable in perl is like a bowl. It's an empty vessel you can put things in. You can change the contents of the bowl, you can empty the bowl but it doesn't really *do* anything. It has no real attributes aside from the fact that it's a container. So when I create a variable in perl it looks like this: $x = 'hello' If I want to make the first letter of the value of $x a capital letter, I have to use a function to do it: $y = ucfirst($x) now $y contains the value 'Hello' In python one doesn't really create variables, one creates objects. Sring objects, list objects, etc. And objects are cool because they can do things. They are more than just merely bowls, they are like swiss army knives. So in python, if I say: x = 'hello' Then I can do all sorts of things with x: x.capitalize() -> 'Hello' x.swapcase() -> 'HELLO' x.count('l') -> 2 This is just a very small example but I hope that my example can help you understand what objects are what makes OOP different from procedural programming. -mtw On Wed, Apr 19, 2006 at 06:07:27PM +0530, Kaushal Shriyan (kaushalshriyan at gmail.com) wrote: > Hi All > > I wanted to understand about OOPs Concept in Python in a easy way, > Please explain me with an example > > I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm > but at the moment still the concept is not clear > > Thanks in Advance > > Regards > > Kaushal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From kent37 at tds.net Wed Apr 19 17:32:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Apr 2006 11:32:59 -0400 Subject: [Tutor] Re-instantiate within __init__ In-Reply-To: References: Message-ID: <4446582B.1080702@tds.net> Jan Eden wrote: > Hi, > > is it correct that an object cannot be re-instantiated within it's __init__ method? > > I tried: > > class Omega: > def Display(self): > print self > > class Alpha(Omega): > def __init__(self): > self = Beta() > > class Beta(Omega): > def __init__(self): > pass > > objectus = Alpha() > objectus.Display() > > which prints > > <__main__.Alpha instance at 0x54d50> Binding to self in a method just changes the local value of self, it doesn't change the object itself. The only thing special about 'self' is the way it is bound before the method is entered; inside the method it is a local name like any other. To bind objectus to a new object you have to assign to objectus. But I suspect you are really looking for a way to change the behaviour of the object bound to objectus. > > Background: I need to create a new object upon instantiation when a database query returns no records. The rest of the program should just use the new object. > > Is there any way to achieve this? I can always place the equivalent > of 'self = Beta()' in the Display() function: > > def Display(self): > if self.not_found: > self = Beta() > self.Display() > return > print self > > but this does not look very elegant. I don't understand what you are trying to do, but here are some ideas: - have Display() look at self.not_found itself, or pass self.not_found as a parameter to display. - use a factory method to create a class of the correct type - change self.Display to be the correct function - you can change the class of an object at runtime by assigning to its __class__ attribute. This may be what you are looking for but I suspect there is a simpler, less magic solution - I'm not sure why classes are needed at all here. Can you give a more complete example of what you are trying to do? Even if your code above worked the way you want it to, it wouldn't do anything interesting, since Alpha and Beta have exactly the same attributes and behaviour. Kent From kaushalshriyan at gmail.com Wed Apr 19 17:40:41 2006 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Wed, 19 Apr 2006 21:10:41 +0530 Subject: [Tutor] OOPs Concept In-Reply-To: <20060419153253.GJ16865@ttsd.k12.or.us> References: <6b16fb4c0604190537k413a9bb0ofda196b69ce8793@mail.gmail.com> <20060419153253.GJ16865@ttsd.k12.or.us> Message-ID: <6b16fb4c0604190840q79a2cc3ep34084f02fe73095b@mail.gmail.com> On 4/19/06, Matthew White wrote: > Even though I am still new to python, I've recently had an insight as > to what makes OOP different from procedural programming. > > Let's take perl for example. A variable in perl is like a bowl. It's an > empty vessel you can put things in. You can change the contents of > the bowl, you can empty the bowl but it doesn't really *do* anything. > It has no real attributes aside from the fact that it's a container. > > So when I create a variable in perl it looks like this: > > $x = 'hello' > > If I want to make the first letter of the value of $x a capital letter, > I have to use a function to do it: > > $y = ucfirst($x) > > now $y contains the value 'Hello' > > In python one doesn't really create variables, one creates objects. > Sring objects, list objects, etc. And objects are cool because they can > do things. They are more than just merely bowls, they are like swiss > army knives. So in python, if I say: > > x = 'hello' > > Then I can do all sorts of things with x: > > x.capitalize() -> 'Hello' > x.swapcase() -> 'HELLO' > x.count('l') -> 2 > > This is just a very small example but I hope that my example can help > you understand what objects are what makes OOP different from procedural > programming. > > -mtw > > On Wed, Apr 19, 2006 at 06:07:27PM +0530, Kaushal Shriyan (kaushalshriyan at gmail.com) wrote: > > Hi All > > > > I wanted to understand about OOPs Concept in Python in a easy way, > > Please explain me with an example > > > > I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm > > but at the moment still the concept is not clear > > > > Thanks in Advance > > > > Regards > > > > Kaushal > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Matthew White - District Systems Administrator > Tigard/Tualatin School District > 503.431.4128 > > "The greatest thing in this world is not so much where we are, but in > what direction we are moving." -Oliver Wendell Holmes > > Thanks Matthew Just wanted to know x.count('l') -> 2 Here 2 means what I didnot understood this and also does x is a object and capitalize(), swapcase() and count('l') are methods, is that correct what i understand Awaiting your earnest reply Regards Kaushal From mwhite3 at ttsd.k12.or.us Wed Apr 19 17:49:18 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 19 Apr 2006 08:49:18 -0700 Subject: [Tutor] OOPs Concept In-Reply-To: <6b16fb4c0604190840q79a2cc3ep34084f02fe73095b@mail.gmail.com> References: <6b16fb4c0604190537k413a9bb0ofda196b69ce8793@mail.gmail.com> <20060419153253.GJ16865@ttsd.k12.or.us> <6b16fb4c0604190840q79a2cc3ep34084f02fe73095b@mail.gmail.com> Message-ID: <20060419154918.GK16865@ttsd.k12.or.us> On Wed, Apr 19, 2006 at 09:10:41PM +0530, Kaushal Shriyan (kaushalshriyan at gmail.com) wrote: > Thanks Matthew > Just wanted to know > x.count('l') -> 2 Here 2 means what I didnot understood this > and also does x is a object and capitalize(), swapcase() and > count('l') are methods, is that correct what i understand yes, count(), capitalize(), and swapcase() are called methods. The count() method counts the number of the given string in the object. x = 'hello' x.count('l') -> 2 x.count('h') -> 1 y = 'good morning' y.count('o') -> 3 y.count('oo') -> 1 you can find out which methods belong to an object using the dir() function and can get help for a method by using the help() function: % python Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 'hello' >>> dir(x) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> help(x.swapcase) Help on built-in function swapcase: swapcase(...) S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. >>> -mtw -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From alan.gauld at freenet.co.uk Wed Apr 19 18:15:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 19 Apr 2006 17:15:20 +0100 Subject: [Tutor] Fw: anybody tried Google calendar? Message-ID: <014801c663cc$74732820$0a01a8c0@xp> Contained in a reply about a Google calendar issue... > http://www.google.com/support/calendar/bin/answer.py?answer=37083&query=free+busy&topic=0&type=f > Note the answer.py Looks like Google have expanded their use of Python from test scripts and config/admin to mainstream web pages, albeit their help system... Alan G. From darfoo at gmail.com Wed Apr 19 18:46:27 2006 From: darfoo at gmail.com (Mark True) Date: Wed, 19 Apr 2006 12:46:27 -0400 Subject: [Tutor] Some help with properties and accessor functions.... Message-ID: <647d31c20604190946g34d313a6s4c5c4699a19589d@mail.gmail.com> class SOFileIndexRecord(object): def __init__(self, so): self._so=so def _get_code(self): return self._so.code def _set_code(self, value): self._so.code=value testCode=property(_get_code, _set_code) # What does this do? def _get_fileName(self): return self._so.fileName def _set_fileName(self, value): self._so.fileName=value fileName=property(_get_fileName, _set_fileName) # What does this do? I am playing with SQLobject, and I managed to cobble together some code for it based on information in the FAQ but I am not understanding entirely what I am doing....can someone help? I don't really understand what setting properties does and how I access the defined get/set functions in this object. Any info would be wonderful, thanks in advance! --Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060419/03776e05/attachment.htm From andre.roberge at gmail.com Wed Apr 19 19:04:17 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 19 Apr 2006 14:04:17 -0300 Subject: [Tutor] [Summary] Re: unit testing raw_input() In-Reply-To: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: <7528bcdd0604191004n38618396u625cbda0da9d5c86@mail.gmail.com> Thank you Michael, Danny and Alan for your suggestions. I've included below my summary of the three very different suggestions, my brief analysis of them, and my conclusion. Anyone is free and welcome to comment! On 4/18/06, Andre Roberge wrote: > Hi all- > > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? > > Andr? > Alan Gauld suggested to create a data file that simulate possible user responses and to use redirection to feed the data to the program. Assuming the function to be tested is in y_n.py, it would look like the following: $ python y_n.py < fake_user_data > test_result Then, I assume I would do an automated comparison between "test_result" and some "expected_result" file to ensure everything is ok. This, in my opinion, is the "cleanest" solution. However, it may not scale well if one wants to build a test suite with many functions/methods, some of which require some user-input. Ideally, one should be able to change the order in which unit tests are run; with this approach, both the test suite and the user data file would probably have to be change in sync. ==== Danny Yoo suggested to change the function to be tested, to include an extra parameter, i.e. go from def y_n(prompt="Answer yes or no"): to def y_n(prompt="Answer yes or no", raw_input=raw_input): To quote Danny: But now we can hardcode particular inputs by sending y_n() a mock "raw_input" that returns precooked values. ########################### def yes1_raw_input(prompt): return "y" def yes2_raw_input(prompt): return "Y" def yes3_raw_input(prompt): return "yes" def yes4_raw_input(prompt): return "YES" ########################### [end quote] My first reaction is "Neat! :-)". However, this is only usable if one has access to the original function. If one uses a "library" function like y_n() (for example, there is a similar function in the livewires module which some of you probably know) which is not, in principle, modifyable, this approach fails. ==== Michael (last name unknown) suggests another approach, which shares some similarities with Danny's. Here's Michael's edited/truncated explanation: You create a mock for raw_input, put the above code inside a module and rebind raw_input in the module before calling your function. ie: ------------(CONTENTS of y_n.py)------------ def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break [snip] ------------(END CONTENTS of y_n.py)------------ [Michael's explanation using the interpreter is modified below] Then, one can have a test function in a separate file ------- begin test function import y_n def raw_input_mock(prompt): # create a mock return "n" y_n.raw_input = raw_input_mock # rebind the name inside the module y_n.y_n() # Run, this now calls our mock instead of the real raw_input ------- end test function [end of quote] Note that y_n() should probably return a string (instead of using a print statement) so that the output can be compared with the expected result; otherwise, one has to redirect the output to a file and do a comparison, as I mentioned with Alan's explanation. This is a rather clever method; I would never have thought of rebinding y_n.raw_input in this way. The only weakness that I see with this approach is if one wants to test a function like y_n() knowing that it ask the user for some input ... but not knowing what function it uses to do so. This can be the case if one has a compiled library with only the interface (what values can be passed to the functions and how; what are the expected outputs) being known. Danny's approach would also not work here, whereas Alan's would. As it is, I will be working on a very small project with another programmer, where I will be responsible to write some unit tests. I have access to the source code (so I know which function is used to get input from the user), but I do not want the other programmer to have to change the way his code is written simply to accommodate my tests. The other programmer's code will be in a single module; similarly, I want to write a single test module myself - without having to worry about keeping a separate data file. Therefore, I will go with Michael's approach. Thanks to everyone, and I hope that I didn't misrepresent any of the three solutions proposed. It's been fun! Andr? From andre.roberge at gmail.com Wed Apr 19 19:04:17 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 19 Apr 2006 14:04:17 -0300 Subject: [Tutor] [Summary] Re: unit testing raw_input() In-Reply-To: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: <7528bcdd0604191004n38618396u625cbda0da9d5c86@mail.gmail.com> Thank you Michael, Danny and Alan for your suggestions. I've included below my summary of the three very different suggestions, my brief analysis of them, and my conclusion. Anyone is free and welcome to comment! On 4/18/06, Andre Roberge wrote: > Hi all- > > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? > > Andr? > Alan Gauld suggested to create a data file that simulate possible user responses and to use redirection to feed the data to the program. Assuming the function to be tested is in y_n.py, it would look like the following: $ python y_n.py < fake_user_data > test_result Then, I assume I would do an automated comparison between "test_result" and some "expected_result" file to ensure everything is ok. This, in my opinion, is the "cleanest" solution. However, it may not scale well if one wants to build a test suite with many functions/methods, some of which require some user-input. Ideally, one should be able to change the order in which unit tests are run; with this approach, both the test suite and the user data file would probably have to be change in sync. ==== Danny Yoo suggested to change the function to be tested, to include an extra parameter, i.e. go from def y_n(prompt="Answer yes or no"): to def y_n(prompt="Answer yes or no", raw_input=raw_input): To quote Danny: But now we can hardcode particular inputs by sending y_n() a mock "raw_input" that returns precooked values. ########################### def yes1_raw_input(prompt): return "y" def yes2_raw_input(prompt): return "Y" def yes3_raw_input(prompt): return "yes" def yes4_raw_input(prompt): return "YES" ########################### [end quote] My first reaction is "Neat! :-)". However, this is only usable if one has access to the original function. If one uses a "library" function like y_n() (for example, there is a similar function in the livewires module which some of you probably know) which is not, in principle, modifyable, this approach fails. ==== Michael (last name unknown) suggests another approach, which shares some similarities with Danny's. Here's Michael's edited/truncated explanation: You create a mock for raw_input, put the above code inside a module and rebind raw_input in the module before calling your function. ie: ------------(CONTENTS of y_n.py)------------ def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break [snip] ------------(END CONTENTS of y_n.py)------------ [Michael's explanation using the interpreter is modified below] Then, one can have a test function in a separate file ------- begin test function import y_n def raw_input_mock(prompt): # create a mock return "n" y_n.raw_input = raw_input_mock # rebind the name inside the module y_n.y_n() # Run, this now calls our mock instead of the real raw_input ------- end test function [end of quote] Note that y_n() should probably return a string (instead of using a print statement) so that the output can be compared with the expected result; otherwise, one has to redirect the output to a file and do a comparison, as I mentioned with Alan's explanation. This is a rather clever method; I would never have thought of rebinding y_n.raw_input in this way. The only weakness that I see with this approach is if one wants to test a function like y_n() knowing that it ask the user for some input ... but not knowing what function it uses to do so. This can be the case if one has a compiled library with only the interface (what values can be passed to the functions and how; what are the expected outputs) being known. Danny's approach would also not work here, whereas Alan's would. As it is, I will be working on a very small project with another programmer, where I will be responsible to write some unit tests. I have access to the source code (so I know which function is used to get input from the user), but I do not want the other programmer to have to change the way his code is written simply to accommodate my tests. The other programmer's code will be in a single module; similarly, I want to write a single test module myself - without having to worry about keeping a separate data file. Therefore, I will go with Michael's approach. Thanks to everyone, and I hope that I didn't misrepresent any of the three solutions proposed. It's been fun! Andr? From andre.roberge at gmail.com Wed Apr 19 19:04:17 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 19 Apr 2006 14:04:17 -0300 Subject: [Tutor] [Summary] Re: unit testing raw_input() In-Reply-To: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> References: <7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f@mail.gmail.com> Message-ID: <7528bcdd0604191004n38618396u625cbda0da9d5c86@mail.gmail.com> Thank you Michael, Danny and Alan for your suggestions. I've included below my summary of the three very different suggestions, my brief analysis of them, and my conclusion. Anyone is free and welcome to comment! On 4/18/06, Andre Roberge wrote: > Hi all- > > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): > while True: > answer = raw_input(prompt) > if answer in ['y', 'Y', 'yes']: > print "You said yes!" > break > elif answer in ['n', 'N', 'no']: > print "You said no!" > break > else: > print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? > > Andr? > Alan Gauld suggested to create a data file that simulate possible user responses and to use redirection to feed the data to the program. Assuming the function to be tested is in y_n.py, it would look like the following: $ python y_n.py < fake_user_data > test_result Then, I assume I would do an automated comparison between "test_result" and some "expected_result" file to ensure everything is ok. This, in my opinion, is the "cleanest" solution. However, it may not scale well if one wants to build a test suite with many functions/methods, some of which require some user-input. Ideally, one should be able to change the order in which unit tests are run; with this approach, both the test suite and the user data file would probably have to be change in sync. ==== Danny Yoo suggested to change the function to be tested, to include an extra parameter, i.e. go from def y_n(prompt="Answer yes or no"): to def y_n(prompt="Answer yes or no", raw_input=raw_input): To quote Danny: But now we can hardcode particular inputs by sending y_n() a mock "raw_input" that returns precooked values. ########################### def yes1_raw_input(prompt): return "y" def yes2_raw_input(prompt): return "Y" def yes3_raw_input(prompt): return "yes" def yes4_raw_input(prompt): return "YES" ########################### [end quote] My first reaction is "Neat! :-)". However, this is only usable if one has access to the original function. If one uses a "library" function like y_n() (for example, there is a similar function in the livewires module which some of you probably know) which is not, in principle, modifyable, this approach fails. ==== Michael (last name unknown) suggests another approach, which shares some similarities with Danny's. Here's Michael's edited/truncated explanation: You create a mock for raw_input, put the above code inside a module and rebind raw_input in the module before calling your function. ie: ------------(CONTENTS of y_n.py)------------ def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break [snip] ------------(END CONTENTS of y_n.py)------------ [Michael's explanation using the interpreter is modified below] Then, one can have a test function in a separate file ------- begin test function import y_n def raw_input_mock(prompt): # create a mock return "n" y_n.raw_input = raw_input_mock # rebind the name inside the module y_n.y_n() # Run, this now calls our mock instead of the real raw_input ------- end test function [end of quote] Note that y_n() should probably return a string (instead of using a print statement) so that the output can be compared with the expected result; otherwise, one has to redirect the output to a file and do a comparison, as I mentioned with Alan's explanation. This is a rather clever method; I would never have thought of rebinding y_n.raw_input in this way. The only weakness that I see with this approach is if one wants to test a function like y_n() knowing that it ask the user for some input ... but not knowing what function it uses to do so. This can be the case if one has a compiled library with only the interface (what values can be passed to the functions and how; what are the expected outputs) being known. Danny's approach would also not work here, whereas Alan's would. As it is, I will be working on a very small project with another programmer, where I will be responsible to write some unit tests. I have access to the source code (so I know which function is used to get input from the user), but I do not want the other programmer to have to change the way his code is written simply to accommodate my tests. The other programmer's code will be in a single module; similarly, I want to write a single test module myself - without having to worry about keeping a separate data file. Therefore, I will go with Michael's approach. Thanks to everyone, and I hope that I didn't misrepresent any of the three solutions proposed. It's been fun! Andr? From alan.gauld at freenet.co.uk Wed Apr 19 19:24:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 19 Apr 2006 18:24:47 +0100 Subject: [Tutor] Re-instantiate within __init__ References: Message-ID: <017401c663d6$28b21b30$0a01a8c0@xp> > is it correct that an object cannot be re-instantiated within it's > __init__ method? There are some tricks you can pull but the object is actually instantiated before the init gets called. Really init is for initialisation of the instance, it's not a true constructor. > Background: I need to create a new object upon instantiation > when a database query returns no records. I'd probably create a factory function to do this that returns the appropriate type of instance. def makeDbResponseInstance(queryStatus): if queryStatus: return DBClass() else: return Emptyclass() If the two classes are subclassed from a common ancestor you might put the factory into the class as a class method, but I'd probably just keep it as a function. That keeps the two class's definitions clean and decoupled from the instantiation decision which isn't really their responsibility - children don't choose to be born!. Alan G. From alan.gauld at freenet.co.uk Wed Apr 19 19:34:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 19 Apr 2006 18:34:29 +0100 Subject: [Tutor] Some help with properties and accessor functions.... References: <647d31c20604190946g34d313a6s4c5c4699a19589d@mail.gmail.com> Message-ID: <018401c663d7$834e8f00$0a01a8c0@xp> class SOFileIndexRecord(object): def __init__(self, so): self._so=so def _get_code(self): return self._so.code def _set_code(self, value): self._so.code=value testCode=property(_get_code, _set_code) # What does this do? It says that testCode is a property of SOFileIndexRecord A property looks like a data attribute from the user of the class's point of view but internallty it is accessed via the get/set methods. Thus I can do: s = SOFileIndexRecord(mySo): s.testCode = myCode # actually does s._setCode(myCode) print s.testCode # actually s._getCode() properties allow for creation of read only attributes in Python by having a null set method.(Of course you can still cheat and use the 'hidden' methods, or even the real data attributes. Buit if everyone behaves properly it can help a wee bit. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From hugonz-lists at h-lab.net Wed Apr 19 06:34:18 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 18 Apr 2006 22:34:18 -0600 Subject: [Tutor] GUI In-Reply-To: <44452B59.1000509@micron.com> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> <44452B59.1000509@micron.com> Message-ID: <4445BDCA.2050501@h-lab.net> > Ok, > If I can get it for free, I might as well go with say wxPython. Thanks Yes, free as in beer, as in speech, and cross platform. Oh, and better documented. Hugo From learner404 at gmail.com Wed Apr 19 19:55:14 2006 From: learner404 at gmail.com (learner404) Date: Wed, 19 Apr 2006 19:55:14 +0200 Subject: [Tutor] [Linux] open a file in any home "~" ? Message-ID: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> Hello, I want to read a configuration file from a small python app (user preferences). The ".myapp.conf" is in the home folder of the user. if I do: f=open("/home/user1/.myapp.conf","r") #it works obviously I won't know the home user folder name then I wanted to use: f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No such file or directory: How can I do to access this file whatever the user is ? Thanks for your help. --- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060419/cd2d8a1f/attachment.htm From mwhite3 at ttsd.k12.or.us Wed Apr 19 20:10:50 2006 From: mwhite3 at ttsd.k12.or.us (Matthew White) Date: Wed, 19 Apr 2006 11:10:50 -0700 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> Message-ID: <20060419181049.GN16865@ttsd.k12.or.us> os.getenv('HOME') will return the user's home directory as long as that environment variable is set. you can also use the pwd module: >>> pwd.getpwnam('mtw') ('mtw', 'x', 1000, 1000, ',,,', '/home/mtw', '/bin/bash') -mtw On Wed, Apr 19, 2006 at 07:55:14PM +0200, learner404 (learner404 at gmail.com) wrote: > Hello, > > I want to read a configuration file from a small python app (user > preferences). > > The ".myapp.conf" is in the home folder of the user. > > if I do: > > f=open("/home/user1/.myapp.conf","r") #it works > > obviously I won't know the home user folder name then I wanted to use: > > f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No such > file or directory: > > How can I do to access this file whatever the user is ? > > Thanks for your help. > > --- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes From wescpy at gmail.com Wed Apr 19 20:24:43 2006 From: wescpy at gmail.com (w chun) Date: Wed, 19 Apr 2006 11:24:43 -0700 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> Message-ID: <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> > f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No such > file or directory: > > How can I do to access this file whatever the user is ? use os.path.expanduser(path) http://www.python.org/doc/2.4.3/lib/module-os.path.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Wed Apr 19 20:30:05 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Apr 2006 11:30:05 -0700 (PDT) Subject: [Tutor] Re-instantiate within __init__ In-Reply-To: References: Message-ID: > I tried: > > class Omega: > def Display(self): > print self > > class Alpha(Omega): > def __init__(self): > self = Beta() > > class Beta(Omega): > def __init__(self): > pass > > objectus = Alpha() > objectus.Display() > > which prints > > <__main__.Alpha instance at 0x54d50> > > Background: I need to create a new object upon instantiation when a > database query returns no records. The rest of the program should just > use the new object. I think you're looking for the "Strategy" design pattern: your class has a default behavior, but in a certain case, you want it to switch behaviors to something else. http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/StrategyPattern.htm That is, rather than Alpha being a subclass of Omega, Alpha can have an instance of Omega: ######################################### class Alpha: def __init__(self): self.strategy = DefaultStrategy() def display(self): self.strategy.display() class DefaultStrategy: def display(self): print "I am the default strategy" ######################################### The advantage here is that the strategy can be swapped out just by setting self.strategy to something else. From paidhi at mospheira.net Wed Apr 19 20:38:11 2006 From: paidhi at mospheira.net (Paidhi Aiji) Date: Wed, 19 Apr 2006 20:38:11 +0200 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> Message-ID: <1145471891.44468393d917d@www.domainfactory-webmail.de> Hi, You can use expanduser() from os.path for this: import os.path homedir = os.path.expanduser('~user1') file_to_open = os.path.join(homedir, '.myapp.conf') f = open(file_to_open, 'r') Regards, -Markus- Quoting learner404 : > Hello, > > I want to read a configuration file from a small python app (user > preferences). > > The ".myapp.conf" is in the home folder of the user. > > if I do: > > f=open("/home/user1/.myapp.conf","r") #it works > > obviously I won't know the home user folder name then I wanted to use: > > f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No such > file or directory: > > How can I do to access this file whatever the user is ? > > Thanks for your help. > > --- > From learner404 at gmail.com Wed Apr 19 20:40:52 2006 From: learner404 at gmail.com (learner404) Date: Wed, 19 Apr 2006 20:40:52 +0200 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> Message-ID: <13a83ca10604191140r3eaeeec8v7bda7c00e3c0e894@mail.gmail.com> It works great, thanks very much to the three of you for these light-speed answers ... I love this list ! Wesley, I've just pre-order your new edition "Core Python programming" on amazon France, it looks great. :) Thanks On 19/04/06, w chun wrote: > > > f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No > such > > file or directory: > > > > How can I do to access this file whatever the user is ? > > use os.path.expanduser(path) > > http://www.python.org/doc/2.4.3/lib/module-os.path.html > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060419/cebd5588/attachment.html From alan.gauld at freenet.co.uk Wed Apr 19 21:29:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 19 Apr 2006 20:29:36 +0100 Subject: [Tutor] [Linux] open a file in any home "~" ? References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> Message-ID: <002401c663e7$983f2c70$0a01a8c0@xp> > The ".myapp.conf" is in the home folder of the user. > ... > obviously I won't know the home user folder name then I wanted to use: > How can I do to access this file whatever the user is ? You can get the user name using getpass.getuser() as described in the OS topic of my tutor under the Securiity heading. You can also try using os.getenv() or the os.environ variable to look up the HOME environment variable, also discussed in the OS topic. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Wed Apr 19 21:46:52 2006 From: wescpy at gmail.com (w chun) Date: Wed, 19 Apr 2006 12:46:52 -0700 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <13a83ca10604191140r3eaeeec8v7bda7c00e3c0e894@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> <13a83ca10604191140r3eaeeec8v7bda7c00e3c0e894@mail.gmail.com> Message-ID: <78b3a9580604191246n67664fd5hfed82e8198ac3725@mail.gmail.com> we are all happy to help. it is really good that you were able to get it working so fast! also, if you want to do any kind of pattern matching with * or ?, then check out the "glob" module. merci! "le livre" does not look that good from here... it is a mess and i have to clean it up before giving it to the publisher! :-) cheers, -wesley On 4/19/06, learner404 wrote: > It works great, thanks very much to the three of you for these light-speed > answers ... I love this list ! > > Wesley, I've just pre-order your new edition "Core Python programming" on > amazon France, it looks great. :) From amonroe at columbus.rr.com Thu Apr 20 00:03:14 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 19 Apr 2006 18:03:14 -0400 Subject: [Tutor] GUI In-Reply-To: <4445BDCA.2050501@h-lab.net> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> <44452B59.1000509@micron.com> <4445BDCA.2050501@h-lab.net> Message-ID: <34345490448.20060419180314@columbus.rr.com> >> If I can get it for free, I might as well go with say wxPython. Thanks > Yes, free as in beer, as in speech, and cross platform. Oh, and better > documented. Sadly, you still pay for it in RAM usage :^) Alan From ml.cyresse at gmail.com Thu Apr 20 00:25:18 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Apr 2006 10:25:18 +1200 Subject: [Tutor] GUI In-Reply-To: <34345490448.20060419180314@columbus.rr.com> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> <44452B59.1000509@micron.com> <4445BDCA.2050501@h-lab.net> <34345490448.20060419180314@columbus.rr.com> Message-ID: Hmm? How so? I'm using a whole lot of raw wxPython mixed with Pythoncard for a project, and the entire process sits at 7Mb RAM usage idle. WinXP btw. Considering my small command line appns to start/stop Windows services written in C use just over 1Mb, 7Mb isn't overly bad. The other good thing about wxPython is stuff like Pythoncard and Wax, although development on Pythoncard seems to have slowed right down, Kevin Altis got busy, I guess; Wax is nice looking but... not very well documented... It's great being able to use Pythoncard for the not overly complicated stuff, but with the wxPython still lurking beneath the surface. Regards, Liam Clarke On 4/20/06, R. Alan Monroe wrote: > >> If I can get it for free, I might as well go with say wxPython. Thanks > > > Yes, free as in beer, as in speech, and cross platform. Oh, and better > > documented. > > Sadly, you still pay for it in RAM usage :^) > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From doug.shawhan at gmail.com Thu Apr 20 01:20:26 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 19 Apr 2006 18:20:26 -0500 Subject: [Tutor] Brain In Vice: Why is this so fun to me? Message-ID: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> I think I'm going to have to suck it up and learn some regular expressions. I have finally gotten my script (using the excellent pyserial module) to behave. Most of my troubles as enumerated here before were utterly self-induced. Apparently one cannot watch the execution of one's script through another program without affecting it's outcome in unforseen ways. (Sound familiar Herr Schroedinger? :-) Now that I am actually extracting data in a fairly predictable way, I am at the point where I need to parse it! I have some output here (modified to show the ESC and NUL characters.) When I pull data from the port, the remote computer sends it in one long string per screen: newlines are not painted in by using the expected x\0a that I had hoped for! No easy readlines() fun for me. Instead I get: ESC=( 1. ESC=($4x2, 6-239 (3.9L) ..........................................ESC=(a03252 ESC=(k0 ESC=) 2. ESC=))8-318 (5.2L) ..........................................ESC=)a03242 ESC=)k0 ESC=* 3. ESC=*)8-360 (5.9L) ..........................................ESC=*a03351 ESC=*k 0 ESC=+ 4. ESC=+$4x4, 6-239 (3.9L) ..........................................ESC=+a03240 ESC=+k 0 ESC=, 5. ESC=,)8-318 (5.2L) ..........................................ESC=,a03243 ESC=,k 0 ESC=- 6. ESC=-)8-360 (5.9L) ..........................................ESC=-a03352 ESC=-k 0 ESC=. 7. ESC=.aCH8299 ESCTNULESC)NULESC=% LINEESCTNULESC=& R = RELIST = NONE I have broken it up for ease of viewing. I need to split the string where ESC= , k and 0 are found, but ESC= ,k and 0 are seperated by various spaces, parentheis and other characters that are apparently used to mark the end of the line until the next ESC is found, thereby displaying a new line (note how the character after the first ESC on each line is repeated after the ESC on the end. I cannot for the life of me figure out a pythonic way (read: using the split() builtin) to scan for instances of these characters in such and such order and proximity. I know this is what regex is for, but I have no experience. I have obtained a copy of "Mastering Regular Expressions" but thought I would inquire here first for caveats and tips as the book is larger than my brain, and I haven't used the re module, ever. Why in the world does this make me so happy? :-)~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060419/0ddaec9f/attachment-0001.html From ml.cyresse at gmail.com Thu Apr 20 01:32:02 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Apr 2006 11:32:02 +1200 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> Message-ID: Hi Doug, Best tip ever is your_python_dir\tools\scripts\redemo.py Interactive regexes. :) This is pretty good as well - http://www.amk.ca/python/howto/regex/ Good luck, Liam Clarke On 4/20/06, doug shawhan wrote: > I think I'm going to have to suck it up and learn some regular expressions. > > I have finally gotten my script (using the excellent pyserial module) to > behave. Most of my troubles as enumerated here before were utterly > self-induced. Apparently one cannot watch the execution of one's script > through another program without affecting it's outcome in unforseen ways. > (Sound familiar Herr Schroedinger? :-) > > Now that I am actually extracting data in a fairly predictable way, I am at > the point where I need to parse it! I have some output here (modified to > show the ESC and NUL characters.) > > When I pull data from the port, the remote computer sends it in one long > string per screen: newlines are not painted in by using the expected x\0a > that I had hoped for! No easy readlines() fun for me. Instead I get: > > ESC=( 1. ESC=($4x2, 6-239 (3.9L) > ..........................................ESC=(a03252 > ESC=(k0 > ESC=) 2. ESC=))8-318 (5.2L) > ..........................................ESC=)a03242 > ESC=)k0 > ESC=* 3. ESC=*)8-360 (5.9L) > ..........................................ESC=*a03351 > ESC=*k 0 > ESC=+ 4. ESC=+$4x4, 6-239 (3.9L) > ..........................................ESC=+a03240 > ESC=+k 0 > ESC=, 5. ESC=,)8-318 (5.2L) > ..........................................ESC=,a03243 > ESC=,k 0 > ESC=- 6. ESC=-)8-360 (5.9L) > ..........................................ESC=-a03352 > ESC=-k 0 > ESC=. 7. ESC=.aCH8299 ESCTNULESC)NULESC=% LINEESCTNULESC=& R = > RELIST = NONE > > I have broken it up for ease of viewing. I need to split the string where > ESC= , k and 0 are found, but ESC= ,k and 0 are seperated by various > spaces, parentheis and other characters that are apparently used to mark the > end of the line until the next ESC is found, thereby displaying a new line > (note how the character after the first ESC on each line is repeated after > the ESC on the end. > > I cannot for the life of me figure out a pythonic way (read: using the > split() builtin) to scan for instances of these characters in such and such > order and proximity. I know this is what regex is for, but I have no > experience. I have obtained a copy of "Mastering Regular Expressions" but > thought I would inquire here first for caveats and tips as the book is > larger than my brain, and I haven't used the re module, ever. > > Why in the world does this make me so happy? :-)~ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Thu Apr 20 01:48:31 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Apr 2006 11:48:31 +1200 Subject: [Tutor] Reqiest Centre - Adding New Call Message-ID: Hi, The categories of calls under this drop down box, are they going to increase anytime soon, or shall I go with what's there? Regards, Liam Clarke From alan.gauld at freenet.co.uk Thu Apr 20 02:17:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 20 Apr 2006 01:17:34 +0100 Subject: [Tutor] [Linux] open a file in any home "~" ? References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> Message-ID: <005b01c6640f$d28e0e50$0a01a8c0@xp> > How can I do to access this file whatever the user is ? > > use os.path.expanduser(path) Neat Wesley, I've never noticed that one before. Alan G. From alan.gauld at freenet.co.uk Thu Apr 20 02:25:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 20 Apr 2006 01:25:38 +0100 Subject: [Tutor] Brain In Vice: Why is this so fun to me? References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> Message-ID: <007101c66410$f385bbc0$0a01a8c0@xp> > I cannot for the life of me figure out a pythonic way (read: using the > split() builtin) to scan for instances of these characters in such and > such > order and proximity. I know this is what regex is for, I'm afraid so, it looks like the time has come to import re. > I have obtained a copy of "Mastering Regular Expressions" Good book but probably overkill unless you get really serious > I would inquire here first for caveats and tips Build them up gradually, test them at the >>> prompt or using the tool that comes with Python. Don;t forget the power of building a negative of what you want and then searching for the inverse. Finally remember that match() is usually the wrong function to use - it only searches at the beginning of the string! And, of course, I have a topic on regex :-) Good luck! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Barry.Carroll at psc.com Thu Apr 20 02:17:09 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 19 Apr 2006 17:17:09 -0700 Subject: [Tutor] Splitting a number into even- and odd- numbered digits Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C365C@eugsrv400.psc.pscnet.com> Greetings: I am writing a function that accepts a string of decimal digits, calculates a checksum and returns it as a single character string. The first step in the calculation is to split the input into two strings: the even- and odd- numbered digits, respectively. The least significant digit is defined as odd. The following code fragment does the job but seems sort of brutish and inelegant to me: >>>>>>> >>> s = '987654321' >>> odd = '' >>> for c in s[::-2]: ... odd = c + odd ... >>> s = s[:-1] >>> even = '' >>> for c in s[::-2]: ... even = c + even ... >>> odd '97531' >>> even '8642' >>>>>>> Is there a better (i.e. more Pythonic) way to do this? Thanks in advance for all your help. Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From john at fouhy.net Thu Apr 20 02:48:34 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 20 Apr 2006 12:48:34 +1200 Subject: [Tutor] Splitting a number into even- and odd- numbered digits In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C365C@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C365C@eugsrv400.psc.pscnet.com> Message-ID: <5e58f2e40604191748r6431601cje17190b32d5682f@mail.gmail.com> On 20/04/06, Carroll, Barry wrote: > The following code fragment does the job but seems sort of brutish and inelegant to me: > > >>>>>>> > >>> s = '987654321' > >>> odd = '' > >>> for c in s[::-2]: > ... odd = c + odd > ... > >>> String slicing will actually produce strings :-) eg: >>> s = '987654321' >>> s1, s2 = s[::-2], s[-2::-2] >>> s1 '13579' >>> s2 '2468' -- John. From nospamformeSVP at gmail.com Thu Apr 20 03:48:13 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Wed, 19 Apr 2006 21:48:13 -0400 Subject: [Tutor] Version of a .pyc file In-Reply-To: References: Message-ID: Terry Carroll wrote: >>How can I tell if a .pyc file was built with 2.3 or 2.4? > > > There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether > you consider the \r\n part of the MN). > > >>>>f = open("pycfile.pyc", "rb") >>>>magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"} >>>>magic = f.read(4) >>>>release = magictable.get(magic,"unknown") >>>>print "Python release:", release > > Python release: 2.4 > I have used Terry's code to write a script to find all of the the .pyc files on my system that were compiled with the 2.3 version of the compiler, and I have removed these files. But my underlying problem still occurs: somewhere somebody is calling for the 2.3 version of the Python vm .dll and not finding it. This is happening under Pydev/Eclipse and my only recourse is to blow Eclipse away using Task Manager. So maybe I have a .pyd file somewhere that is a 2.3 extension. Is there a way to examine .pyd files to see if they were built for Python 2.3? Finally, are there any other possible file extension types that I should be looking at? Thanks, Don. From kent37 at tds.net Thu Apr 20 05:05:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Apr 2006 23:05:56 -0400 Subject: [Tutor] Version of a .pyc file In-Reply-To: References: Message-ID: <4446FA94.4020008@tds.net> Don Taylor wrote: > Finally, are there any other possible file extension types that I should > be looking at? .pyo is like a .pyc but compiled with optimizations on. Kent From ml.cyresse at gmail.com Thu Apr 20 07:48:21 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Apr 2006 17:48:21 +1200 Subject: [Tutor] Reqiest Centre - Adding New Call In-Reply-To: <4446ECF3.1020203@alum.rpi.edu> References: <4446ECF3.1020203@alum.rpi.edu> Message-ID: Hi all, I do apologise for this, This was an email that has nothing to do with Python or the tutor list, so my apologies to all. Somehow I managed to send it to the wrong recepient. (And my thanks to Bob for being brave enough to attempt to answer what would be a hopelessly vague question. :-) ) Regards, an embarrassed Liam Clarke On 4/20/06, Bob Gailer wrote: > Liam Clarke wrote: > > Hi, > > > > The categories of calls under this drop down box, are they going to > > increase anytime soon, or shall I go with what's there? > > > I'm in the dark. What is "this drop down box"? > From 9bh4frs02 at sneakemail.com Thu Apr 20 08:51:02 2006 From: 9bh4frs02 at sneakemail.com (Ron Britton) Date: Wed, 19 Apr 2006 23:51:02 -0700 Subject: [Tutor] Use iterator to refer to an object's attribute? In-Reply-To: References: Message-ID: <9690-16163@sneakemail.com> Short version: How do I use an iterator to refer to an object's attribute? E.g., "z" is a list of attributes of "b": for x, y in z: for a in b.x.y Also, any suggestions for my overall structure below? ---------- Long version: I need to make a program to send commands to an instrument. I've been working on it for a while, and my employer is starting to get itchy. Here's a simplified description: ? The instrument has three modules (motherboard, controller, and end user). ? Each module has an arbitrary number of components (motherboard has internal camera; controller has major and minor controllers; and end user has x-, y-, and z-motors). ? Each component has an arbitrary number of commands. ? Each command has a fixed number of attributes. I will ultimately create a GUI with a 4-pane browser: ? Pane 1 will display the modules. When the user clicks on a module, its components will appear in pane 2. ? When the user clicks on a component, its commands will appear in pane 3. ? When the user clicks on a command, its parameters will appear in pane 4. ? The user will then click a Send button, which will send the command and its parameters to the instrument. I haven't coded the GUI yet, because I'm stuck on the underlying structure. Here's how I'm tackling it: ? I have a bunch of lists that have everything defined in them (module_list; cpt_??_lists for components; and cmd_??_lists for commands). ? I'm creating a database object, "db", which will hold everything. ? I iterate across the module list. The idea here is to create within the database one module object for each real object in the instrument, in this case three. I should end up with: db.mb, db.ct, and db.eu. ? There is a short name (for use by the program), a long name (which will be displayed to the user), and the name of that module's component list. ? I also create an empty list object, which will ultimately be populated with the contents of that module's component list. ? Then (theoretically) for each module, I iterate across that module's component list to create several component objects inside the module (I will then continue this process, creating command objects within the components.). ---------- My immediate problem is that Python doesn't let me use the iterator as the name of an object's attribute. E.g.: I have object "db.mb". I have iterator "shortmod" with a value of "mb". Why can't I call "db.shortmod"? Also, if you have any better ideas on how to put this thing together, I'm all ears. The reason for doing it this way is that I wanted my database to be the logical equivalent of the instrument. Here's the error message I get: ---------- Traceback (most recent call last): File "/Developer/Python/CZM Scripts/CmdList.py", line 111, in -toplevel- main() File "/Developer/Python/CZM Scripts/CmdList.py", line 108, in main fillout_DB(db) File "/Developer/Python/CZM Scripts/CmdList.py", line 62, in fillout_DB for shortcpt, longcpt, cmdlist in filldb.shortmod.cptlist: AttributeError: Database instance has no attribute 'shortmod' ---------- My code follows. If you jump down to the section marked "#---Logic---", you should be able to see the immediate culprit. I greatly appreciate any help that anybody on this list can provide! Thanks! Ron ************************************************************************ ** #--- Definitions----------------------------------------------------------- # shortname, longname, component list name #---Modules module_list = [ ['mb', 'Motherboard', 'cpt_mb_list'], ['ct', 'Controller', 'cpt_ct_list'], ['eu', 'End User', 'cpt_eu_list']] #---Components # shortname, longname, command list name # Motherboard cpt_mb_list = [ ['icam', 'Internal Camera', 'cmd_icam_list']] # Controller cpt_ct_list = [ ['maj', 'Major Controller', 'cmd_maj_list'], ['min', 'Minor Controller', 'cmd_min_list']] # End User cpt_eu_list = [ ['xmtr', 'X Motor', 'cmd_xmtr_list'], ['ymtr', 'Y Motor', 'cmd_ymtr_list'], ['zmtr', 'Z Motor', 'cmd_zmtr_list']] #---Commands # Abbreviation, string, command, param1, param2 # Motherboard Commands cmd_icam_list = [ ['ss', 'Shutter Speed', 'shutSpeed', 0, 0], ['ap', 'Aperture', 'aperture', 0, 0], ['exp', 'Exposure', 'exposure', 0, 0]] # Controller Commands cmd_maj_list = [ ['on', 'Turn it on', 'turnON', 0, 0], ['off', 'Turn it off', 'turnOFF', 0, 0]] cmd_min_list = [ ['low', 'Set Power Low', 'setLow', 0, 0], ['hi', 'Set Power High', 'setHigh', 0, 0]] # End User Commands cmd_xmtr_list = [ ['xpos', 'Go to X-Position', 'xPosition', 0, 0]] cmd_ymtr_list = [ ['ypos', 'Go to Y-Position', 'yPosition', 0, 0]] cmd_zmtr_list = [ ['zpos', 'Go to Z-Position', 'zPosition', 0, 0]] #--- Logic----------------------------------------------------------------- #****************My immediate problem occurs in this object*************** def fillout_DB(filldb): '''Build the database of modules, components, and commands. Feed it an empty database, and it will fill it out.''' # Add modules for shortmod, longmod, cptlist in module_list: filldb.addMod([shortmod, longmod, cptlist]) print filldb.modlist print 'Just loaded %r, %r, and %r' % (shortmod, longmod, cptlist) # Add components #********************The following line chokes******************** for shortcpt, longcpt, cmdlist in filldb.shortmod.cptlist: # It doesn't get to next line. Suspect it won't work either. filldb.shortmod.addCpt([shortcpt, longcpt, cmdlist]) print 'Just loaded %r, %r, and %r' % (shortcpt, longcpt, cmdlist) print 'Finished buildModules()!!!!' return filldb class Database: '''This is the root class. The database contains all of the module objects. Each module contains all of its component objects, etc.''' def __init__(self): self.modlist = [] def addMod(self, mod): self.modlist.append(mod) class Module: def __init__(self, shortname, longname, cptlistname): self.name = shortname self.longname = longname self.cptlistname = cptlistname self.cptlist = [] def addCpt(self, cpt): self.cptlist.append(cpt) class Component: def __init__(self, shortname, longname, cmdlistname): self.name = shortname self.longname = longname self.cmdlistname = cmdlistname self.cmdlist = [] def addCmd(self, cmd): self.cmdlist.append(cmd) class Command: def __init__(self, shortname, longname, actualcommand, param1, param2): self.name = shortname self.longname = longname self.actcmd = actualcommand self.paramlist = [param1, param2] def main(): print "It's working so far!" db = Database() fillout_DB(db) if __name__ == "__main__": main() From titvirak at khmeros.info Thu Apr 20 09:56:23 2006 From: titvirak at khmeros.info (=?UTF-8?B?4Z6R4Z634Z6P4Z+S4Z6Z4Z6c4Z634Z6a4Z+I?=) Date: Thu, 20 Apr 2006 14:56:23 +0700 Subject: [Tutor] Parsing html user HTMLParser Message-ID: <44473EA7.6030807@khmeros.info> Hi folks, I need help here, I'm struggling with html parsing method, up until now I can only put and html file as instance. I have no experience with this, I want to read the childs inside this document and modify the data. What can I do if I start from here? > from HTMLParser import HTMLParser > > p = HTMLParser() > s = open('/home/virak/Documents/peace/test.html').read() > p.feed(s) > > print p > > p.close() Titvirak From alan.gauld at freenet.co.uk Thu Apr 20 10:21:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 20 Apr 2006 09:21:39 +0100 Subject: [Tutor] Use iterator to refer to an object's attribute? References: <9690-16163@sneakemail.com> Message-ID: <00a301c66453$730e0680$0a01a8c0@xp> Hi Ron, I'm confused and may be missing something but it sounds to me like a classic tree structure that you are trying to build for each module. > Also, any suggestions for my overall structure below? I''m not sure why you put filling the database into a separate function rather than as a method of the Database class, it could then be called from the init method. This would give it direct access to the Database attributes. Also I don't understand why you need the componentlist name. What is this used for? The name of the list is surely an internal variable within the module of no relevance to the outside world? I'm also not clear about the database structure. Is the one represented here the final striucture - ie a set of Python lists. Or will you eventually be loading the data from a config file or a relational database at somne point in the future? If it stays at it is then the whole design seems overly complex since you could simply load the data as part of the object construction/instantiation process, something like this: ModuleList = [ Module( "Motherboard", [Component("Camera", [Command(p1,p2,p3), Command(p4,p5)]), ]), Module("Controller", [Component("Major Controller", [Command(....),....]), Component("Minor Controller", [Command(....),....]),... ]), Module("End User", [Component("xMotor", [Command(...),...]),... ]) ] I suspect the use of a dictionary might be beneficial too. However if the data varies at runtime and you have to read it from an external source that approach won't work. OTOH if you are iusing a relational DB then the links between the components can be constructed as relations between the tables so that will simplify construction. The most complex case is where you are loading from flat files. But we need a bit more info I think. But whichever method is used I'd put the code into the classes and let each class load its own data. Here's how I'm tackling it: ? I have a bunch of lists that have everything defined in them (module_list; cpt_??_lists for components; and cmd_??_lists for commands). ? I'm creating a database object, "db", which will hold everything. ? I iterate across the module list. The idea here is to create within the database one module object for each real object in the instrument, in this case three. I should end up with: db.mb, db.ct, and db.eu. Why not a dictionary of modules keyed by module name? ? There is a short name (for use by the program), a long name (which will be displayed to the user), and the name of that module's component list. Why not write constructors that take a list as a parameter. The constructor can manage its own liust and the higher level constructor just passes in the appropriate list. That way each class only needs to know about the data at the lebvel it is responsible for. So the Module class might look a bit like: class Module: def __init__(self, name, componentlist): self.components = {} self.name = name for component in componentlist: self.components[component[0]] = Component(component) This implies that the component list is structured as a list of tuples. ? I also create an empty list object, which will ultimately be populated with the contents of that module's component list. As above I'd recommend using a dictionary rather than a list. ? Then (theoretically) for each module, I iterate across that module's component list to create several component objects inside the module (I will then continue this process, creating command objects within the components.). Yes, thats the idea but let the objects do it for themselves. > My immediate problem is that Python doesn't let me use the iterator as > the name of an object's attribute. Thats where the dictionary comes in. > I have object "db.mb". I have iterator "shortmod" with a value of "mb". > Why can't I call "db.shortmod"? You can use db.getattr(shortmod) but I think its easier and clearer in this case to use: db.Modules[shortmod] > I'm all ears. The reason for doing it this way is that I wanted my > database to be the logical equivalent of the instrument. I think you can make it a miuch closer equivalent than you have at present, and I think that by breaking up the fill db function and moving responsibility into the classes that it will be much simplified. And use dictionaries rather than lists. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld #--- Definitions----------------------------------------------------------- # shortname, longname, component list name #---Modules module_list = [ ['mb', 'Motherboard', 'cpt_mb_list'], ['ct', 'Controller', 'cpt_ct_list'], ['eu', 'End User', 'cpt_eu_list']] #---Components # shortname, longname, command list name # Motherboard cpt_mb_list = [ ['icam', 'Internal Camera', 'cmd_icam_list']] # Controller cpt_ct_list = [ ['maj', 'Major Controller', 'cmd_maj_list'], ['min', 'Minor Controller', 'cmd_min_list']] # End User cpt_eu_list = [ ['xmtr', 'X Motor', 'cmd_xmtr_list'], ['ymtr', 'Y Motor', 'cmd_ymtr_list'], ['zmtr', 'Z Motor', 'cmd_zmtr_list']] #---Commands # Abbreviation, string, command, param1, param2 # Motherboard Commands cmd_icam_list = [ ['ss', 'Shutter Speed', 'shutSpeed', 0, 0], ['ap', 'Aperture', 'aperture', 0, 0], ['exp', 'Exposure', 'exposure', 0, 0]] # Controller Commands cmd_maj_list = [ ['on', 'Turn it on', 'turnON', 0, 0], ['off', 'Turn it off', 'turnOFF', 0, 0]] cmd_min_list = [ ['low', 'Set Power Low', 'setLow', 0, 0], ['hi', 'Set Power High', 'setHigh', 0, 0]] # End User Commands cmd_xmtr_list = [ ['xpos', 'Go to X-Position', 'xPosition', 0, 0]] cmd_ymtr_list = [ ['ypos', 'Go to Y-Position', 'yPosition', 0, 0]] cmd_zmtr_list = [ ['zpos', 'Go to Z-Position', 'zPosition', 0, 0]] #--- Logic----------------------------------------------------------------- #****************My immediate problem occurs in this object*************** def fillout_DB(filldb): '''Build the database of modules, components, and commands. Feed it an empty database, and it will fill it out.''' # Add modules for shortmod, longmod, cptlist in module_list: filldb.addMod([shortmod, longmod, cptlist]) print filldb.modlist print 'Just loaded %r, %r, and %r' % (shortmod, longmod, cptlist) # Add components #********************The following line chokes******************** for shortcpt, longcpt, cmdlist in filldb.shortmod.cptlist: # It doesn't get to next line. Suspect it won't work either. filldb.shortmod.addCpt([shortcpt, longcpt, cmdlist]) print 'Just loaded %r, %r, and %r' % (shortcpt, longcpt, cmdlist) print 'Finished buildModules()!!!!' return filldb class Database: '''This is the root class. The database contains all of the module objects. Each module contains all of its component objects, etc.''' def __init__(self): self.modlist = [] def addMod(self, mod): self.modlist.append(mod) class Module: def __init__(self, shortname, longname, cptlistname): self.name = shortname self.longname = longname self.cptlistname = cptlistname self.cptlist = [] def addCpt(self, cpt): self.cptlist.append(cpt) class Component: def __init__(self, shortname, longname, cmdlistname): self.name = shortname self.longname = longname self.cmdlistname = cmdlistname self.cmdlist = [] def addCmd(self, cmd): self.cmdlist.append(cmd) class Command: def __init__(self, shortname, longname, actualcommand, param1, param2): self.name = shortname self.longname = longname self.actcmd = actualcommand self.paramlist = [param1, param2] def main(): print "It's working so far!" db = Database() fillout_DB(db) if __name__ == "__main__": main() From ml.cyresse at gmail.com Thu Apr 20 10:46:34 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 20 Apr 2006 20:46:34 +1200 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> <5e1ceb8a0604191637u2a942605qa07132735e6022f2@mail.gmail.com> <5e1ceb8a0604191638u5b53867n4ebe57d058be77fd@mail.gmail.com> <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> Message-ID: Yeah, Alan's tutorial is what I used to learn how to code, it's very good. Regexes are very powerful; which can be a very good thing and a very bad thing. ;) Good luck. On 4/20/06, doug shawhan wrote: > Got it! Thanks! Mr. Gald hooked me up with his re tutorial as well. Great! > > > On 4/19/06, Liam Clarke wrote: > > Here's my copy, it should work if you have Tkinter. > > > > Good luck! > > > > On 4/20/06, doug shawhan wrote: > > > Drat, I installed from the OpenBSD ports tree and this is not included. > I'll > > > scout around on the net. > > > > > > Thanks again! > > > > > > > > > On 4/19/06, doug shawhan wrote: > > > > > > > > Holy moley. > > > > > > > > Thanks! > > > > > > > > > > > > > > > > On 4/19/06, Liam Clarke < ml.cyresse at gmail.com> wrote: > > > > > Hi Doug, > > > > > > > > > > Best tip ever is > > > your_python_dir\tools\scripts\redemo.py > > > > > > > > > > Interactive regexes. :) > > > > > > > > > > This is pretty good as well - > > > http://www.amk.ca/python/howto/regex/ > > > > > > > > > > Good luck, > > > > > > > > > > Liam Clarke > > > > > > > > > > On 4/20/06, doug shawhan < doug.shawhan at gmail.com> wrote: > > > > > > I think I'm going to have to suck it up and learn some regular > > > expressions. > > > > > > > > > > > > I have finally gotten my script (using the excellent pyserial > module) > > > to > > > > > > behave. Most of my troubles as enumerated here before were utterly > > > > > > self-induced. Apparently one cannot watch the execution of one's > > > script > > > > > > through another program without affecting it's outcome in > unforseen > > > ways. > > > > > > (Sound familiar Herr Schroedinger? :-) > > > > > > > > > > > > Now that I am actually extracting data in a fairly predictable > way, I > > > am at > > > > > > the point where I need to parse it! I have some output here > (modified > > > to > > > > > > show the ESC and NUL characters.) > > > > > > > > > > > > When I pull data from the port, the remote computer sends it in > one > > > long > > > > > > string per screen: newlines are not painted in by using the > expected > > > x\0a > > > > > > that I had hoped for! No easy readlines() fun for me. Instead I > get: > > > > > > > > > > > > ESC=( 1. ESC=($4x2, 6-239 (3.9L) > > > > > > > ..........................................ESC=(a03252 > > > > > > ESC=(k0 > > > > > > ESC=) 2. ESC=))8-318 ( 5.2L) > > > > > > > ..........................................ESC=)a03242 > > > > > > ESC=)k0 > > > > > > ESC=* 3. ESC=*)8-360 ( 5.9L) > > > > > > > ..........................................ESC=*a03351 > > > > > > ESC=*k 0 > > > > > > ESC=+ 4. ESC=+$4x4, 6-239 ( 3.9L) > > > > > > > ..........................................ESC=+a03240 > > > > > > ESC=+k 0 > > > > > > ESC=, 5. ESC=,)8-318 (5.2L) > > > > > > > ..........................................ESC=,a03243 > > > > > > ESC=,k 0 > > > > > > ESC=- 6. ESC=-)8-360 ( 5.9L) > > > > > > > ..........................................ESC=-a03352 > > > > > > ESC=-k 0 > > > > > > ESC=. 7. ESC=.aCH8299 ESCTNULESC)NULESC=% > > > LINEESCTNULESC=& R = > > > > > > RELIST = NONE > > > > > > > > > > > > I have broken it up for ease of viewing. I need to split the > string > > > where > > > > > > ESC= , k and 0 are found, but ESC= ,k and 0 are seperated by > various > > > > > > spaces, parentheis and other characters that are apparently used > to > > > mark the > > > > > > end of the line until the next ESC is found, thereby displaying a > new > > > line > > > > > > (note how the character after the first ESC on each line is > repeated > > > after > > > > > > the ESC on the end. > > > > > > > > > > > > I cannot for the life of me figure out a pythonic way (read: > using > > > the > > > > > > split() builtin) to scan for instances of these characters in such > and > > > such > > > > > > order and proximity. I know this is what regex is for, but I have > no > > > > > > experience. I have obtained a copy of "Mastering Regular > Expressions" > > > but > > > > > > thought I would inquire here first for caveats and tips as the > book is > > > > > > larger than my brain, and I haven't used the re module, ever. > > > > > > > > > > > > Why in the world does this make me so happy? :-)~ > > > > > > > > > > > > _______________________________________________ > > > > > > Tutor maillist - Tutor at python.org > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > From justin.mailinglists at gmail.com Thu Apr 20 11:26:11 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Thu, 20 Apr 2006 17:26:11 +0800 Subject: [Tutor] pyExcelerator for Python 2.3 Message-ID: <3c6718980604200226m7bb2f235l16036bdfca834258@mail.gmail.com> Does anyone know where I can get pyExcelerator for Python 2.3? I have not yet updated my development machine to 2.4. Thanks in advance. From K.Weinert at gmx.net Thu Apr 20 13:04:37 2006 From: K.Weinert at gmx.net (K.Weinert at gmx.net) Date: Thu, 20 Apr 2006 13:04:37 +0200 (MEST) Subject: [Tutor] [Linux] open a file in any home "~" ? Message-ID: <6421.1145531077@www058.gmx.net> Hi, try f=file(os.path.join(os.path.expanduser("~")),"myfile"), "r") Kind regards, Karsten. -- Echte DSL-Flatrate dauerhaft für 0,- Euro*! "Feel free" mit GMX DSL! http://www.gmx.net/de/go/dsl From kent37 at tds.net Thu Apr 20 13:44:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 07:44:25 -0400 Subject: [Tutor] Use iterator to refer to an object's attribute? In-Reply-To: <9690-16163@sneakemail.com> References: <9690-16163@sneakemail.com> Message-ID: <44477419.9030109@tds.net> Ron Britton wrote: > Short version: How do I use an iterator to refer to an object's > attribute? E.g., "z" is a list of attributes of "b": > for x, y in z: > for a in b.x.y getattr(b, 'foo') is the same as b.foo. getattr takes a string for the name of the attribute. So you would need getattr(getattr(b, x), y) > > Also, any suggestions for my overall structure below? For once I agree with Alan on a design question :-) You can define a useful structure directly in your configuration. It could be nested lists and dictionaries or nested class instances, whichever works better for the application. I think I would use nested class instances. This is one of Python's great strengths - that you can easily declare complex data structures in code. PS I suggest you call your data structure something other than 'database' since that word has a fairly specific meaning. Kent From kent37 at tds.net Thu Apr 20 13:54:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 07:54:18 -0400 Subject: [Tutor] pyExcelerator for Python 2.3 In-Reply-To: <3c6718980604200226m7bb2f235l16036bdfca834258@mail.gmail.com> References: <3c6718980604200226m7bb2f235l16036bdfca834258@mail.gmail.com> Message-ID: <4447766A.6080209@tds.net> Justin Ezequiel wrote: > Does anyone know where I can get pyExcelerator for Python 2.3? > I have not yet updated my development machine to 2.4. - look through the past releases on sourceforge - ask on the pyExcelerator list - hack the current release to work on 2.3 - most of what is new in 2.4 can be done fairly easily in 2.3 Kent From kent37 at tds.net Thu Apr 20 13:56:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 07:56:17 -0400 Subject: [Tutor] Parsing html user HTMLParser In-Reply-To: <44473EA7.6030807@khmeros.info> References: <44473EA7.6030807@khmeros.info> Message-ID: <444776E1.3060707@tds.net> ????????? wrote: > Hi folks, > > I need help here, I'm struggling with html parsing method, up until now > I can only put and html file as instance. I have no experience with > this, I want to read the childs inside this document and modify the > data. What can I do if I start from here? > >> from HTMLParser import HTMLParser >> >> p = HTMLParser() >> s = open('/home/virak/Documents/peace/test.html').read() >> p.feed(s) >> >> print p >> >> p.close() Here is an example that might be useful, though the usage is not too clear... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286269 Kent From python at venix.com Thu Apr 20 14:04:06 2006 From: python at venix.com (Python) Date: Thu, 20 Apr 2006 08:04:06 -0400 Subject: [Tutor] Splitting a number into even- and odd- numbered digits In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C365C@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C365C@eugsrv400.psc.pscnet.com> Message-ID: <1145534646.6268.142.camel@www.venix.com> On Wed, 2006-04-19 at 17:17 -0700, Carroll, Barry wrote: > Greetings: > > I am writing a function that accepts a string of decimal digits, > calculates a checksum and returns it as a single character string. > The first step in the calculation is to split the input into two > strings: the even- and odd- numbered digits, respectively. The least > significant digit is defined as odd. > This sounds like credit card checksum processing. This is my code for that: def isbad(cardnumber): factors = ([2,1] * 8)[-len(cardnumber):] # alternating factors of 2 and 1 ending with 1 chkprods = [int(d)*f for (d,f) in zip(cardnumber,factors)] return sum(chkprods) % 10 This deviates quite a bit from your description and the description of the algorithm that I was working from. It was only after I had coded up separate even/odd character lists and looked at what was going on that I realized there was a much simpler way to describe the rules. Hopefully, I am not off in left field here. > The following code fragment does the job but seems sort of brutish and inelegant to me: > > >>>>>>> > >>> s = '987654321' > >>> odd = '' > >>> for c in s[::-2]: > ... odd = c + odd > ... > >>> s = s[:-1] > >>> even = '' > >>> for c in s[::-2]: > ... even = c + even > ... > >>> odd > '97531' > >>> even > '8642' > >>>>>>> > > Is there a better (i.e. more Pythonic) way to do this? > > Thanks in advance for all your help. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > -Quarry worker's creed > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From carroll at tjc.com Thu Apr 20 16:02:54 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 20 Apr 2006 07:02:54 -0700 (PDT) Subject: [Tutor] Version of a .pyc file In-Reply-To: Message-ID: On Wed, 19 Apr 2006, Don Taylor wrote: > But my underlying problem still occurs: somewhere somebody is calling > for the 2.3 version of the Python vm .dll and not finding it. This is > happening under Pydev/Eclipse and my only recourse is to blow Eclipse > away using Task Manager. Don -- I've had some pretty good luck using Process Explorer, freeware from SysInternals, to locate processes that are using a particular file or DLL and shutting them down. I don't know how well that will work for you, because it might just ID Eclipse as the culprit, with no further information, and you already know that. But its tree view may give you more info. It's a great utility in any event. http://www.sysinternals.com/Utilities/ProcessExplorer.html I'm gathering from the reference to DLLs that you're running under Windows. If I misunderstand, ignore this; Process Explorer is for Windows. From mhansen at cso.atmel.com Thu Apr 20 17:23:00 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 20 Apr 2006 09:23:00 -0600 Subject: [Tutor] Tutor FAQ? Message-ID: <001701c6648e$4f401050$28645f0a@mikehansen> I'd like to send a big Thank You to Danny, Alan, Kent and others(whos names escape me) for being such an asset to the Python community by relentlessly answering questions on the tutor list.(Do these guys sleep? They must work in shifts.) This list is one of the most civilized and responsive lists I have ever read. When many pop onto the list and ask what may seem like some of the most obvious questions, you guys calmly answer and nudge them in the right direction without ever losing your patience. It's a great list. Anyway, I've been reading the list for a couple of years now, and I wonder if a Tutor FAQ would be helpful. I don't believe one exists. Should there be something on the Python wiki that would list the most common questions to the tutor list along with their answers? It would be a FAQ about the tutor list as well as common questions to the tutor list. FAQ about the Tutor List would include - The policy on answering homework assignment - Why the reply-to is set that way. - Post code and exact error message. (A lot of this might be in that initial message you get from mailman when joining the list, but it might be a good idea to put it on the wiki) FAQ for common questions to the list would include - ord() and chr() - Common GUI programming questions - String module is deprecated, use string methods - ??? I'm sure you can come up with more of the common questions. Does this sound like a reasonable idea? Mike From alan.gauld at freenet.co.uk Thu Apr 20 17:31:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 20 Apr 2006 16:31:04 +0100 Subject: [Tutor] Use iterator to refer to an object's attribute? References: <9690-16163@sneakemail.com> <00a301c66453$730e0680$0a01a8c0@xp> <18029-47793@sneakemail.com> Message-ID: <00ca01c6648f$700a9340$0a01a8c0@xp> > Dictionaries are only pairs of data. I assume a list can be one of > those elements, but I couldn't figure out how to make it work in the > structure I presented. Yes, the object that is stored can be anything. Thus >>> numList = [1,2,3] >>> chrList = ['1','2','3'] >>> numDict = {} >>> numDict['asNum'] = numList >>> numDict['asChr'] = chrList >>> for item in numDict['asNum']: print item, ... 1 2 3 >>> shows two lists being stored in a dictionary. You can also store instances of classes or functions or even the classes themselves! > I wanted to make the methods flexible enough that I wouldn't have to > edit every method if the module list ever changed. I guess I don't > understand how a dictionary works in this situation. I don;t understand what you don;t understand here. Can you expand on why you don't think a dictionary would work? >> Why not write constructors that take a list as a parameter. >> The constructor can manage its own list and the higher >> level constructor just passes in the appropriate list. That way >> each class only needs to know about the data at the level >> it is responsible for. So the Module class might look a bit like: >> >> class Module: >> def __init__(self, name, componentlist): >> self.components = {} >> self.name = name >> for component in componentlist: >> self.components[component[0]] = Component(component) >> >> This implies that the component list is structured as a list of tuples. > > I originally had tuples, but you can't access individual elements. What makes you think so? >>> t = (1,2,3) >>> print t[0] 1 >>> The only thing you can't do is alter the data in the tuple - which is exactly the behaviour you want if reading the tuple from a config file! >>> I have object "db.mb". I have iterator "shortmod" with a value of >>> "mb". Why can't I call "db.shortmod"? >> >> You can use db.getattr(shortmod) > > That doesn't work. It tells me "Database instance has no attribute > 'getattr'". Its actually a special method so needs the underscores __getattr__ and accessed via a function. I got my syntax muddled: getattr(db, shortmod) is how it should be written. >> but I think its easier and clearer in this case to use: >> >> db.Modules[shortmod] > > If Modules is a class name, how am I able to call it like that? Modules is a dictionary of Modules in the db object. I should probably have used the example from my Module class above: myModule.components[compname] > "AttributeError: Database instance has no attribute 'Modules'" You will need to modify the definition of the database class to have the Modules dictionary first! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tinoloc at gmail.com Thu Apr 20 17:37:48 2006 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 20 Apr 2006 11:37:48 -0400 Subject: [Tutor] Config file parsing Message-ID: Hi Everybody, Before I start reinventing the wheel, is there any code out there for parsing configuration filesn in paragraph format. I am creating a multi-process monitor that will read in a configuration file that will contain the processes that they will monitor also what to do when they get get an alert. Below is an example of what I envision the configure file to look like apache { process=/usr/bin/httpd processNum = 8 whenDown = "Apache is totally down" whenDegraded = "Apache has degraded (one or more processes has gone away" whenUp = "Apache is up" severityDown=1 severityDegraded=3 severityUp=5 .... etc .... } Thanks in advance, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060420/359eae4a/attachment.html From kent37 at tds.net Thu Apr 20 18:34:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 12:34:58 -0400 Subject: [Tutor] Tutor FAQ? In-Reply-To: <001701c6648e$4f401050$28645f0a@mikehansen> References: <001701c6648e$4f401050$28645f0a@mikehansen> Message-ID: <4447B832.10002@tds.net> Mike Hansen wrote: > I'd like to send a big Thank You to Danny, Alan, Kent and others(whos names > escape me) for being such an asset to the Python community by relentlessly > answering questions on the tutor list.(Do these guys sleep? They must work > in shifts.) This list is one of the most civilized and responsive lists I > have ever read. When many pop onto the list and ask what may seem like some > of the most obvious questions, you guys calmly answer and nudge them in the > right direction without ever losing your patience. It's a great list. Thanks! I do sleep but I have my email tied in to my clock radio so whenever an email arrives on the tutor list I am awakened to answer it ;) > > Anyway, I've been reading the list for a couple of years now, and I wonder > if a Tutor FAQ would be helpful. I don't believe one exists. Should there be > something on the Python wiki that would list the most common questions to > the tutor list along with their answers? It would be a FAQ about the tutor > list as well as common questions to the tutor list. I wonder about this sometimes too. I think it would be good to have a place to collect this stuff. Maybe this could be integrated with the main Python FAQ in a beginner's section? Fredrik Lundh is experimenting with a FAQ wiki here: http://pyfaq.infogami.com/ > > FAQ about the Tutor List would include > - The policy on answering homework assignment > - Why the reply-to is set that way. > - Post code and exact error message. > (A lot of this might be in that initial message you get from mailman when > joining the list, but it might be a good idea to put it on the wiki) > > FAQ for common questions to the list would include > - ord() and chr() > - Common GUI programming questions > - String module is deprecated, use string methods > - ??? > > I'm sure you can come up with more of the common questions. Does this sound > like a reasonable idea? Sounds good to me. Are you volunteering? Kent From kent37 at tds.net Thu Apr 20 18:42:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 12:42:51 -0400 Subject: [Tutor] Config file parsing In-Reply-To: References: Message-ID: <4447BA0B.8060208@tds.net> Tino Dai wrote: > Hi Everybody, > > Before I start reinventing the wheel, is there any code out there > for parsing configuration filesn in paragraph format. I am creating a > multi-process monitor that will read in a configuration file that will If you have control over the config file format you can use ConfigParser in the standard lib. It reads .ini style files so you would write [apache] process=/usr/bin/httpd ...etc You could also use one of the add-on config file readers which have more features, for example http://voidspace.org.uk/python/modules.shtml#configobj Another option is to make your config file be a Python module that you just import. What you wrote is pretty close to dictionary syntax. You could use this: config = dict( apache = dict( process = '/usr/bin/httpd', # etc ) ) The syntax is not quite as user friendly but reading it is as easy as 'import config' Kent > contain the processes that they will monitor also what to do when they > get get an alert. Below is an example of what I envision the configure > file to look like > > apache { > process=/usr/bin/httpd > processNum = 8 > whenDown = "Apache is totally down" > whenDegraded = "Apache has degraded (one or more processes has gone away" > whenUp = "Apache is up" > severityDown=1 > severityDegraded=3 > severityUp=5 > .... etc .... > } > > Thanks in advance, > Tino > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Barry.Carroll at psc.com Thu Apr 20 18:49:28 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 20 Apr 2006 09:49:28 -0700 Subject: [Tutor] FW: Splitting a number into even- and odd- numbered digits Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C365E@eugsrv400.psc.pscnet.com> Greetings: First of all, thanks to those who contributed suggestions. Unfortunately, my description was incomplete. > I am writing a function that accepts a string of decimal digits, > calculates a checksum and returns it as a single character string. > The first step in the calculation is to split the input into two strings: > the even- and odd- numbered digits, respectively. The least significant > digit is defined as odd. I forgot to include two important requirements: 1. the length of the input string is arbitrary, 2. the order of the digits must be maintained. I could not find a way to include these requirements in a single, simple expression. I decided to make an explicit test for string length, which simplified matters. I came up with this: >>>>>>> >>> def odd_even(x): ... if len(x) % 2 == 1: ... return x[::2], x[1::2] ... else: ... return x[1::2], x[::2] >>> odd_even('987654321') ('97531', '8642') >>> odd_even('98765432') ('8642', '9753') >>> >>>>>>> which is an improvement, I think, on my original. > >>>>>>> > >>> s = '987654321' > >>> odd = '' > >>> for c in s[::-2]: > ... odd = c + odd > ... > >>> s = s[:-1] > >>> even = '' > >>> for c in s[::-2]: > ... even = c + even > ... > >>> odd > '97531' > >>> even > '8642' > >>>>>>> Thanks again. This is the most useful list I've ever found. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From ewalker at micron.com Thu Apr 20 18:50:23 2006 From: ewalker at micron.com (Eric Walker) Date: Thu, 20 Apr 2006 10:50:23 -0600 Subject: [Tutor] Tutor FAQ? In-Reply-To: <4447B832.10002@tds.net> References: <001701c6648e$4f401050$28645f0a@mikehansen> <4447B832.10002@tds.net> Message-ID: <4447BBCF.1070003@micron.com> Kent Johnson wrote: > Mike Hansen wrote: > >> I'd like to send a big Thank You to Danny, Alan, Kent and others(whos names >> escape me) for being such an asset to the Python community by relentlessly >> answering questions on the tutor list.(Do these guys sleep? They must work >> in shifts.) This list is one of the most civilized and responsive lists I >> have ever read. When many pop onto the list and ask what may seem like some >> of the most obvious questions, you guys calmly answer and nudge them in the >> right direction without ever losing your patience. It's a great list. >> > > Thanks! I do sleep but I have my email tied in to my clock radio so > whenever an email arrives on the tutor list I am awakened to answer it ;) > >> Anyway, I've been reading the list for a couple of years now, and I wonder >> if a Tutor FAQ would be helpful. I don't believe one exists. Should there be >> something on the Python wiki that would list the most common questions to >> the tutor list along with their answers? It would be a FAQ about the tutor >> list as well as common questions to the tutor list. >> > > I wonder about this sometimes too. I think it would be good to have a > place to collect this stuff. > > Maybe this could be integrated with the main Python FAQ in a beginner's > section? Fredrik Lundh is experimenting with a FAQ wiki here: > http://pyfaq.infogami.com/ > > >> FAQ about the Tutor List would include >> - The policy on answering homework assignment >> - Why the reply-to is set that way. >> - Post code and exact error message. >> (A lot of this might be in that initial message you get from mailman when >> joining the list, but it might be a good idea to put it on the wiki) >> >> FAQ for common questions to the list would include >> - ord() and chr() >> - Common GUI programming questions >> - String module is deprecated, use string methods >> - ??? >> >> I'm sure you can come up with more of the common questions. Does this sound >> like a reasonable idea? >> > > Sounds good to me. Are you volunteering? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hey guys the FAQ thing sound great. I found what I think is the best pyQT tutorial around. Took me like 10 minutes and I am off and running. http://www.cs.usfca.edu/~afedosov/qttut/ -------------- next part -------------- A non-text attachment was scrubbed... Name: ewalker.vcf Type: text/x-vcard Size: 176 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060420/cf083795/attachment.vcf From Barry.Carroll at psc.com Thu Apr 20 18:55:26 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 20 Apr 2006 09:55:26 -0700 Subject: [Tutor] Splitting a number into even- and odd- numbered digits Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C365F@eugsrv400.psc.pscnet.com> Greetings: First of all, thanks to those who contributed suggestions. Unfortunately, my description was incomplete. > I am writing a function that accepts a string of decimal digits, > calculates a checksum and returns it as a single character string. > The first step in the calculation is to split the input into two strings: > the even- and odd- numbered digits, respectively. The least significant > digit is defined as odd. I forgot to include two important requirements: 1. the length of the input string is arbitrary, 2. the order of the digits must be maintained. I could not find a way to include these requirements in a single, simple expression. I decided to make an explicit test for string length, which simplified matters. I came up with this: >>>>>>> >>> def odd_even(x): ... if len(x) % 2 == 1: ... return x[::2], x[1::2] ... else: ... return x[1::2], x[::2] >>> odd_even('987654321') ('97531', '8642') >>> odd_even('98765432') ('8642', '9753') >>> >>>>>>> which is an improvement, I think, on my original. > >>>>>>> > >>> s = '987654321' > >>> odd = '' > >>> for c in s[::-2]: > ... odd = c + odd > ... > >>> s = s[:-1] > >>> even = '' > >>> for c in s[::-2]: > ... even = c + even > ... > >>> odd > '97531' > >>> even > '8642' > >>>>>>> Thanks again. This is the most useful list I've ever found. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From Barry.Carroll at psc.com Thu Apr 20 19:01:41 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 20 Apr 2006 10:01:41 -0700 Subject: [Tutor] Splitting a number into even- and odd- numbered digits Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3660@eugsrv400.psc.pscnet.com> Greetings: Unfortunately, my problem description was incomplete. I forgot to include two important requirements: 1. the length of the input string is arbitrary, 2. the order of the digits must be maintained. I could not find a way to include these requirements in a single, simple expression. I decided to make an explicit test for string length, which simplified matters. I came up with this: >>>>>>> >>> def odd_even(x): ... if len(x) % 2 == 1: ... return x[::2], x[1::2] ... else: ... return x[1::2], x[::2] >>> odd_even('987654321') ('97531', '8642') >>> odd_even('98765432') ('8642', '9753') >>> >>>>>>> which is an improvement, I think, on my original. Thanks to those who provided suggestions. This is the most useful list I've ever found. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From carroll at tjc.com Thu Apr 20 19:14:23 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 20 Apr 2006 10:14:23 -0700 (PDT) Subject: [Tutor] FW: Splitting a number into even- and odd- numbered digits In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C365E@eugsrv400.psc.pscnet.com> Message-ID: On Thu, 20 Apr 2006, Carroll, Barry wrote: > > The first step in the calculation is to split the input into two > strings: > > the even- and odd- numbered digits, respectively. The least > significant > > digit is defined as odd. > > I forgot to include two important requirements: > > 1. the length of the input string is arbitrary, > 2. the order of the digits must be maintained. > > I could not find a way to include these requirements in a single, simple > expression. I really liked John Fouhy's approach, or at least a variation of it: >>> def odd_even(s): ... ''' ... Returns a tuple of two strings taken from s. The first string is ... the odd-numbered characters (counting from the right), and the ... second is the even-numbered characters. ... ''' ... return (s[::-2][::-1], s[-2::-2][::-1]) ... >>> odd_even("1234567") ('1357', '246') >>> odd_even("2345") ('35', '24') >>> odd_even("1") ('1', '') >>> John's original solution returned values with the digits in reverse order; but that's easily changed by reslicing each string with [::-1]. From alan.gauld at freenet.co.uk Thu Apr 20 19:26:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 20 Apr 2006 18:26:42 +0100 Subject: [Tutor] Tutor FAQ? References: <001701c6648e$4f401050$28645f0a@mikehansen> Message-ID: <00ee01c6649f$978bff70$0a01a8c0@xp> > I'd like to send a big Thank You to Danny, Alan, Kent and others Over the years there have been many, some have moved from tutor list to c.l.python others have just got too busy. Others reappear and then disappear again at intervals. (Who remembers Ivan, Gregor, Magnus etc etc.) > answering questions on the tutor list.(Do these guys sleep? They must work > in shifts.) I live in the UK, Kent and Danny in the US so that gives a 5-7 hour time shift for free! :-) > if a Tutor FAQ would be helpful. I don't believe one exists. It's been discussed several times but no-one ever quite got round to it. If you want to make a worthwhile contribution to the Python community that would be a good starting point! My tutor tries to answer the most common questions but its not so easy to findthe answers when buried inside a prose topic page. > the tutor list along with their answers? It would be a FAQ about the tutor > list as well as common questions to the tutor list. Agreed. > FAQ about the Tutor List would include > FAQ for common questions to the list would include > > I'm sure you can come up with more of the common questions. And then "all" it takes is someone to collate them and provide the answers. The Active State searchable artchive should be a good starting point. > like a reasonable idea? Absolutely, are you volunteering? :-) Alan G. From mhansen at cso.atmel.com Thu Apr 20 19:56:16 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 20 Apr 2006 11:56:16 -0600 Subject: [Tutor] Tutor FAQ? In-Reply-To: <4447B832.10002@tds.net> Message-ID: <000a01c664a3$b8ca9990$28645f0a@mikehansen> > Thanks! I do sleep but I have my email tied in to my clock > radio so whenever an email arrives on the tutor list I am > awakened to answer it ;) Hmmm.. I wouldn't be surprised if there's an X10 module that does that. =) [...] > Maybe this could be integrated with the main Python FAQ in a > beginner's section? Fredrik Lundh is experimenting with a FAQ > wiki here: > http://pyfaq.infogami.com/ I'll take a look at this. > Sounds good to me. Are you volunteering? Yes, I'll get the ball rolling. I'll most likely do something on the site above. I'll post to this list when I have something worth looking at. Mike From Barry.Carroll at psc.com Thu Apr 20 20:09:28 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 20 Apr 2006 11:09:28 -0700 Subject: [Tutor] Apology (Was: Re: Splitting a number into even- and odd- numbered digits) Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3661@eugsrv400.psc.pscnet.com> Greetings: > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of tutor-request at python.org > Sent: Thursday, April 20, 2006 10:57 AM > To: tutor at python.org > Subject: Tutor Digest, Vol 26, Issue 71 > <> > > Today's Topics: > > 1. Re: Config file parsing (Kent Johnson) > 2. FW: Splitting a number into even- and odd- numbered digits > (Carroll, Barry) > 3. Re: Tutor FAQ? (Eric Walker) > 4. Re: Splitting a number into even- and odd- numbered digits > (Carroll, Barry) > 5. Re: Splitting a number into even- and odd- numbered digits > (Carroll, Barry) > 6. Re: FW: Splitting a number into even- and odd- numbered > digits (Terry Carroll) > 7. Re: Tutor FAQ? (Alan Gauld) > 8. Re: Tutor FAQ? (Mike Hansen) > <> > I apologize for the multiple postings. The first two resulted in this reply: > From: postmaster at ec.se [mailto:postmaster at ec.se] > Sent: Thursday, April 20, 2006 9:55 AM > To: Carroll, Barry > Subject: RE: [Tutor] FW: Splitting a number into even- and odd- numbered > digits > > MDaemon has indentified your message as spam. It will not be delivered. > > From : tutor-bounces at python.org > To : een673 at ec.se > Subject : ***SPAM*** Score/Req: 10.0/9.0 - [Tutor] FW: Splitting a > number into even- and odd- numbered digits > Message-ID: > <2BBAEE949D384D40A2B851287ADB6A432C365E at eugsrv400.psc.pscnet.com> > > Yes, score=10.0 required=9.0 tests=BAYES_99 autolearn=no version=3.0.4 > ********** > * 10 BAYES_99 BODY: Bayesian spam probability is 99 to 100% * > [score: 0.9972] Taking the message at its word, I resent the post. I don't know what triggered the response, or why the posts were delivered anyway. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From dyoo at hkn.eecs.berkeley.edu Thu Apr 20 20:15:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 20 Apr 2006 11:15:56 -0700 (PDT) Subject: [Tutor] Parsing html user HTMLParser In-Reply-To: <44473EA7.6030807@khmeros.info> References: <44473EA7.6030807@khmeros.info> Message-ID: > I need help here, I'm struggling with html parsing method, up until now > I can only put and html file as instance. I have no experience with > this, I want to read the childs inside this document and modify the > data. What can I do if I start from here? Hi Titvirak, You might want to take a look at a different module for parsing HTML. A popular one is BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Their quick-start page shows how to do simple stuff. There are a few oddities with BeautifulSoup, but on the whole, it's pretty good. Good luck to you! From Barry.Carroll at psc.com Thu Apr 20 20:24:35 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 20 Apr 2006 11:24:35 -0700 Subject: [Tutor] Tutor Digest, Vol 26, Issue 71 Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3663@eugsrv400.psc.pscnet.com> Terry: > -----Original Message----- > Date: Thu, 20 Apr 2006 10:14:23 -0700 (PDT) > From: Terry Carroll > Subject: Re: [Tutor] FW: Splitting a number into even- and odd- > numbered digits > To: tutor at python.org > Message-ID: > > Content-Type: TEXT/PLAIN; charset=US-ASCII > <> > > > > I could not find a way to include these requirements in a single, simple > > expression. > > I really liked John Fouhy's approach, or at least a variation of it: > > >>> def odd_even(s): > ... ''' > ... Returns a tuple of two strings taken from s. The first string is > ... the odd-numbered characters (counting from the right), and the > ... second is the even-numbered characters. > ... ''' > ... return (s[::-2][::-1], s[-2::-2][::-1]) > ... > >>> odd_even("1234567") > ('1357', '246') > >>> odd_even("2345") > ('35', '24') > >>> odd_even("1") > ('1', '') > >>> > > John's original solution returned values with the digits in reverse > order; but that's easily changed by reslicing each string with [::-1]. By golly you're right! That is a very slick solution. It didn't occur to me to re-reverse the strings like that. Thanks to both you and John. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From 9bh4frs02 at sneakemail.com Thu Apr 20 20:37:34 2006 From: 9bh4frs02 at sneakemail.com (Ron Britton) Date: Thu, 20 Apr 2006 11:37:34 -0700 Subject: [Tutor] Use iterator to refer to an object's attribute? In-Reply-To: References: Message-ID: <15954-04931@sneakemail.com> >> I wanted to make the methods flexible enough that I wouldn't have to >> edit every method if the module list ever changed. I guess I don't >> understand how a dictionary works in this situation. > > I don;t understand what you don;t understand here. Can you expand on > why you don't think a dictionary would work? This remark was based on one of my earlier designs. It didn't work there, so I abandoned dictionaries. The library reference says: "Only values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys." This added to the problem, at least in the design I attempted it in. >> I originally had tuples, but you can't access individual elements. > > What makes you think so? > >>>> t = (1,2,3) >>>> print t[0] > 1 I didn't work before when I used it as an index. Now it does. I must have done something different originally. But you are right. This works: >>> mylist = ['one', 'two', 'three'] >>> t = (0,1,2) >>> print mylist[t[0]] one >>>> I have object "db.mb". I have iterator "shortmod" with a value of >>>> "mb". Why can't I call "db.shortmod"? >>> >>> You can use db.getattr(shortmod) >> That doesn't work. It tells me "Database instance has no attribute >> 'getattr'". > > Its actually a special method so needs the underscores __getattr__ > and accessed via a function. I got my syntax muddled: > > getattr(db, shortmod) > > is how it should be written. That works! I knew there had to be a way! Thanks for the help! Ron From ml.cyresse at gmail.com Thu Apr 20 23:21:59 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 21 Apr 2006 09:21:59 +1200 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: <5e1ceb8a0604200657o2f566ce1x78fb65d826f4a8c5@mail.gmail.com> References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> <5e1ceb8a0604191637u2a942605qa07132735e6022f2@mail.gmail.com> <5e1ceb8a0604191638u5b53867n4ebe57d058be77fd@mail.gmail.com> <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> <5e1ceb8a0604200657o2f566ce1x78fb65d826f4a8c5@mail.gmail.com> Message-ID: Trick is, to limit them very carefully by specifying what they are to match. Watch .* - I always use .*? myself. For instance, for one of your strings, which ends with the ESC=k(some whitespace or not)0 \x1b.*?0 would certainly match that, but it'd also match ESC foo ### # ESC=#k0 Whereas \x1b\=.k\w*?0 would match it far more precisely, because that's the regex for esc=k0 *excluding \n unless the flag re.DOTALL is used. So yeah; something else to note, certain characters need to be escaped in regex strings. Namely, these ones - .^$*+?{[|( That second to last one is a pipe by the way, not an I. And * is very greedy, but a ? limits it's greediness greatly. Good luck, Liam Clarke On 4/21/06, doug shawhan wrote: > I am discovering that. They tend to get all Ayn Rand on you and grab too > much. :-) > > > On 4/20/06, Liam Clarke wrote: > > Yeah, Alan's tutorial is what I used to learn how to code, it's very good. > > Regexes are very powerful; which can be a very good thing and a very > > bad thing. ;) > > > > Good luck. > > > > On 4/20/06, doug shawhan wrote: > > > Got it! Thanks! Mr. Gald hooked me up with his re tutorial as well. > Great! > > > > > > > > > On 4/19/06, Liam Clarke wrote: > > > > Here's my copy, it should work if you have Tkinter. > > > > > > > > Good luck! > > > > > > > > On 4/20/06, doug shawhan wrote: > > > > > Drat, I installed from the OpenBSD ports tree and this is not > included. > > > I'll > > > > > scout around on the net. > > > > > > > > > > Thanks again! > > > > > > > > > > > > > > > On 4/19/06, doug shawhan < doug.shawhan at gmail.com> wrote: > > > > > > > > > > > > Holy moley. > > > > > > > > > > > > Thanks! > > > > > > > > > > > > > > > > > > > > > > > > On 4/19/06, Liam Clarke < ml.cyresse at gmail.com> wrote: > > > > > > > Hi Doug, > > > > > > > > > > > > > > Best tip ever is > > > > > your_python_dir\tools\scripts\redemo.py > > > > > > > > > > > > > > Interactive regexes. :) > > > > > > > > > > > > > > This is pretty good as well - > > > > > http://www.amk.ca/python/howto/regex/ > > > > > > > > > > > > > > Good luck, > > > > > > > > > > > > > > Liam Clarke > > > > > > > > > > > > > > On 4/20/06, doug shawhan < doug.shawhan at gmail.com> wrote: > > > > > > > > I think I'm going to have to suck it up and learn some regular > > > > > expressions. > > > > > > > > > > > > > > > > I have finally gotten my script (using the excellent pyserial > > > module) > > > > > to > > > > > > > > behave. Most of my troubles as enumerated here before were > utterly > > > > > > > > self-induced. Apparently one cannot watch the execution of > one's > > > > > script > > > > > > > > through another program without affecting it's outcome in > > > unforseen > > > > > ways. > > > > > > > > (Sound familiar Herr Schroedinger? :-) > > > > > > > > > > > > > > > > Now that I am actually extracting data in a fairly > predictable > > > way, I > > > > > am at > > > > > > > > the point where I need to parse it! I have some output here > > > (modified > > > > > to > > > > > > > > show the ESC and NUL characters.) > > > > > > > > > > > > > > > > When I pull data from the port, the remote computer sends it > in > > > one > > > > > long > > > > > > > > string per screen: newlines are not painted in by using the > > > expected > > > > > x\0a > > > > > > > > that I had hoped for! No easy readlines() fun for me. Instead > I > > > get: > > > > > > > > > > > > > > > > ESC=( 1. ESC=($4x2, 6-239 ( 3.9L) > > > > > > > > > > > ..........................................ESC=(a03252 > > > > > > > > ESC=(k0 > > > > > > > > ESC=) 2. ESC=))8-318 ( 5.2L) > > > > > > > > > > > ..........................................ESC=)a03242 > > > > > > > > ESC=)k0 > > > > > > > > ESC=* 3. ESC=*)8-360 ( 5.9L) > > > > > > > > > > > ..........................................ESC=*a03351 > > > > > > > > ESC=*k 0 > > > > > > > > ESC=+ 4. ESC=+$4x4, 6-239 ( 3.9L) > > > > > > > > > > > ..........................................ESC=+a03240 > > > > > > > > ESC=+k 0 > > > > > > > > ESC=, 5. ESC=,)8-318 (5.2L) > > > > > > > > > > > ..........................................ESC=,a03243 > > > > > > > > ESC=,k 0 > > > > > > > > ESC=- 6. ESC=-)8-360 ( 5.9L) > > > > > > > > > > > ..........................................ESC=-a03352 > > > > > > > > ESC=-k 0 > > > > > > > > ESC=. 7. ESC=.aCH8299 ESCTNULESC)NULESC=% > > > > > LINEESCTNULESC=& R = > > > > > > > > RELIST = NONE > > > > > > > > > > > > > > > > I have broken it up for ease of viewing. I need to split the > > > string > > > > > where > > > > > > > > ESC= , k and 0 are found, but ESC= ,k and 0 are seperated by > > > various > > > > > > > > spaces, parentheis and other characters that are apparently > used > > > to > > > > > mark the > > > > > > > > end of the line until the next ESC is found, thereby > displaying a > > > new > > > > > line > > > > > > > > (note how the character after the first ESC on each line is > > > repeated > > > > > after > > > > > > > > the ESC on the end. > > > > > > > > > > > > > > > > I cannot for the life of me figure out a pythonic way (read: > > > using > > > > > the > > > > > > > > split() builtin) to scan for instances of these characters in > such > > > and > > > > > such > > > > > > > > order and proximity. I know this is what regex is for, but I > have > > > no > > > > > > > > experience. I have obtained a copy of "Mastering Regular > > > Expressions" > > > > > but > > > > > > > > thought I would inquire here first for caveats and tips as the > > > book is > > > > > > > > larger than my brain, and I haven't used the re module, ever. > > > > > > > > > > > > > > > > Why in the world does this make me so happy? :-)~ > > > > > > > > > > > > > > > > > _______________________________________________ > > > > > > > > Tutor maillist - Tutor at python.org > > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > From kent37 at tds.net Thu Apr 20 23:34:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Apr 2006 17:34:03 -0400 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> <5e1ceb8a0604191637u2a942605qa07132735e6022f2@mail.gmail.com> <5e1ceb8a0604191638u5b53867n4ebe57d058be77fd@mail.gmail.com> <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> <5e1ceb8a0604200657o2f566ce1x78fb65d826f4a8c5@mail.gmail.com> Message-ID: <4447FE4B.5050507@tds.net> Liam Clarke wrote: > Whereas \x1b\=.k\w*?0 would match it far more precisely, because > that's the regex for > > esc=k0 Slight correction: \w means any 'Word' character - alphanumeric plus underscore. \s matches whiteSpace. Kent From ml.cyresse at gmail.com Fri Apr 21 00:06:16 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 21 Apr 2006 10:06:16 +1200 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: <4447FE4B.5050507@tds.net> References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> <5e1ceb8a0604191637u2a942605qa07132735e6022f2@mail.gmail.com> <5e1ceb8a0604191638u5b53867n4ebe57d058be77fd@mail.gmail.com> <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> <5e1ceb8a0604200657o2f566ce1x78fb65d826f4a8c5@mail.gmail.com> <4447FE4B.5050507@tds.net> Message-ID: Argh, Kent's right. In my defense, I've only had one coffee so far. On 4/21/06, Kent Johnson wrote: > Liam Clarke wrote: > > Whereas \x1b\=.k\w*?0 would match it far more precisely, because > > that's the regex for > > > > esc=k0 > > Slight correction: \w means any 'Word' character - alphanumeric plus > underscore. \s matches whiteSpace. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Fri Apr 21 00:08:57 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 21 Apr 2006 10:08:57 +1200 Subject: [Tutor] GUI In-Reply-To: <66F85FA283D3FE40988AD74B4B209C0601C4D923@PRDEXCH03.ad.dmv.ca.gov> References: <66F85FA283D3FE40988AD74B4B209C0601C4D923@PRDEXCH03.ad.dmv.ca.gov> Message-ID: Tkinter is simpler to use, wxPython is far more powerful but a bit harder to learn. It's based on the C++ library wxWidgets, and sometimes the abstraction leaks a bit, but this is just my opinion. Check out pythoncard though, it simplifies wx development dramatically; even has a drag and drop interface; but you can still use wxPython method calls and objects directly if Pythoncard doesn't do what you want. Regards, Liam Clarke On 4/20/06, Valone, Toren W. wrote: > So I have been how does wxPython measure to Tkinter or vice versa? > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Liam Clarke > Sent: Wednesday, April 19, 2006 3:25 PM > To: R. Alan Monroe > Cc: Python[Tutor] > Subject: Re: [Tutor] GUI > > Hmm? How so? I'm using a whole lot of raw wxPython mixed with > Pythoncard for a project, and the entire process sits at 7Mb RAM usage > idle. WinXP btw. > > Considering my small command line appns to start/stop Windows services > written in C use just over 1Mb, 7Mb isn't overly bad. > > The other good thing about wxPython is stuff like Pythoncard and Wax, > although development on Pythoncard seems to have slowed right down, > Kevin Altis got busy, I guess; Wax is nice looking but... not very > well documented... It's great being able to use Pythoncard for the not > overly complicated stuff, but with the wxPython still lurking beneath > the surface. > > Regards, > > Liam Clarke > > On 4/20/06, R. Alan Monroe wrote: > > >> If I can get it for free, I might as well go with say wxPython. > Thanks > > > > > Yes, free as in beer, as in speech, and cross platform. Oh, and > better > > > documented. > > > > Sadly, you still pay for it in RAM usage :^) > > > > Alan > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nospamformeSVP at gmail.com Fri Apr 21 03:29:16 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Thu, 20 Apr 2006 21:29:16 -0400 Subject: [Tutor] Version of a .pyc file In-Reply-To: <4446FA94.4020008@tds.net> References: <4446FA94.4020008@tds.net> Message-ID: Kent Johnson wrote: > Don Taylor wrote: > >>Finally, are there any other possible file extension types that I should >>be looking at? > > > .pyo is like a .pyc but compiled with optimizations on. > Hi Kent: No, I really meant a .pyd file which is Python's name for a .dll which conforms to the Python requirements to be a Python extension written in C/C++. But, I should check my .pyo files as well so thanks for this. Don. From nospamformeSVP at gmail.com Fri Apr 21 03:31:02 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Thu, 20 Apr 2006 21:31:02 -0400 Subject: [Tutor] Version of a .pyc file In-Reply-To: References: Message-ID: Terry Carroll wrote: > On Wed, 19 Apr 2006, Don Taylor wrote: > > >>But my underlying problem still occurs: somewhere somebody is calling >>for the 2.3 version of the Python vm .dll and not finding it. This is >>happening under Pydev/Eclipse and my only recourse is to blow Eclipse >>away using Task Manager. > > > Don -- > I've had some pretty good luck using Process Explorer, freeware from > SysInternals, to locate processes that are using a particular file or DLL > and shutting them down. I don't know how well that will work for you, > because it might just ID Eclipse as the culprit, with no further > information, and you already know that. But its tree view may give you > more info. > > It's a great utility in any event. > > http://www.sysinternals.com/Utilities/ProcessExplorer.html > > I'm gathering from the reference to DLLs that you're running under > Windows. If I misunderstand, ignore this; Process Explorer is for Windows. > Terry: Yes I am using Windows so I will take a look at Process Explorer. Thanks, Don. From intermezzoooh at gmail.com Fri Apr 21 04:40:20 2006 From: intermezzoooh at gmail.com (Jesse) Date: Thu, 20 Apr 2006 20:40:20 -0600 Subject: [Tutor] A simple solution to the even/odd problem Message-ID: Hey, I'm a Python newbie, and I'm not even sure I've correctly interpreted the problem, but from what I gather the idea is to take an integer with an arbitrary number of digits and return two [strings/lists/tuples/whatever]: one containing all of the odd digits, and another containing all of the even digits. This should work: def make_string(words): string = " " for x in words: string = string + x + " " return string def even_odd(num): even = [] odd = [] num_string = str(num) for x in num_string: a = int(x) if a%2 == 0: even.append(x) else: odd.append(x) odd_string = make_string(odd) even_string = make_string(even) return (odd_string, even_string) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060420/adc6b1c3/attachment.html From justin.mailinglists at gmail.com Fri Apr 21 06:42:17 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 21 Apr 2006 12:42:17 +0800 Subject: [Tutor] pyExcelerator for Python 2.3 In-Reply-To: <44478C41.5060405@pooryorick.com> References: <3c6718980604200226m7bb2f235l16036bdfca834258@mail.gmail.com> <44478C41.5060405@pooryorick.com> Message-ID: <3c6718980604202142n7b38c4d9r16c6a2dd0b0d8fc7@mail.gmail.com> > there is a patch submitted there that you can apply to the current > release to make it compatible with >2.4. Thanks lots Poor Yorick. From ryan_gm at sbcglobal.net Fri Apr 21 09:03:51 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Fri, 21 Apr 2006 00:03:51 -0700 (PDT) Subject: [Tutor] Bug in python, or is it just 3am Message-ID: <20060421070351.21492.qmail@web80807.mail.yahoo.com> Hey everyone, i believe i might have found a bug in python? im not sure, heres a screen shot. http://img151.imageshack.us/img151/4268/pythonbug8by.jpg When i type number + 1 and print it, It adds one, But when i use a number = number + 1 right after the value stays the same, Now i thought that number = number + 1 just wasn't vailed in python untill i tried it again and it worked, Is this a bug or im i just missing somthing, Cause it is rather late. From ryan_gm at sbcglobal.net Fri Apr 21 09:11:18 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Fri, 21 Apr 2006 00:11:18 -0700 (PDT) Subject: [Tutor] Bug in python, or is it just 3am Message-ID: <20060421071118.43456.qmail@web80828.mail.yahoo.com> HA! ignore me, im stupid, XD i knew i should have waited untill morning =P, No bug, the number = number was just point to the old number which was one number lower, sorry. night =P.... Oh i see someone replied -_- sorry lol From r.arunchand at gmail.com Fri Apr 21 09:29:07 2006 From: r.arunchand at gmail.com (arun) Date: Fri, 21 Apr 2006 12:59:07 +0530 Subject: [Tutor] Invoking Excel Macro Message-ID: <8e82677d0604210029h16facfd9ja0a4c45e97a7bc6f@mail.gmail.com> Hi, I tried invoking a macro from my python script and It is throwing an error message that reads 'Run-time error 1004': "This operation requires the merged cells to be identically sized" My script looks like this from win32com.client import Dispatch xl = Dispatch('Excel.Application') xl.Workbooks.Add('E:\Templates\sample.xls') xl.Run('Import_file') # name of the macro Also while (running the macro)opening the workbook it names it as " sample1.xls' ,and so It says there is no such file sample.xls " Filename = Myexcel.xls Workbooks("sample.xls").SaveAs Filename " Can somebody help me with this issue : ( Thanx arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/be914afc/attachment.htm From r.arunchand at gmail.com Fri Apr 21 09:44:08 2006 From: r.arunchand at gmail.com (arun) Date: Fri, 21 Apr 2006 13:14:08 +0530 Subject: [Tutor] Invoking Excel Macro In-Reply-To: <8e82677d0604210029h16facfd9ja0a4c45e97a7bc6f@mail.gmail.com> References: <8e82677d0604210029h16facfd9ja0a4c45e97a7bc6f@mail.gmail.com> Message-ID: <8e82677d0604210044r1cb7be48q4ef259203eb6acf9@mail.gmail.com> I'm sorry , there is something realy wrong with 'Run-time error 1004':. I have fixed it now but still it throws an error while trying to save the workbook. On 4/21/06, arun wrote: > > Hi, > I tried invoking a macro from my python script and It is throwing an > error message that reads 'Run-time error 1004': > > "This operation requires the merged cells to be identically sized" > > My script looks like this > > from win32com.client import Dispatch > xl = Dispatch('Excel.Application') > xl.Workbooks.Add('E:\Templates\sample.xls') > xl.Run('Import_file') # name of the macro > > Also while (running the macro)opening the workbook it names it as " > sample1.xls' ,and so > It says there is no such file sample.xls > > " > Filename = Myexcel.xls > Workbooks("sample.xls").SaveAs Filename > " > > Can somebody help me with this issue : ( > > > Thanx > arun > > > > > > -- arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/9737c2e7/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Apr 21 10:19:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 21 Apr 2006 01:19:51 -0700 (PDT) Subject: [Tutor] Bug in python, or is it just 3am In-Reply-To: <20060421071118.43456.qmail@web80828.mail.yahoo.com> References: <20060421071118.43456.qmail@web80828.mail.yahoo.com> Message-ID: On Fri, 21 Apr 2006, ryan luna wrote: > HA! ignore me, im stupid, XD i knew i should have waited untill morning > =P, No bug, the number = number was just point to the old number which > was one number lower, sorry. night =P.... Get some sleep. *grin* From amazonron at sanbrunocable.com Thu Apr 20 16:03:39 2006 From: amazonron at sanbrunocable.com (Ron Britton) Date: Thu, 20 Apr 2006 07:03:39 -0700 Subject: [Tutor] Use iterator to refer to an object's attribute? In-Reply-To: <00a301c66453$730e0680$0a01a8c0@xp> References: <9690-16163@sneakemail.com> <00a301c66453$730e0680$0a01a8c0@xp> Message-ID: Alan Thanks for the thorough reply. > Hi Ron, I'm confused and may be missing something but it > sounds to me like a classic tree structure that you are trying > to build for each module. It seems like a tree to me. > I''m not sure why you put filling the database into a separate > function rather than as a method of the Database class, it > could then be called from the init method. This would give > it direct access to the Database attributes. This structure evolved. As I solved one problem, I ran into another, and eventually ended up with the current design. I know it's not ideal, but it's the result of my spotty knowledge of Python and what I was able to locate in the assorted documentation that I have skimmed through looking for things that looked relevant. > Also I don't understand why you need the componentlist > name. What is this used for? The name of the list is surely > an internal variable within the module of no relevance to > the outside world? I was hoping to eventually put all of the data in a separate Python module. That way if it ever changed, I could just edit that file. > I'm also not clear about the database structure. Is the one > represented here the final striucture - ie a set of Python lists. > Or will you eventually be loading the data from a config file > or a relational database at some point in the future? I'm not talking to a SQL database or anything like that. I just have this chunk of data. It will change occasionally, so I need a convenient place to edit the data > If it stays as it is then the whole design seems overly > complex since you could simply load the data as part of > the object construction/instantiation process, something like this: > > ModuleList = [ > Module( "Motherboard", > [Component("Camera", > [Command(p1,p2,p3), > Command(p4,p5)]), > ]), > Module("Controller", > [Component("Major Controller", > [Command(....),....]), > Component("Minor Controller", > [Command(....),....]),... > ]), > Module("End User", > [Component("xMotor", [Command(...),...]),... > ]) > ] That looks similar to something I did before and had to abandon. I suspect my earlier attempt was flawed in some way. The above might work. > I suspect the use of a dictionary might be beneficial too. Dictionaries are only pairs of data. I assume a list can be one of those elements, but I couldn't figure out how to make it work in the structure I presented. > However if the data varies at runtime and you have to read it > from an external source that approach won't work. It doesn't. > Why not a dictionary of modules keyed by module name? I wanted to make the methods flexible enough that I wouldn't have to edit every method if the module list ever changed. I guess I don't understand how a dictionary works in this situation. > Why not write constructors that take a list as a parameter. > The constructor can manage its own list and the higher > level constructor just passes in the appropriate list. That way > each class only needs to know about the data at the level > it is responsible for. So the Module class might look a bit like: > > class Module: > def __init__(self, name, componentlist): > self.components = {} > self.name = name > for component in componentlist: > self.components[component[0]] = Component(component) > > This implies that the component list is structured as a list of tuples. I originally had tuples, but you can't access individual elements. E.g., give me the second item in each tuple. I see you're using a dictionary in the above structure. Maybe that solves that issue. I'll have to give the above a try and see if it works. >> I have object "db.mb". I have iterator "shortmod" with a value of >> "mb". Why can't I call "db.shortmod"? > > You can use db.getattr(shortmod) That doesn't work. It tells me "Database instance has no attribute 'getattr'". > but I think its easier and clearer in this case to use: > > db.Modules[shortmod] If Modules is a class name, how am I able to call it like that? I plugged that into my program, and it said: "AttributeError: Database instance has no attribute 'Modules'" > I think you can make it a much closer equivalent than you > have at present, and I think that by breaking up the fill db > function and moving responsibility into the classes that it > will be much simplified. And use dictionaries rather than lists. > > HTH IDD (it definitely does!) I have to run off to work now. I'll try your suggestions when I get there. Thanks a whole lot!! Ron From alan.gauld at freenet.co.uk Fri Apr 21 12:30:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 11:30:59 +0100 Subject: [Tutor] Bug in python, or is it just 3am References: <20060421070351.21492.qmail@web80807.mail.yahoo.com> Message-ID: <016001c6652e$bfb6d850$0a01a8c0@xp> > But when i use a number = number + 1 > right after the value stays the same, I'm not sure what you mean by that. > Now i thought that number = number + 1 just wasn't > vailed in python untill i tried it again and it > worked, variable = variable + 1 is perfectly valid. It is not the normal math meaning of an equation however, it is an assignment statement. In a language like Smalltalk or Pascal they use a different symbol (:=) for assignment which is IMHO A Good Thing(TM) And they traditionally read that symbol as "becomes", thus: variable := variable + 1 is read: "variable becomes variable plus one" What it means is that variable takes on the previous value of variable plus one. So if it starts as 42 it ends as 43 This is such a common thing to do that Python actually has a shorthand for it: variable += 1 And after all that, I've just realised that I don't discuss this at all in my tutorial so I need to add an explanation this weekend. So thanks for asking the question! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Apr 21 12:35:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 11:35:09 +0100 Subject: [Tutor] Invoking Excel Macro References: <8e82677d0604210029h16facfd9ja0a4c45e97a7bc6f@mail.gmail.com> Message-ID: <016d01c6652f$4554c710$0a01a8c0@xp> Hi arun, Although you are invoking this from Python it is really more of a COM/Excel issue. I think you might have more success asking on an Excel forum. The Pythonwin community might be able to help too, buit it looks to me like the problem is in the macro itself. It seems to have dependencies on its runtime environment being set up in a particular way. Sorry I can't be more help, Alan G ----- Original Message ----- From: "arun" To: Sent: Friday, April 21, 2006 8:29 AM Subject: [Tutor] Invoking Excel Macro Hi, I tried invoking a macro from my python script and It is throwing an error message that reads 'Run-time error 1004': "This operation requires the merged cells to be identically sized" My script looks like this from win32com.client import Dispatch xl = Dispatch('Excel.Application') xl.Workbooks.Add('E:\Templates\sample.xls') xl.Run('Import_file') # name of the macro Also while (running the macro)opening the workbook it names it as " sample1.xls' ,and so It says there is no such file sample.xls " Filename = Myexcel.xls Workbooks("sample.xls").SaveAs Filename " Can somebody help me with this issue : ( Thanx arun From RPhillips at engineer.co.summit.oh.us Fri Apr 21 12:53:12 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri, 21 Apr 2006 06:53:12 -0400 Subject: [Tutor] Brain In Vice: Why is this so fun to me? Message-ID: Regex aside, just for a moment * the subject line gets my vote for "Most Succinct Description of Programmer Mindset", if there's a competition on. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/43fc4b6e/attachment.htm From samrobertsmith at gmail.com Fri Apr 21 13:29:19 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 21 Apr 2006 04:29:19 -0700 Subject: [Tutor] locations Message-ID: <1d987df30604210429ycb70477ldb3d0a7d6b988dd2@mail.gmail.com> I have a question. in the LIST M= [[1,1,1,1], [0,1,1,1], [1,1,0,1], [1,1,1,1]] If treat them as the locations of 16 points, I want to generate another list N to hold the corresponding value for each point to its nearest 0. For example: the nearest 0 point to M[0][0] is M[1][0], so N[0][0]=1; M[0][1]'s nearest 0 is also at M[1][0], so N[0][1]=2; but N[0][3]=3 because 0 at M[2][2] is much nearer; N[1][0]=0 because the distance to itself is 0; N should be [[1,2,2,3], [0,1,1,2], [1,1,0,1], [2,2,1,2]] I am really very new to Python and have no idea how to write the code. Thanks! Linda -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/38a5096c/attachment.htm From singletoned at gmail.com Fri Apr 21 15:38:54 2006 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 21 Apr 2006 14:38:54 +0100 Subject: [Tutor] Tutor FAQ? In-Reply-To: <4447B832.10002@tds.net> References: <001701c6648e$4f401050$28645f0a@mikehansen> <4447B832.10002@tds.net> Message-ID: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> On 20/04/06, Kent Johnson wrote: > Mike Hansen wrote: > > I'd like to send a big Thank You to Danny, Alan, Kent and others(whos names > > escape me) for being such an asset to the Python community by relentlessly > > answering questions on the tutor list.(Do these guys sleep? They must work > > in shifts.) This list is one of the most civilized and responsive lists I > > have ever read. When many pop onto the list and ask what may seem like some > > of the most obvious questions, you guys calmly answer and nudge them in the > > right direction without ever losing your patience. It's a great list. > > Thanks! I do sleep but I have my email tied in to my clock radio so > whenever an email arrives on the tutor list I am awakened to answer it ;) > > > > Anyway, I've been reading the list for a couple of years now, and I wonder > > if a Tutor FAQ would be helpful. I don't believe one exists. Should there be > > something on the Python wiki that would list the most common questions to > > the tutor list along with their answers? It would be a FAQ about the tutor > > list as well as common questions to the tutor list. > > I wonder about this sometimes too. I think it would be good to have a > place to collect this stuff. > > Maybe this could be integrated with the main Python FAQ in a beginner's > section? Fredrik Lundh is experimenting with a FAQ wiki here: > http://pyfaq.infogami.com/ Actually I put something about this on PyFAQ just the other day. Fredrik was quite keen on the idea, but I've been busy the last couple of days and haven't got around to doing anything about it. Mike, if you're volunteering that would be perfect. If anyone here has ideas for questions that get asked a lot (like "How do I write a program that prints a word backwards") then just posting them in this thread would be a good start. I assume Kent, Alan and Danny don't mind their answers being reused in the wiki, but it would probably best to get explicit permission from them (and other people) to re-use text from their answers. Ed From nospamformeSVP at gmail.com Fri Apr 21 15:42:39 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Fri, 21 Apr 2006 09:42:39 -0400 Subject: [Tutor] GUI In-Reply-To: <44452B59.1000509@micron.com> References: <4444F9CE.7060800@micron.com> <00a201c66310$cb1a1ab0$0a01a8c0@xp> <44452B59.1000509@micron.com> Message-ID: Eric Walker wrote: > Ok, > If I can get it for free, I might as well go with say wxPython. Thanks However, you really should spend a few bucks buying the recently published "wxPython In Action" book by Noel Rappin and Robin Dunn (the designer of wxPython). It will save you lots of time. You also might like to check out wxGlade which is a FOSS GUI designer for wxPython. It will play happily with your chosen editor. I have tried most of the available GUI designers and liked this one the best although is is a little brittle. http://wxglade.sourceforge.net/ Another _very_ promising system is Dabo but this is not quite ready for prime-time. I think that Dabo is going to be a dynamite system for building GUI db apps. http://dabodev.com/ Don. From kent37 at tds.net Fri Apr 21 15:47:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Apr 2006 09:47:25 -0400 Subject: [Tutor] Tutor FAQ? In-Reply-To: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> References: <001701c6648e$4f401050$28645f0a@mikehansen> <4447B832.10002@tds.net> <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> Message-ID: <4448E26D.8020009@tds.net> Ed Singleton wrote: > If anyone here > has ideas for questions that get asked a lot (like "How do I write a > program that prints a word backwards") then just posting them in this > thread would be a good start. We should be careful about posting solutions to homework problems, which this could easily be. > > I assume Kent, Alan and Danny don't mind their answers being reused in > the wiki, but it would probably best to get explicit permission from > them (and other people) to re-use text from their answers. Fine with me! Kent From nospamformeSVP at gmail.com Fri Apr 21 15:44:52 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Fri, 21 Apr 2006 09:44:52 -0400 Subject: [Tutor] Version of a .pyc file In-Reply-To: References: Message-ID: Terry Carroll wrote: > I've had some pretty good luck using Process Explorer, freeware from That did it, and it was a .pyd file that was giving me problems, thanks once again Terry. Process Explorer is _very_ nice and will certainly stay on my machine. Don. From doug.shawhan at gmail.com Fri Apr 21 17:14:01 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 21 Apr 2006 10:14:01 -0500 Subject: [Tutor] Brain In Vice: Why is this so fun to me? In-Reply-To: References: <5e1ceb8a0604191620i3b739618o291b89a3a43a71ad@mail.gmail.com> <5e1ceb8a0604191637u2a942605qa07132735e6022f2@mail.gmail.com> <5e1ceb8a0604191638u5b53867n4ebe57d058be77fd@mail.gmail.com> <5e1ceb8a0604191932hdfb8392n28ae2daf6359a254@mail.gmail.com> <5e1ceb8a0604200657o2f566ce1x78fb65d826f4a8c5@mail.gmail.com> Message-ID: <5e1ceb8a0604210814i2373b093t7cc023784ffdb572@mail.gmail.com> That works wonderfully! Thanks! On 4/20/06, Liam Clarke wrote: > > Trick is, to limit them very carefully by specifying what they are to > match. > Watch .* - I always use .*? myself. > > For instance, for one of your strings, which ends with the ESC= character>k(some whitespace or not)0 > > \x1b.*?0 would certainly match that, but it'd also match ESC foo ### # > ESC=#k0 > > Whereas \x1b\=.k\w*?0 would match it far more precisely, because > that's the regex for > > esc=k0 > > *excluding \n unless the flag re.DOTALL is used. > > So yeah; something else to note, certain characters need to be escaped > in regex strings. > Namely, these ones - .^$*+?{[|( That second to last one is a pipe by > the way, not an I. > And * is very greedy, but a ? limits it's greediness greatly. > > Good luck, > > Liam Clarke > > On 4/21/06, doug shawhan wrote: > > I am discovering that. They tend to get all Ayn Rand on you and grab too > > much. :-) > > > > > > On 4/20/06, Liam Clarke wrote: > > > Yeah, Alan's tutorial is what I used to learn how to code, it's very > good. > > > Regexes are very powerful; which can be a very good thing and a very > > > bad thing. ;) > > > > > > Good luck. > > > > > > On 4/20/06, doug shawhan wrote: > > > > Got it! Thanks! Mr. Gald hooked me up with his re tutorial as well. > > Great! > > > > > > > > > > > > On 4/19/06, Liam Clarke wrote: > > > > > Here's my copy, it should work if you have Tkinter. > > > > > > > > > > Good luck! > > > > > > > > > > On 4/20/06, doug shawhan wrote: > > > > > > Drat, I installed from the OpenBSD ports tree and this is not > > included. > > > > I'll > > > > > > scout around on the net. > > > > > > > > > > > > Thanks again! > > > > > > > > > > > > > > > > > > On 4/19/06, doug shawhan < doug.shawhan at gmail.com> wrote: > > > > > > > > > > > > > > Holy moley. > > > > > > > > > > > > > > Thanks! > > > > > > > > > > > > > > > > > > > > > > > > > > > > On 4/19/06, Liam Clarke < ml.cyresse at gmail.com> wrote: > > > > > > > > Hi Doug, > > > > > > > > > > > > > > > > Best tip ever is > > > > > > your_python_dir\tools\scripts\redemo.py > > > > > > > > > > > > > > > > Interactive regexes. :) > > > > > > > > > > > > > > > > This is pretty good as well - > > > > > > http://www.amk.ca/python/howto/regex/ > > > > > > > > > > > > > > > > Good luck, > > > > > > > > > > > > > > > > Liam Clarke > > > > > > > > > > > > > > > > On 4/20/06, doug shawhan < doug.shawhan at gmail.com> wrote: > > > > > > > > > I think I'm going to have to suck it up and learn some > regular > > > > > > expressions. > > > > > > > > > > > > > > > > > > I have finally gotten my script (using the excellent > pyserial > > > > module) > > > > > > to > > > > > > > > > behave. Most of my troubles as enumerated here before were > > utterly > > > > > > > > > self-induced. Apparently one cannot watch the execution of > > one's > > > > > > script > > > > > > > > > through another program without affecting it's outcome in > > > > unforseen > > > > > > ways. > > > > > > > > > (Sound familiar Herr Schroedinger? :-) > > > > > > > > > > > > > > > > > > Now that I am actually extracting data in a fairly > > predictable > > > > way, I > > > > > > am at > > > > > > > > > the point where I need to parse it! I have some output > here > > > > (modified > > > > > > to > > > > > > > > > show the ESC and NUL characters.) > > > > > > > > > > > > > > > > > > When I pull data from the port, the remote computer sends > it > > in > > > > one > > > > > > long > > > > > > > > > string per screen: newlines are not painted in by using > the > > > > expected > > > > > > x\0a > > > > > > > > > that I had hoped for! No easy readlines() fun for me. > Instead > > I > > > > get: > > > > > > > > > > > > > > > > > > ESC=( 1. ESC=($4x2, 6-239 ( 3.9L) > > > > > > > > > > > > > ..........................................ESC=(a03252 > > > > > > > > > ESC=(k0 > > > > > > > > > ESC=) 2. ESC=))8-318 ( 5.2L) > > > > > > > > > > > > > ..........................................ESC=)a03242 > > > > > > > > > ESC=)k0 > > > > > > > > > ESC=* 3. ESC=*)8-360 ( 5.9L) > > > > > > > > > > > > > ..........................................ESC=*a03351 > > > > > > > > > ESC=*k 0 > > > > > > > > > ESC=+ 4. ESC=+$4x4, 6-239 ( 3.9L) > > > > > > > > > > > > > ..........................................ESC=+a03240 > > > > > > > > > ESC=+k 0 > > > > > > > > > ESC=, 5. ESC=,)8-318 (5.2L) > > > > > > > > > > > > > ..........................................ESC=,a03243 > > > > > > > > > ESC=,k 0 > > > > > > > > > ESC=- 6. ESC=-)8-360 ( 5.9L) > > > > > > > > > > > > > ..........................................ESC=-a03352 > > > > > > > > > ESC=-k 0 > > > > > > > > > ESC=. 7. ESC=.aCH8299 ESCTNULESC)NULESC=% > > > > > > LINEESCTNULESC=& R = > > > > > > > > > RELIST = NONE > > > > > > > > > > > > > > > > > > I have broken it up for ease of viewing. I need to split > the > > > > string > > > > > > where > > > > > > > > > ESC= , k and 0 are found, but ESC= ,k and 0 are seperated > by > > > > various > > > > > > > > > spaces, parentheis and other characters that are > apparently > > used > > > > to > > > > > > mark the > > > > > > > > > end of the line until the next ESC is found, thereby > > displaying a > > > > new > > > > > > line > > > > > > > > > (note how the character after the first ESC on each line > is > > > > repeated > > > > > > after > > > > > > > > > the ESC on the end. > > > > > > > > > > > > > > > > > > I cannot for the life of me figure out a pythonic way > (read: > > > > using > > > > > > the > > > > > > > > > split() builtin) to scan for instances of these characters > in > > such > > > > and > > > > > > such > > > > > > > > > order and proximity. I know this is what regex is for, but > I > > have > > > > no > > > > > > > > > experience. I have obtained a copy of "Mastering Regular > > > > Expressions" > > > > > > but > > > > > > > > > thought I would inquire here first for caveats and tips as > the > > > > book is > > > > > > > > > larger than my brain, and I haven't used the re module, > ever. > > > > > > > > > > > > > > > > > > Why in the world does this make me so happy? :-)~ > > > > > > > > > > > > > > > > > > > > _______________________________________________ > > > > > > > > > Tutor maillist - Tutor at python.org > > > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/d6cbfd67/attachment.html From alan.gauld at freenet.co.uk Fri Apr 21 17:49:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 16:49:26 +0100 Subject: [Tutor] locations References: <1d987df30604210429ycb70477ldb3d0a7d6b988dd2@mail.gmail.com> Message-ID: <018b01c6655b$30dfa3f0$0a01a8c0@xp> > --------------------- I have a question. in the LIST M= [[1,1,1,1], [0,1,1,1], [1,1,0,1], [1,1,1,1]] If treat them as the locations of 16 points, I want to generate another list N to hold the corresponding value for each point to its nearest 0. > ------------------ Your explanation of the problem is clear up to this point, but... > ----------------------- For example: the nearest 0 point to M[0][0] is M[1][0], so N[0][0]=1; > ---------------------- You lost me there, how do you calculate the 1? Is it the linear distance? The number of hops? related to the index numbering? I'm confused. > M[0][1]'s nearest 0 is also at M[1][0], so N[0][1]=2; Linearly this is root 2 in distance not 2 so I assume you are counting hops? > but N[0][3]=3 because 0 at M[2][2] is much nearer; If you are counting hops then 3 is valid but its only one hop nearer not *much* nearer! > ------------------- N should be [[1,2,2,3], [0,1,1,2], [1,1,0,1], [2,2,1,2]] > ------------------- Assuming you mean hops... (and there probably is a proper mathematical algorithm for this.) I would do this: Locate the first zero(1,1) in this case. Mark all boxes with their distance to it. N looks like this (forget the python syntax for now, focus on the problem): 1234 0123 1234 2345 Can you figure out the algorithm for doing that? Now find the next zero in M and do the same, except you only overwrite values where the new value is less than previously. Thus the values: 4323 3212 2101 3212 becomes 1223 0112 1101 2212 when overlaid on the previous matrix. Which is your required matrix N - QED. Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Apr 21 17:52:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 16:52:03 +0100 Subject: [Tutor] Tutor FAQ? References: <001701c6648e$4f401050$28645f0a@mikehansen><4447B832.10002@tds.net> <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> Message-ID: <018d01c6655b$8a8d8e80$0a01a8c0@xp> I hereby give my permission for any answer I've ever posted to this list or to any other Python list or newsgroup to be used in any Python related FAQ anyone cares to produce! :-) Alan G. ----- Original Message ----- From: "Ed Singleton" To: Sent: Friday, April 21, 2006 2:38 PM Subject: Re: [Tutor] Tutor FAQ? > -------------------------------------- Mike, if you're volunteering that would be perfect. If anyone here has ideas for questions that get asked a lot (like "How do I write a program that prints a word backwards") then just posting them in this thread would be a good start. I assume Kent, Alan and Danny don't mind their answers being reused in the wiki, but it would probably best to get explicit permission from them (and other people) to re-use text from their answers. Ed From alan.gauld at freenet.co.uk Fri Apr 21 17:56:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 16:56:12 +0100 Subject: [Tutor] locations Message-ID: <019b01c6655c$1d937f00$0a01a8c0@xp> I should have added that this solution quickly explodes for large matrixes. There are tweaks such as factoring in the distance between subsequent zeros etc to keep the calculation size down. But for 4x4 sizes it should be adequate in its simple state. Alan G. ----- Original Message ----- From: "Alan Gauld" To: "linda.s" ; "Pujo Aji" Cc: Sent: Friday, April 21, 2006 4:49 PM Subject: Re: [Tutor] locations >> --------------------- > I have a question. in the LIST M= > [[1,1,1,1], > [0,1,1,1], > [1,1,0,1], > [1,1,1,1]] > If treat them as the locations of 16 points, I want to generate another > list > N to hold the corresponding value for each point to its nearest 0. >> ------------------ > > Your explanation of the problem is clear up to this point, but... > >> ----------------------- > For example: > the nearest 0 point to M[0][0] is M[1][0], so N[0][0]=1; >> ---------------------- > > You lost me there, how do you calculate the 1? > Is it the linear distance? The number of hops? > related to the index numbering? I'm confused. > >> M[0][1]'s nearest 0 is also at M[1][0], so N[0][1]=2; > > Linearly this is root 2 in distance not 2 so I assume you > are counting hops? > >> but N[0][3]=3 because 0 at M[2][2] is much nearer; > > If you are counting hops then 3 is valid but its only one hop > nearer not *much* nearer! > >> ------------------- > N should be > [[1,2,2,3], > [0,1,1,2], > [1,1,0,1], > [2,2,1,2]] >> ------------------- > > Assuming you mean hops... (and there probably is a proper > mathematical algorithm for this.) I would do this: > > Locate the first zero(1,1) in this case. > Mark all boxes with their distance to it. > N looks like this (forget the python syntax > for now, focus on the problem): > > 1234 > 0123 > 1234 > 2345 > > Can you figure out the algorithm for doing that? > > Now find the next zero in M and do the same, except you > only overwrite values where the new value is less than > previously. Thus the values: > > 4323 > 3212 > 2101 > 3212 > > becomes > > 1223 > 0112 > 1101 > 2212 > > when overlaid on the previous matrix. > > Which is your required matrix N - QED. > > Does that help? > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From singletoned at gmail.com Fri Apr 21 18:08:08 2006 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 21 Apr 2006 17:08:08 +0100 Subject: [Tutor] Tutor FAQ? In-Reply-To: <4448E26D.8020009@tds.net> References: <001701c6648e$4f401050$28645f0a@mikehansen> <4447B832.10002@tds.net> <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <4448E26D.8020009@tds.net> Message-ID: <34bb7f5b0604210908n6b83dd1aw6d7fb00629e2d633@mail.gmail.com> On 21/04/06, Kent Johnson wrote: > Ed Singleton wrote: > > If anyone here > > has ideas for questions that get asked a lot (like "How do I write a > > program that prints a word backwards") then just posting them in this > > thread would be a good start. > > We should be careful about posting solutions to homework problems, which > this could easily be. Agreed ;-) The last couple of times people have asked this, there's been some really good replies that helped them tease out the solution (what to think about, how to think about the problem, etc). I think quite a lot of the answers to some FAQs won't be solutions, but advice. Ed From dyoo at hkn.eecs.berkeley.edu Fri Apr 21 18:37:47 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 21 Apr 2006 09:37:47 -0700 (PDT) Subject: [Tutor] Tutor FAQ? In-Reply-To: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> References: <001701c6648e$4f401050$28645f0a@mikehansen> <4447B832.10002@tds.net> <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> Message-ID: > I assume Kent, Alan and Danny don't mind their answers being reused in > the wiki, but it would probably best to get explicit permission from > them (and other people) to re-use text from their answers. I give explicit permission for any of my replies to be reused this way. From mhansen at cso.atmel.com Fri Apr 21 18:38:12 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 21 Apr 2006 10:38:12 -0600 Subject: [Tutor] Invoking Excel Macro In-Reply-To: <8e82677d0604210044r1cb7be48q4ef259203eb6acf9@mail.gmail.com> Message-ID: <004901c66561$fb0b1b40$28645f0a@mikehansen> In the macro, you might try Application.DisplayAlerts = False and reset it to True after you save. I think it might be trying to display a dialog box before it saves. Mike _____ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of arun Sent: Friday, April 21, 2006 1:44 AM To: tutor at python.org Subject: Re: [Tutor] Invoking Excel Macro I'm sorry , there is something realy wrong with 'Run-time error 1004':. I have fixed it now but still it throws an error while trying to save the workbook. On 4/21/06, arun wrote: Hi, I tried invoking a macro from my python script and It is throwing an error message that reads 'Run-time error 1004': "This operation requires the merged cells to be identically sized" My script looks like this from win32com.client import Dispatch xl = Dispatch('Excel.Application') xl.Workbooks.Add('E:\Templates\sample.xls') xl.Run('Import_file') # name of the macro Also while (running the macro)opening the workbook it names it as "sample1.xls' ,and so It says there is no such file sample.xls " Filename = Myexcel.xls Workbooks("sample.xls").SaveAs Filename " Can somebody help me with this issue : ( Thanx arun -- arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060421/c9fe0c58/attachment.htm From carroll at tjc.com Fri Apr 21 19:43:38 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 21 Apr 2006 10:43:38 -0700 (PDT) Subject: [Tutor] Version of a .pyc file In-Reply-To: Message-ID: On Fri, 21 Apr 2006, Don Taylor wrote: > That did it, and it was a .pyd file that was giving me problems, thanks > once again Terry. Great to hear! From mhansen at cso.atmel.com Fri Apr 21 19:59:04 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 21 Apr 2006 11:59:04 -0600 Subject: [Tutor] Tutor FAQ? In-Reply-To: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> Message-ID: <006501c6656d$47061760$28645f0a@mikehansen> > > Maybe this could be integrated with the main Python FAQ in a > > beginner's section? Fredrik Lundh is experimenting with a > FAQ wiki here: > > http://pyfaq.infogami.com/ > > Actually I put something about this on PyFAQ just the other day. > Fredrik was quite keen on the idea, but I've been busy the > last couple of days and haven't got around to doing anything about it. > > Mike, if you're volunteering that would be perfect. If > anyone here has ideas for questions that get asked a lot > (like "How do I write a program that prints a word > backwards") then just posting them in this thread would be a > good start. > > I assume Kent, Alan and Danny don't mind their answers being > reused in the wiki, but it would probably best to get > explicit permission from them (and other people) to re-use > text from their answers. > > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Yep, I'm volunteering. Forgive my ignorance, but I couldn't seem to figure out how to edit/add pages to http://pyfaq.infogami.com/. The tutorial wiki has the edit, but the pyfaq page doesn't. I am logged in using my reddit login. Below is what little I slapped together last night. I copied the content from the Python tutor mailman page for the first question. ===================================================================== Python Tutor FAQ --------------------------------------------------------------------- What is Python Tutor? This list is for folks who want to ask questions regarding how to learn computer programming with the Python language. Python (http://www.python.org) is a programming language which many feel is a good first language, because it makes it easy to express the fundamental concepts of programming such as data structures and algorithms with a syntax which many find easy to read and write. Folks interested in learning about programming with Python are encouraged to join, as are folks interested in helping others learn. While the list is called tutor, anyone, whether novice or expert, can answer questions. If individuals wish to start off-line conversations about a particular concept and become one-on-one tutor/tutee, that's fine. If either party wants to summarize what they learned for others to benefit, that's fine too. There is a searchable interface to archived Tutor messages on Activestate's web site at http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor. To see the collection of prior postings to the list, visit the Tutor Archives at http://mail.python.org/pipermail/tutor/ Using Tutor To post a message to all the list members, send email to tutor at python.org --------------------------------------------------------------------- I need help; I'm getting an error in my program. What should I do? If you are getting an error in your Python program that you don't understand, post the error message and any relevant code. Post the exact error message. Don't paraphrase the error message. The error message has details that can help resolve the issue that caused the error. --------------------------------------------------------------------- What is the policy on homework? Although those on the Python tutor mail list are eager to help, they don't want to hand you the answers to your homework. They want to help you find the answers. If you are having difficulty with your homework, send a message to the list about the problem and what you have tried. The tutors will try to nudge you in the right direction. --------------------------------------------------------------------- Why do my replies go to the person who sent the message and not to the list? This is by design. See http://www.unicom.com/pw/reply-to-harmful.html Also see this explanation http://mail.python.org/pipermail/tutor/2005-July/039889.html ===================================================================== Unless anyone has any more, I think the above covers the FAQs about the tutor list. Here's some of the FAQs that I came across scanning the list: ord and chr parsing html beautifulsoup editors/ides getters and setters regex match and find maxtrix operations how do I make an exe out of a python script books what should I program? unicode/encoding Mike From kent37 at tds.net Fri Apr 21 20:25:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Apr 2006 14:25:56 -0400 Subject: [Tutor] Tutor FAQ? In-Reply-To: <006501c6656d$47061760$28645f0a@mikehansen> References: <006501c6656d$47061760$28645f0a@mikehansen> Message-ID: <444923B4.1080000@tds.net> Mike Hansen wrote: > --------------------------------------------------------------------- > I need help; I'm getting an error in my program. What should I do? > > If you are getting an error in your Python program that you don't > understand, post the error message and any relevant code. Post the exact > error message. Don't paraphrase the error message. The error message has > details that can help resolve the issue that caused the error. Instead of "Post the exact error message." I would say "Copy and paste the entire error message into your email, including the traceback." Kent From Barry.Carroll at psc.com Fri Apr 21 20:05:43 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 21 Apr 2006 11:05:43 -0700 Subject: [Tutor] locations Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3665@eugsrv400.psc.pscnet.com> Hi, Linda, > -----Original Message----- > I have a question. in the LIST M= > [[1,1,1,1], > [0,1,1,1], > [1,1,0,1], > [1,1,1,1]] > If treat them as the locations of 16 points, I want to generate another > list > N to hold the corresponding value for each point to its nearest 0. > For example: > the nearest 0 point to M[0][0] is M[1][0], so N[0][0]=1; > M[0][1]'s nearest 0 is also at M[1][0], so N[0][1]=2; > but N[0][3]=3 because 0 at M[2][2] is much nearer; > N[1][0]=0 because the distance to itself is 0; > N should be > [[1,2,2,3], > [0,1,1,2], > [1,1,0,1], > [2,2,1,2]] > I am really very new to Python and have no idea how to write the code. > Thanks! > Linda Basically, what you need to do is compare the coordinates of each cell in N with the coordinates of each cell in M WHICH CONTAINS A 0. Here is my solution: 1. create the list N a. same structure as M b. set each cell to a huge integer value (will be replaced later) 2. make a third list, C, containing the coordinates of the 0 cells in M 3. walk the list N a. compare each cell's coordinates with each coordinate pair in C 1. calculate the distance between the two coordinate pairs b. assign the smallest value obtained from 3.a. to this cell in N. Here are some code fragments to get you started. To, create the coordinate list (C), walk the list M, looking for 0s: >>>>>>> C = [] for i in xrange(len(M)): for j in xrange(len(M[i])): if M[i][j] == 0: C.append((i,j)) >>>>>>> (This could probably be rewritten as a list comprehension, but I'm not very good at them yet.) =8^( To find the distance between the coordinate pairs: >>>>>>> dist = abs(C[k][0] - i) + abs(C[k][1] - j) >>>>>>> To check for a minimum distance: >>>>>>> if dist < N[i][j]: N[i][j] = dist >>>>>>> Does this give you enough information to write your solution? If not, just post more questions. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From alan.gauld at freenet.co.uk Fri Apr 21 21:14:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 21 Apr 2006 20:14:47 +0100 Subject: [Tutor] Tutor FAQ? References: <006501c6656d$47061760$28645f0a@mikehansen> Message-ID: <01bb01c66577$db78abb0$0a01a8c0@xp> I suspect the best way to generate a scientific list of FAQ is by scanning the subjects in the list archives. But here are a few more: Special function _xxx_ doesn't work - double underscore needed Lack of indentation or inconsistent indents - inc tabs and spaces How to name an object based on user input - use a dictionary usually! How to get an attribute of an object by name - getattr() How does Python do my favourite PHP/Perl/VB trick Various possibilities here Binding functions to widgets ie not using parens after the function name How do I read the output from a program called via os.system() popen, command and the new Popen class Changing elements in a mutable object changes the object for all references assignment versus equality in x=x+1 That should keep you busy :-) Alan G. > Below is what little I slapped together last night. I copied the content > from the Python tutor mailman page for the first question. > > Here's some of the FAQs that I came across scanning the list: > > ord and chr > parsing html beautifulsoup > editors/ides > getters and setters > regex match and find > maxtrix operations > how do I make an exe out of a python script > books > what should I program? > unicode/encoding > > Mike > > > From mhansen at cso.atmel.com Fri Apr 21 21:30:52 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 21 Apr 2006 13:30:52 -0600 Subject: [Tutor] Tutor FAQ? In-Reply-To: <444923B4.1080000@tds.net> Message-ID: <006801c6657a$19e39ac0$28645f0a@mikehansen> > --------------------------------------------------------------------- > > I need help; I'm getting an error in my program. What should I do? > > > > If you are getting an error in your Python program that you don't > > understand, post the error message and any relevant code. Post the > > exact error message. Don't paraphrase the error message. The error > > message has details that can help resolve the issue that > caused the error. > > Instead of "Post the exact error message." I would say "Copy > and paste the entire error message into your email, including > the traceback." > > Kent > That's good. It didn't occur to me since I considered the error message as including the traceback. --------------------------------------------------------------------- I need help; I'm getting an error in my program. What should I do? If you are getting an error in your Python program that you don't understand, post the error message and any relevant code. Copy and paste the entire error message into your email, including the traceback. Don't paraphrase the error message. The error message has details that can help resolve the issue that caused the error. Mike From aggie0222 at yahoo.com Sat Apr 22 00:14:21 2006 From: aggie0222 at yahoo.com (Aguilar Arcadio) Date: Fri, 21 Apr 2006 15:14:21 -0700 (PDT) Subject: [Tutor] Cancel Subscription Message-ID: <20060421221421.87415.qmail@web34208.mail.mud.yahoo.com> Please delete my e-mail from the tutor at python.org mailing list. Thank you!! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From srini_iyyer_bio at yahoo.com Sat Apr 22 00:49:28 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 21 Apr 2006 15:49:28 -0700 (PDT) Subject: [Tutor] Creating a graphical interface to database of gene coordinates Message-ID: <20060421224928.87408.qmail@web38105.mail.mud.yahoo.com> Dear group, I am happy that I am slowly finding pyhonian projects related to my research area. Problem: 1. I have a database of human gene coordinates on chromosomes. 2. I have gene expression data from my lab concerning the genes I mentioned above. 3. I want to visualize expression data laid on chromosomes. Eg. Coordinates: Chr Gene From To Exon 1 x 100 120 exon:1 1 x 200 250 exon:2 1 x 350 450 exon:3 Expression data: IDent sample Chr From To Expression value xxx_at lung 1 110 120 100.35 x_s_at heart 1 225 250 124.35 x_a_at eye 1 375 400 146.35 What I want: I want to have a simpler window, that would connect to my database. I want to give a gene, this python/tk interfacce or what ever would query the database draw a graph of gene according the exons and plot the values. -------_______----------_______------- -- : exon __: regions that are not exons, introns. My questions to Tutor/BioPython forums: 1. What should I decide to work on a. Py/Tk framework b. python imaging libraries etc. 2. I do not want to impress any one with this work, except that it should help me understand the relationships as the number game in the tables above is highly confusing. So, a working version that accurately plots the expression values for as many samples I have 3. Are there any available modules to jump-start? or do I have to create some from scratch. which would be a problem because I am between novice to mediocral level of python programing. 4. Any ideas/suggestions/pointers are highly appreciated. thanks Sri __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ml.cyresse at gmail.com Sat Apr 22 00:58:00 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 22 Apr 2006 10:58:00 +1200 Subject: [Tutor] Creating a graphical interface to database of gene coordinates In-Reply-To: <20060421224928.87408.qmail@web38105.mail.mud.yahoo.com> References: <20060421224928.87408.qmail@web38105.mail.mud.yahoo.com> Message-ID: For graphing you can't really beat Scipy. On 4/22/06, Srinivas Iyyer wrote: > Dear group, > I am happy that I am slowly finding pyhonian projects > related to my research area. > > Problem: > 1. I have a database of human gene coordinates on > chromosomes. > 2. I have gene expression data from my lab concerning > the genes I mentioned above. > > 3. I want to visualize expression data laid on > chromosomes. > > Eg. > Coordinates: > Chr Gene From To Exon > 1 x 100 120 exon:1 > 1 x 200 250 exon:2 > 1 x 350 450 exon:3 > > > Expression data: > > IDent sample Chr From To Expression > value > xxx_at lung 1 110 120 100.35 > x_s_at heart 1 225 250 124.35 > x_a_at eye 1 375 400 146.35 > > What I want: > > I want to have a simpler window, that would connect to > my database. I want to give a gene, this python/tk > interfacce or what ever would query the database > draw a graph of gene according the exons and plot the > values. > > -------_______----------_______------- > > -- : exon > __: regions that are not exons, introns. > > > > My questions to Tutor/BioPython forums: > > 1. What should I decide to work on a. Py/Tk framework > b. python imaging libraries etc. > > 2. I do not want to impress any one with this work, > except that it should help me understand the > relationships as the number game in the tables above > is highly confusing. So, a working version that > accurately plots the expression values for as many > samples I have > > 3. Are there any available modules to jump-start? or > do I have to create some from scratch. which would be > a problem because I am between novice to mediocral > level of python programing. > > 4. Any ideas/suggestions/pointers are highly > appreciated. > > thanks > Sri > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From simplebob at gmail.com Sat Apr 22 04:07:51 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Fri, 21 Apr 2006 22:07:51 -0400 Subject: [Tutor] Cancel Subscription In-Reply-To: <20060421221421.87415.qmail@web34208.mail.mud.yahoo.com> References: <20060421221421.87415.qmail@web34208.mail.mud.yahoo.com> Message-ID: <44498FF7.5000003@gmail.com> Aguilar Arcadio wrote: > Please delete my e-mail from the tutor at python.org > mailing list. Thank you!! > To unsubscribe you will have to visit: http://mail.python.org/mailman/options/tutor > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Daniel McQuay Dead Possum Productions ctrl-alt-del.us 814.825.0847 From meenakshi at mbi.ucla.edu Sat Apr 22 04:44:57 2006 From: meenakshi at mbi.ucla.edu (meenakshi at mbi.ucla.edu) Date: Fri, 21 Apr 2006 19:44:57 -0700 (PDT) Subject: [Tutor] looking to hire a tutor Message-ID: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> Hi, I apologize if this has been covered before. I am a postdoctoral research scientist learning Python programming. I would like to hire a tutor who can spend 1-2 hours a week with me going overand critiquing my programming. I have looked for online Python programming classes (not free tutorials), which offer structure and feedback for a reasonable price. To my surprise, I havent been very successful. Working with online free tutorials hasnt been an ideal approach, partly because I dont get feedback and partly because they dont completely meet my requirements. How would I go about hiring a python tutor who: Spends time critiquing my code and providing detailed feedback. Cares about good programming practices and is able to provide cogent explanations of programming principles. Can instruct me in the finer points of breaking a programming problem down into constituent parts. Is well versed in Python. It would be great (but not necessary) if he/she were also familiar with data mining practices. I would be willing to pay 20-30$ an hour (or more depending on instructor qualifications). How do I go about doing this? Any suggestions? Thanks Meenakshi From dyoo at hkn.eecs.berkeley.edu Sat Apr 22 07:00:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 21 Apr 2006 22:00:20 -0700 (PDT) Subject: [Tutor] looking to hire a tutor In-Reply-To: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> References: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> Message-ID: > How would I go about hiring a python tutor who: > > Spends time critiquing my code and providing detailed feedback. Hi Meenakshi, People here are usually suprisingly gracious with their time, and will be happy to look and critique code. You may want to try your hand at showing us some code. We might be rough at times, but we'll try to be as constructive as we can. If you share what you have with the group here at Python-Tutor, you might be able to get some of the feedback and advice that you're looking for. Python-tutor acts very much like a "writers workshop" in the sense that Richard Gabriel explains in: http://www.dreamsongs.com/NewFiles/WritersWorkshop.pdf If you'd like to see examples of this, take a look at the mailing list archive at: http://mail.python.org/pipermail/tutor/ and look at the kinds of questions that are being asked and answered. Good luck to you. From ml.cyresse at gmail.com Sat Apr 22 07:01:25 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 22 Apr 2006 17:01:25 +1200 Subject: [Tutor] Bug in python, or is it just 3am In-Reply-To: <016001c6652e$bfb6d850$0a01a8c0@xp> References: <20060421070351.21492.qmail@web80807.mail.yahoo.com> <016001c6652e$bfb6d850$0a01a8c0@xp> Message-ID: Hi Ryan, I see what confused you; the " >>> number + 1 6 >>> print number 5 " part. Yeah, it's only evaluating the the first one. So you're asking it "What's number + 1"? Whereas, >>> number = number + 1 or >>> number += 1 Is saying "Make number equal number plus 1" Ha, it's all a learning experience. Regards, Liam Clarke On 4/21/06, Alan Gauld wrote: > > But when i use a number = number + 1 > > right after the value stays the same, > > I'm not sure what you mean by that. > > > Now i thought that number = number + 1 just wasn't > > vailed in python untill i tried it again and it > > worked, > > variable = variable + 1 > > is perfectly valid. It is not the normal math meaning of an equation > however, it is an assignment statement. In a language like Smalltalk > or Pascal they use a different symbol (:=) for assignment which > is IMHO A Good Thing(TM) And they traditionally read that > symbol as "becomes", thus: > > variable := variable + 1 > > is read: "variable becomes variable plus one" > > What it means is that variable takes on the previous value > of variable plus one. So if it starts as 42 it ends as 43 > > This is such a common thing to do that Python actually > has a shorthand for it: > > variable += 1 > > And after all that, I've just realised that I don't discuss this > at all in my tutorial so I need to add an explanation this weekend. > So thanks for asking the question! :-) > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From singletoned at gmail.com Sat Apr 22 09:39:00 2006 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 22 Apr 2006 08:39:00 +0100 Subject: [Tutor] Tutor FAQ? In-Reply-To: <006501c6656d$47061760$28645f0a@mikehansen> References: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <006501c6656d$47061760$28645f0a@mikehansen> Message-ID: <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> > Yep, I'm volunteering. Forgive my ignorance, but I couldn't seem to figure > out how to edit/add pages to http://pyfaq.infogami.com/. The tutorial wiki > has the edit, but the pyfaq page doesn't. I am logged in using my reddit > login. I don't think the FAQ is open to public editing yet. I'm not sure when it will be, but Fredrik might be able to give a timescale. I've made a start on adding your questions, but probably won't get to do much more until tomorrow. Ed On 21/04/06, Mike Hansen wrote: > > > > > Maybe this could be integrated with the main Python FAQ in a > > > beginner's section? Fredrik Lundh is experimenting with a > > FAQ wiki here: > > > http://pyfaq.infogami.com/ > > > > Actually I put something about this on PyFAQ just the other day. > > Fredrik was quite keen on the idea, but I've been busy the > > last couple of days and haven't got around to doing anything about it. > > > > Mike, if you're volunteering that would be perfect. If > > anyone here has ideas for questions that get asked a lot > > (like "How do I write a program that prints a word > > backwards") then just posting them in this thread would be a > > good start. > > > > I assume Kent, Alan and Danny don't mind their answers being > > reused in the wiki, but it would probably best to get > > explicit permission from them (and other people) to re-use > > text from their answers. > > > > Ed > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > Yep, I'm volunteering. Forgive my ignorance, but I couldn't seem to figure > out how to edit/add pages to http://pyfaq.infogami.com/. The tutorial wiki > has the edit, but the pyfaq page doesn't. I am logged in using my reddit > login. > > Below is what little I slapped together last night. I copied the content > from the Python tutor mailman page for the first question. > > ===================================================================== > Python Tutor FAQ > --------------------------------------------------------------------- > What is Python Tutor? > > This list is for folks who want to ask questions regarding how to learn > computer programming with the Python language. > > Python (http://www.python.org) is a programming language which many feel is > a good first language, because it makes it easy to express the fundamental > concepts of programming such as data structures and algorithms with a syntax > which many find easy to read and write. > > Folks interested in learning about programming with Python are encouraged to > join, as are folks interested in helping others learn. While the list is > called tutor, anyone, whether novice or expert, can answer questions. > > If individuals wish to start off-line conversations about a particular > concept and become one-on-one tutor/tutee, that's fine. If either party > wants to summarize what they learned for others to benefit, that's fine too. > > There is a searchable interface to archived Tutor messages on Activestate's > web site at > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor. > > To see the collection of prior postings to the list, visit the Tutor > Archives at http://mail.python.org/pipermail/tutor/ > > Using Tutor > To post a message to all the list members, send email to tutor at python.org > > --------------------------------------------------------------------- > I need help; I'm getting an error in my program. What should I do? > > If you are getting an error in your Python program that you don't > understand, post the error message and any relevant code. Post the exact > error message. Don't paraphrase the error message. The error message has > details that can help resolve the issue that caused the error. > > --------------------------------------------------------------------- > What is the policy on homework? > > Although those on the Python tutor mail list are eager to help, they don't > want to hand you the answers to your homework. They want to help you find > the answers. If you are having difficulty with your homework, send a message > to the list about the problem and what you have tried. The tutors will try > to nudge you in the right direction. > > --------------------------------------------------------------------- > Why do my replies go to the person who sent the message and not to the list? > > This is by design. > See http://www.unicom.com/pw/reply-to-harmful.html > > Also see this explanation > http://mail.python.org/pipermail/tutor/2005-July/039889.html > > ===================================================================== > > Unless anyone has any more, I think the above covers the FAQs about the > tutor list. > > Here's some of the FAQs that I came across scanning the list: > > ord and chr > parsing html beautifulsoup > editors/ides > getters and setters > regex match and find > maxtrix operations > how do I make an exe out of a python script > books > what should I program? > unicode/encoding > > Mike > > From alan.gauld at freenet.co.uk Sat Apr 22 10:22:50 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 22 Apr 2006 09:22:50 +0100 Subject: [Tutor] looking to hire a tutor References: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> Message-ID: <004501c665e5$f213d520$0a01a8c0@xp> > I am a postdoctoral research scientist learning Python programming. I > would like to hire a tutor who can spend 1-2 hours a week with me going > overand critiquing my programming. We are not available for hire but we do offer a critique service on code to a limited degree - ie we don;t code review hundreds (or thousands) of lines worth! But if you want to try ideas out and ask us how they can be improved we can do that. > programming classes (not free tutorials), which offer structure and > feedback for a reasonable price. To my surprise, I havent been very > successful. There are some traditional traiing companies that teach Python, mainly in the US although at least one is here in the UK too. But I don't know of anyone online who does that. > Working with online free tutorials hasnt been an ideal approach, partly > because I dont get feedback and partly because they dont completely > meet my requirements. This list tries to provide feedback for most of the online tuts, and I provide a feedback link on every page of my tutor and usually respond to queries etc within 48 hours. > Cares about good programming practices and is able to provide cogent > explanations of programming principles. > Can instruct me in the finer points of breaking a programming problem down > into constituent parts. > Is well versed in Python. It would be great (but not necessary) if he/she > were also familiar with data mining practices. We do that here, but instead of one tutor you get dozens... > I would be willing to pay 20-30$ an hour (or more depending on instructor > qualifications). And we are free. But you don't get one on one tuition. And its public so you have to be happy to share your mistakes. So I don't know how you get exactly what you want but this list offers some of it for free. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From python at venix.com Sat Apr 22 14:03:14 2006 From: python at venix.com (Python) Date: Sat, 22 Apr 2006 08:03:14 -0400 Subject: [Tutor] looking to hire a tutor In-Reply-To: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> References: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> Message-ID: <1145707394.6268.320.camel@www.venix.com> On Fri, 2006-04-21 at 19:44 -0700, meenakshi at mbi.ucla.edu wrote: > How would I go about hiring a python tutor who: > > Spends time critiquing my code and providing detailed feedback. > Cares about good programming practices and is able to provide cogent > explanations of programming principles. > Can instruct me in the finer points of breaking a programming problem > down > into constituent parts. > Is well versed in Python. It would be great (but not necessary) if > he/she > were also familiar with data mining practices. > > I would be willing to pay 20-30$ an hour (or more depending on > instructor > qualifications). > > How do I go about doing this? Any suggestions? Sometimes having someone sitting at your side helping you get acclimated can be a big help. I would expect your school would have some computer oriented clubs or groups where you could find the expertise you're looking for. A Linux User Group could be a good source of help, even if you are using Windows since the percentage of Python users is generally higher among Linux folks than in the Windows population. For remote help, this list is hard to beat. -- Lloyd Kvam Venix Corp From srini_iyyer_bio at yahoo.com Sat Apr 22 14:51:19 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sat, 22 Apr 2006 05:51:19 -0700 (PDT) Subject: [Tutor] looking to hire a tutor In-Reply-To: <1956.128.97.41.117.1145673897.squirrel@webmail.mbi.ucla.edu> Message-ID: <20060422125119.43593.qmail@web38107.mail.mud.yahoo.com> Hi meenakshi, I am a postdoctoral fellow in oncology and with passion and I wanted to learn programming especially Python. I tried my luck in C, Java and PERL. To my surprise they were much harder to understand and work with. I chose Python to help my work and it helped me run my life easily. just like you, I contacted many experts who would spend their time to train me. I dared to spend around '$10 K' to learn programming (at programming camps). The truth is, it may sound strange, you may hire the best tutor on this planet, BUT the seed-logic of coding cannot be planted in your brain by none other than you. My suggestions: 1. choose exercises/problems from your own area of research, instead of 'Hello world' type. 2. Regularly read 'Tutor' mailing list. Here experts, are so passionate and with patience spend their time for no cost, in critiquing your code, not matter how simple or harder it may be. At no cost, you get top notch programmers instead of one. 3. Post your questions here. Believe me, THIS IS THE place to learn serious Python programming. 4. After a tutor responds to your question, go back to simple books and try to understand the nuances. Books: Dont forget to carry these whereever your go: 1. Alan Gauld's : Learn to Program using Python 2. Mark Lutz'z: Learning Python Rest other books are up to your taste and choice. good luck. --- meenakshi at mbi.ucla.edu wrote: > > Hi, > I apologize if this has been covered before. > I am a postdoctoral research scientist learning > Python programming. I > would like to hire a tutor who can spend 1-2 hours a > week with me going > overand critiquing my programming. I have looked > for online Python > programming classes (not free tutorials), which > offer structure and > feedback for a reasonable price. To my surprise, I > havent been very > successful. > Working with online free tutorials hasnt been an > ideal approach, partly > because I dont get feedback and partly because they > dont completely > meet my requirements. > > How would I go about hiring a python tutor who: > > Spends time critiquing my code and providing > detailed feedback. > Cares about good programming practices and is able > to provide cogent > explanations of programming principles. > Can instruct me in the finer points of breaking a > programming problem down > into constituent parts. > Is well versed in Python. It would be great (but > not necessary) if he/she > were also familiar with data mining practices. > > I would be willing to pay 20-30$ an hour (or more > depending on instructor > qualifications). > > How do I go about doing this? Any suggestions? > > Thanks > Meenakshi > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From srini_iyyer_bio at yahoo.com Sun Apr 23 07:46:02 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sat, 22 Apr 2006 22:46:02 -0700 (PDT) Subject: [Tutor] how can I use Set.interaction function on a dictionary Message-ID: <20060423054602.52304.qmail@web38114.mail.mud.yahoo.com> Hi Tutors, Background: 1. I have a dictionary with 4 keys and some repeated values for each key. >>> dida {'NM_001033044': [32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32845745], 'NM_002065': [32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32845745], 'NM_015701': [32844783, 32844783, 32844783, 32844783, 32844783, 32844783], 'NM_001033056': [32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32842023, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32843894, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32844846, 32845745]} In the case of 'dida', the list of values have repeated elements. So I got rid of duplicates in the value lists (value as in key:value pair) in the case of 'didi' >>> didi {'NM_001033044': [32842023, 32843894, 32844846, 32845745], 'NM_002065': [32844846, 32842023, 32845745, 32843894], 'NM_015701': [32844783], 'NM_001033056': [32843894, 32844846, 32845745, 32842023]} Question: 1. How can I get A^B^C^D(^ = intersection) where A, B, C and D are keys from dida or didi. 2. How can I store values generated dynamically. For example, here in 'dida' I know there are 4 keys, but how can I create 4 lists while running in for loop and store the key values in 'dida'. Do I have to write an class object that will create empty lists depending on number of keys a dictionary has? I am loosing my mind because I do not know how to store the values for each key in a loop and do set operations. For instance, I tried the following way: >>> for m in range(len(didi.keys())): ... x = m+1 ... a = Set(didi[didi.keys()[m]]) ... print a ... Set([32845745, 32844846, 32843894, 32842023]) Set([32845745, 32843894, 32844846, 32842023]) Set([32844783]) Set([32845745, 32844846, 32843894, 32842023]) I would be happy, if I could store all 4 sets (above)into listsor sets A, B, C and D and do (A^B)^(C^D). Could any one help me please. My ultimate goal is to do set operations on this dictionary. If things get more complicated, I will seek R's help through RPy. Thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Sun Apr 23 10:39:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 23 Apr 2006 01:39:44 -0700 (PDT) Subject: [Tutor] how can I use Set.interaction function on a dictionary In-Reply-To: <20060423054602.52304.qmail@web38114.mail.mud.yahoo.com> References: <20060423054602.52304.qmail@web38114.mail.mud.yahoo.com> Message-ID: > 1. I have a dictionary with 4 keys and some repeated > values for each key. > >>>> dida > {'NM_001033044': [32842023, 32842023, 32842023, > 32842023, 32842023, 32842023, 32842023, 32842023, > 32842023, 32842023, 32842023, 32842023, 32843894, > 32843894, 32843894, 32843894, 32843894, 32843894, > 32843894, 32843894, 32843894, 32843894, 32844846, > 32844846, 32844846, 32844846, 32844846, 32844846, > 32844846, 32844846, 32844846, 32844846, 32845745], [cut] > 1. How can I get A^B^C^D(^ = intersection) where A, B, C and D are keys > from dida or didi. What would be a few concrete examples of this operation? What would be a concrete instance of this problem, and the expected result? That is, let's call this operation "intersection()" for the moment, and just pretend that it exists. Can you construct a simple, sample call to this imaginary "intersection()" function? What expected value do we get back? Wishful thinking through examples is a good technique when one is not quite sure how to do something yet. (Plus it will be less ambiguous than English --- I have to admit that I do not understand the problem statement yet.) Also, simplify the problem a little more: doing an operation on four elements at once seems a bit arbitrary. Rather than four, let's bring the problem's complexity down a bit. If you had a function to do it on two items: A ^ B where A and B are either from dida or didi, would this be easier for you to consider? Would you be able to do this smaller problem? I'd recommend tackling this first before going all out on the bigger problem. From alan.gauld at freenet.co.uk Sun Apr 23 16:21:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 23 Apr 2006 15:21:00 +0100 Subject: [Tutor] looking to hire a tutor References: <20060422125119.43593.qmail@web38107.mail.mud.yahoo.com> Message-ID: <000d01c666e1$25df1710$0a01a8c0@xp> > Books: > Dont forget to carry these whereever your go: > 1. Alan Gauld's : Learn to Program using Python > 2. Mark Lutz'z: Learning Python While I appreciate the compliment I feel I should point out that my book is really a beginners tutorial and, even when I wrote it, I expected it to have limited value as a reference book (except perhaps for some of the CS concepts). Lutz' book is similar but is at least more in-depth although even it can be quickly outgrown. The best current ready reference is Python in a Nutshell. And Lutz' much bigger volume - Programming Python - is also worth keeping on your desk if not in your bag... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Apr 23 16:43:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 23 Apr 2006 15:43:51 +0100 Subject: [Tutor] how can I use Set.interaction function on a dictionary References: <20060423054602.52304.qmail@web38114.mail.mud.yahoo.com> Message-ID: <001501c666e4$569f60a0$0a01a8c0@xp> > 1. I have a dictionary with 4 keys and some repeated > values for each key. > >>>> dida > {'NM_001033044': [32842023, 32842023, 32842023, > 32842023, 32842023, 32842023, 32842023, 32842023, > 32842023, 32842023, 32842023, 32842023, 32843894, > 32843894, 32843894, 32843894, 32843894, 32843894, > 32843894, 32843894, 32843894, 32843894, 32844846, > 32844846, 32844846, 32844846, 32844846, 32844846, > 32844846, 32844846, 32844846, 32844846, 32845745], >>>> didi > {'NM_001033044': [32842023, 32843894, 32844846, > 32845745], 'NM_002065': [32844846, 32842023, 32845745, > 32843894], 'NM_015701': [32844783], 'NM_001033056': > [32843894, 32844846, 32845745, 32842023]} > > Question: > > 1. How can I get A^B^C^D(^ = intersection) where A, B, > C and D are keys from dida or didi. I assume the value of A,B etc are the lists of data purged of duplicates? And you now want to find the common elements across all four sets? > 2. How can I store values generated dynamically. For > example, here in 'dida' I know there are 4 keys, but > how can I create 4 lists while running in for loop and > store the key values in 'dida'. I'm not sure what the problem is here: len(dida.keys()) Will give the number of keys, and dida[key] will give you the list. But I think you know enough Python for that to be too simple. Can you elaborate further? > Do I have to write an class object that will create > empty lists depending on number of keys a dictionary > has? > > I am loosing my mind because I do not know how to > store the values for each key in a loop and do set > operations. mysets = [] for value in dida.itervalues(): mysets.append(set(value)) Gives you a list of 4 sets. You can get the intersect of 4 sets by taking the intersects of two at a time: result = mysets[0] for s in mysets[1:] result = result.intersection(s) >>>> for m in range(len(didi.keys())): > ... x = m+1 > ... a = Set(didi[didi.keys()[m]]) Any time you use len() in a for loop you should ask whether thats really the best way. And if you then use the index to get the items, ask again. > I would be happy, if I could store all 4 sets > (above)into listsor sets A, B, C and D and do > (A^B)^(C^D). See my code above which gives you a list of 4 sets. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tinoloc at gmail.com Sun Apr 23 17:55:16 2006 From: tinoloc at gmail.com (Tino Dai) Date: Sun, 23 Apr 2006 11:55:16 -0400 Subject: [Tutor] Locking a specific variable Message-ID: Hi there, I am wondering if you could lock a specific variable with thread locking. Let me illustrate: def ftpQueuePut(filename=""):: if len(filename) > 0: try: fileQueue.put(filename,True,1) #Variable that I would like to lock except Queue.full: print "Queue is full" else: pass def ftpQueueGet(): try: filename=fileQueue.get(True,1) #Variable that I would like to lock return filename except Queue.Empty: pass Presently, the only way that I can see to do this using Python is to combine the two functions into one and lock and unlock the entire thing . That doesn't seem efficient and/or elegant to me. Any pointers about this? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060423/60b520fe/attachment.htm From george at galis.org Mon Apr 24 02:43:04 2006 From: george at galis.org (George Georgalis) Date: Sun, 23 Apr 2006 20:43:04 -0400 Subject: [Tutor] hash.update( argv[0] ) Message-ID: <20060424004304.GH25812@sta.duo> Hi! I've been struggling to find a way up seed hash.update() with the sha1 (or similar) of the file that is the program running. this is not a security task but rather a means to generate reasonably unique filenames based on various parameters including changes to the program: name = hash.hexdigest() so new files are generated when the program or parameters are changed; but cached files are used when identical results are expected. help! I cannot figure out how to pass the program body as a seed to hash.update(). // George -- George Georgalis, systems architect, administrator < http://galis.org/ cell:646-331-2027 mailto:george at galis.org From fredrik at pythonware.com Sat Apr 22 11:21:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Apr 2006 11:21:08 +0200 Subject: [Tutor] Tutor FAQ? In-Reply-To: <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> References: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <006501c6656d$47061760$28645f0a@mikehansen> <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> Message-ID: <368a5cd50604220221p27b3c647o25bd4bff5fc9b67f@mail.gmail.com> > When Ed brought up the tutor/tutorial FAQ idea and yes, I'll change "tutorial FAQ" to "tutor FAQ", to make things a bit less confusing. From fredrik at pythonware.com Sat Apr 22 11:15:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Apr 2006 11:15:00 +0200 Subject: [Tutor] Tutor FAQ? In-Reply-To: <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> References: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <006501c6656d$47061760$28645f0a@mikehansen> <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> Message-ID: <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> Ed wrote: > I don't think the FAQ is open to public editing yet. I'm not sure > when it will be, but Fredrik might be able to give a timescale. There are a few known conversion issues to deal with (the FAQ uses a lot more "looks like markdown syntax" than the tutorial, which con- fused the converter). I've made some progress, but it'll probably take another week before everything's sorted out. When Ed brought up the tutor/tutorial FAQ idea, my first thought was that Ed and other volunteers could add pages in a separate "tutor-" namespace (to avoid collisions with material from the existing FAQ), and ended up writing a couple of paragraphs on how to manually convert titles to page names. When I found that I had written "this isn't quite as hard as it may look", I realized that it would be better if I just wrote a script that did this. So, while I'm working on that script, I suggest that you start adding stuff the "tutor suggestion" page that I just set up: http://pyfaq.infogami.com/suggest-tutor One entry per comment; use "## title" to mark the first line as the FAQ entry. I've added Mike's examples. cheers /F From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 07:41:15 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 23 Apr 2006 22:41:15 -0700 (PDT) Subject: [Tutor] Locking a specific variable In-Reply-To: References: Message-ID: On Sun, 23 Apr 2006, Tino Dai wrote: > I am wondering if you could lock a specific variable with thread > locking. Let me illustrate: > > def ftpQueuePut(filename=""):: > if len(filename) > 0: > try: > fileQueue.put(filename,True,1) #Variable that I would like to > lock > except Queue.full: > print "Queue is full" > else: > pass > > def ftpQueueGet(): > try: > filename=fileQueue.get(True,1) #Variable that I would like to > lock > return filename > except Queue.Empty: > pass Hi Tino, I'm not quite sure I get it, but ok. *grin* I'll assume that fileQueue is an instance of the Queue class: http://www.python.org/doc/lib/module-Queue.html If so: why not allow fileQueue to grow unbounded? > Presently, the only way that I can see to do this using Python is to > combine the two functions into one and lock and unlock the entire thing > . That doesn't seem efficient and/or elegant to me. Any pointers about > this? Do you know about the thread-locking primitives? There are a few kinds provided by Python's threading module: http://www.python.org/doc/lib/module-threading.html Are you already familiar with the concept of a RLock or a Lock? From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 07:49:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 23 Apr 2006 22:49:00 -0700 (PDT) Subject: [Tutor] hash.update( argv[0] ) In-Reply-To: <20060424004304.GH25812@sta.duo> References: <20060424004304.GH25812@sta.duo> Message-ID: On Sun, 23 Apr 2006, George Georgalis wrote: > Hi! I've been struggling to find a way up seed hash.update() with > the sha1 (or similar) of the file that is the program running. > > this is not a security task but rather a means to generate > reasonably unique filenames based on various parameters including > changes to the program: name = hash.hexdigest() > > so new files are generated when the program or parameters are > changed; but cached files are used when identical results are > expected. > > help! I cannot figure out how to pass the program body as a seed > to hash.update(). Hi George, I'm slightly confused. Isn't this a matter of doing: ################################################################### def prepare_md5(filename): m = md5.new() m.update(open(filename).read()) ## not so smart: do this ## progressively in real life! return m ################################################################### So I think I'm missing something. Are you asking instead: how do I get the filename of the currently running program? From keosophon at khmeros.info Mon Apr 24 09:16:25 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Mon, 24 Apr 2006 14:16:25 +0700 Subject: [Tutor] How use relative path of Linux environment in Python Message-ID: <200604241416.25713.keosophon@khmeros.info> Hi all, Do you have any idea of how to use relative path of Linux environment in Python. For example, if a program would like to create an oupfile from these assignment: outputfile = "~/Desktop/" + workingfile, while "~" is the short cut to the path of current user. Thanks, Phon From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 09:24:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 00:24:00 -0700 (PDT) Subject: [Tutor] How use relative path of Linux environment in Python In-Reply-To: <200604241416.25713.keosophon@khmeros.info> References: <200604241416.25713.keosophon@khmeros.info> Message-ID: On Mon, 24 Apr 2006, Keo Sophon wrote: > Do you have any idea of how to use relative path of Linux environment in > Python. For example, if a program would like to create an oupfile from > these assignment: outputfile = "~/Desktop/" + workingfile, while "~" is > the short cut to the path of current user. This seems similar to a question that was asked and answered a few days ago: http://mail.python.org/pipermail/tutor/2006-April/046613.html Are you trying to do something similar? From hokkakada at khmeros.info Mon Apr 24 09:59:54 2006 From: hokkakada at khmeros.info (kakada) Date: Mon, 24 Apr 2006 14:59:54 +0700 Subject: [Tutor] [Linux] open a file in any home "~" ? In-Reply-To: <13a83ca10604191140r3eaeeec8v7bda7c00e3c0e894@mail.gmail.com> References: <13a83ca10604191055o6a78bee3t16d6792d2d27cf9f@mail.gmail.com> <78b3a9580604191124y2bedf534m9bc0942e07820de7@mail.gmail.com> <13a83ca10604191140r3eaeeec8v7bda7c00e3c0e894@mail.gmail.com> Message-ID: <444C857A.50606@khmeros.info> learner404 wrote: > It works great, thanks very much to the three of you for these > light-speed answers ... I love this list ! > > Wesley, I've just pre-order your new edition "Core Python programming" > on amazon France, it looks great. :) > > Thanks I love this list too. Da From r.arunchand at gmail.com Mon Apr 24 15:32:43 2006 From: r.arunchand at gmail.com (arun) Date: Mon, 24 Apr 2006 19:02:43 +0530 Subject: [Tutor] Invoking Excel Macro In-Reply-To: <004901c66561$fb0b1b40$28645f0a@mikehansen> References: <8e82677d0604210044r1cb7be48q4ef259203eb6acf9@mail.gmail.com> <004901c66561$fb0b1b40$28645f0a@mikehansen> Message-ID: <8e82677d0604240632u30b251d6rdef568795fbdb74a@mail.gmail.com> Hi Mike, It doesn't display any dialog box rather it gives a temporary name to the file. Ex newsheet.xls as newsheet1.xls So i'm not able to save it. Is there an alternative to invoke the macro and save the file from my script itself .(saving it through macro wud be a better option : ) ) Thanx and Regards, arun On 4/21/06, Mike Hansen wrote: > > In the macro, you might try Application.DisplayAlerts = False and reset > it to True after you save. > I think it might be trying to display a dialog box before it saves. > > Mike > > ------------------------------ > *From:* tutor-bounces at python.org [mailto:tutor-bounces at python.org] *On > Behalf Of *arun > *Sent:* Friday, April 21, 2006 1:44 AM > *To:* tutor at python.org > *Subject:* Re: [Tutor] Invoking Excel Macro > > > > I'm sorry , there is something realy wrong with 'Run-time error 1004':. I > have fixed it now but still it throws an error while trying to save the > workbook. > > On 4/21/06, arun wrote: > > > > Hi, > > I tried invoking a macro from my python script and It is throwing an > > error message that reads 'Run-time error 1004': > > > > "This operation requires the merged cells to be identically sized" > > > > My script looks like this > > > > from win32com.client import Dispatch > > xl = Dispatch('Excel.Application') > > xl.Workbooks.Add('E:\Templates\sample.xls') > > xl.Run('Import_file') # name of the macro > > > > Also while (running the macro)opening the workbook it names it as " > > sample1.xls' ,and so > > It says there is no such file sample.xls > > > > " > > Filename = Myexcel.xls > > Workbooks("sample.xls").SaveAs Filename > > " > > > > Can somebody help me with this issue : ( > > > > > > Thanx > > arun > > > > > > > > > > > > > > > > -- > arun > > -- arun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060424/15c9f67a/attachment.htm From etrade.griffiths at dsl.pipex.com Mon Apr 24 15:26:40 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Mon, 24 Apr 2006 14:26:40 +0100 Subject: [Tutor] Looping over lists of objects Message-ID: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> Hi just feeling my way into Python with a small app that reads data from file, creates objects using that data, stores the objects in a list, loops over the list doing comparison tests to filter out various objects. Here is a code snippet: class myObj: def __init__(self,a,b): self.a=a self.b=b def get_a(self): return self.a def get_b(self): return self.b # Read data from file L1=[] nobj=0 for line in input: L0=line.split() a=L0[1] b=L0[2] nobj=nobj+1 an_obj=myObj(a,b) L1.append(an_obj) # Filter data for i in range(1,nobj): for x in L1: # ... loop over all objects in list a=x.get_a() # ... get value of a from current object b=x.get_b() if test(a,b): print 'test succeeded' else: print 'test failed' Trying to debug this using IDLE. The calls x.get_a and x.get_b always return zero so something is going wrong somewhere. I think I'm either not storing the objects correctly or retrieving them correctly but no idea why! All suggestions gratefully received!!! Thanks in advance Alun Griffiths -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060424/491f4d31/attachment.html From andreengels at gmail.com Mon Apr 24 16:46:31 2006 From: andreengels at gmail.com (Andre Engels) Date: Mon, 24 Apr 2006 16:46:31 +0200 Subject: [Tutor] Object defined by initialization parameters Message-ID: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> Is it possible to define a class in such a way, that if twice an object is made with the same initialization parameters, the same object is returned in both cases? More specifically, suppose I have the following program: class myObj(object): def __init__(self,a): self._a = a self._seen = 0 def touch(self): self._seen += 1 def count(self): return self._seen x = myObj("a") y = myObj("a") z = myObj("b") x.touch() After this, x._seen will return 1, but y._seen and z._seenwill return 0. I would like the definition of the myObj class to be such that after these definitions x and y refer to the same object, but z to a different one. If there is not such possibility, does anyone have a better or more elegant workaround than the one I am using, which is: class myObj(object): def __init__(self,a): self._a = a self._seen = 0 def touch(self): self._seen += 1 def count(self): return self._seen def obj(a): try: return objects[a] except KeyError: objects[a] = myObj(a) return objects[a] objects = {} x = obj("a") y = obj("a") z = obj("b") x.touch() -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From george at galis.org Mon Apr 24 16:56:57 2006 From: george at galis.org (George Georgalis) Date: Mon, 24 Apr 2006 10:56:57 -0400 Subject: [Tutor] hash.update( argv[0] ) In-Reply-To: References: <20060424004304.GH25812@sta.duo> Message-ID: <20060424145657.GK25812@sta.duo> On Sun, Apr 23, 2006 at 10:49:00PM -0700, Danny Yoo wrote: > > >On Sun, 23 Apr 2006, George Georgalis wrote: > >>Hi! I've been struggling to find a way up seed hash.update() with >>the sha1 (or similar) of the file that is the program running. >> >>this is not a security task but rather a means to generate >>reasonably unique filenames based on various parameters including >>changes to the program: name = hash.hexdigest() >> >>so new files are generated when the program or parameters are >>changed; but cached files are used when identical results are >>expected. >> >>help! I cannot figure out how to pass the program body as a seed >>to hash.update(). > >Hi George, > >I'm slightly confused. Isn't this a matter of doing: > >################################################################### >def prepare_md5(filename): > m = md5.new() > m.update(open(filename).read()) ## not so smart: do this > ## progressively in real life! > return m >################################################################### I'm pretty green as far as python is concerned, but that looks good. However filename is unpredictable, as this is a website plugin module, and the path could be anything. open(filename).read() >Are you asking instead: how do I get the filename of the currently running >program? yep, that's the main part of the problem.... I have # Use a hash of the parameters to generate a cache filename. hash = sha.new(texData) hash.update( "%d %d" % (density, int(texMag)) ) hash.update( outputVersion ) name = hash.hexdigest() imageFile = "%s/%s.%s" % (imagePath, name, 'png') where outputVersion is a manual set variable in the program (so I have to purge all the imageFile each time I adjust the program. maybe this is going to work, less progressive approach # Use a hash of the parameters to generate a cache filename. hash = sha.new(texData) hash.update( "%d %d" % (density, int(texMag)) ) hash.update( open(argv[0]).read() ) name = hash.hexdigest() imageFile = "%s/%s.%s" % (imagePath, name, 'png') I cannot test till the evening because of $WORK; but is that a good way to do it? // George -- George Georgalis, systems architect, administrator < http://galis.org/ cell:646-331-2027 mailto:george at galis.org From singletoned at gmail.com Mon Apr 24 18:19:31 2006 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 24 Apr 2006 17:19:31 +0100 Subject: [Tutor] Looping over lists of objects In-Reply-To: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> References: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> Message-ID: <34bb7f5b0604240919k32aa8d13n67f87f0f073186e1@mail.gmail.com> On 24/04/06, Etrade Griffiths wrote: > Hi > > just feeling my way into Python with a small app that reads data from > file, creates objects using that data, stores the objects in a list, loops > over the list doing comparison tests to filter out various objects. Here is > a code snippet: > [snip] > > Trying to debug this using IDLE. The calls x.get_a and x.get_b always > return zero so something is going wrong somewhere. I think I'm either not > storing the objects correctly or retrieving them correctly but no idea why! > All suggestions gratefully received!!! I added some test input to give the code below, and it works fine for me. Can you give us some test input that fails for you? Can you also show us your test() function as it may the code in there that is failing. Ed class myObj: def __init__(self,a,b): self.a=a self.b=b def get_a(self): return self.a def get_b(self): return self.b input = ["1 2 3", "4 5 6"] L1=[] nobj=0 for line in input: L0=line.split() a=L0[1] b=L0[2] nobj=nobj+1 an_obj=myObj(a,b) L1.append(an_obj) # Filter data for i in range(1,nobj): for x in L1: # ... loop over all objects in list print "a -> ", x.get_a() # ... get value of a from current object print "b -> ", x.get_b() It returns: a -> 2 b -> 3 a -> 5 b -> 6 From etrade.griffiths at dsl.pipex.com Mon Apr 24 18:42:02 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Mon, 24 Apr 2006 17:42:02 +0100 Subject: [Tutor] Looping over lists of objects In-Reply-To: <34bb7f5b0604240919k32aa8d13n67f87f0f073186e1@mail.gmail.co m> References: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> <34bb7f5b0604240919k32aa8d13n67f87f0f073186e1@mail.gmail.com> Message-ID: <6.1.2.0.2.20060424173902.03734040@pop.dsl.pipex.com> Ed the problem is that my original code did not have the closing brackets for the method calls get_a and get_b whereas the code snippet I posted did. That's probably why your version works and mine failed. Thanks for your help! Alun At 17:19 24/04/2006, Ed Singleton wrote: >On 24/04/06, Etrade Griffiths wrote: > > Hi > > > > just feeling my way into Python with a small app that reads data from > > file, creates objects using that data, stores the objects in a list, loops > > over the list doing comparison tests to filter out various > objects. Here is > > a code snippet: > > >[snip] > > > > Trying to debug this using IDLE. The calls x.get_a and x.get_b always > > return zero so something is going wrong somewhere. I think I'm either not > > storing the objects correctly or retrieving them correctly but no idea why! > > All suggestions gratefully received!!! > >I added some test input to give the code below, and it works fine for >me. Can you give us some test input that fails for you? Can you also >show us your test() function as it may the code in there that is >failing. > >Ed > >class myObj: > def __init__(self,a,b): > self.a=a > self.b=b > > def get_a(self): > return self.a > > def get_b(self): > return self.b > > >input = ["1 2 3", "4 5 6"] > >L1=[] >nobj=0 > >for line in input: > L0=line.split() > a=L0[1] > b=L0[2] > nobj=nobj+1 > > an_obj=myObj(a,b) > > L1.append(an_obj) > ># Filter data > >for i in range(1,nobj): > for x in L1: # ... loop over all objects in list > print "a -> ", x.get_a() # ... get value >of a from current object > print "b -> ", x.get_b() > > >It returns: > >a -> 2 >b -> 3 >a -> 5 >b -> 6 From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 19:49:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 10:49:51 -0700 (PDT) Subject: [Tutor] How use relative path of Linux environment in Python (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 24 Apr 2006 14:28:34 +0700 From: Keo Sophon To: Danny Yoo Subject: Re: [Tutor] How use relative path of Linux environment in Python On Monday 24 April 2006 14:24, you wrote: > On Mon, 24 Apr 2006, Keo Sophon wrote: >> Do you have any idea of how to use relative path of Linux environment in >> Python. For example, if a program would like to create an oupfile from >> these assignment: outputfile = "~/Desktop/" + workingfile, while "~" is >> the short cut to the path of current user. > > This seems similar to a question that was asked and answered a few days > ago: > > http://mail.python.org/pipermail/tutor/2006-April/046613.html > > Are you trying to do something similar? Yes, same. Just a small point different, he tried to read the file, i am trying to write the file. Phon From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 19:51:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 10:51:14 -0700 (PDT) Subject: [Tutor] Locking a specific variable (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 24 Apr 2006 07:32:04 -0400 From: Tino Dai To: Danny Yoo Subject: Re: [Tutor] Locking a specific variable Hey there Danny, I'm not quite sure I get it, but ok. *grin* I'll assume that fileQueue is > an instance of the Queue class: > > http://www.python.org/doc/lib/module-Queue.html > > If so: why not allow fileQueue to grow unbounded? > > >> Presently, the only way that I can see to do this using Python is to >> combine the two functions into one and lock and unlock the entire thing >> . That doesn't seem efficient and/or elegant to me. Any pointers about >> this? > > Do you know about the thread-locking primitives? There are a few kinds > provided by Python's threading module: > > http://www.python.org/doc/lib/module-threading.html > > Are you already familiar with the concept of a RLock or a Lock? > Yup, I'm familiar with those. In all of the examples, I have seen, the critical region happens in one specific area eg a part of a function with a lock and release around it. My question is there a way to lock a specific variable so that even though other functions are attempting to access it, they will not until the first function has released it. Examples below # This example shows the way I have seen it in python tutorials def function1(): blah blah function3() blah blah def function2(): blah blah function3() blah blah def function3(): acquire lock does some stuff release lock t = Thread.thread() t.start(function1()) t.start(function2()) # The way I would like to do it, so we have two different instances of the same variable, and only # one function can access it at a time. If a function comes to that variable and finds a lock on it, # it will wait until the lock is released. And the variable happens to be a queue def function1(): blah blah acquire lock of variable only so that only function1 can access this at a given time ....increment some variable..... release the function2 lock on this variable blah blah def function2(): blah blah acquire lock of variable only so that only function2 can access this at a given time ....decrement some variable...... release the function2 lock on this variable blah blah t = Thread.thread() t.start(function1()) t.start(function2()) Does that make more sense? TIA, Tino From Barry.Carroll at psc.com Mon Apr 24 20:06:23 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 24 Apr 2006 11:06:23 -0700 Subject: [Tutor] looking to hire a tutor Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3669@eugsrv400.psc.pscnet.com> Hello, Meenakshi, > -----Original Message----- > Date: Fri, 21 Apr 2006 19:44:57 -0700 (PDT) > From: meenakshi at mbi.ucla.edu > Subject: [Tutor] looking to hire a tutor > To: tutor at python.org > Message-ID: > <1956.128.97.41.117.1145673897.squirrel at webmail.mbi.ucla.edu> > Content-Type: text/plain;charset=iso-8859-1 > > > Hi, > I apologize if this has been covered before. > I am a postdoctoral research scientist learning Python programming. I > would like to hire a tutor who can spend 1-2 hours a week with me going > overand critiquing my programming. I have looked for online Python > programming classes (not free tutorials), which offer structure and > feedback for a reasonable price. To my surprise, I havent been very > successful. > Working with online free tutorials hasnt been an ideal approach, partly > because I dont get feedback and partly because they dont completely > meet my requirements. > > How would I go about hiring a python tutor who: > > Spends time critiquing my code and providing detailed feedback. > Cares about good programming practices and is able to provide cogent > explanations of programming principles. > Can instruct me in the finer points of breaking a programming problem down > into constituent parts. > Is well versed in Python. It would be great (but not necessary) if he/she > were also familiar with data mining practices. > > I would be willing to pay 20-30$ an hour (or more depending on instructor > qualifications). > > How do I go about doing this? Any suggestions? > > Thanks > Meenakshi I agree with the others that this list is an excellent place to learn both Python and best programming practices. However, the more personal, one-on-one approach can be very useful. Have you checked the resources available there? I'm thinking particularly of the Computer Science department and the Student Placement Service (or whatever they are called on your campus). Most placement services have a student employment service (web page, bulletin board, etc) where students in need of part-time work can find job listings. Likewise, many computer science departments have a job board or web page that does the same thing. I'd be very surprised if UCLA doesn't have something similar. Good luck. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 20:16:03 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 11:16:03 -0700 (PDT) Subject: [Tutor] Looping over lists of objects In-Reply-To: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> References: <6.1.2.0.2.20060424140948.0339ab30@pop.dsl.pipex.com> Message-ID: On Mon, 24 Apr 2006, Etrade Griffiths wrote: > just feeling my way into Python with a small app that reads data from > file, creates objects using that data, stores the objects in a list, > loops over the list doing comparison tests to filter out various > objects. Here is a code snippet: > > class myObj: > def __init__(self,a,b): > self.a=a > self.b=b > > def get_a(self): > return self.a > > def get_b(self): > return self.b Hi Alun, Looks ok so far. Python specific tip: we can avoid writing getters and setters in Python. Python supports an alternative way to control how clients set and get attributes. If you're interested, look for information on Python "properties". So for now, I'd recommend simplifying this to: ########################## class myObj: def __init__(self,a,b): self.a=a self.b=b ########################## until we get into a real need to set up explicit get/set methods. > # Read data from file > > L1=[] > nobj=0 > > for line in input: > L0=line.split() > a=L0[1] > b=L0[2] > nobj=nobj+1 > > an_obj=myObj(a,b) > > L1.append(an_obj) There must be additional context here, in the sense that I don't know what 'input' is. I suspect this is a file of some sort. So unfortunately, we won't be able to test the exact same situation that you have. I'd recommend turning this into a function as well, just to make the commend superfluous: ########################## def read_data_from_file(input): L1=[] nobj=0 for line in input: L0=line.split() a=L0[1] b=L0[2] nobj=nobj+1 an_obj=myObj(a,b) L1.append(an_obj) return L1, nobj ########################## If we have this function, we can then test by doing: ##################################### L1, nobj = read_data_from_file(input) ##################################### and preserve the original behavior of our program. (We may want to do some additional revision --- the nobj variable is also superfluous.) > Trying to debug this using IDLE. The calls x.get_a and x.get_b always > return zero so something is going wrong somewhere. I think I'm either > not storing the objects correctly or retrieving them correctly but no > idea why! All suggestions gratefully received!!! I don't see anything horribly wrong with the code. There are at least two possibilities when a problem comes up: * There's something wrong with the program (which might be the case, although I don't see it yet.) * The input to the program is weird. I'll assume, for the moment, that the input may be weird. *grin* If we do have read_data_from_file() as function, we can test it by passing it hardcoded "files", and see that we get the myObj values we expect. Here's one test to start you off: #################################################### import StringIO def test1(): sample_data = StringIO.StringIO("foo\tbar\tbaz\n") objs, nobjs = read_data_from_input(sample_data) assert (len(objs) == 1 == nobjs) first_object = objs[0] assert (first_object.a == "bar") assert (first_object.b == "baz") #################################################### (This uses the very useful StringIO module to disguise a string to make it look like a file. See: http://www.python.org/doc/lib/module-StringIO.html) Does this test case make sense to you? If this test works out ok, then we've still made progress: we can at least know that our parser is working well. That bolsters the possibility that the input we're getting from our other source is weird. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 20:20:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 11:20:28 -0700 (PDT) Subject: [Tutor] Object defined by initialization parameters In-Reply-To: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> References: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> Message-ID: On Mon, 24 Apr 2006, Andre Engels wrote: > Is it possible to define a class in such a way, that if twice an object > is made with the same initialization parameters, the same object is > returned in both cases? Yes. The idea is to have the "constructor" really be a function that delegates off to actual object instantiation only after it's comfortable with the situation. That is, we can make a "factory" function. For example: ############################## class _Boolean: def __init__(self, value): self.value = value def Boolean(b): if b: return _Boolean(True) else: return _Boolean(False) ############################## The idea is that no one should directly call the underscored _Boolean(): they should go through Boolean(), which can do some additional things to make sure clients get the canonical objects. From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 20:33:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 11:33:33 -0700 (PDT) Subject: [Tutor] Locking a specific variable (fwd) In-Reply-To: References: Message-ID: > # The way I would like to do it, so we have two different instances of > the same variable, and only # one function can access it at a time. If a > function comes to that variable and finds a lock on it, # it will wait > until the lock is released. And the variable happens to be a queue Hi Tino, One way to do this is to add a level of indirection. ############################################## class LockedVariable: def __init__(self, val): self.val = val self.internal_lock = RLock() def acquire(self): self.internal_lock.acquire() def release(self): self.internal_lock.release() def with_lock(locked_variable, function): locked_variable.acquire() try: return function(locked_variable.val) finally: locked_variable.release() ############################################## The idea is that this allows us to pair up values with individual locks. There's nothing that restricts us to having one lock per program. If you have some experience with treating functions as values, the last function, with_lock(), might be useful. It's meant to be used as: ######################################################### ## Pseudocode def function_using_some_locked_resource(locked_resource): def actual_work(val): ## ... with_lock(locked_variable, actual_work) ######################################################### with_lock() here tries to capture the mutual-exclusion abstraction, and might make programs a little less error prone: we'll never forget to release the lock, because it handles both resource acquiring and releasing. From dyoo at hkn.eecs.berkeley.edu Mon Apr 24 20:38:23 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 24 Apr 2006 11:38:23 -0700 (PDT) Subject: [Tutor] hash.update( argv[0] ) In-Reply-To: <20060424145657.GK25812@sta.duo> References: <20060424004304.GH25812@sta.duo> <20060424145657.GK25812@sta.duo> Message-ID: > where outputVersion is a manual set variable in the program > (so I have to purge all the imageFile each time I adjust the > program. maybe this is going to work, less progressive approach ^^^^^^^^^^^ Hi George, Just to make sure: by "progressive", I meant the technical concept: progressive: read the file a chunk at a time rather than sucking the file all at once. *grin* > # Use a hash of the parameters to generate a cache filename. > hash = sha.new(texData) > hash.update( "%d %d" % (density, int(texMag)) ) > hash.update( open(argv[0]).read() ) > name = hash.hexdigest() > imageFile = "%s/%s.%s" % (imagePath, name, 'png') > > I cannot test till the evening because of $WORK; but is that a > good way to do it? Yes, I think this will work. One thing that it may not be robust against is changes to the current working directory. I'd recommend capturing the program's filename at the program's entry as an absolute-pathed variable, so that if we shake things up by changing current working directory, we should still be able to work. The os.path module may be useful here: http://www.python.org/doc/lib/module-os.path.html It has a few path-normalizing functions that should make this a relatively easy fix. From bgailer at alum.rpi.edu Mon Apr 24 22:17:45 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 24 Apr 2006 13:17:45 -0700 Subject: [Tutor] Object defined by initialization parameters In-Reply-To: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> References: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> Message-ID: <444D3269.7080402@alum.rpi.edu> Andre Engels wrote: > Is it possible to define a class in such a way, that if twice an > object is made with the same initialization parameters, the same > object is returned in both cases? > Use a "factory" function, and store a dictionary of instances as a class property: class myObj(object): instances = {} def __init__(self,a): # the rest of your code def makemyObj(a): if a in myObj.instances: return myObj.instances[a] else: new_instance = myObj(a) myObj.instances[a] = new_instance return new_instance [snip] From bgailer at alum.rpi.edu Mon Apr 24 22:42:21 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 24 Apr 2006 13:42:21 -0700 Subject: [Tutor] Object defined by initialization parameters ADDITION In-Reply-To: <444D3269.7080402@alum.rpi.edu> References: <6faf39c90604240746h2de7ce2cl8b3e16b0c4825297@mail.gmail.com> <444D3269.7080402@alum.rpi.edu> Message-ID: <444D382D.80807@alum.rpi.edu> Bob Gailer wrote: > Andre Engels wrote: > >> Is it possible to define a class in such a way, that if twice an >> object is made with the same initialization parameters, the same >> object is returned in both cases? >> >> > Use a "factory" function, and store a dictionary of instances as a class > property: > > class myObj(object): > instances = {} > def __init__(self,a): > # the rest of your code > > def makemyObj(a): > if a in myObj.instances: > return myObj.instances[a] > else: > new_instance = myObj(a) > myObj.instances[a] = new_instance > return new_instance > > I neglected to show the function call: a = makemyObj("a") b = makemyObj("b") c = makemyObj("a") a and c will point to the same object b will be a different object -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060424/889db232/attachment.html From andre.roberge at gmail.com Mon Apr 24 23:37:01 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 24 Apr 2006 18:37:01 -0300 Subject: [Tutor] Avoiding the use of files to store intermediate results Message-ID: <7528bcdd0604241437sf6b9af1w34ba011e6bc0a300@mail.gmail.com> I wrote a small wxPython based app to test code snippets. (google for "python lightning compiler" if you want to see the full code). In the basic mode, I redirect the standard input and output and execute the code taken from the editor window so that the result appears in the output window. Here are the 4 main lines of code to accomplish this: sys.stdout = self.outputWindow sys.stderr = self.outputWindow user_code = self.PythonEditor.GetText() exec user_code in myGlobals For example, if I have the following situation: ====input window==== print "Hello world!" ==================== the result of running the program will be this: ====output window=== Hello world! ==================== Simple enough :-) [Actually, there's more to it, but this description should suffice for illustration purposes.] Now, I want to be able to test the code using the doctest module. I can't use exec as doctest.testmod() will be testing my entire application, not simply the code in the input window! The solution I chose was to 1. Create a new file which contains the code to be tested with the appropriate "doctest" call. 2. Run this file with Python, redirecting the result to a second file. 3. Read the result from the second file into a string. 4. Print the string (which, because of redirection) appears in the output window. Here are the main lines of code to do this: sys.stdout = self.outputWindow sys.stderr = self.outputWindow user_code = self.PythonEditor.GetText() user_code += "\nimport doctest\ndoctest.testmod()" f = open('_doctest_file.py', 'w') f.write(user_code) f.close() if verbose: os.popen("python _doctest_file.py -v> _doctest_file.output") else: os.popen("python _doctest_file.py> _doctest_file.output") result = open("_doctest_file.output", 'r').read() print result ###### While this works, I find it "messy", as it creates some intermediate files. I was wondering if there was a better way to do things all in memory, in an OS independent way. [Note that the complete application is approximately 665 lines long ... a bit too much to post all here :-)] Andr? From kent37 at tds.net Tue Apr 25 00:25:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Apr 2006 18:25:57 -0400 Subject: [Tutor] Locking a specific variable (fwd) In-Reply-To: References: Message-ID: <444D5075.6050002@tds.net> > Yup, I'm familiar with those. In all of the examples, I have seen, the > critical region happens in one specific area eg a part of a function with a > lock and release around it. My question is there a way to lock a specific > variable so that even though other functions are attempting to access it, > they will not until the first function has released it. Examples below > > # This example shows the way I have seen it in python tutorials > def function1(): > blah blah > function3() > blah blah > > def function2(): > blah blah > function3() > blah blah > > def function3(): > acquire lock > does some stuff > release lock > > t = Thread.thread() > t.start(function1()) > t.start(function2()) What is wrong with doing exactly this? > > # The way I would like to do it, so we have two different instances of the > same variable, and only # one function can access it at a time. If a I don't understand what you mean by "two different instances of the same variable." Can you give an example? > function comes to that variable and finds a lock on it, # it will wait until > the lock is released. And the variable happens to be a queue Do you know that Queues are already thread safe? They use locks internally and are intended for multi-threaded use. You shouldn't have to use any additional locks to use a Queue. > def function1(): > blah blah > acquire lock of variable only so that only function1 can access this at > a given time > ....increment some variable..... > release the function2 lock on this variable > blah blah > > def function2(): > blah blah > acquire lock of variable only so that only function2 can access this at > a given time > ....decrement some variable...... > release the function2 lock on this variable > blah blah > > t = Thread.thread() > t.start(function1()) > t.start(function2()) This code is the same as the first version except function3() has been inlined. I don't see the benefit of this style, it just causes code duplication. Kent From oztriking at hotmail.com Tue Apr 25 00:53:42 2006 From: oztriking at hotmail.com (John Connors) Date: Tue, 25 Apr 2006 08:53:42 +1000 Subject: [Tutor] Importing Modules Message-ID: G'day, I'm having trouble understanding the difference between, import sys and from sys import * It seems to me they both do the same thing. John _________________________________________________________________ New year, new job – there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT From ukc802591034 at btconnect.com Tue Apr 25 01:28:59 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Tue, 25 Apr 2006 00:28:59 +0100 Subject: [Tutor] Importing Modules References: Message-ID: > I'm having trouble understanding the difference between, > > import sys This brings the *name* "sys" into your module. It does not give you access to any of the names inside sys itself (such as exit for example). To access those you need to prefix them with sys, as in sys.exit() > from sys import * This does NOT bring the name "sys" into your module, instead it brings all of the names inside sys(like exit for example) into your module. Now you can access those names without a prefix, like this: exit() So why not do that instead of import sys? The reason is that the second form will overwrite and names you have already declared - like exit say. exit = 42 from sys import * # hides my exit variable. OR more likely, the other way round from sys import * exit = 42 # now hides the sys.exit function so I can't use it. Of course some of these are obvious but there can be a lot of names in a module, and some modules have the same name in them, for example: from os import * from urllib import * open(foo) # which open gets called, os.open or urllib.open? Can you see how it gets confusing. Bottom line is it is usually better to accept the extra typing and use import foo or for just a few names from foo import bar,baz > It seems to me they both do the same thing. A subtle but very important difference! HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From paul.churchill at cyanfusion.com Tue Apr 25 01:06:35 2006 From: paul.churchill at cyanfusion.com (Paul Churchill) Date: Tue, 25 Apr 2006 00:06:35 +0100 Subject: [Tutor] Dictionaries and aggregation Message-ID: <20060424230638.B94F1E000314@ranger.systems.pipex.net> I am trying to create a dictionary using data produced by a load balancing admin tool and aggregate the results. When I invoke the tool from within the shell ('sudo ~/ZLBbalctl --action=cells') the following output is produced: Load Balancer 1 usage, over the last 30 seconds Port 80, rules - /(nol)|(ws) server001 alive 18.1% 2 requests/s 14536543 total server002 alive 43.1% 7 requests/s 14842618 total server003 alive 21.2% 2 requests/s 14884487 total server004 alive 17.3% 2 requests/s 15092053 total Load Balancer 2 usage, over the last 30 seconds Port 80, rules - /(nol)|(ws) server001 alive 11.6% 2 requests/s 14482578 total server002 alive 35.6% 9 requests/s 14820991 total server003 alive 28.7% 6 requests/s 14928991 total server004 alive 23.7% 5 requests/s 15147525 total I have managed to get something close to what I'm looking for using lists i.e. the aggregate of the fourth column (requests/s) lbstat = commands.getoutput("sudo ~/ZLBbalctl --action=cells | awk '$1 ~ /^server00/ { print $4 }'") rLst = lbstat.split('\n') rLst = [ int(rLst[i]) for i in range(len(rLst)) ] rTotal = reduce(operator.add, rLst) However here's what I'm now trying to do: 1) Not have to rely on using awk at all. 2) Create a dictionary with server names for keys e.g. server001, server002 etc and the aggregate of the request for that server as the value part of the pairing. I got this far with part 1) lbstat = commands.getoutput("sudo ~/ZLBbalctl --action=cells") tmpLst = lbstat.split('\n') rLst = [] for i in tmpLst: m = re.search(' server[0-9]+', i) if m: rLst.append(i) for i in rLst: print i, type(i) server001 alive 22.3% 6 requests/s 14527762 total server002 alive 23.5% 7 requests/s 14833265 total server003 alive 38.2% 14 requests/s 14872750 total server004 alive 15.6% 4 requests/s 15083443 total server001 alive 24.1% 8 requests/s 14473672 total server002 alive 23.2% 7 requests/s 14810866 total server003 alive 30.2% 8 requests/s 14918322 total server004 alive 22.1% 6 requests/s 15137847 total At this point I ran out of ideas and began to think that there must be something fundamentally wrong with my approach. Not least of my concerns was the fact that I needed integers and these were strings. Any help would be much appreciated. Regards, Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060425/9c5b85dd/attachment.html From mahansen at adelphia.net Tue Apr 25 02:49:27 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Mon, 24 Apr 2006 18:49:27 -0600 Subject: [Tutor] Tutor FAQ? In-Reply-To: <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> References: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <006501c6656d$47061760$28645f0a@mikehansen> <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> Message-ID: <80c1f08bd55ab2e8aaa6429972268381@adelphia.net> On Apr 22, 2006, at 3:15 AM, Fredrik Lundh wrote: > Ed wrote: > >> I don't think the FAQ is open to public editing yet. I'm not sure >> when it will be, but Fredrik might be able to give a timescale. > > There are a few known conversion issues to deal with (the FAQ uses > a lot more "looks like markdown syntax" than the tutorial, which con- > fused the converter). I've made some progress, but it'll probably take > another week before everything's sorted out. > > When Ed brought up the tutor/tutorial FAQ idea, my first thought > was that Ed and other volunteers could add pages in a separate > "tutor-" namespace (to avoid collisions with material from the > existing FAQ), and ended up writing a couple of paragraphs on > how to manually convert titles to page names. When I found that > I had written "this isn't quite as hard as it may look", I realized > that it would be better if I just wrote a script that did this. > > So, while I'm working on that script, I suggest that you start adding > stuff the "tutor suggestion" page that I just set up: > > http://pyfaq.infogami.com/suggest-tutor > > One entry per comment; use "## title" to mark the first line as the > FAQ entry. I've added Mike's examples. > > cheers /F > Hi, I'll post the questions and answers to the list first. If I don't get any corrections or clarifications in a day or so after posting, I'll add it to the tutor suggestion page. Ed mentioned that you are using restructured text. Should I put the entry in restructured text? I spent some time last night reading up on restructured text and docutils. Thanks, Mike From mahansen at adelphia.net Tue Apr 25 03:09:19 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Mon, 24 Apr 2006 19:09:19 -0600 Subject: [Tutor] Invoking Excel Macro In-Reply-To: <8e82677d0604240632u30b251d6rdef568795fbdb74a@mail.gmail.com> References: <8e82677d0604210044r1cb7be48q4ef259203eb6acf9@mail.gmail.com> <004901c66561$fb0b1b40$28645f0a@mikehansen> <8e82677d0604240632u30b251d6rdef568795fbdb74a@mail.gmail.com> Message-ID: <1a440e03c896f6cc81b04b73ca7ba0d1@adelphia.net> I guess I'm confused. You mentioned that it still throws and error while trying to save the workbook. hmmm.... Do you get this error when trying to close Excel in the macro? Many times, Excel pops up a dialog box when closing it if there's still a workbook open even if it has been saved. That's where the Application.DisplayAlerts comes in. So I may have been a little off on the part of saving. It might be the closing of Excel. Other than that, I'm stumped. Mike On Apr 24, 2006, at 7:32 AM, arun wrote: > Hi Mike, > ?? It doesn't? display any dialog box rather it gives a temporary name > to the file. > Ex > ?newsheet.xls as newsheet1.xls > So i'm not able to save it. Is? there an alternative to invoke the? > macro and save the file from my script itself .(saving it through > macro wud be a better option : )? ) > ? > Thanx? and Regards, > arun > > ? > On 4/21/06, Mike Hansen wrote: In the macro, > you might try Application.DisplayAlerts = False? and reset it to?True > after you save. >> I think it might be trying to display a dialog box before it saves. >> ? >> Mike >> >>> From: tutor-bounces at python.org [mailto: tutor-bounces at python.org] On >>> Behalf Of arun >>> Sent: Friday, April 21, 2006 1:44 AM >>> To: tutor at python.org >>> Subject: Re: [Tutor] Invoking Excel Macro >>> >>> ?I'm sorry , there is something realy wrong with 'Run-time error >>> 1004':. I have fixed it now but still it throws an error while >>> trying to save the workbook. >> >> On 4/21/06, arun wrote: Hi, >>> I tried invoking a macro from my python script and ?It is ?throwing? >>> an error message that reads 'Run-time error 1004': >>> ? >>> "This operation requires the merged cells to be identically sized" >>> ? >>> My script looks like this >>> ? >>> from win32com.client import Dispatch >>> xl = Dispatch('Excel.Application') >>> xl.Workbooks.Add('E:\Templates\sample.xls') >>> xl.Run('Import_file')? # name of the macro >>> ? >>> Also while (running the macro)opening the workbook it??names it as >>> ?"sample1.xls' ,and so >>> It says there is no such file sample.xls >>> ? >>> " >>> Filename =? Myexcel.xls >>> Workbooks("sample.xls").SaveAs Filename >>> " >>> ? >>> Can somebody help me with this issue : ( >>> ? >>> ? >>> Thanx >>> arun? >>> ? >>> ? >>> >>> >>> ? >> >> >> -- >> arun > > > > -- > arun_______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fredrik at pythonware.com Tue Apr 25 03:40:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Apr 2006 03:40:11 +0200 Subject: [Tutor] Tutor FAQ? In-Reply-To: <80c1f08bd55ab2e8aaa6429972268381@adelphia.net> References: <34bb7f5b0604210638q5081f5adhaa8c7a883a964f68@mail.gmail.com> <006501c6656d$47061760$28645f0a@mikehansen> <34bb7f5b0604220039q5e93257fn55320ac151a4342d@mail.gmail.com> <368a5cd50604220215l3d5d1ea7kae81e81ad417c2b4@mail.gmail.com> <80c1f08bd55ab2e8aaa6429972268381@adelphia.net> Message-ID: <368a5cd50604241840l72e49b0dnb616f22f5bbb15cd@mail.gmail.com> Mike Hansen wrote: > I'll post the questions and answers to the list first. If I don't get > any corrections or clarifications in a day or so after posting, I'll > add it to the tutor suggestion page. excellent! > Ed mentioned that you are using restructured text. Should I put > the entry in restructured text? I spent some time last night reading > up on restructured text and docutils. the infogami site uses markdown, which is a similar (but a bit simpler, imo) syntax. There's a very brief introduction on http://pyfaq.infogami.com/suggest-tutor (which basically says that you should use ## to mark the entry title, and indent all code snippets by at least four spaces) and there's an on-line test editor here: http://daringfireball.net/projects/markdown/dingus (that pages also contains a cheatsheet and links to full documentation). When this is moved over to python.org, it'll either be handled as HTML or converted to ReST (which is the main syntax used on python.org), but that'll all be taken care of by tools. The important thing now is to get the content in place. cheers /F From payal-python at scriptkitchen.com Tue Apr 25 05:09:24 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Mon, 24 Apr 2006 23:09:24 -0400 Subject: [Tutor] need to automate connection Message-ID: <20060425030924.GA26232@tranquility.scriptkitchen.com> Hi, I need to automate connection to a IP like this. The IP (or domain name) is taken from command line or from user (whichever is easier for me to code). It should emulate, telnet 127.0.0.1 25 mail from: 250 ok rcpt to: 250 ok quit Can Python do this for me? How do I start? With warm regards, -Payal From hugonz-lists at h-lab.net Tue Apr 25 05:09:48 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 24 Apr 2006 21:09:48 -0600 Subject: [Tutor] Avoiding the use of files to store intermediate results In-Reply-To: <7528bcdd0604241437sf6b9af1w34ba011e6bc0a300@mail.gmail.com> References: <7528bcdd0604241437sf6b9af1w34ba011e6bc0a300@mail.gmail.com> Message-ID: <444D92FC.5060705@h-lab.net> Remember duck typing. An object just needs to look like a file in order to be used like one. Guido's time machine has already forseen your problem. Take a look at the StringIO module. It allows you to use a string where you would normally pass a file object. Hope that helps, Hugo > ###### > While this works, I find it "messy", as it creates some intermediate > files. I was wondering if there was a better way to do things all in > memory, in an OS independent way. > > [Note that the complete application is approximately 665 lines long > ... a bit too much > to post all here :-)] > > Andr? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tvbare at socket.net Tue Apr 25 03:27:25 2006 From: tvbare at socket.net (->Terry<-) Date: Mon, 24 Apr 2006 20:27:25 -0500 (CDT) Subject: [Tutor] Importing Modules In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Tomorrow (Apr 25, 2006) at 8:53am, John Connors spoke these wise words: - ->G'day, - -> - ->I'm having trouble understanding the difference between, - -> - ->import sys - ->and - ->from sys import * - -> - ->It seems to me they both do the same thing. - -> - ->John import sys imports sys elements in their own namespace use by preceding elements with 'sys.' from sys import * imports sys elements in the local namespace use elements as any other local - no 'sys.' prefix d:^) - -- Terry ', .-`-,\__ ."` `, .'_. ._ `;. __ / ` ` `.\ .--. /--,| 0) 0) )`_.-,) | ;.-----.__ _-'); / '--./ `.`/ `"` : '` |. | \ / // \ '---' /' `------' \ jgs/a:f _/ `--... -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFETXsAQvSnsfFzkV0RApBrAJ9gKu6tnxF8cAkmRpqfd8eFPxdEZACdGSk+ 0AvUDxCmUZ+cZeHnp0VHid8= =a8iW -----END PGP SIGNATURE----- From ml.cyresse at gmail.com Tue Apr 25 08:59:29 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 25 Apr 2006 18:59:29 +1200 Subject: [Tutor] need to automate connection In-Reply-To: <20060425030924.GA26232@tranquility.scriptkitchen.com> References: <20060425030924.GA26232@tranquility.scriptkitchen.com> Message-ID: Hi Payal, I see you're connecting to an smtp server Any particular reason yoou can't use smtplib? http://www.python.org/doc/current/lib/module-smtplib.html Here's a sample script using smtplib to send an email - import smtplib ip = "127.0.0.1" txt = "This is an email message" c = smtplib.SMTP(ip) c.sendmail("sender at server.net", "recipient at remote_server.net", txt) c.close() Although it's better to use an email.Message object for this - http://www.python.org/doc/current/lib/module-email.Message.html Here's the same script with an email.Message import smtplib import email.Message as Mg ip = "127.0.0.1" msg = Mg.Message() msg["To"] = "recipient at remote_server.net msg["From"] = "sender at server.net" msg["Subject"] = "Test message" msg["Reply-To"] = "alternate_address at server.net" txt = "This is an email message" msg.set_payload(txt) c = smtplib.SMTP(ip) c.sendmail("sender at server.net", "recipient at remote_server.net", msg.as_string()) c.close() Regards, Liam Clarke On 4/25/06, Payal Rathod wrote: > Hi, > I need to automate connection to a IP like this. The IP (or domain name) > is taken from command line or from user (whichever is easier for me to > code). It should emulate, > > telnet 127.0.0.1 25 > > mail from: > 250 ok > rcpt to: > 250 ok > quit > > Can Python do this for me? How do I start? > > With warm regards, > -Payal > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Tue Apr 25 09:04:16 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 25 Apr 2006 19:04:16 +1200 Subject: [Tutor] Invoking Excel Macro In-Reply-To: <1a440e03c896f6cc81b04b73ca7ba0d1@adelphia.net> References: <8e82677d0604210044r1cb7be48q4ef259203eb6acf9@mail.gmail.com> <004901c66561$fb0b1b40$28645f0a@mikehansen> <8e82677d0604240632u30b251d6rdef568795fbdb74a@mail.gmail.com> <1a440e03c896f6cc81b04b73ca7ba0d1@adelphia.net> Message-ID: Hi Arun et al, Google says - http://support.microsoft.com/default.aspx?scid=kb;en-us;210684 "This problem can occur when you give the workbook a defined name and then copy the worksheet several times without first saving and closing the workbook, as in the following sample code..." (code is in above article) """To resolve this problem, save and close the workbook periodically while the copy process is occurring, as in the following sample code""" ditto above The issue is your macro. As such, there are some excellent Excel and VBA related help forums on the net. Good luck! Regards, Liam Clarke On 4/25/06, Mike Hansen wrote: > I guess I'm confused. You mentioned that it still throws and error > while trying to save the workbook. hmmm.... Do you get this error when > trying to close Excel in the macro? Many times, Excel pops up a dialog > box when closing it if there's still a workbook open even if it has > been saved. That's where the Application.DisplayAlerts comes in. So I > may have been a little off on the part of saving. It might be the > closing of Excel. Other than that, I'm stumped. > > Mike > > On Apr 24, 2006, at 7:32 AM, arun wrote: > > > Hi Mike, > > It doesn't display any dialog box rather it gives a temporary name > > to the file. > > Ex > > newsheet.xls as newsheet1.xls > > So i'm not able to save it. Is there an alternative to invoke the > > macro and save the file from my script itself .(saving it through > > macro wud be a better option : ) ) > > > > Thanx and Regards, > > arun > > > > > > On 4/21/06, Mike Hansen wrote: In the macro, > > you might try Application.DisplayAlerts = False and reset it toTrue > > after you save. > >> I think it might be trying to display a dialog box before it saves. > >> > >> Mike > >> > >>> From: tutor-bounces at python.org [mailto: tutor-bounces at python.org] On > >>> Behalf Of arun > >>> Sent: Friday, April 21, 2006 1:44 AM > >>> To: tutor at python.org > >>> Subject: Re: [Tutor] Invoking Excel Macro > >>> > >>> I'm sorry , there is something realy wrong with 'Run-time error > >>> 1004':. I have fixed it now but still it throws an error while > >>> trying to save the workbook. > >> > >> On 4/21/06, arun wrote: Hi, > >>> I tried invoking a macro from my python script and It is throwing > >>> an error message that reads 'Run-time error 1004': > >>> > >>> "This operation requires the merged cells to be identically sized" > >>> > >>> My script looks like this > >>> > >>> from win32com.client import Dispatch > >>> xl = Dispatch('Excel.Application') > >>> xl.Workbooks.Add('E:\Templates\sample.xls') > >>> xl.Run('Import_file') # name of the macro > >>> > >>> Also while (running the macro)opening the workbook itnames it as > >>> "sample1.xls' ,and so > >>> It says there is no such file sample.xls > >>> > >>> " > >>> Filename = Myexcel.xls > >>> Workbooks("sample.xls").SaveAs Filename > >>> " > >>> > >>> Can somebody help me with this issue : ( > >>> > >>> > >>> Thanx > >>> arun > >>> > >>> > >>> > >>> > >>> > >> > >> > >> -- > >> arun > > > > > > > > -- > > arun_______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Apr 25 12:31:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 06:31:31 -0400 Subject: [Tutor] Importing Modules In-Reply-To: References: Message-ID: <444DFA83.3010309@tds.net> John Connors wrote: > G'day, > > I'm having trouble understanding the difference between, > > import sys > and > from sys import * The second style is strongly discouraged. As Alan pointed out, it can lead to surprises when you import more than you expect. I was once surprised to find out that when I write something like a.py #### foo = 1 bar = 2 b.py #### from a import * c.py #### from b import * Now foo and bar are defined in module c!! The other reason to avoid this style is it removes clues about where a name is defined. If in module c above you want to know where foo comes from, it would be hard to find out. On the other hand if I wrote from a import foo then a search within c would show me where foo is defined. Kent From john.hsu at clear.net.nz Tue Apr 25 07:11:32 2006 From: john.hsu at clear.net.nz (John Hsu) Date: Tue, 25 Apr 2006 17:11:32 +1200 Subject: [Tutor] How to compile _tkinter in Fedora Core 4 Message-ID: <444DAF84.6070805@clear.net.nz> Hi I'd very much appreciate your help if you can advise me how to compile _tkinter in Fedora 4. I installed Fedora core 4 in my machine recently, but struggled to get Tk working for me. The Tcl/Tk is working O.K. because I can run demo programs from /usr/share/tk8.4/demos. The error is caused by missing _tkinter library, and clearly there is no Tkinter module to be imported. I managed to download and recompile a new version of Python (2.4.3), then run "make test". The error message says: ... test_tcl test_tcl skipped -- No module named _tkinter ... 1 skip unexpected on linux2: test_tcl ... John Hsu From kent37 at tds.net Tue Apr 25 12:43:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 06:43:56 -0400 Subject: [Tutor] Dictionaries and aggregation In-Reply-To: <20060424230638.B94F1E000314@ranger.systems.pipex.net> References: <20060424230638.B94F1E000314@ranger.systems.pipex.net> Message-ID: <444DFD6C.7080606@tds.net> > However here's what I'm now trying to do: > > 1) Not have to rely on using awk at all. > > > 2) Create a dictionary with server names for keys e.g. server001, > server002 etc and the aggregate of the request for that server as the value > part of the pairing. > > > I got this far with part 1) > > lbstat = commands.getoutput("sudo ~/ZLBbalctl --action=cells") > tmpLst = lbstat.split('\n') > > rLst = [] > for i in tmpLst: > m = re.search(' server[0-9]+', i) > if m: > rLst.append(i) > > for i in rLst: > print i, type(i) > > server001 alive 22.3% 6 requests/s 14527762 total > server002 alive 23.5% 7 requests/s 14833265 total > server003 alive 38.2% 14 requests/s 14872750 total > server004 alive 15.6% 4 requests/s 15083443 total > server001 alive 24.1% 8 requests/s 14473672 total > server002 alive 23.2% 7 requests/s 14810866 total > server003 alive 30.2% 8 requests/s 14918322 total > server004 alive 22.1% 6 requests/s 15137847 total > > At this point I ran out of ideas and began to think that there must be > something fundamentally wrong with my approach. Not least of my concerns was > the fact that I needed integers and these were strings. Don't get discouraged, you are on the right track! You had one big string that included some data you are interested in and some you don't want, you have converted that to a list of strings containing only the lines of interest. That is a good first step. Now you have to extract the data you want out of each line. Use line.split() to split the text into fields by whitespace: In [1]: line = ' server001 alive 22.3% 6 requests/s 14527762 total' In [2]: line.split() Out[2]: ['server001', 'alive', '22.3%', '6', 'requests/s', '14527762', 'total'] Indexing will pull out the field you want: In [3]: line.split()[5] Out[3]: '14527762' It's still a string: In [4]: type(line.split()[5]) Out[4]: Use int() to convert a string to an integer: In [5]: int(line.split()[5]) Out[5]: 14527762 Then you have to figure out how to accumulate the values in a dictionary but get this much working first. Kent From payal-python at scriptkitchen.com Tue Apr 25 12:59:36 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Tue, 25 Apr 2006 06:59:36 -0400 Subject: [Tutor] need to automate connection In-Reply-To: References: <20060425030924.GA26232@tranquility.scriptkitchen.com> Message-ID: <20060425105936.GA12328@tranquility.scriptkitchen.com> On Tue, Apr 25, 2006 at 06:59:29PM +1200, Liam Clarke wrote: > Hi Payal, > > I see you're connecting to an smtp server Any particular reason yoou > can't use smtplib? > http://www.python.org/doc/current/lib/module-smtplib.html Because I don't know it exists :) But I don't want to send any mail. I just want to establish a connection send MAIL TO: and RCPT TO: and exit. Any ideas with that? With warm regards, -Payal From kraus at hagen-partner.de Tue Apr 25 13:27:35 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 25 Apr 2006 13:27:35 +0200 Subject: [Tutor] need to automate connection In-Reply-To: <20060425105936.GA12328@tranquility.scriptkitchen.com> References: <20060425030924.GA26232@tranquility.scriptkitchen.com> <20060425105936.GA12328@tranquility.scriptkitchen.com> Message-ID: Payal Rathod wrote: > On Tue, Apr 25, 2006 at 06:59:29PM +1200, Liam Clarke wrote: > >>Hi Payal, >> >>I see you're connecting to an smtp server Any particular reason yoou >>can't use smtplib? >>http://www.python.org/doc/current/lib/module-smtplib.html > > > Because I don't know it exists :) > > But I don't want to send any mail. I just want to establish a connection > send MAIL TO: and RCPT TO: and exit. > Any ideas with that? With warm regards, > -Payal What about telnetlib? ;-) http://docs.python.org/lib/module-telnetlib.html HTH, Wolfram From kent37 at tds.net Tue Apr 25 14:48:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 08:48:37 -0400 Subject: [Tutor] need to automate connection In-Reply-To: <20060425105936.GA12328@tranquility.scriptkitchen.com> References: <20060425030924.GA26232@tranquility.scriptkitchen.com> <20060425105936.GA12328@tranquility.scriptkitchen.com> Message-ID: <444E1AA5.509@tds.net> Payal Rathod wrote: > On Tue, Apr 25, 2006 at 06:59:29PM +1200, Liam Clarke wrote: >> Hi Payal, >> >> I see you're connecting to an smtp server Any particular reason yoou >> can't use smtplib? >> http://www.python.org/doc/current/lib/module-smtplib.html > > Because I don't know it exists :) > > But I don't want to send any mail. I just want to establish a connection > send MAIL TO: and RCPT TO: and exit. > Any ideas with that? With warm regards, smtplib.SMTP has a docmd() method. Something like this (not tested so probably not quite right): import smtplib smtp = smtplib.SMTP('127.0.0.1') print smtp.docmd('mail', 'from: ') print smtp.docmd('rcpt', 'to: ') Kent From pjlists at gmail.com Tue Apr 25 15:50:19 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 25 Apr 2006 15:50:19 +0200 Subject: [Tutor] Problem installing MySQLdb under windows Message-ID: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> I am running Python 2.4.3, MySQL 5.0. On trying to install MySQLdb 1.2.1 I ran into the following problem. " D:\Python24\Lib\site-packages\MySQLdb>setup.py build running build running build_py copying MySQLdb\release.py -> build\lib.win32-2.4\MySQLdb running build_ext error: The .NET Framework SDK needs to be installed before building extensions f or Python. " Is it really necessary to install The .NET Framework SDK (354Mb) or is there a simpler way? Thanks for any help Peter Jessop -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060425/280406b9/attachment.html From ml.cyresse at gmail.com Tue Apr 25 16:00:43 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 26 Apr 2006 02:00:43 +1200 Subject: [Tutor] Problem installing MySQLdb under windows In-Reply-To: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> References: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> Message-ID: Hi Peter, you can use a different compiler if you have one, such as mingw32, but I find compiling extensions on Windows is very problematic. Any particular features of MySQLdb 1.2.1 you need? 1.2.0 has a Windows version precompiled - http://prdownloads.sourceforge.net/mysql-python/MySQL-python.exe-1.2.0.win32-py2.4.zip?download If you really need to compile it, grab mingw32 and use the --compiler option for setup.py i.e. setup.py build --compiler mingw32, but I've had heaps of trouble with including Python headers, so YMMV. Regards, Liam Clarke On 4/26/06, Peter Jessop wrote: > I am running Python 2.4.3, MySQL 5.0. > On trying to install MySQLdb 1.2.1 I ran into the following problem. > " > D:\Python24\Lib\site-packages\MySQLdb>setup.py build > running build > running build_py > copying MySQLdb\release.py -> build\lib.win32- 2.4\MySQLdb > running build_ext > error: The .NET Framework SDK needs to be installed before building > extensions f > or Python. > > " > Is it really necessary to install The .NET Framework SDK (354Mb) or is there > a simpler way? > > Thanks for any help > > Peter Jessop > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Tue Apr 25 16:12:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 10:12:33 -0400 Subject: [Tutor] Problem installing MySQLdb under windows In-Reply-To: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> References: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> Message-ID: <444E2E51.8050802@tds.net> Peter Jessop wrote: > I am running Python 2.4.3, MySQL 5.0. > On trying to install MySQLdb 1.2.1 I ran into the following problem. > " > D:\Python24\Lib\site-packages\MySQLdb>setup.py build > running build > running build_py > copying MySQLdb\release.py -> build\lib.win32- 2.4\MySQLdb > running build_ext > error: The .NET Framework SDK needs to be installed before building > extensions f > or Python. > > " > Is it really necessary to install The .NET Framework SDK (354Mb) or is > there a simpler way? Download the windows binary, for example http://prdownloads.sourceforge.net/mysql-python/MySQL-python.exe-1.2.0.win32-py2.4.zip?download The latest version with a Windows build is 1.2.0. Kent From pjlists at gmail.com Tue Apr 25 16:48:38 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 25 Apr 2006 16:48:38 +0200 Subject: [Tutor] Problem installing MySQLdb under windows In-Reply-To: <444E2E51.8050802@tds.net> References: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> <444E2E51.8050802@tds.net> Message-ID: <7a8d5a0c0604250748g7d2e9db4w72bf570fce71f238@mail.gmail.com> Thanks Liam and Kent. Problem is now sorted. Which brings me on to my next question... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060425/fa656194/attachment.html From pjlists at gmail.com Tue Apr 25 16:51:56 2006 From: pjlists at gmail.com (Peter Jessop) Date: Tue, 25 Apr 2006 16:51:56 +0200 Subject: [Tutor] Generating static WEB sites Message-ID: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> I am looking at generating static web pages. What I wish to do is periodically regenerate a WEB site form HTML, text and MySQL data. I have been experimenting with HTMLgen and this seems to be adequate for what I need. However HTMLgen does not seem to have been updated for a while and I was wondering if I should be looking at any other packages. Any suggestions? Thanks Peter Jessop -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060425/4e783d19/attachment.htm From andy.koch at pc-doctor.com Tue Apr 25 16:47:01 2006 From: andy.koch at pc-doctor.com (Andy Koch) Date: Tue, 25 Apr 2006 07:47:01 -0700 Subject: [Tutor] Problem installing MySQLdb under windows In-Reply-To: <444E2E51.8050802@tds.net> References: <7a8d5a0c0604250650q228d4b0cg967234e8b2df628a@mail.gmail.com> <444E2E51.8050802@tds.net> Message-ID: Kent Johnson wrote: > Peter Jessop wrote: >> I am running Python 2.4.3, MySQL 5.0. >> On trying to install MySQLdb 1.2.1 I ran into the following problem. >> " >> D:\Python24\Lib\site-packages\MySQLdb>setup.py build >> running build >> running build_py >> copying MySQLdb\release.py -> build\lib.win32- 2.4\MySQLdb >> running build_ext >> error: The .NET Framework SDK needs to be installed before building >> extensions f >> or Python. >> >> " >> Is it really necessary to install The .NET Framework SDK (354Mb) or is >> there a simpler way? > > Download the windows binary, for example > http://prdownloads.sourceforge.net/mysql-python/MySQL-python.exe-1.2.0.win32-py2.4.zip?download > > The latest version with a Windows build is 1.2.0. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Greetings Python group, I have a question related to the MySQLdb, I have recently installed the 1.2.0 version and it works fine. However, I am running ver. 4.1 of MySQL and the problem is that the python client version does not support the new password protocol of MySQL 4.1+. This only means that one must go into the MySQL and set the password using the OLD_PASSWORD function of MySQL. The question, do any of the newer versions of MySQLdb support the new password protocol? And if not, are there plans to implement this? Disclosure: this is my first post in this group, also it may be worth noting that I'm learning python as a side effect of developing a Plone site. So if my python knowledge comes across as a bit warped... well, Plone can sometimes be a strange thing ;) Regards, Andy Koch From kent37 at tds.net Tue Apr 25 17:03:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 11:03:09 -0400 Subject: [Tutor] Generating static WEB sites In-Reply-To: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> References: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> Message-ID: <444E3A2D.6030607@tds.net> Peter Jessop wrote: > I am looking at generating static web pages. > What I wish to do is periodically regenerate a WEB site form HTML, text > and MySQL data. > > I have been experimenting with HTMLgen and this seems to be adequate for > what I need. > > However HTMLgen does not seem to have been updated for a while and I was > wondering if I should be looking at any other packages. > > Any suggestions? Many. See this page, the sections Templating Engines, HTML Shorthand Processors and HTML Generation class libraries: http://wiki.python.org/moin/WebProgramming Kent From paul.churchill at cyanfusion.com Tue Apr 25 20:00:26 2006 From: paul.churchill at cyanfusion.com (paul.churchill at cyanfusion.com) Date: Tue, 25 Apr 2006 19:00:26 +0100 Subject: [Tutor] Dictionaries and aggregation In-Reply-To: <444DFD6C.7080606@tds.net> References: <20060424230638.B94F1E000314@ranger.systems.pipex.net> <444DFD6C.7080606@tds.net> Message-ID: Kent Johnson writes: >> However here's what I'm now trying to do: >> >> 1) Not have to rely on using awk at all. >> >> >> 2) Create a dictionary with server names for keys e.g. server001, >> server002 etc and the aggregate of the request for that server as the value >> part of the pairing. >> >> >> I got this far with part 1) >> >> lbstat = commands.getoutput("sudo ~/ZLBbalctl --action=cells") >> tmpLst = lbstat.split('\n') >> >> rLst = [] >> for i in tmpLst: >> m = re.search(' server[0-9]+', i) >> if m: >> rLst.append(i) >> >> for i in rLst: >> print i, type(i) >> >> server001 alive 22.3% 6 requests/s 14527762 total >> server002 alive 23.5% 7 requests/s 14833265 total >> server003 alive 38.2% 14 requests/s 14872750 total >> server004 alive 15.6% 4 requests/s 15083443 total >> server001 alive 24.1% 8 requests/s 14473672 total >> server002 alive 23.2% 7 requests/s 14810866 total >> server003 alive 30.2% 8 requests/s 14918322 total >> server004 alive 22.1% 6 requests/s 15137847 total >> >> At this point I ran out of ideas and began to think that there must be >> something fundamentally wrong with my approach. Not least of my concerns was >> the fact that I needed integers and these were strings. > > Don't get discouraged, you are on the right track! You had one big > string that included some data you are interested in and some you don't > want, you have converted that to a list of strings containing only the > lines of interest. That is a good first step. Now you have to extract > the data you want out of each line. > > Use line.split() to split the text into fields by whitespace: > In [1]: line = ' server001 alive 22.3% 6 requests/s 14527762 > total' > > In [2]: line.split() > Out[2]: ['server001', 'alive', '22.3%', '6', 'requests/s', '14527762', > 'total'] > > Indexing will pull out the field you want: > In [3]: line.split()[5] > Out[3]: '14527762' > > It's still a string: > In [4]: type(line.split()[5]) > Out[4]: > > Use int() to convert a string to an integer: > In [5]: int(line.split()[5]) > Out[5]: 14527762 > > Then you have to figure out how to accumulate the values in a dictionary > but get this much working first. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks very much for the steer. I've made a fair bit of progress and look to be within touching distance of getting the problem cracked. Here's the list I'm starting with: >>> for i in rLst: >>> print i, type(i) server001 alive 17.1% 2 requests/s 14805416 total server001 alive 27.2% 7 requests/s 14851125 total server002 alive 22.9% 6 requests/s 15173311 total server002 alive 42.0% 8 requests/s 15147869 total server003 alive 17.9% 4 requests/s 15220280 total server003 alive 22.0% 4 requests/s 15260951 total server004 alive 18.5% 3 requests/s 15484524 total server004 alive 31.6% 9 requests/s 15429303 total I've split each string in the list, extracted what I want and feed it into an empty dictionary. >>> rDict ={} >>> i = 0 >>> while i < (len(rLst)): >>> x, y = rLst[i].split()[0], int(rLst[i].split()[3]) >>> rDict[x] = y >>> print x, y, type(x), type(y) >>> i += 1 server001 4 server001 5 server002 5 server002 9 server003 4 server003 6 server004 8 server004 12 I end up with this. >>> for key, value in rDict.items(): >>> print key, value server001 5 server003 6 server002 9 server004 12 As I understand things this is because the keys must be unique and are being replaced by the final key value pair being feed in from the loop. What I'm hoping to be able to do is update the value, rather than replace it, so that it gives me the total i.e. server001 9 server003 10 server002 14 server004 20 Regards, Paul From khp at pflaesterer.de Tue Apr 25 23:28:02 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue, 25 Apr 2006 23:28:02 +0200 Subject: [Tutor] Dictionaries and aggregation In-Reply-To: (paul churchill's message of "Tue, 25 Apr 2006 19:00:26 +0100") References: <20060424230638.B94F1E000314@ranger.systems.pipex.net> <444DFD6C.7080606@tds.net> Message-ID: On 25 Apr 2006, paul.churchill at cyanfusion.com wrote: [...] > Here's the list I'm starting with: > >>>> for i in rLst: >>>> print i, type(i) > > server001 alive 17.1% 2 requests/s 14805416 total > server001 alive 27.2% 7 requests/s 14851125 total > server002 alive 22.9% 6 requests/s 15173311 total > server002 alive 42.0% 8 requests/s 15147869 total > server003 alive 17.9% 4 requests/s 15220280 total > server003 alive 22.0% 4 requests/s 15260951 total > server004 alive 18.5% 3 requests/s 15484524 total > server004 alive 31.6% 9 requests/s 15429303 total > > I've split each string in the list, extracted what I want and feed it into > an empty dictionary. > >>>> rDict ={} >>>> i = 0 >>>> while i < (len(rLst)): >>>> x, y = rLst[i].split()[0], int(rLst[i].split()[3]) >>>> rDict[x] = y >>>> print x, y, type(x), type(y) >>>> i += 1 [...] > What I'm hoping to be able to do is update the value, rather than replace > it, so that it gives me the total i.e. > server001 9 > server003 10 > server002 14 > server004 20 This is easily done. .>>> rdict = {} .>>> for line in lst: .... ans = line.split() .... rdict[ans[0]] = rdict.get(ans[0], 0) + int(ans[3]) .... .>>> rdict .{'server002': 14, 'server003': 8, 'server001': 9, 'server004': 12} Dictionaries have a get() method, which has an optional second argument, which gets returned if there is no such key in the dictionary. Karl -- Please do *not* send copies of replies to me. I read the list From paul.churchill at cyanfusion.com Wed Apr 26 00:04:37 2006 From: paul.churchill at cyanfusion.com (Paul Churchill) Date: Tue, 25 Apr 2006 23:04:37 +0100 Subject: [Tutor] Dictionaries and aggregation In-Reply-To: Message-ID: <20060425220440.9528AE0004B9@blaster.systems.pipex.net> Right think I've got the idea now. Thanks for all contributions on this. Paul -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Karl "Pfl?sterer" Sent: 25 April 2006 22:28 To: tutor at python.org Subject: Re: [Tutor] Dictionaries and aggregation On 25 Apr 2006, paul.churchill at cyanfusion.com wrote: [...] > Here's the list I'm starting with: > >>>> for i in rLst: >>>> print i, type(i) > > server001 alive 17.1% 2 requests/s 14805416 total > server001 alive 27.2% 7 requests/s 14851125 total > server002 alive 22.9% 6 requests/s 15173311 total > server002 alive 42.0% 8 requests/s 15147869 total > server003 alive 17.9% 4 requests/s 15220280 total > server003 alive 22.0% 4 requests/s 15260951 total > server004 alive 18.5% 3 requests/s 15484524 total > server004 alive 31.6% 9 requests/s 15429303 total > > I've split each string in the list, extracted what I want and feed it into > an empty dictionary. > >>>> rDict ={} >>>> i = 0 >>>> while i < (len(rLst)): >>>> x, y = rLst[i].split()[0], int(rLst[i].split()[3]) >>>> rDict[x] = y >>>> print x, y, type(x), type(y) >>>> i += 1 [...] > What I'm hoping to be able to do is update the value, rather than replace > it, so that it gives me the total i.e. > server001 9 > server003 10 > server002 14 > server004 20 This is easily done. .>>> rdict = {} .>>> for line in lst: .... ans = line.split() .... rdict[ans[0]] = rdict.get(ans[0], 0) + int(ans[3]) .... .>>> rdict .{'server002': 14, 'server003': 8, 'server001': 9, 'server004': 12} Dictionaries have a get() method, which has an optional second argument, which gets returned if there is no such key in the dictionary. Karl -- Please do *not* send copies of replies to me. I read the list _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kp8 at mac.com Wed Apr 26 02:31:42 2006 From: kp8 at mac.com (kevin parks) Date: Tue, 25 Apr 2006 20:31:42 -0400 Subject: [Tutor] seq looping In-Reply-To: References: Message-ID: <3d020a3264cb80f4cae221c4d40d4ecb@mac.com> I have a loop that process each item in a sequence and after each item some updating is done to some variables. However i don't what these variable updated if we are processing the last item in the list. i could put in a conditional and test if the list is now empty after popping items from the list... but testing for an empty list and the bookkeeping of maintaining the popped list seems horribly inefficient and this is for a real time multimedia playback type situation so learning a more efficient idiom for this seems worth while: You won't have all the dependancies... including the player (STEREO) and some tables of durations.. but you get the gist: def playall(startime, amp, wet_percent, rest_percent, duty_factor, smpl_lst): ''' a play-loop that plays all samples in a directory, just once with some temporal padding and also returns the end of the last duration so that the begining of the next section can be determined''' event = 1; inskip = 0; inchan = 0; incr = 0 for sample in smpl_lst: splt = os.path.split(sample) rtinput(sample) loc = random.random() dur = DUR() STEREO(startime, inskip, dur, amp, loc) print "event no. %d @ %.2f (dur: %.2f, end: %.2f) --> sf: %s : [flag: %.2f]" % (event, startime, dur, startime+dur, splt[1], dry) incr = (dur * duty_factor) + kptools.windex(kptools.durations) startime = startime + incr restflag = random.random() if (restflag < rest_percent): rest = kptools.windex(kptools.rest) print "\n", "<>-" * 8, "[ rest : ", rest, "]", "-<>" * 8, "\n" startime = startime + rest event = event + 1 print '\n', 'Next start = ', startime, '\n\n' so what i am trying to do its skip that if (restflag < rest_percent): biz on the last item if we are on our last sequence item. The rests (which are random) is for padding between events and since we have just played our last event, we don't want any extra padding so that our next call of the loop starts at the proper time (just at the last event of this loop is over). The loop function will calculate the next start time, and return it so that we can use it as the start time argument for our next call of the loop. so if i want to play 7 items i might get something like: loop_call_01: item_1 item_2 rest item_3 rest item_4 item_5 item_6 rest item_7 (but we don't want any rest here ever! cause we might want our next loop to start w/o any pause) gosh.. i hope this is clear.... anyway that's my query .. hehe ... cheers, kevin From andre.roberge at gmail.com Wed Apr 26 03:45:19 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 25 Apr 2006 22:45:19 -0300 Subject: [Tutor] Avoiding the use of files to store intermediate results In-Reply-To: <444D92FC.5060705@h-lab.net> References: <7528bcdd0604241437sf6b9af1w34ba011e6bc0a300@mail.gmail.com> <444D92FC.5060705@h-lab.net> Message-ID: <7528bcdd0604251845p17463306s2615f60f5e8ab5cf@mail.gmail.com> On 4/25/06, Hugo Gonz?lez Monteverde wrote: > Remember duck typing. An object just needs to look like a file in order > to be used like one. > > Guido's time machine has already forseen your problem. Take a look at > the StringIO module. It allows you to use a string where you would > normally pass a file object. > Since I do something like os.open("python some_file.py > some_output") I don't see how I can pass a file-like object. As far as I can tell "python" (the command) looks for a real file on the current path. Andr? > Hope that helps, > > Hugo > > > ###### > > While this works, I find it "messy", as it creates some intermediate > > files. I was wondering if there was a better way to do things all in > > memory, in an OS independent way. > > > > [Note that the complete application is approximately 665 lines long > > ... a bit too much > > to post all here :-)] > > > > Andr? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From nospamformeSVP at gmail.com Wed Apr 26 03:50:33 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 25 Apr 2006 21:50:33 -0400 Subject: [Tutor] A Python idiom that I don't get Message-ID: I am trying to get some existing CPython 2.4 code working under Jython (2.1) and I am puzzled by a line in the following function. It seems to be a Python 2.4 idiom that is opaque to me. The line is: prefix = os.path.commonprefix(filter( bool, lines )) and I don't understand what that 'bool' is doing. Or rather, I think that I see what it is doing, but I am not sure - and I don't much like it. filter is the built-in filter and it requires a callable returning a bool as the first argument. It seems that 'bool' without arguments is a callable that always evaluates to True (or at least non-zero) so this 'bool' always returns True. Is this really true (sic) by intention or is it just an implemenation artifact? I tried replacing 'bool' with 'True' but that won't work because True is not callable. I replaced 'bool' with 'lambda True: True' as in: prefix = os.path.commonprefix(filter( lambda True: True, lines )) and that does seem to work - and pass its unit tests. Have I got this right and can I replace 'bool' with the lambda expression? Or is there a clearer way to do this? Thanks, Don. The full function is: def find_common( lines ): """find and return a common prefix to all the passed lines. Should not include trailing spaces """ if not lines: return "" # get the common prefix of the non-blank lines. This isn't the most # efficient way of doing this by _far_, but it _is_ the shortest prefix = os.path.commonprefix(filter( bool, lines )) if not prefix: return "" # this regular expression will match an 'interesting' line prefix matched = re.match("(\s*\w{1,4}>|\W+)", prefix) if not matched: return "" From kent37 at tds.net Wed Apr 26 04:43:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Apr 2006 22:43:25 -0400 Subject: [Tutor] A Python idiom that I don't get In-Reply-To: References: Message-ID: <444EDE4D.1090101@tds.net> Don Taylor wrote: > I am trying to get some existing CPython 2.4 code working under Jython > (2.1) and I am puzzled by a line in the following function. It seems to > be a Python 2.4 idiom that is opaque to me. > > The line is: > prefix = os.path.commonprefix(filter( bool, lines )) > > and I don't understand what that 'bool' is doing. Or rather, I think > that I see what it is doing, but I am not sure - and I don't much like it. > > filter is the built-in filter and it requires a callable returning a > bool as the first argument. It seems that 'bool' without arguments is a > callable that always evaluates to True (or at least non-zero) so this > 'bool' always returns True. Is this really true (sic) by intention or > is it just an implemenation artifact? No, bool() doesn't always return true, it returns true for arguments that would evaluate to true in a boolean context, and false otherwise. In [2]: bool(0) Out[2]: False In [3]: bool(1) Out[3]: True In [4]: bool([]) Out[4]: False In [5]: bool(42) Out[5]: True > > I tried replacing 'bool' with 'True' but that won't work because True is > not callable. > > I replaced 'bool' with 'lambda True: True' as in: > prefix = os.path.commonprefix(filter( lambda True: True, lines )) > and that does seem to work - and pass its unit tests. This works but it isn't doing what you think it is. lambda True: True is the same as lambda x: x i.e. it is just an identity function. > > Have I got this right and can I replace 'bool' with the lambda expression? > > Or is there a clearer way to do this? Try filter(None, lines) or use a list comprehension: [ line for line in lines if line ] Kent From bgailer at alum.rpi.edu Wed Apr 26 05:14:25 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 25 Apr 2006 20:14:25 -0700 Subject: [Tutor] Avoiding the use of files to store intermediate results In-Reply-To: <7528bcdd0604251845p17463306s2615f60f5e8ab5cf@mail.gmail.com> References: <7528bcdd0604241437sf6b9af1w34ba011e6bc0a300@mail.gmail.com> <444D92FC.5060705@h-lab.net> <7528bcdd0604251845p17463306s2615f60f5e8ab5cf@mail.gmail.com> Message-ID: <444EE591.4010406@alum.rpi.edu> Andre Roberge wrote: > On 4/25/06, Hugo Gonz?lez Monteverde wrote: > >> Remember duck typing. An object just needs to look like a file in order >> to be used like one. >> >> Guido's time machine has already forseen your problem. Take a look at >> the StringIO module. It allows you to use a string where you would >> normally pass a file object. >> >> > > Since I do something like > os.open("python some_file.py > some_output") > I don't see how I can pass a file-like object. As far as I can tell > "python" (the command) looks for a real file on the current path. > How about using one of the os.popen functions, that returns a file-like object for stdout? > Andr? > > >> Hope that helps, >> >> Hugo >> >> >>> ###### >>> While this works, I find it "messy", as it creates some intermediate >>> files. I was wondering if there was a better way to do things all in >>> memory, in an OS independent way. >>> >>> [Note that the complete application is approximately 665 lines long >>> ... a bit too much >>> to post all here :-)] >>> >>> Andr? >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From wescpy at gmail.com Wed Apr 26 05:16:36 2006 From: wescpy at gmail.com (w chun) Date: Tue, 25 Apr 2006 20:16:36 -0700 Subject: [Tutor] A Python idiom that I don't get In-Reply-To: <444EDE4D.1090101@tds.net> References: <444EDE4D.1090101@tds.net> Message-ID: <78b3a9580604252016j4938a4a5ne046570e4d0410bc@mail.gmail.com> > > prefix = os.path.commonprefix(filter( bool, lines )) that is an interesting and yes, not very optimal way of saving the set of non-blank lines. the commonprefix() function takes a list of pathnames and returns the longest prefix that all strings have in common, presumably for disk filenames, although this sounds like just a string processing function that would work with non-pathnames too. > > and I don't understand what that 'bool' is doing. Or rather, I think > > that I see what it is doing, but I am not sure - and I don't much like it. > : > > I tried replacing 'bool'... it sounds like you did not develop the original code. it seems to work... why are you trying to replace it? are you refactoring? > This works but it isn't doing what you think it is. > lambda True: True > is the same as > lambda x: x kent is right. True is not a keyword, so you are just using "True" as a variable name. scarily, one can do stuff like this: >>> True, False = False, True >>> True False >>> False True > Try filter(None, lines) or use a list comprehension: > [ line for line in lines if line ] i like both of these better... they will perform better than with bool(). of the two, it would be interesting to study which one's faster... and why. -wesley From keosophon at khmeros.info Wed Apr 26 05:36:50 2006 From: keosophon at khmeros.info (Keo Sophon) Date: Wed, 26 Apr 2006 10:36:50 +0700 Subject: [Tutor] getting system temporary directory. Message-ID: <200604261036.50704.keosophon@khmeros.info> Hi all, Does python has any function to get a system tempdir of an OS? Thanks, Phon From tim.golden at viacom-outdoor.co.uk Wed Apr 26 09:33:46 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 26 Apr 2006 08:33:46 +0100 Subject: [Tutor] getting system temporary directory. Message-ID: [Keo Sophon] | Does python has any function to get a system tempdir of an OS? You want to be looking at the tempfile module (and in particular at the gettempdir). http://docs.python.org/lib/module-tempfile.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kp8 at mac.com Wed Apr 26 10:52:31 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 26 Apr 2006 04:52:31 -0400 Subject: [Tutor] seq looping In-Reply-To: <444EE886.6070805@alum.rpi.edu> References: <3d020a3264cb80f4cae221c4d40d4ecb@mac.com> <444EE886.6070805@alum.rpi.edu> Message-ID: <47EE487D-0E8F-4FB9-84B7-DD0AFAAED403@mac.com> Bob ... i used my kludge which defines some bounds and tests for it... but your idea of stuffing that into a seperate black box as golden in that it made me think of the problem as input --> doit --> result. and made my loops simpler and easier to read... and i use that same gap making typing thing in several loops, so encapsulating that meant that i could make it general purpose, and re-usable and i can add to it later more easily. Thanks for that suggestion. I ended up with this: # if the flag (random float) is lower than our percentage of rest, we pick # a rest duration and add that to our start time creating a gap between events. def make_rest(event, lowerbound, upperbound, start, rest_percent): restflag = random.random() if (restflag < rest_percent): # This kludge makes sure our last event does not get a rest, and we can # prevent the first few events from getting rests as well to insure # our transitions between sections are seamless & sufficiently busy # NOTE LOWER bound is included if event >= lowerbound and event < upperbound: rest_dur = windex(rest) print "\n", "<>-" * 8, "[ rest : ", rest_dur, "]", "-<>" * 8, "\n" start = start + rest_dur else: print "[bang]" # debug return start then in the master bedroom i just call it: startime = foo.make_rest(event, 1, upperbound, startime, rest_percent) cheers, kevin On Apr 25, 2006, at 11:27 PM, Bob Gailer wrote: > How about separating the body into 2 functions, calling both for > all but the last list element, then calling just the first for the > last element: > : > def step1(sample): > global incr > splt = os.path.split(sample) > rtinput(sample) > loc = random.random() > dur = DUR() > STEREO(startime, inskip, dur, amp, loc) > print "event no. %d @ %.2f (dur: %.2f, end: %.2f) --> sf: %s : > [flag: %.2f]" % (event, startime, dur, startime+dur, splt[1], dry) > incr = (dur * duty_factor) + kptools.windex(kptools.durations) > startime = startime + incr > > def rest(): > global event > restflag = random.random() > if (restflag < rest_percent): > rest = kptools.windex(kptools.rest) > print "\n", "<>-" * 8, "[ rest : ", rest, "]", "-<>" * 8, "\n" > startime = startime + rest > event = event + 1 > > for sample in smpl_lst[:-1]: > step1(sample) > rest() > step1(smpl_lst[-1]) > > > so what i am trying to do its skip that >> if (restflag < rest_percent): >> >> biz on the last item if we are on our last sequence item. The >> rests (which are random) is for padding between events >> and since we have just played our last event, we don't want any >> extra padding so that our next call of the loop >> starts at the proper time (just at the last event of this loop is >> over). The loop function will calculate the >> next start time, and return it so that we can use it as the start >> time argument for our next call of the loop. >> >> so if i want to play 7 items i might get something like: >> >> loop_call_01: >> item_1 >> item_2 >> rest >> item_3 >> rest >> item_4 >> item_5 >> item_6 >> rest >> item_7 (but we don't want any rest here ever! cause we might want >> our next loop to start w/o any pause) >> > From winfried at tilanus.com Wed Apr 26 10:57:36 2006 From: winfried at tilanus.com (Winfried Tilanus) Date: Wed, 26 Apr 2006 10:57:36 +0200 Subject: [Tutor] Web-templating systems (was: Re: Generating static WEB sites) In-Reply-To: <444E3A2D.6030607@tds.net> References: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> <444E3A2D.6030607@tds.net> Message-ID: <444F3600.9000004@tilanus.com> On 04/25/2006 Kent Johnson wrote: > Many. See this page, the sections Templating Engines, HTML Shorthand > Processors and HTML Generation class libraries: > http://wiki.python.org/moin/WebProgramming Hmmm,lets toss in my own problem: I know the list mentioned above, and it is too long for me to test each of the templating systems and evalute if they are right for me. So does anybody have any suggestions for my situation, so I can make a shortlist? I maintain a web-application that has its templates partly in a language designed by a previous programmer (basicly a way to mix python code into HTML) and has an other part of the templates programmed in python. I would like to standarize these to a system that has the following charactistics: - First of all: easy to learn for web-desingers and translators. My ideal would be something that feels like "As little programming als possible", so the templates should be very close to the HTML/Javascript/CSS and have some extentions to it. It should be well documented (I don't mind to do some documantation on my own) and, if possible, use existing standards. - can (of course) include a supplied variable - can make conditional statements - can loop over a supplied list of lists or dictionaries - possible to include templates - can run under mod_python - possible to generate snippets of html, without generating / sending of a complete website - possible to store the templates on disk or in a database - open-source and actively maintained I don't mind to write my own code for things like escaping, character conversion, retrieving the template, sending of the resulting HTML, error handling etc. The main goal is to make it as easy as possible for webdesingers and / or translators to change the templates without having any Python knowledge. Any suggstion or discussion is welcome! thanks & best wishes, Winfried From ryan_gm at sbcglobal.net Wed Apr 26 11:59:04 2006 From: ryan_gm at sbcglobal.net (ryan luna) Date: Wed, 26 Apr 2006 02:59:04 -0700 (PDT) Subject: [Tutor] Livewires Message-ID: <20060426095904.51527.qmail@web80830.mail.yahoo.com> Hey, So i decided to check out this Livewires Modules, but while running through the tutorial i run into a problem, When i was trying to do the graphics stuff, when i try and use this code circle(300,195, endpoints = ((280,180),(320,180))) and i get this error Traceback (most recent call last): File "(stdin)", line 1, in ? File "D:\programfiles\python\livewires\beginners.py", line 527, in circle if r <0: raise ExVadParmaeters('negative radius') livewires.beginngers.ExBadParameters: negative radius So im pretty new to this Livewires crap, which iv said, so any help would be great. From francis.moore at rawflow.com Wed Apr 26 11:15:44 2006 From: francis.moore at rawflow.com (Frank Moore) Date: Wed, 26 Apr 2006 10:15:44 +0100 Subject: [Tutor] Regex across multiple lines Message-ID: <444F3A40.6040505@rawflow.com> Hi, Can anyone tell me how to do a regex substitution across multiple lines in HTML? I can search for the piece of HTML I want to substitute, for instance: This is my title using html_text = file('some.html', 'r').read() search_string = '.*' p = re.compile(search_string, re.DOTALL) But when I try and use: replace_string = 'Another title' html_text = re.sub(search_string, replace_string, html_text) it doesn't work. However, if the HTML is all on one line: This is my title it works fine. Any ideas? Many thanks, Frank. From kent37 at tds.net Wed Apr 26 12:50:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 06:50:45 -0400 Subject: [Tutor] Web-templating systems In-Reply-To: <444F3600.9000004@tilanus.com> References: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> <444E3A2D.6030607@tds.net> <444F3600.9000004@tilanus.com> Message-ID: <444F5085.5080402@tds.net> Winfried Tilanus wrote: > On 04/25/2006 Kent Johnson wrote: >> Many. See this page, the sections Templating Engines, HTML Shorthand >> Processors and HTML Generation class libraries: >> http://wiki.python.org/moin/WebProgramming > > Hmmm,lets toss in my own problem: > I know the list mentioned above, and it is too long for me to test each > of the templating systems and evalute if they are right for me. So does > anybody have any suggestions for my situation, so I can make a shortlist? I think Kid meets your requirements: http://kid.lesscode.org/ Other template systems that seem to be popular these days: Cheetah HTMLTemplate Myghty Kent From kent37 at tds.net Wed Apr 26 13:10:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 07:10:40 -0400 Subject: [Tutor] A Python idiom that I don't get In-Reply-To: <78b3a9580604252016j4938a4a5ne046570e4d0410bc@mail.gmail.com> References: <444EDE4D.1090101@tds.net> <78b3a9580604252016j4938a4a5ne046570e4d0410bc@mail.gmail.com> Message-ID: <444F5530.6030503@tds.net> w chun wrote: >>> prefix = os.path.commonprefix(filter( bool, lines )) > > that is an interesting and yes, not very optimal way of saving the set > of non-blank lines. the commonprefix() function takes a list of > pathnames and returns the longest prefix that all strings have in > common, presumably for disk filenames, although this sounds like just > a string processing function that would work with non-pathnames too. I think it is the commonprefix() call that is expensive, not the filter. > > >>> and I don't understand what that 'bool' is doing. Or rather, I think >>> that I see what it is doing, but I am not sure - and I don't much like it. >> : >>> I tried replacing 'bool'... > > it sounds like you did not develop the original code. it seems to > work... why are you trying to replace it? are you refactoring? He is porting to Jython which doesn't have bool(), which was introduced in CPython 2.2. Kent From kent37 at tds.net Wed Apr 26 13:18:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 07:18:51 -0400 Subject: [Tutor] Livewires In-Reply-To: <20060426095904.51527.qmail@web80830.mail.yahoo.com> References: <20060426095904.51527.qmail@web80830.mail.yahoo.com> Message-ID: <444F571B.5030209@tds.net> ryan luna wrote: > Hey, > So i decided to check out this Livewires Modules, but > while running through the tutorial i run into a > problem, > When i was trying to do the graphics stuff, > when i try and use this code > > circle(300,195, endpoints = ((280,180),(320,180))) > > and i get this error > > Traceback (most recent call last): > File "(stdin)", line 1, in ? > File > "D:\programfiles\python\livewires\beginners.py", line > 527, in circle > if r <0: raise ExVadParmaeters('negative > radius') > livewires.beginngers.ExBadParameters: negative radius This looks to me like a bug in LiveWires. It is comparing None to 0 which has an undefined result. Try changing line 527 in beginners.py to if r is not None and r < 0: raise ExBadParameters('negative radius') > So im pretty new to this Livewires ****, which iv > said, so any help would be great. Please take your bad language somewhere else, it's not appropriate on this list. Kent From kent37 at tds.net Wed Apr 26 13:21:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 07:21:09 -0400 Subject: [Tutor] Regex across multiple lines In-Reply-To: <444F3A40.6040505@rawflow.com> References: <444F3A40.6040505@rawflow.com> Message-ID: <444F57A5.10907@tds.net> Frank Moore wrote: > Hi, > > Can anyone tell me how to do a regex substitution across multiple lines > in HTML? > I can search for the piece of HTML I want to substitute, for instance: > > > This is my title > > > using > > html_text = file('some.html', 'r').read() > search_string = '.*' > p = re.compile(search_string, re.DOTALL) > > But when I try and use: > > replace_string = 'Another title' > html_text = re.sub(search_string, replace_string, html_text) > > it doesn't work. > > However, if the HTML is all on one line: > > This is my title > > it works fine. Use your compiled regex for the sub(), so it will have the DOTALL flag set: html_text = p.sub(replace_string, html_text) Kent From francis.moore at rawflow.com Wed Apr 26 13:46:41 2006 From: francis.moore at rawflow.com (Frank Moore) Date: Wed, 26 Apr 2006 12:46:41 +0100 Subject: [Tutor] Regex across multiple lines In-Reply-To: <444F57A5.10907@tds.net> References: <444F3A40.6040505@rawflow.com> <444F57A5.10907@tds.net> Message-ID: <444F5DA1.9080803@rawflow.com> Kent Johnson wrote: >Use your compiled regex for the sub(), so it will have the DOTALL flag set: >html_text = p.sub(replace_string, html_text) > > Kent, I was trying to work out how to use the DOTALL flag with the sub method, but couldn't figure it out. It's so obvious once someone points it out. ;-) Many thanks, Frank From ml.cyresse at gmail.com Wed Apr 26 14:25:42 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 27 Apr 2006 00:25:42 +1200 Subject: [Tutor] Regex across multiple lines In-Reply-To: <444F5DA1.9080803@rawflow.com> References: <444F3A40.6040505@rawflow.com> <444F57A5.10907@tds.net> <444F5DA1.9080803@rawflow.com> Message-ID: Hi Frank, just bear in mind that the pattern: patObj = re.compile(".*", re.DOTALL) will match This is my title But, it'll also match This is my title

Some content here

Another title; not going to happen with a title tag in HTML, but more an illustration All of that. Got to watch .* with re.DOTALL; try using .*? instead, it makes it non-greedy. Functionality for your current use case won't change, but you won't spend ages when you have a different use case trying to figure out why half your data is matching. >_< To the Tutor list - can't re.MULTILINE also be used? I've never really used that flag. Regards, Liam Clarke On 4/26/06, Frank Moore wrote: > Kent Johnson wrote: > > >Use your compiled regex for the sub(), so it will have the DOTALL flag set: > >html_text = p.sub(replace_string, html_text) > > > > > Kent, > > I was trying to work out how to use the DOTALL flag with the sub method, > but couldn't figure it out. > It's so obvious once someone points it out. ;-) > > Many thanks, > Frank > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From oztriking at hotmail.com Wed Apr 26 15:24:01 2006 From: oztriking at hotmail.com (John Connors) Date: Wed, 26 Apr 2006 23:24:01 +1000 Subject: [Tutor] Checking in lists Message-ID: G'day, I found something today that has me confused. I'm making a list of 6 random dice rolls and I want to check if any 1's or 5's were rolled. I tried this way first and it returns true even if there are no 1's or 5's. I'll use a roll of all 2's as an example. rollList = [2,2,2,2,2,2] if 1 or 5 in rollList: print 'yes' else: print 'no' Then I tried this and it works fine. rollList = [2,2,2,2,2,2] if 1 in rollList or 5 in rollList: print 'yes' else: print 'no' It doesn't really matter because the second way does what I want but I would like to know why the first way doesn't work and if the syntax is wrong why doesn't it return an error. John PS I apologise if this is a duplicate, hotmail did some kind of spam check when I tried to send it, I've waited 30 mins and I don't think it went the 1st time so I'll post it again. _________________________________________________________________ New year, new job – there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT From kent37 at tds.net Wed Apr 26 15:33:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 09:33:41 -0400 Subject: [Tutor] Regex across multiple lines In-Reply-To: References: <444F3A40.6040505@rawflow.com> <444F57A5.10907@tds.net> <444F5DA1.9080803@rawflow.com> Message-ID: <444F76B5.3020202@tds.net> Liam Clarke wrote: > To the Tutor list - can't re.MULTILINE also be used? I've never really > used that flag. re.MULTILINE affects the meaning of ^ and $ - do they match only the beginning and end of the target string (the default) or do they match the beginning or end of any line in the string. re.DOTALL affects the meaning of . - does it match newlines or not? The docs on these flags are pretty clear, take a look. Kent From jason.massey at gmail.com Wed Apr 26 15:30:48 2006 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 26 Apr 2006 08:30:48 -0500 Subject: [Tutor] Checking in lists In-Reply-To: References: Message-ID: <7e3eab2c0604260630r2a50be55k7fe0da14877ec2ac@mail.gmail.com> John, Basically it's not evaluating it the way you think it is: Your first example really equates to: if (1 or 5) in rollList: etc... (1 or 5) equals 1 and 1 isn't in the your list. On 4/26/06, John Connors wrote: > > G'day, > > I found something today that has me confused. I'm making a list of 6 > random > dice rolls and I want to check if any 1's or 5's were rolled. I tried this > way first and it returns true even if there are no 1's or 5's. I'll use a > roll of all 2's as an example. > > rollList = [2,2,2,2,2,2] > if 1 or 5 in rollList: > print 'yes' > else: > print 'no' > > Then I tried this and it works fine. > > rollList = [2,2,2,2,2,2] > if 1 in rollList or 5 in rollList: > print 'yes' > else: > print 'no' > > It doesn't really matter because the second way does what I want but I > would > like to know why the first way doesn't work and if the syntax is wrong why > doesn't it return an error. > > John > > PS I apologise if this is a duplicate, hotmail did some kind of spam check > when I tried to send it, I've waited 30 mins and I don't think it went the > 1st time so I'll post it again. > > _________________________________________________________________ > New year, new job ? there's more than 100,00 jobs at SEEK > > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060426/b6b53f40/attachment-0001.html From kent37 at tds.net Wed Apr 26 16:05:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 10:05:49 -0400 Subject: [Tutor] Checking in lists In-Reply-To: <7e3eab2c0604260630r2a50be55k7fe0da14877ec2ac@mail.gmail.com> References: <7e3eab2c0604260630r2a50be55k7fe0da14877ec2ac@mail.gmail.com> Message-ID: <444F7E3D.8030905@tds.net> Jason Massey wrote: > John, > > Basically it's not evaluating it the way you think it is: Right. > > Your first example really equates to: > > if (1 or 5) in rollList: > etc... > > (1 or 5) equals 1 and 1 isn't in the your list. Not quite. It's if 1 or (5 in rollList): Since 1 evaluates to true, the result will always be 1. Operator precedence is summarized here: http://docs.python.org/ref/summary.html Kent From nospamformeSVP at gmail.com Wed Apr 26 16:05:30 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Wed, 26 Apr 2006 10:05:30 -0400 Subject: [Tutor] A Python idiom that I don't get In-Reply-To: <78b3a9580604252016j4938a4a5ne046570e4d0410bc@mail.gmail.com> References: <444EDE4D.1090101@tds.net> <78b3a9580604252016j4938a4a5ne046570e4d0410bc@mail.gmail.com> Message-ID: w chun wrote: > it sounds like you did not develop the original code. it seems to > work... why are you trying to replace it? are you refactoring? No it is not my code. I am trying to get it running in Jython which does not support the bool function. I may refactor it after I get it working in Jython, but right now I have added the following function to my module: def bool(value): if value: return 1 return 0 and this seems to work and lets me leave the original source code untouched for now. > i like both of these better... they will perform better than with > bool(). of the two, it would be interesting to study which one's > faster... and why. > Performance is not really important but I will try some instrumentation on this code. FWIW. I am trying to write a Jython extension to the Pydev/Eclipse IDE that will re-wrap selected comment blocks and docstrings. Pydev now supports extensions written in Jython - see: http://pydev.sourceforge.net/ Don. From payal-python at scriptkitchen.com Wed Apr 26 19:41:59 2006 From: payal-python at scriptkitchen.com (Payal Rathod) Date: Wed, 26 Apr 2006 13:41:59 -0400 Subject: [Tutor] Alan Gauld's tut - namespaces Message-ID: <20060426174159.GA21428@tranquility.scriptkitchen.com> Hi, In Alan's tutorial I haven't got the example of print42() even after reading the explanation. I get 110 if I use it as a function. >>> spam = 42 >>> def print42(): print spam ... >>> spam = 110 >>> print42() 110 Why do you get 42 when you use it as module? I haven't understood the explantaion. With warm regards, -Payal From alan.gauld at freenet.co.uk Wed Apr 26 20:45:21 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 26 Apr 2006 19:45:21 +0100 Subject: [Tutor] Checking in lists References: <7e3eab2c0604260630r2a50be55k7fe0da14877ec2ac@mail.gmail.com> Message-ID: <006a01c66961$93a005c0$0a01a8c0@xp> > Basically it's not evaluating it the way you think it is: > >Your first example really equates to: > > if (1 or 5) in rollList: Not quite, its doing: if 1 or 5 in rollList: We can demonstrate that with: >>> if 1 or 0 in [6,2,3]: print 'True' ... True >>> if (1or 0) in [6,2,3]: print 'True' ... >>> Here the first expression evaluates to True and never attempts the 'in' comparison (which would fail). The second uses your parenthesis style and evaluates to 1 in [6,2,3] which is False A minor nit pick. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld On 4/26/06, John Connors wrote: > > G'day, > > I found something today that has me confused. I'm making a list of 6 > random > dice rolls and I want to check if any 1's or 5's were rolled. I tried this > way first and it returns true even if there are no 1's or 5's. I'll use a > roll of all 2's as an example. > > rollList = [2,2,2,2,2,2] > if 1 or 5 in rollList: > print 'yes' > else: > print 'no' > > Then I tried this and it works fine. > > rollList = [2,2,2,2,2,2] > if 1 in rollList or 5 in rollList: > print 'yes' > else: > print 'no' > > It doesn't really matter because the second way does what I want but I > would > like to know why the first way doesn't work and if the syntax is wrong why > doesn't it return an error. > > John > > PS I apologise if this is a duplicate, hotmail did some kind of spam check > when I tried to send it, I've waited 30 mins and I don't think it went the > 1st time so I'll post it again. > > _________________________________________________________________ > New year, new job ? there's more than 100,00 jobs at SEEK > > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From mhansen at cso.atmel.com Wed Apr 26 21:12:15 2006 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 26 Apr 2006 13:12:15 -0600 Subject: [Tutor] Cheetah Message-ID: <003f01c66965$543c7720$28645f0a@mikehansen> I'm having a little trouble populating a cheetah template. I thought I'd ask here first before checking the cheetah mailing list or c.l.p. I have a simple template This is a test

$title

#for $item in $items

category: $item.category

name: $item.name

price: $item.price

#end for That I compiled using cheetah. Here's the python code that uses it: #!/usr/bin/env python import testform import cgitb; cgitb.enable() class ReqItem(object): def __init__(self, category, name, price): self.category = category self.name = name self.price = price t = testform.testform() t.title = "this and that" items = [] category = "little stuff" name = "hotwheel" price = "2" item = ReqItem(category, name, price) items.append(item) category = "big stuff" name = "monster truck" price = "30000" item = ReqItem(category, name, price) items.append(item) t.items = items print "Content-Type: text/html\n\n" print str(t) However, I get the following error: Traceback (most recent call last): File "./testit.py", line 36, in ? print str(t) File "testform.py", line 100, in respond __v = VFFSL(SL,"item.category",True) NotFound: cannot find 'category' while searching for 'item.category' Does anyone know what I'm doing wrong? From doug.shawhan at gmail.com Wed Apr 26 23:35:53 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Wed, 26 Apr 2006 16:35:53 -0500 Subject: [Tutor] SOAP Modules - I need a little direction. Message-ID: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> I am in preparation mode for creating a script which uses SOAP. I have been looking at the various SOAP modules: soapy, soap.py, ZSI, pywebsvcs. I'm very confused as to the status of these projects. Most seem to be only partially supported, if not abandoned completely. Thre appears to have been a flurry of interest in 2001, then everyone got jobs! ;-) This project is going to be a lulu for someone of my limited abilites, so I'd really rather not give myself a skull hernia on a dead-end module. Which of these modules I've listed (or haven't!) is most complete and appears to have a future? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060426/1ceb2aee/attachment.html From oztriking at hotmail.com Wed Apr 26 23:44:20 2006 From: oztriking at hotmail.com (John Connors) Date: Thu, 27 Apr 2006 07:44:20 +1000 Subject: [Tutor] Alan Gauld's tut - namespaces In-Reply-To: <20060426174159.GA21428@tranquility.scriptkitchen.com> Message-ID: G'day Payal, I had trouble understanding the namespaces section of the tutorial too but it all clicked the other day when Alan explained the difference between import first and from first import * John >Hi, >In Alan's tutorial I haven't got the example of print42() even after >reading the explanation. >I get 110 if I use it as a function. > > >>> spam = 42 > >>> def print42(): print spam >... > >>> spam = 110 > >>> print42() >110 > >Why do you get 42 when you use it as module? I haven't understood the >explantaion. > >With warm regards, >-Payal >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ 15,000 Velocity Points Velocity NAB Credit Card http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fadsfac%2Enet%2Flink%2Easp%3Fcc%3DNAT030%2E23080%2E0%26clk%3D1%26creativeID%3D34301&_t=754983092&_r=emailtagline&_m=EXT From kp8 at mac.com Thu Apr 27 00:37:10 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 26 Apr 2006 18:37:10 -0400 Subject: [Tutor] cycle w/ shuffle In-Reply-To: <444EE886.6070805@alum.rpi.edu> References: <3d020a3264cb80f4cae221c4d40d4ecb@mac.com> <444EE886.6070805@alum.rpi.edu> Message-ID: I am trying to write a loop that iterates over a sequence and do something x number of times. But sometimes i will need more events (larger number x) than i have have items in the sequence, so if i need more events that i have stuff in my sequence i would like to have the loop reload and shuffle the deck and start all over again, reloading as many times as necessary to get the number of events needed. I suppose i could go around cyclically modulo the list size but i would want to shuffle the deck before doing that again... it seems to me that i need something like itertools cycle, except that i need to keep track of when i have exhausted my list and then call random.shuffle() on my sequence. def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element def test(): seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') loop = cycle(seq) count = 1 for item in range(25): print count, loop.next() count = count + 1 if __name__ == '__main__': test() here i have gone through my list 2.5 times .. and somewhere after the second and third(tho incomplete) rounds i need to shuffle... but i am not sure how to fix that. From kp8 at mac.com Thu Apr 27 00:43:48 2006 From: kp8 at mac.com (kevin parks) Date: Wed, 26 Apr 2006 18:43:48 -0400 Subject: [Tutor] cycle w/ shuffle In-Reply-To: References: Message-ID: <407af86914b2d34d245f1bc5904bc508@mac.com> I am trying to write a loop that iterates over a sequence and do something x number of times. But sometimes i will need more events (larger number x) than i have have items in the sequence, so if i need more events that i have stuff in my sequence i would like to have the loop reload and shuffle the deck and start all over again, reloading as many times as necessary to get the number of events needed. I suppose i could go around cyclically modulo the list size but i would want to shuffle the deck before doing that again... it seems to me that i need something like itertools cycle, except that i need to keep track of when i have exhausted my list and then call random.shuffle() on my sequence. def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element def test(): seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') loop = cycle(seq) count = 1 for item in range(25): print count, loop.next() count = count + 1 if __name__ == '__main__': test() here i have gone through my list 2.5 times .. and somewhere after the second and third(tho incomplete) rounds i need to shuffle... but i am not sure how to fix that. From ukc802591034 at btconnect.com Thu Apr 27 01:21:37 2006 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Thu, 27 Apr 2006 00:21:37 +0100 Subject: [Tutor] Alan Gauld's tut - namespaces References: <20060426174159.GA21428@tranquility.scriptkitchen.com> Message-ID: "Payal Rathod" wrote in message news:20060426174159.GA21428 at tranquility.scriptkitchen.com... > In Alan's tutorial I haven't got the example of print42() even after > reading the explanation. > I get 110 if I use it as a function. > >>>> spam = 42 >>>> def print42(): print spam > ... >>>> spam = 110 >>>> print42() > 110 > > Why do you get 42 when you use it as module? I haven't understood the > explantaion. The problem here is that you are typing it all at the >>> prompt. If you look closely you will notice that the code examples are in different modules - ie different files. The >>> prompt basically acts like all the code you type is in the same module, namespaces are really only effectoive when you are using multiple files/modules. However I'll refrain from saying much more since I do think the namespaces topic could be significantly improved if only I could find better words and examples. So please everyone, feel free to try to explain this idea to Payal so that I can steal your ideas for the tutorial!! :-) -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Apr 27 03:17:40 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 21:17:40 -0400 Subject: [Tutor] cycle w/ shuffle In-Reply-To: References: <3d020a3264cb80f4cae221c4d40d4ecb@mac.com> <444EE886.6070805@alum.rpi.edu> Message-ID: <44501BB4.9030506@tds.net> kevin parks wrote: > it seems to me that i need something like itertools cycle, except that > i need to keep track of when i have exhausted my list and then call > random.shuffle() on my sequence. > > def cycle(iterable): > saved = [] > for element in iterable: > yield element > saved.append(element) > while saved: random.shuffle(saved) ############### > for element in saved: > yield element Kent From mahansen at adelphia.net Thu Apr 27 03:19:17 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 26 Apr 2006 19:19:17 -0600 Subject: [Tutor] Tutor FAQ Message-ID: <58ee78e0f1c508b3d595dfc3b1a32761@adelphia.net> Here's the next batch of questions and answers for the tutor FAQ. If you have any clarifications or corrections, please let me know. I'll try to post this on the web site in a couple of days. --------------------------------------------------------------------- How do I get data out of HTML? Try Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup is more forgiving than other parsers in that it won't choke on bad markup. --------------------------------------------------------------------- What's the best editor/IDE for Python? It's really a matter of preference. There are many features of an editor or IDE such as syntax highlighting, code completion, code folding, buffers, tabs, ... Each editor or IDE has some or all of these features, and you'll have to decide which features are important to you. See http://wiki.python.org/moin/PythonEditors for a list of editors. Also http://wiki.python.org/moin/IntegratedDevelopmentEnvironments has a list of IDEs. --------------------------------------------------------------------- How do I make public and private attributes and methods in my classes? Python followws the philosophy of "we're all adults here" with respect to hiding attributes and methods. i.e. trust the other programmers who will use your classes. You can't really hide variables and methods in Python. You can give clues to other programmers. Python does do name mangling. By putting two underscores before the attribute or method name and not putting two underscores after the name, Python will mangle the name by putting the class name in front of it. For an short example see http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python --------------------------------------------------------------------- Why doesn't my regular expression work? Typically, it's an isssue between re.match and re.search. Match matches the beginning only and search checks the entire string. See the regular expression HOWTO for more details. http://www.amk.ca/python/howto/regex/ --------------------------------------------------------------------- How do I perform matrix operations using Python? The Python FAQ has an entry on how to create multidimensional lists: http://python.org/doc/faq/programming.html#how-do-i-create-a- multidimensional-list You may want to look into the 'numarray' third party module: http://www.stsci.edu/resources/software_hardware/numarray --------------------------------------------------------------------- How do I make an executable out of my Python program? Although it isn't necessary to turn your Python programs into executables, many people want to be able to put their Python programs on other machines that don't have Python installed. Py2exe makes an executable of your Python program. For Windows only. http://sourceforge.net/projects/py2exe/ From kent37 at tds.net Thu Apr 27 03:25:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 21:25:19 -0400 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> Message-ID: <44501D7F.4020604@tds.net> doug shawhan wrote: > I am in preparation mode for creating a script which uses SOAP. > > I have been looking at the various SOAP modules: soapy, soap.py, ZSI, > pywebsvcs. > > I'm very confused as to the status of these projects. Most seem to be > only partially supported, if not abandoned completely. Thre appears to > have been a flurry of interest in 2001, then everyone got jobs! ;-) SOAPpy seems to be the most commonly mentioned one, though I think Python developers tend to avoid SOAP if possible, preferring lighter protocols. Kent From kent37 at tds.net Thu Apr 27 03:42:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Apr 2006 21:42:35 -0400 Subject: [Tutor] Tutor FAQ In-Reply-To: <58ee78e0f1c508b3d595dfc3b1a32761@adelphia.net> References: <58ee78e0f1c508b3d595dfc3b1a32761@adelphia.net> Message-ID: <4450218B.6010004@tds.net> Mike Hansen wrote: > Here's the next batch of questions and answers for the tutor FAQ. If > you have any clarifications or corrections, please let me know. I'll > try to post this on the web site in a couple of days. Thanks Mike! > --------------------------------------------------------------------- > What's the best editor/IDE for Python? > > It's really a matter of preference. There are many features of an > editor or IDE such as syntax highlighting, code completion, code > folding, buffers, tabs, ... Each editor or IDE has some or all of > these features, and you'll have to decide which features are important > to you. > See http://wiki.python.org/moin/PythonEditors for a list of editors. > Also http://wiki.python.org/moin/IntegratedDevelopmentEnvironments has > a list of IDEs. This question is asked every few weeks on comp.lang.python so searching the archives will yield many opinions. > > --------------------------------------------------------------------- > How do I make public and private attributes and methods in my classes? > > Python followws the philosophy of "we're all adults here" with respect > to hiding attributes and methods. i.e. trust the other programmers who > will use your classes. You can't really hide variables and methods in > Python. You can give clues to other programmers. By convention, a name that starts with a single underscore is an implementation detail that may change and should not be used by client code. Python does do name > mangling. By putting two underscores before the attribute or method > name and not putting two underscores after the name, Python will mangle > the name by putting the class name in front of it. > > For an short example see > http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python > > --------------------------------------------------------------------- > Why doesn't my regular expression work? > > Typically, it's an isssue between re.match and re.search. Match matches > the beginning only and search checks the entire string. See the regular > expression HOWTO for more details. > > http://www.amk.ca/python/howto/regex/ Python comes with a handy program for testing regular expressions, Tools\Scripts\redemo.py. > > --------------------------------------------------------------------- > How do I perform matrix operations using Python? > > The Python FAQ has an entry on how to create multidimensional lists: > http://python.org/doc/faq/programming.html#how-do-i-create-a- > multidimensional-list > > You may want to look into the 'numarray' third party module: > http://www.stsci.edu/resources/software_hardware/numarray You may want to look into the 'numpy' module which contains many resources for scientific computing including powerful matrix operations: http://numeric.scipy.org/ Kent From mahansen at adelphia.net Thu Apr 27 04:29:44 2006 From: mahansen at adelphia.net (Mike Hansen) Date: Wed, 26 Apr 2006 20:29:44 -0600 Subject: [Tutor] Tutor FAQ In-Reply-To: <4450218B.6010004@tds.net> References: <58ee78e0f1c508b3d595dfc3b1a32761@adelphia.net> <4450218B.6010004@tds.net> Message-ID: <29f39fe89058ef9a4f275c7342d6a846@adelphia.net> Thanks Kent. I'll make those additions/corrections and rework the question about private and public attributes and methods. Mike On Apr 26, 2006, at 7:42 PM, Kent Johnson wrote: > Mike Hansen wrote: >> Here's the next batch of questions and answers for the tutor FAQ. If >> you have any clarifications or corrections, please let me know. I'll >> try to post this on the web site in a couple of days. > > Thanks Mike! > >> --------------------------------------------------------------------- >> What's the best editor/IDE for Python? >> >> It's really a matter of preference. There are many features of an >> editor or IDE such as syntax highlighting, code completion, code >> folding, buffers, tabs, ... Each editor or IDE has some or all of >> these features, and you'll have to decide which features are important >> to you. >> See http://wiki.python.org/moin/PythonEditors for a list of editors. >> Also http://wiki.python.org/moin/IntegratedDevelopmentEnvironments has >> a list of IDEs. > This question is asked every few weeks on comp.lang.python so searching > the archives will yield many opinions. >> >> --------------------------------------------------------------------- >> How do I make public and private attributes and methods in my classes? >> >> Python followws the philosophy of "we're all adults here" with respect >> to hiding attributes and methods. i.e. trust the other programmers who >> will use your classes. You can't really hide variables and methods in >> Python. You can give clues to other programmers. > By convention, a name that starts with a single underscore is an > implementation detail that may change and should not be used by client > code. > Python does do name >> mangling. By putting two underscores before the attribute or method >> name and not putting two underscores after the name, Python will >> mangle >> the name by putting the class name in front of it. > >> >> For an short example see >> http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python >> >> --------------------------------------------------------------------- >> Why doesn't my regular expression work? >> >> Typically, it's an isssue between re.match and re.search. Match >> matches >> the beginning only and search checks the entire string. See the >> regular >> expression HOWTO for more details. >> >> http://www.amk.ca/python/howto/regex/ > > Python comes with a handy program for testing regular expressions, > Tools\Scripts\redemo.py. >> >> --------------------------------------------------------------------- >> How do I perform matrix operations using Python? >> >> The Python FAQ has an entry on how to create multidimensional lists: >> http://python.org/doc/faq/programming.html#how-do-i-create-a- >> multidimensional-list >> >> You may want to look into the 'numarray' third party module: >> http://www.stsci.edu/resources/software_hardware/numarray > > You may want to look into the 'numpy' module which contains many > resources for scientific computing including powerful matrix > operations: > http://numeric.scipy.org/ > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From oztriking at hotmail.com Thu Apr 27 08:46:40 2006 From: oztriking at hotmail.com (John Connors) Date: Thu, 27 Apr 2006 16:46:40 +1000 Subject: [Tutor] Alan Gauld's tut - namespaces Message-ID: G'day Alan, >However I'll refrain from saying much more since I do think the >namespaces topic could be significantly improved if only I could >find better words and examples. > >So please everyone, feel free to try to explain this idea to Payal >so that I can steal your ideas for the tutorial!! :-) Maybe it would would be a good idea to say that the first part of the example has to be saved as first.py before the example works. And maybe an explanation of the difference between import module and from module import * .It seems so simple now but until I understood that I couldn't understand the namespaces part of the tutorial. John _________________________________________________________________ Bounce Back from sickness and injury today. http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fclk%2Eatdmt%2Ecom%2FMOS%2Fgo%2Fnnmsngem0010000007mos%2Fdirect%2F01%2F&_t=753470755&_r=HM_Tagline_Apr06&_m=EXT From singletoned at gmail.com Thu Apr 27 12:16:08 2006 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 27 Apr 2006 11:16:08 +0100 Subject: [Tutor] Regex across multiple lines In-Reply-To: References: <444F3A40.6040505@rawflow.com> <444F57A5.10907@tds.net> <444F5DA1.9080803@rawflow.com> Message-ID: <34bb7f5b0604270316l42e3d69cuf6440f8648cd777f@mail.gmail.com> On 26/04/06, Liam Clarke wrote: > Hi Frank, just bear in mind that the pattern: > > patObj = re.compile(".*", re.DOTALL) > > will match > > > This is my title > > > But, it'll also match > > > This is my title > >

Some content here

> > Another title; not going to happen with a title tag in HTML, but > more an illustration > > > All of that. > > Got to watch .* with re.DOTALL; try using .*? instead, it makes it > non-greedy. Functionality for your current use case won't change, but > you won't spend ages when you have a different use case trying to > figure out why half your data is matching. >_< When you only want a tag like with no nested tags, I sometimes use: <title>[^<]* though for anything but the most trivial cases, it's often better to use BeautifulSoup Ed From kent37 at tds.net Thu Apr 27 12:19:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 06:19:55 -0400 Subject: [Tutor] Alan Gauld's tut - namespaces In-Reply-To: References: <20060426174159.GA21428@tranquility.scriptkitchen.com> Message-ID: <44509ACB.7030205@tds.net> Alan Gauld wrote: > However I'll refrain from saying much more since I do think the > namespaces topic could be significantly improved if only I could > find better words and examples. Hi Alan, Looking at the tutorial, I think it jumps too quickly to more advanced material (multiple modules) before explaining the basics of how a name is resolved within a single module. You list the different scopes but you don't explain how they are searched for a name. Once it is clear that names are searched in the *lexically* enclosing module, it will make more sense that print42() prints the value of spam in first.py. It might help to talk about name binding explicitly - that importing a module binds a name to the module, and importing a function from the module binds a name to the function. This might help make the distinction that importing doesn't include anything new in the importing module, it just creates references to the imported module or its attributes. You are missing a namespace, BTW. Since Python 2.1 the search order is local, *enclosing*, global and builtin. Kent From alan.gauld at freenet.co.uk Thu Apr 27 13:21:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 27 Apr 2006 12:21:36 +0100 Subject: [Tutor] Tutor FAQ References: <58ee78e0f1c508b3d595dfc3b1a32761@adelphia.net> Message-ID: <003301c669ec$e72a5f70$0a01a8c0@xp> > Py2exe makes an executable of your Python program. For Windows only. > http://sourceforge.net/projects/py2exe/ > I believe Gordon McMillan's installer (now called pyInstaller) also makes Linux (and Irix!) executables so may be worth a link/mention here too. http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi Although Linux users seem far less likely to want/need to create standalone executables. Alan G. From lindaik at earthlink.net Thu Apr 27 14:04:06 2006 From: lindaik at earthlink.net (Linda Kvam) Date: Thu, 27 Apr 2006 08:04:06 -0400 Subject: [Tutor] Python and Oracle Message-ID: <410-2200644271246234@earthlink.net> I have Oracle 10g and Python 2.4 on my PC. I just installed cx_Oracle and then entered - import cx_Oracle -in PythonWin and got the following error - >>> import cx_Oracle Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: The specified procedure could not be found. >>> I have XP Professional OS and in my Path, I have Python24 (where my python executables are), Python24/Scripts and the path for oci.dll (Oracle's dll). I installed Oracle's Developer Suite from a CD and I downloaded Oracle 10G - so I'm not sure if I have Oracle Client - I think I have to do something on the Oracle side but I'm not sure what. When I installed cx_Oracle, 2 files were added to my directory Python24 - I have attached the log file for your information - I know the removecx_oracle works because I have run it. Any hints or ideas you have will be appreciated. Thanks, Linda Kvam lindakvam at lynxconsulting.us -------------- next part -------------- A non-text attachment was scrubbed... Name: cx_Oracle-wininst.log Type: application/octet-stream Size: 4726 bytes Desc: cx_Oracle-wininst.log Url : http://mail.python.org/pipermail/tutor/attachments/20060427/abf87688/attachment.obj From francis.moore at rawflow.com Thu Apr 27 15:01:05 2006 From: francis.moore at rawflow.com (Frank Moore) Date: Thu, 27 Apr 2006 14:01:05 +0100 Subject: [Tutor] Unicode Encode Error Message-ID: <4450C091.3020707@rawflow.com> Hi, I'm getting the following error when I try and write some HTML with German text in it. UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1367: ordinal not in range(128) This was my code: html_text = open(inFile, 'r').read() # ... do some processing on html_text file(outFile, 'w').write(html_text) I've now read the 'Unicode - How To' by AMKuchling and changed the code to: html_text = codecs.open(inFile, encoding='utf-8').read() # ... do some processing on html_text f = codecs.open(outFile, encoding='utf-8', mode='w') f.write(html_text) but I'm still getting the error. Does anybody know what I'm doing wrong? Cheers, Frank. From kent37 at tds.net Thu Apr 27 15:21:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 09:21:38 -0400 Subject: [Tutor] Unicode Encode Error In-Reply-To: <4450C091.3020707@rawflow.com> References: <4450C091.3020707@rawflow.com> Message-ID: <4450C562.5030706@tds.net> Frank Moore wrote: > Hi, > > I'm getting the following error when I try and write some HTML with > German text in it. > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in > position 1367: ordinal not in range(128) > > This was my code: > > html_text = open(inFile, 'r').read() > # ... do some processing on html_text > file(outFile, 'w').write(html_text) > > I've now read the 'Unicode - How To' by AMKuchling and changed the code to: > > html_text = codecs.open(inFile, encoding='utf-8').read() > # ... do some processing on html_text > f = codecs.open(outFile, encoding='utf-8', mode='w') > f.write(html_text) > > but I'm still getting the error. > Does anybody know what I'm doing wrong? Was it exactly the same error in both cases? Can you show us the whole error message with the traceback? Kent From tim.golden at viacom-outdoor.co.uk Thu Apr 27 15:19:06 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 27 Apr 2006 14:19:06 +0100 Subject: [Tutor] Unicode Encode Error Message-ID: [Frank Moore] | I'm getting the following error when I try and write some HTML with | German text in it. | | UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in | position 1367: ordinal not in range(128) | | I've now read the 'Unicode - How To' by AMKuchling and | changed the code to: | | html_text = codecs.open(inFile, encoding='utf-8').read() | # ... do some processing on html_text | f = codecs.open(outFile, encoding='utf-8', mode='w') | f.write(html_text) | | but I'm still getting the error. | Does anybody know what I'm doing wrong? At what point in your script does the error occur? You say "when I try and write" but does the error occur after the f.write... line or earlier on after the codecs.open (..).read line? There doesn't seem to be anything wrong with your code fragment, except that you are assuming -- and maybe with good reason -- that the text in inFile is in fact utf8-encoded. Could you run your code fragment on an interpreter and then dump the screen output into an email? This, for example, works on my Win32 Python console: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import codecs >>> inFile = "in.utf8" >>> outFile = "out.utf8" >>> >>> # ... # Create dummy infile ... # ... f = codecs.open (inFile, encoding="utf-8", mode="w") >>> f.write (u"Tim G\xf6lden") >>> f.close () >>> >>> html_text = codecs.open(inFile, encoding='utf-8').read() >>> # ... do some processing on html_text ... f = codecs.open(outFile, encoding='utf-8', mode='w') >>> f.write(html_text) >>> >>> TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent37 at tds.net Thu Apr 27 16:32:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 10:32:50 -0400 Subject: [Tutor] Unicode Encode Error In-Reply-To: <4450D23D.5070007@rawflow.com> References: <4450C091.3020707@rawflow.com> <4450C562.5030706@tds.net> <4450D23D.5070007@rawflow.com> Message-ID: <4450D612.70904@tds.net> Frank Moore wrote: > The later code (where I use codecs) is not giving me an error (I must > have got that error during an intermediate step I performed). > However, it's also not writing anything away. It seems to be silently > failing as html_text definitely has content. Do you explicitly close the output file? If not, the data may not be actually written. Kent From winfried at tilanus.com Thu Apr 27 16:51:13 2006 From: winfried at tilanus.com (Winfried Tilanus) Date: Thu, 27 Apr 2006 16:51:13 +0200 Subject: [Tutor] Web-templating systems In-Reply-To: <444F5085.5080402@tds.net> References: <7a8d5a0c0604250751o6f8e7169sa04e9089966a47e8@mail.gmail.com> <444E3A2D.6030607@tds.net> <444F3600.9000004@tilanus.com> <444F5085.5080402@tds.net> Message-ID: <4450DA61.6000408@tilanus.com> On 04/26/2006 Kent Johnson wrote: > I think Kid meets your requirements: > http://kid.lesscode.org/ > > Other template systems that seem to be popular these days: > Cheetah > HTMLTemplate > Myghty Thanks for the suggestions (also for those off-line). Kid and cheetah look the most promising. I will do some testing with those. thanks, Winfried From max.russell at barco.com Thu Apr 27 16:47:34 2006 From: max.russell at barco.com (Max Russell) Date: Thu, 27 Apr 2006 15:47:34 +0100 Subject: [Tutor] Setting a global variable on class initialisation Message-ID: Hello- I know that overall Global variables are bad idea, however, I have a situation where on on initialisation of a class, I need to read in two files and then populate two lists. The lists need to would appear to need to be outwith the class I am working with and global. Can anyone give good examples of this? thanks Max Russell Senior Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com max.russell at barco.com Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060427/872807e3/attachment.html From kent37 at tds.net Thu Apr 27 17:17:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 11:17:00 -0400 Subject: [Tutor] Setting a global variable on class initialisation In-Reply-To: References: Message-ID: <4450E06C.2070901@tds.net> Max Russell wrote: > Hello- > > I know that overall Global variables are bad idea, however, I have a > situation where on on initialisation of a class, I need to read in two > files and then populate two lists. What do you mean by class initialization? If you want to read the files and populate the lists when the class is defined, it might work to do this at the module level. Then the lists would be populated when the module is first imported: ## mymodule.py specialList = open('specialfile.txt').readlines() # Whatever file processing you need goes here class MyClass(object): # etc # do something with specialList If you want to read the files when an instance is initialized, then put the code in the class __init__() method. > The lists need to would appear to need to be outwith the class I am > working with and global. ?? What ?? Kent From tim.golden at viacom-outdoor.co.uk Thu Apr 27 17:22:11 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 27 Apr 2006 16:22:11 +0100 Subject: [Tutor] Setting a global variable on class initialisation Message-ID: [Max Russell] | I know that overall Global variables are bad idea, however, | I have a situation where on on initialisation of a class, I | need to read in two files and then populate two lists. | The lists need to would appear to need to be outwith the | class I am working with and global. | | Can anyone give good examples of this? Well, in simple terms this *sounds* like what you're trying to do (not attempting any more Python approach at this juncture): l1 = [] l2 = [] class X: def __init__ (self, filename1, filename2): l1.extend (open (filename1).readlines ()) l2.extend (open (filename2).readlines ()) if __name__ == '__main__': open ("test1.txt", "w").write ("hello\nworld\n") open ("test2.txt", "w").write ("goodbye\nworld\n") x = X ("test1.txt", "test2.txt") print l1 print l2 Obviously this code doesn't do anything terribly useful, but I wanted to see if it was more-or-less what you had in mind? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From francis.moore at rawflow.com Thu Apr 27 18:15:06 2006 From: francis.moore at rawflow.com (Frank Moore) Date: Thu, 27 Apr 2006 17:15:06 +0100 Subject: [Tutor] Unicode Encode Error In-Reply-To: <4450D612.70904@tds.net> References: <4450C091.3020707@rawflow.com> <4450C562.5030706@tds.net> <4450D23D.5070007@rawflow.com> <4450D612.70904@tds.net> Message-ID: <4450EE0A.8060002@rawflow.com> Kent Johnson wrote: >Do you explicitly close the output file? If not, the data may not be >actually written. > > Kent, You're right, I realised after playing with Tim's example that the problem was that I wasn't calling close() on the codecs file. Adding this after the f.write(html_text) seems to flush the buffer which means that the content now gets written to the file. Thanks for your help, Frank. From dyoo at hkn.eecs.berkeley.edu Thu Apr 27 21:05:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 27 Apr 2006 12:05:00 -0700 (PDT) Subject: [Tutor] Setting a global variable on class initialisation In-Reply-To: References: Message-ID: > I know that overall Global variables are bad idea, however, I have a > situation where on on initialisation of a class, I need to read in two > files and then populate two lists. Hi Max, Could you give more context to this problem? I'm not sure we get it yet. *grin* > The lists need to would appear to need to be outwith the class I am > working with and global. Are the lists a part of the "state" of the instance? If not, why is this a part of the instance's initialization? I think we'd better wait on advice until we learn a little more about the situation. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Apr 27 21:07:14 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 27 Apr 2006 12:07:14 -0700 (PDT) Subject: [Tutor] Unicode Encode Error In-Reply-To: <4450EE0A.8060002@rawflow.com> References: <4450C091.3020707@rawflow.com> <4450C562.5030706@tds.net> <4450D23D.5070007@rawflow.com> <4450D612.70904@tds.net> <4450EE0A.8060002@rawflow.com> Message-ID: > You're right, I realised after playing with Tim's example that the > problem was that I wasn't calling close() on the codecs file. Adding > this after the f.write(html_text) seems to flush the buffer which means > that the content now gets written to the file. Hi Frank, Quick note: it may be important to write and read from the file using binary mode "b". It's not so significant under Unix, but it is more significant under Windows, because otherwise we may get some weird results. Good luck! From kent37 at tds.net Thu Apr 27 21:24:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 15:24:34 -0400 Subject: [Tutor] Unicode Encode Error In-Reply-To: References: <4450C091.3020707@rawflow.com> <4450C562.5030706@tds.net> <4450D23D.5070007@rawflow.com> <4450D612.70904@tds.net> <4450EE0A.8060002@rawflow.com> Message-ID: <44511A72.3030700@tds.net> Danny Yoo wrote: >> You're right, I realised after playing with Tim's example that the >> problem was that I wasn't calling close() on the codecs file. Adding >> this after the f.write(html_text) seems to flush the buffer which means >> that the content now gets written to the file. > > Hi Frank, > > Quick note: it may be important to write and read from the file using > binary mode "b". It's not so significant under Unix, but it is more > significant under Windows, because otherwise we may get some weird > results. But the file is utf-8 text, ISTM it should be written as text, not binary. Why do you recommend binaray mode? Kent From doug.shawhan at gmail.com Thu Apr 27 21:46:11 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 27 Apr 2006 14:46:11 -0500 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <44501D7F.4020604@tds.net> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> <44501D7F.4020604@tds.net> Message-ID: <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> The problem is, I am trying to develop a script to upload massive amounts of stuff onto an ebay store. Unfortunately the folks at ebay have settled on a couple sorts of soapism as their standard. (They seem to be very Java and Dot Net happy over there ...) I would prefer nearly *any* other protocol. Reading the official SOAP documentation has been like licking the hoof of a very angry mule. But if you gotta, you gotta! On 4/26/06, Kent Johnson wrote: > > doug shawhan wrote: > > I am in preparation mode for creating a script which uses SOAP. > > > > I have been looking at the various SOAP modules: soapy, soap.py, ZSI, > > pywebsvcs. > > > > I'm very confused as to the status of these projects. Most seem to be > > only partially supported, if not abandoned completely. Thre appears to > > have been a flurry of interest in 2001, then everyone got jobs! ;-) > > SOAPpy seems to be the most commonly mentioned one, though I think > Python developers tend to avoid SOAP if possible, preferring lighter > protocols. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060427/1314e914/attachment.htm From kent37 at tds.net Thu Apr 27 22:01:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 16:01:43 -0400 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> <44501D7F.4020604@tds.net> <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> Message-ID: <44512327.7050007@tds.net> doug shawhan wrote: > The problem is, I am trying to develop a script to upload massive > amounts of stuff onto an ebay store. Unfortunately the folks at ebay > have settled on a couple sorts of soapism as their standard. (They seem > to be very Java and Dot Net happy over there ...) > > I would prefer nearly *any* other protocol. Reading the official SOAP > documentation has been like licking the hoof of a very angry mule. But > if you gotta, you gotta! A quick Google for "python ebay" turns up a couple of Python packages that might be useful. The eBay developer docs talk about REST and XML APIs as well as SOAP. Looks like you need to dig a little more. Kent From doug.shawhan at gmail.com Thu Apr 27 22:15:50 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 27 Apr 2006 15:15:50 -0500 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <44512327.7050007@tds.net> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> <44501D7F.4020604@tds.net> <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> <44512327.7050007@tds.net> Message-ID: <5e1ceb8a0604271315g62b0ab17pd92f428df6ffb99@mail.gmail.com> The https/XML API is deprecated and will no longer be supported after the first of June. :-/ The real drag is: the older XML api had *2* very nice python implementations. I was successfull in less than 10 minutes with both of those. It's a shame. I was hoping to avoid the REST method, as I would like to have the whole shebang on one computer and not worry about making sure my hosting provider is using the same version of as I am developing with ... I'm just chicken, I guess. :-) On 4/27/06, Kent Johnson wrote: > > doug shawhan wrote: > > The problem is, I am trying to develop a script to upload massive > > amounts of stuff onto an ebay store. Unfortunately the folks at ebay > > have settled on a couple sorts of soapism as their standard. (They seem > > to be very Java and Dot Net happy over there ...) > > > > I would prefer nearly *any* other protocol. Reading the official SOAP > > documentation has been like licking the hoof of a very angry mule. But > > if you gotta, you gotta! > > A quick Google for "python ebay" turns up a couple of Python packages > that might be useful. The eBay developer docs talk about REST and XML > APIs as well as SOAP. Looks like you need to dig a little more. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060427/7e52ba54/attachment.html From kent37 at tds.net Thu Apr 27 22:31:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Apr 2006 16:31:16 -0400 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <5e1ceb8a0604271315g62b0ab17pd92f428df6ffb99@mail.gmail.com> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> <44501D7F.4020604@tds.net> <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> <44512327.7050007@tds.net> <5e1ceb8a0604271315g62b0ab17pd92f428df6ffb99@mail.gmail.com> Message-ID: <44512A14.2090601@tds.net> doug shawhan wrote: > The https/XML API is deprecated and will no longer be supported after > the first of June. :-/ What about the "Unified Schema XML API"? It's XML but it's not SOAP; the XML formats look pretty straightforward. They have a lot of fields but the structure is pretty simple. > > I was hoping to avoid the REST method, as I would like to have the whole > shebang on one computer and not worry about making sure my hosting > provider is using the same version of as > I am developing with ... I'm just chicken, I guess. :-) ?? I don't know what important doodad you are worried about here...REST just means that you make requests using ordinary HTTP requests such as GET. The request parameters are part of the query, as opposed to SOAP for example where the query parameters are in an XML payload included with the request. Hmm...the REST API seems to only support one call, GetSearchResults, so that won't be very useful to you. I hope I'm not way off base here, I'm just doing a little Googling myself, I don't have any actual experience with this stuff... Kent From doug.shawhan at gmail.com Thu Apr 27 22:31:58 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Thu, 27 Apr 2006 15:31:58 -0500 Subject: [Tutor] SOAP Modules - I need a little direction. In-Reply-To: <5e1ceb8a0604271315g62b0ab17pd92f428df6ffb99@mail.gmail.com> References: <5e1ceb8a0604261435yf971fc9ie0a4b5029c5e4e2a@mail.gmail.com> <44501D7F.4020604@tds.net> <5e1ceb8a0604271246p5fea2b5ak2a5c3c6b4b9ccad1@mail.gmail.com> <44512327.7050007@tds.net> <5e1ceb8a0604271315g62b0ab17pd92f428df6ffb99@mail.gmail.com> Message-ID: <5e1ceb8a0604271331w2d0ce392j75775b37715db3fc@mail.gmail.com> ... Upon which I completely expose my ignorance of REST. I was completely concentrating on SOAP, since it seemed to have much more activity and had not looked at the REST description. It look like, for eBay's purposes, that to use the older xml-based systems, one must append "schema=1" to the requests. *blush* Ah well, not the first time I have dined on my foot on this mailing list! (Memo to self, stock up on ketchup) On 4/27/06, doug shawhan wrote: > > The https/XML API is deprecated and will no longer be supported after the > first of June. :-/ > > The real drag is: the older XML api had *2* very nice python > implementations. I was successfull in less than 10 minutes with both of > those. It's a shame. > > I was hoping to avoid the REST method, as I would like to have the whole > shebang on one computer and not worry about making sure my hosting provider > is using the same version of as I am > developing with ... I'm just chicken, I guess. :-) > > > > > On 4/27/06, Kent Johnson wrote: > > > > doug shawhan wrote: > > > The problem is, I am trying to develop a script to upload massive > > > amounts of stuff onto an ebay store. Unfortunately the folks at ebay > > > have settled on a couple sorts of soapism as their standard. (They > > seem > > > to be very Java and Dot Net happy over there ...) > > > > > > I would prefer nearly *any* other protocol. Reading the official SOAP > > > documentation has been like licking the hoof of a very angry mule. But > > > > > if you gotta, you gotta! > > > > A quick Google for "python ebay" turns up a couple of Python packages > > that might be useful. The eBay developer docs talk about REST and XML > > APIs as well as SOAP. Looks like you need to dig a little more. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060427/fff3b11e/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Apr 27 23:12:40 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 27 Apr 2006 14:12:40 -0700 (PDT) Subject: [Tutor] Unicode Encode Error In-Reply-To: <44511A72.3030700@tds.net> References: <4450C091.3020707@rawflow.com> <4450C562.5030706@tds.net> <4450D23D.5070007@rawflow.com> <4450D612.70904@tds.net> <4450EE0A.8060002@rawflow.com> <44511A72.3030700@tds.net> Message-ID: >>> You're right, I realised after playing with Tim's example that the >>> problem was that I wasn't calling close() on the codecs file. Adding >>> this after the f.write(html_text) seems to flush the buffer which >>> means that the content now gets written to the file. >> >> Quick note: it may be important to write and read from the file using >> binary mode "b". It's not so significant under Unix, but it is more >> significant under Windows, because otherwise we may get some weird >> results. > > But the file is utf-8 text, ISTM it should be written as text, not > binary. Why do you recommend binaray mode? Hi Kent, Oh! I just wrote that out because I had a vague and fuzzy feeling that utf-8, having high-order binary bits, needed to be written carefully. But let me examine that unexamined assumption... No, you're right, we don't have to be so careful here, for carriage returns and newlines have their standard interpretation under utf-8 too. Ok, good to know. Thank you! I'd seen too many problems with Windows and binary data that I do 'rb' out of habit whenever dealing with high-order binary data. For example, ord(26) causes Windows to prematurely truncate the reading of a file in text mode: http://mail.python.org/pipermail/python-list/2003-March/154659.html On a close reading of how the utf-8 encoding standard, though, I see that it does say that utf-8 avoids encoding high Unicode code points with control characters, so my caution is unfounded. From hugonz-lists at h-lab.net Thu Apr 27 23:11:14 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 27 Apr 2006 15:11:14 -0600 Subject: [Tutor] cycle w/ shuffle In-Reply-To: <407af86914b2d34d245f1bc5904bc508@mac.com> References: <407af86914b2d34d245f1bc5904bc508@mac.com> Message-ID: <44513372.1040806@h-lab.net> Hi Kevin, kevin parks wrote: > I am trying to write a loop that iterates over a sequence and do > something x number of times. But sometimes i will need more events > (larger number x) than i have have items in the sequence, so if i need > more events that i have stuff in my sequence i would like to have the > loop reload and shuffle the deck and start all over again, reloading as > many times as necessary to get the number of events needed. I suppose i > could go around cyclically modulo the list size but i would want to > shuffle the deck before doing that again... > Why not save the iterable it in the generator, then just reuse it? You can copy the iterable like this: import random def cycle(iterable): saved = list(iterable) #notice how I saved into a list, for I could not shuffle a TUPLE! while True: for element in saved: yield element random.shuffle(saved) def test(): seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') loop = cycle(seq) count = 1 for item in range(25): print count, loop.next() count = count + 1 #you could use enumerate() instead of manually making the loop here. #for i, v in enumerate(loop): # print i, v Hope that helps, Hugo if __name__ == '__main__': test() From kp8 at mac.com Fri Apr 28 03:59:18 2006 From: kp8 at mac.com (kevin parks) Date: Thu, 27 Apr 2006 21:59:18 -0400 Subject: [Tutor] how to *really* copy a list In-Reply-To: <44513372.1040806@h-lab.net> References: <407af86914b2d34d245f1bc5904bc508@mac.com> <44513372.1040806@h-lab.net> Message-ID: <0867c06f67f4c2c35d82b88e93ea1657@mac.com> I know there is an answer to this somewhere. it is prolly the biggest stumbling block to all python n00bs, but it hasn't been an issue for me in a while. Suddenly i am getting bit by it and can't for the life of me keep straight the two way of opperating on lists. In most case you are fine operating on the list in place and altering the existing list. In some cases you want your code to stop molesting your poor mutables and really honestly sincerly copy the dang thing. In this case i am making a function that does odd smmetry mirroring. But i want my orginal list to remain intact.... >>> a = [1, 2, 3, 4] >>> mirror(a) [1, 2, 3, 4, 3, 2, 1] >>> a [1, 2, 3, 4, 3, 2, 1] clearly this is not happening. believe it or not i googled around figuring the answer would be posted someplace... but if it is i haven't found it. Every thing i land on says copy a list by [:] slicing like i have below... how to i really (not kidding) copy a list? I swear i used to know this, but i haven't had to do it in a long long long time. # =================================== dumb code: def mirror(seq): """odd symmetry mirroring [1, 2, 3, 4] --> [1, 2, 3, 4, 3, 2, 1]""" foo=seq[:-1] # copy list, excluding last element for odd symetry foo.reverse() # flip it seq.extend(foo) return seq From john at fouhy.net Fri Apr 28 04:14:07 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 28 Apr 2006 14:14:07 +1200 Subject: [Tutor] how to *really* copy a list In-Reply-To: <0867c06f67f4c2c35d82b88e93ea1657@mac.com> References: <407af86914b2d34d245f1bc5904bc508@mac.com> <44513372.1040806@h-lab.net> <0867c06f67f4c2c35d82b88e93ea1657@mac.com> Message-ID: <5e58f2e40604271914q335951b2l803aac8b066ebe1c@mail.gmail.com> On 28/04/06, kevin parks wrote: > In most case you are fine operating on the list in place and altering the > existing list. In some cases you want your code to stop molesting your poor > mutables and really honestly sincerly copy the dang thing. In this case i am > making a function that does odd smmetry mirroring. But i want my orginal list > to remain intact.... > > def mirror(seq): > """odd symmetry mirroring [1, 2, 3, 4] --> [1, 2, 3, 4, 3, 2, 1]""" > foo=seq[:-1] # copy list, excluding last element for odd symetry > foo.reverse() # flip it > seq.extend(foo) > return seq Hi Kevin, Your problem is this line: seq.extend(foo) This is the line that mutates your original list. There are a few ways you could procede here. One way is to make a copy of the argument, like this: def mirror(seq): start = list(seq) end = seq[:-1] end.reverse() start.extend(end) return start Notice that we've not calling any methods on seq, so seq won't be changed. The first line, "start = list(seq)", instructs python to build a new list out of the elements of seq. You could also write "start = seq[:]" here --- I'm not sure which is the preferred way. Another option is to use arithmetic --- you can add lists together, and this creates a new list. eg: def mirror(seq): end = seq[:-1] end.reverse() return seq + end Finally, just a side comment: You can use slicing to reverse the end for you as well. So, we could rewrite the last function as: def mirror(seq): end = seq[-2::-1] return seq + end Which means there is a one-line version as well: def mirror(seq): return seq + seq[-2::-1] HTH! -- John. From max.russell at barco.com Fri Apr 28 10:46:20 2006 From: max.russell at barco.com (Max Russell) Date: Fri, 28 Apr 2006 09:46:20 +0100 Subject: [Tutor] Setting a global variable on class initialisation Message-ID: Hello again Sorry I didn't make the problem I'm working with all too clear. Basically I'm working with a class (Directory) that upon creation reads in a 3 files and from these files populates one main list. This bit is fine. The trickier bit was that I need to use two of the sublists (e.g the contents of two of the files) outwith the module. I didn't want to read the lists in again as I wanted the data to be set at the time the Directory class is created. The lists are accessed from other classes and although I tried passing the instance of Directory into the new class (Item) but this was causing real problems Item was trying to read in the lists: def __init__(self, filename, **args): I noted that I couldn't put my argument for an instance of Directory after **args (presumably because **args is used to mop up the remaining arguments as a list) and when I put it before it messed up the reading of the list. So my code now has this format- def GetCategories(self): #Assign the list values read in via platformCategories and typeCategories global platformCategories platformCategories = self.GetPlatformsFile() global typeCategories typeCategories = self.GetTypesFile() The method above is within Directory and updates the two lists with the values I need. (The methods called within GetCategories do the returning of the lists.) I think I've got a grasp on what was going wrong. ta Max Russell Senior Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com max.russell at barco.com Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060428/d2cfd86a/attachment.htm From singletoned at gmail.com Fri Apr 28 12:06:08 2006 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 28 Apr 2006 11:06:08 +0100 Subject: [Tutor] how to *really* copy a list In-Reply-To: <5e58f2e40604271914q335951b2l803aac8b066ebe1c@mail.gmail.com> References: <407af86914b2d34d245f1bc5904bc508@mac.com> <44513372.1040806@h-lab.net> <0867c06f67f4c2c35d82b88e93ea1657@mac.com> <5e58f2e40604271914q335951b2l803aac8b066ebe1c@mail.gmail.com> Message-ID: <34bb7f5b0604280306w768bb42n5d16a8f469a6abec@mail.gmail.com> On 28/04/06, John Fouhy wrote: > On 28/04/06, kevin parks wrote: > > In most case you are fine operating on the list in place and altering the > > existing list. In some cases you want your code to stop molesting your poor > > mutables and really honestly sincerly copy the dang thing. In this case i am > > making a function that does odd smmetry mirroring. But i want my orginal list > > to remain intact.... > > > > def mirror(seq): > > """odd symmetry mirroring [1, 2, 3, 4] --> [1, 2, 3, 4, 3, 2, 1]""" > > foo=seq[:-1] # copy list, excluding last element for odd symetry > > foo.reverse() # flip it > > seq.extend(foo) > > return seq > > Hi Kevin, > > Your problem is this line: > seq.extend(foo) > > This is the line that mutates your original list. > > There are a few ways you could procede here. One way is to make a > copy of the argument, like this: > > def mirror(seq): > start = list(seq) > end = seq[:-1] > end.reverse() > start.extend(end) > return start > > Notice that we've not calling any methods on seq, so seq won't be > changed. The first line, "start = list(seq)", instructs python to > build a new list out of the elements of seq. You could also write > "start = seq[:]" here --- I'm not sure which is the preferred way. A little 'gotcha' with this is that if you have nested lists, these methods don't copy the nested lists, only the outer list (which makes sense, but can be surprising the first time you encounter it). If for some reason you want to copy nested lists, look into deepcopy(), otherwise you'll be fine. Also, personally I think list(seq) is better than seq[:] because it can cope with anything put into it that it could possibly work with (even dicts and iterators). >>> def i(): ... for n in range(3): ... yield n ... >>> list(i()) [0, 1, 2] >>> >>> d = {'a':1,'b':2} >>> list(d) ['a', 'b'] >>> i()[:] Traceback (most recent call last): File "", line 1, in ? TypeError: unsubscriptable object >>> d[:] Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type Ed From alan.gauld at freenet.co.uk Fri Apr 28 12:28:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 28 Apr 2006 11:28:55 +0100 Subject: [Tutor] Setting a global variable on class initialisation References: Message-ID: <002401c66aae$8dd750f0$0a01a8c0@xp> > Sorry I didn't make the problem I'm working with all too clear. Basically > I'm working with a class (Directory) that upon creation reads in a 3 files > and from these files populates one main list. > This bit is fine. > > The trickier bit was that I need to use two of the sublists (e.g the > contents of two of the files) outwith the module. If the lists are data within your Directory then any class that needs to use that data is treading in dubious water. Either that or the data shouldn't be in Directory! Are you sure that there isn't a service that Directory can perform on behalf of your new class? > class is created. The lists are accessed from other classes and although I > tried passing the instance of Directory into the new class (Item) but this > was causing real problems I don't understand why this would cause problems. Its certainly the normal approach to this kind of design scenario. > I noted that I couldn't put my argument for an instance of Directory after > **args (presumably because **args is used to mop up the remaining > arguments Correct, you would need to either treat directory as partrty of the **args stuff or pass it explicitly before them. > as a list) and when I put it before it messed up the reading of the list. And this I don't understand. > So my code now has this format- > > def GetCategories(self): > global platformCategories > platformCategories = self.GetPlatformsFile() > global typeCategories > typeCategories = self.GetTypesFile() > > The method above is within Directory and updates the two lists with the > values I need. (The methods called within GetCategories do the returning > of > the lists.) I'm afraid I don;t see anythoing here that should require a global, but I don't really undestand why passing a Directory instance around wasn't working. Can you explain that part of the problem a bit more? I guess I'd also be interested in why another class needs access to the data in Directory - what is it going to do to the data that Directory couldn't do for it? Alan G. From tinoloc at gmail.com Fri Apr 28 16:30:21 2006 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 28 Apr 2006 10:30:21 -0400 Subject: [Tutor] Python and Oracle In-Reply-To: <410-2200644271246234@earthlink.net> References: <410-2200644271246234@earthlink.net> Message-ID: On 4/27/06, Linda Kvam wrote: > > I have Oracle 10g and Python 2.4 on my PC. I just installed cx_Oracle and > then entered - import cx_Oracle -in PythonWin and got the following error > - > > >>> import cx_Oracle > Traceback (most recent call last): > File "", line 1, in ? > ImportError: DLL load failed: The specified procedure could not be found. > >>> > This is just a guess. You might need to run regsvr32 to tell WinXP where > it is. > > -Tino > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060428/ab142aae/attachment.htm From glingl at aon.at Fri Apr 28 18:44:01 2006 From: glingl at aon.at (Gregor Lingl) Date: Fri, 28 Apr 2006 18:44:01 +0200 Subject: [Tutor] question concerning deepcopy Message-ID: <44524651.9090008@aon.at> Hi all of you, I've some Vector class, which is a subclass of tuple and which is working satisfactorily since long in different contexts. Now I've constructed objects with attributes of Vec-type, which I wanted to deepcopy. But that doesn't work, because I can't (deep)copy Vec-s: >>> from copy import deepcopy >>> class Vec(tuple): def __new__(cls, x, y): return tuple.__new__(cls, (x,y)) def __abs__(self): return (self[0]**2+self[1]**2)**0.5 ## more methods ... >>> a=Vec(3,4) >>> abs(a) 5.0 >>> b = deepcopy(a) Traceback (most recent call last): File "", line 1, in -toplevel- b = deepcopy(a) File "C:\Python24\lib\copy.py", line 204, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\Python24\lib\copy.py", line 336, in _reconstruct y = callable(*args) File "C:\Python24\lib\copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: __new__() takes exactly 3 arguments (2 given) Explanation? Remedy? Bug? Workaround? Regards, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From kent37 at tds.net Fri Apr 28 19:44:18 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Apr 2006 13:44:18 -0400 Subject: [Tutor] question concerning deepcopy In-Reply-To: <44524651.9090008@aon.at> References: <44524651.9090008@aon.at> Message-ID: <44525472.5040004@tds.net> Gregor Lingl wrote: > Hi all of you, > > I've some Vector class, which is a subclass of tuple and which is > working satisfactorily since long in different contexts. Now I've > constructed objects with attributes of Vec-type, which I wanted to > deepcopy. But that doesn't work, because I can't (deep)copy Vec-s: > > >>> from copy import deepcopy > >>> class Vec(tuple): > def __new__(cls, x, y): > return tuple.__new__(cls, (x,y)) > def __abs__(self): > return (self[0]**2+self[1]**2)**0.5 > ## more methods ... > > > >>> a=Vec(3,4) > >>> abs(a) > 5.0 > >>> b = deepcopy(a) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > b = deepcopy(a) > File "C:\Python24\lib\copy.py", line 204, in deepcopy > y = _reconstruct(x, rv, 1, memo) > File "C:\Python24\lib\copy.py", line 336, in _reconstruct > y = callable(*args) > File "C:\Python24\lib\copy_reg.py", line 92, in __newobj__ > return cls.__new__(cls, *args) > TypeError: __new__() takes exactly 3 arguments (2 given) Apparently you need to define __getnewargs__() for your class. This works: def __getnewargs__(self): return (self[0], self[1]) __getnewargs__() is documented with the pickle module but it is used by deepcopy() as well. http://docs.python.org/lib/pickle-inst.html Kent From glingl at aon.at Sat Apr 29 11:04:31 2006 From: glingl at aon.at (Gregor Lingl) Date: Sat, 29 Apr 2006 11:04:31 +0200 Subject: [Tutor] question concerning deepcopy In-Reply-To: <44525472.5040004@tds.net> References: <44524651.9090008@aon.at> <44525472.5040004@tds.net> Message-ID: <44532C1F.5000401@aon.at> Kent Johnson schrieb: > Gregor Lingl wrote: > >>Hi all of you, ... >>> from copy import deepcopy >> >>> class Vec(tuple): >> def __new__(cls, x, y): >> return tuple.__new__(cls, (x,y)) >> def __abs__(self): >> return (self[0]**2+self[1]**2)**0.5 >> ## more methods ... >> >> >>> a=Vec(3,4) >> >>> abs(a) >>5.0 >> >>> b = deepcopy(a) >> >>Traceback (most recent call last): ... >>TypeError: __new__() takes exactly 3 arguments (2 given) > > > Apparently you need to define __getnewargs__() for your class. This works: > def __getnewargs__(self): > return (self[0], self[1]) > > __getnewargs__() is documented with the pickle module but it is used by > deepcopy() as well. > http://docs.python.org/lib/pickle-inst.html Thanks, Kent for the hint. It works (of course). Skimming through this part of the docs I discovered, that there is a special method __deepcopy__. So I also tried using this, adding def __deepcopy__(self,visit): return self to my Vec class, which also seems to work. (I think this not to be harmful as Vecs should be, like tuples, immutable). And, indeed, it also seems to work. Do you think this is also a correct way? If so, do you see there any advantages of one solution over the other one? Regards, Gregor From kent37 at tds.net Sat Apr 29 12:49:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Apr 2006 06:49:59 -0400 Subject: [Tutor] question concerning deepcopy In-Reply-To: <44532C1F.5000401@aon.at> References: <44524651.9090008@aon.at> <44525472.5040004@tds.net> <44532C1F.5000401@aon.at> Message-ID: <445344D7.6040404@tds.net> Gregor Lingl wrote: > Thanks, Kent for the hint. It works (of course). > Skimming through this part of the docs I discovered, that there is a > special method __deepcopy__. So I also tried using this, adding > > def __deepcopy__(self,visit): > return self > > to my Vec class, which also seems to work. (I think this not to > be harmful as Vecs should be, like tuples, immutable). > And, indeed, it also seems to work. That is not a correct deep copy, it is a shallow copy. Although Vec objects are immutable they may contain mutable objects. The point of deep copy is to copy "all the way down" so the objects contained by a Vec should also be copied. Kent From oztriking at hotmail.com Sat Apr 29 13:25:34 2006 From: oztriking at hotmail.com (John Connors) Date: Sat, 29 Apr 2006 21:25:34 +1000 Subject: [Tutor] How Big Is Too Big? Message-ID: G'day, Just wondering how many lines of code is the maximum to post in the list to have it critiqued. I realise people are using their own time to help others in here for no real personal gain and I would hate to impose on their goodwill. Would about 100 lines of code be considered too much? John _________________________________________________________________ New year, new job – there's more than 100,00 jobs at SEEK http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT From kent37 at tds.net Sat Apr 29 13:40:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Apr 2006 07:40:00 -0400 Subject: [Tutor] How Big Is Too Big? In-Reply-To: References: Message-ID: <44535090.2010801@tds.net> John Connors wrote: > G'day, > > Just wondering how many lines of code is the maximum to post in the list to > have it critiqued. I realise people are using their own time to help others > in here for no real personal gain and I would hate to impose on their > goodwill. Would about 100 lines of code be considered too much? Try it and see :-) For me I think the quality of review tends to go down as the quantity of code goes up. For short pieces I might look the whole thing over carefully. Longer ones I tend to skim or, sometimes, ignore the whole thing. It depends on my mood, time available, whether the code looks interesting... It also helps if you have a specific question to focus my attention. Kent From oztriking at hotmail.com Sat Apr 29 14:20:52 2006 From: oztriking at hotmail.com (John Connors) Date: Sat, 29 Apr 2006 22:20:52 +1000 Subject: [Tutor] Silly Dice Game Message-ID: G'day, The wife and I play a silly dice game and I thought it would be a good challange for me to write it as a program. No specific question, just wondering if my technique is ok and is there anything that could be done better. The 2 hardest things I find as a python beginner who has no real need to learn a programming language other than curiosity and too much spare time, are thinking of something to program and then knowing if what I have written could be done more efficiently. import random def removeDice(): for a in range(3): dieList.remove(checkThree) while True: dieLeft = 6 totalScore = 0 while dieLeft > 0: dieList = [] score = 0 # roll the dice if dieLeft == 6: raw_input("\nPress enter to roll the dice ") print for dieRoll in range(dieLeft): dieList.append(random.randint(1,6)) print "Die roll %d is %d" % (dieRoll +1, dieList[dieRoll]) dieList.sort() if dieLeft == 6: #check if all dice are the same for fatChance in range(1,7): if dieList.count(fatChance) == 6: score += 5000 dieLeft = 0 print "\nYou rolled all %d's, WoW!!!" % (fatChance) #check for a straight if dieList == [1,2,3,4,5,6]: score += 1500 dieLeft = 0 print "\nYou rolled a straight" #check for 3 pairs if dieLeft == 6: if dieList[0] == dieList[1] and dieList[2] == dieList[3] and dieList[4] == dieList[5]: score += 1500 dieLeft = 0 print"\nYou rolled three pairs" #check for 3 of a kind if dieLeft > 2: for checkThree in range(1,7): if dieList.count(checkThree) >= 3: print "\nYou rolled three %d's" % (checkThree) yourChoice = raw_input("\nDo you wish to keep them? y/n ") if yourChoice == 'y': dieLeft -= 3 if checkThree == 1: score += 1000 removeDice() else: score = score + checkThree * 100 removeDice() #check for 1's and 5's if 1 in dieList or 5 in dieList: for testDice in range(dieLeft): if dieList[testDice] == 1: score += 100 dieLeft -= 1 if dieList[testDice] == 5: score += 50 dieLeft -= 1 totalScore = totalScore + score if score != 0: print "\nYour score is %d and you have %d dice left" % (totalScore, dieLeft) if score == 0: print "\nYou busted and score nothing" totalScore = 0 break if dieLeft >= 1: rollAgain = raw_input ("\nRoll the remaining dice? y/n ") if rollAgain != "y": break if dieLeft == 0: dieLeft = 6 print "\nYou used all the dice and must roll again" print "\n\nYour total score for that round was %d" % (totalScore) playAgain = raw_input("\nPlay again? (y/n) ") print if playAgain != "y": break John _________________________________________________________________ realestate.com.au: the biggest address in property http://ninemsn.realestate.com.au From john at fouhy.net Sat Apr 29 14:40:25 2006 From: john at fouhy.net (John Fouhy) Date: Sun, 30 Apr 2006 00:40:25 +1200 Subject: [Tutor] Silly Dice Game In-Reply-To: References: Message-ID: <5e58f2e40604290540u62ba7269j4b981f9ed5f77371@mail.gmail.com> On 30/04/06, John Connors wrote: > The wife and I play a silly dice game and I thought it would be a good > challange for me to write it as a program. No specific question, just > wondering if my technique is ok and is there anything that could be done > better. The 2 hardest things I find as a python beginner who has no real > need to learn a programming language other than curiosity and too much spare > time, are thinking of something to program and then knowing if what I have > written could be done more efficiently. Hi John, If I were you, I would look at separating more of my program out into functions. Good use of functions will make your program more readable, easier to debug, and easier to change, should the rules of your dice game change :-) So, your basic game structure is (correct me if I'm wrong): while True: roll some dice check if we've won anything The "check if we've won anything" section seems like an excellent place to start writing functions. For example, you have: #check if all dice are the same for fatChance in range(1,7): if dieList.count(fatChance) == 6: score += 5000 dieLeft = 0 print "\nYou rolled all %d's, WoW!!!" % (fatChance) #check for a straight if dieList == [1,2,3,4,5,6]: score += 1500 dieLeft = 0 print "\nYou rolled a straight" #check for 3 pairs if dieLeft == 6: if dieList[0] == dieList[1] and dieList[2] == dieList[3] and dieList[4] == dieList[5]: score += 1500 dieLeft = 0 print"\nYou rolled three pairs" We could change this as follows: def checkSame(dieList): """ Check if all the dice are the same. """ return len(set(dieList)) == 1 def checkStraight(dieList): """ Check if the die list is a straight. """ return set(dieList) == set(range(1, 7)) def checkThreePairs(dieList): """ Check if the die list comprises three pairs. """ dieList = sorted(dieList) return dieList[0] == dieList[1] and dieList[2] == dieList[3] and dieList[4] == dieList[5] These functions would go at the top of your code somewhere. Then, we can change your if statement to something like this: if checkSame(dieList): score += 5000 dieLeft = 0 print "\nYou rolled all %d's, WoW!!!" % dieList[0] elif checkStraight(dieList): score += 1500 dieLeft = 0 print 'You rolled a straight.' elif checkThreePairs(dieList): score += 1500 dieLeft = 0 print 'You rolled three pairs.' Now, we could go even furthere here, by observing that a lot of this is still the same. So, maybe we could build a little data structure: tests = [(checkSame, 5000, 'You rolled all the same!'), (checkStraight, 1500, 'You rolled a straight.'), (checkThreePairs, 1500, 'You rolled three pairs.')] for test, points, message in tests: if test(dieList): score += points dieLeft = 0 print message break Do you understand what is going on there? -- John. From oztriking at hotmail.com Sat Apr 29 15:13:23 2006 From: oztriking at hotmail.com (John Connors) Date: Sat, 29 Apr 2006 23:13:23 +1000 Subject: [Tutor] Silly Dice Game In-Reply-To: <5e58f2e40604290540u62ba7269j4b981f9ed5f77371@mail.gmail.com> Message-ID: G'day John, >If I were you, I would look at separating more of my program out into >functions. Good use of functions will make your program more >readable, easier to debug, and easier to change, should the rules of >your dice game change :-) Yes, the rules change on a regular basis, usually by the wife when I start to win :) >Do you understand what is going on there? Some of the commands are new to me but I think I understand what's going on. I was assuming that functions were only really useful if they were used more than once but I see what you mean about them making a program easier to read and debug. Thanks. John _________________________________________________________________ 1000s of Sexy Singles online now at Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D22031&_t=751140432&_m=EXT From alan.gauld at btinternet.com Sat Apr 29 17:49:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Apr 2006 16:49:51 +0100 Subject: [Tutor] How Big Is Too Big? References: Message-ID: > Just wondering how many lines of code is the maximum > to post in the list to have it critiqued. > Would about 100 lines of code be considered too much? 100 lines is probably about the top end just on the basis of how long it takes to read and comment on. As Kent says the longer the code the less likely it is to be read thoroughly. However, If you have a longer program you can put it on a web site and post a URL and some keen folks might go and read their way through it, but in that case I'd suggest askling for direct comments rather than via the list. NB. These are all my personal thoughts and do not in any way reflect official list policy! BUT it probably should be a question in the FAQ...Ed/Mike? Alan G. From alan.gauld at btinternet.com Sat Apr 29 17:53:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Apr 2006 16:53:53 +0100 Subject: [Tutor] Silly Dice Game References: Message-ID: "John Connors" wrote in message news:BAY108-F291303747F6C650D85C8CABEB30 at phx.gbl... > ... thinking of something to program and then knowing if what I have > written could be done more efficiently. The first one is hardest to ansdwer, but anything repetitive that you do on a regular basis should be a candidate. And as to efficiency, if it works and its fast enough don't get too hung up on it. Pero's have to worry about squeezing speed out because its a selling point againstbthe competition, but for an amateur "fast enough" is good enough IMHO. Alan g. From glingl at aon.at Sat Apr 29 21:15:56 2006 From: glingl at aon.at (Gregor Lingl) Date: Sat, 29 Apr 2006 21:15:56 +0200 Subject: [Tutor] question concerning deepcopy Message-ID: <4453BB6C.3080907@aon.at> Kent Johnson schrieb: > Gregor Lingl wrote: > >>Thanks, Kent for the hint. It works (of course). >>Skimming through this part of the docs I discovered, that there is a >>special method __deepcopy__. So I also tried using this, adding >> >> def __deepcopy__(self,visit): >> return self >> >>to my Vec class, which also seems to work. (I think this not to >>be harmful as Vecs should be, like tuples, immutable). >>And, indeed, it also seems to work. > > > That is not a correct deep copy, it is a shallow copy. Although Vec > objects are immutable they may contain mutable objects. The point of > deep copy is to copy "all the way down" so the objects contained by a > Vec should also be copied. O.k. I understand. It's just that my Vec class invariably has two numbers as elements (otherwise the abs-method wouldn't make sense. That's what I meant with 'Vecs are immutable'). So in my case it works, but would have to be considered bad style? Thanks, again Gregor > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From ml.cyresse at gmail.com Sat Apr 29 22:58:38 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 30 Apr 2006 08:58:38 +1200 Subject: [Tutor] How Big Is Too Big? In-Reply-To: References: Message-ID: Hi John, For longer programmes, if posting here, I recommend using something like www.rafb.net/paste; having syntax highlighted (and not butchered by webmail!) is a great help. Regards, Liam Clarke On 4/29/06, John Connors wrote: > G'day, > > Just wondering how many lines of code is the maximum to post in the list to > have it critiqued. I realise people are using their own time to help others > in here for no real personal gain and I would hate to impose on their > goodwill. Would about 100 lines of code be considered too much? > > John > > _________________________________________________________________ > New year, new job ? there's more than 100,00 jobs at SEEK > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eseek%2Ecom%2Eau&_t=752315885&_r=Jan05_tagline&_m=EXT > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kp8 at mac.com Sun Apr 30 00:51:51 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 29 Apr 2006 18:51:51 -0400 Subject: [Tutor] cycle w/ shuffle In-Reply-To: References: Message-ID: <733e352f3ac5a99f2643509ab4b600d9@mac.com> Thanks Kent. That is what i did the first time around but it didn't work ... but that was do to something else that was not working in the script.... hehe.... of course, this just shuffles the saved copy of the list which is egg-zactly what i needed "duh" ... sorry... gosh... -kevin-- On Apr 27, 2006, at 6:00 AM, tutor-request at python.org wrote: > kevin parks wrote: >> it seems to me that i need something like itertools cycle, except that >> i need to keep track of when i have exhausted my list and then call >> random.shuffle() on my sequence. >> >> def cycle(iterable): >> saved = [] >> for element in iterable: >> yield element >> saved.append(element) >> while saved: > random.shuffle(saved) ############### >> for element in saved: >> yield element > > Kent From kp8 at mac.com Sun Apr 30 00:55:08 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 29 Apr 2006 18:55:08 -0400 Subject: [Tutor] how to *really* copy a list In-Reply-To: References: Message-ID: <05103692f82287c49c4da73215b2497e@mac.com> John, Thanks. Your message was very helpful. I will tattoo it to my forehead. hehe... i notice that the "learning python" book also explains so of this and i shall study that as well.... cheers, kevin On Apr 27, 2006, at 10:14 PM, tutor-request at python.org wrote: > > On 28/04/06, kevin parks wrote: >> In most case you are fine operating on the list in place and altering >> the >> existing list. In some cases you want your code to stop molesting >> your poor >> mutables and really honestly sincerly copy the dang thing. In this >> case i am >> making a function that does odd smmetry mirroring. But i want my >> orginal list >> to remain intact.... >> >> def mirror(seq): >> """odd symmetry mirroring [1, 2, 3, 4] --> [1, 2, 3, 4, 3, >> 2, 1]""" >> foo=seq[:-1] # copy list, >> excluding last element for odd symetry >> foo.reverse() # flip it >> seq.extend(foo) >> return seq > > Hi Kevin, > > Your problem is this line: > seq.extend(foo) From kp8 at mac.com Sun Apr 30 01:01:42 2006 From: kp8 at mac.com (kevin parks) Date: Sat, 29 Apr 2006 19:01:42 -0400 Subject: [Tutor] how to *really* copy a list In-Reply-To: References: Message-ID: <085e0e6dff8c7f446c2406e1cc4194ef@mac.com> Ed, I should have realized that the nesting would create the problem, but i didn't have that in mind... i always thought that the difference between extend and append was that extend did not yield a nested list. I really need to revisit this issue and get it right in my mind. It is a 'gotcha' that i remember reading about often but, now that it has bit me a few times hehe .... so much to know... -kevin-- On Apr 29, 2006, at 6:00 AM, tutor-request at python.org wrote: >> >> Hi Kevin, >> >> Your problem is this line: >> seq.extend(foo) >> >> This is the line that mutates your original list. >> >> There are a few ways you could procede here. One way is to make a >> copy of the argument, like this: >> >> def mirror(seq): >> start = list(seq) >> end = seq[:-1] >> end.reverse() >> start.extend(end) >> return start >> >> Notice that we've not calling any methods on seq, so seq won't be >> changed. The first line, "start = list(seq)", instructs python to >> build a new list out of the elements of seq. You could also write >> "start = seq[:]" here --- I'm not sure which is the preferred way. > > A little 'gotcha' with this is that if you have nested lists, these > methods don't copy the nested lists, only the outer list (which makes > sense, but can be surprising the first time you encounter it). If for > some reason you want to copy nested lists, look into deepcopy(), > otherwise you'll be fine. From gnulinuxgeek at rochester.rr.com Sun Apr 30 03:23:12 2006 From: gnulinuxgeek at rochester.rr.com (GNULinuxGeek) Date: Sat, 29 Apr 2006 21:23:12 -0400 Subject: [Tutor] Strange Question Message-ID: <44541180.50408@rochester.rr.com> All, First, I think this is a wonderful list. I always see great advice and great attitudes about helping. My post is not about evaluating code but instead trying to get a reasonable judgment as to whether or not python is the best choice for what I am trying to do. I have not learned Python yet. In point of fact, I have not, as yet learned any programming language much to my dismay. I post the process I need below. So, here goes the work flow I need to support on my job. 1. Person goes to a web page. 2. The page allows them to retrieve a file from their local hard drive. 3. They make one or two selections with check boxes or drop lists that define things about image resolution and preferences. 4. They enter their E-Mail address to allow the resultant file to be sent back to them. 5. They submit the graphics file (TIFF image) along with the selections and the file is uploaded. 6. The code on the server drops the file in a directory created from the submitted file name. 7. The Python code (cgi script?) calls another application (server resident) that performs processing on the graphics file. 8. The original file, a processed "proof" file and a raw bitmap file are stored back in the created directory. 9. The resultant proof file is sent back to them in an E-Mail message for their approval. 10. The person would then go back to another page and "OK" the file and then the processed image would be sent to yet another E-Mail address. Does anyone see a problem with Python doing this? Also, from my knowledge position in programming and in Python (zero), should I attempt this? Thanks, Best Regards, and keep up the great work, Ralph -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060429/8028b7b7/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Apr 30 08:31:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 29 Apr 2006 23:31:29 -0700 (PDT) Subject: [Tutor] Strange Question In-Reply-To: <44541180.50408@rochester.rr.com> References: <44541180.50408@rochester.rr.com> Message-ID: > First, I think this is a wonderful list. I always see great advice and > great attitudes about helping. > > My post is not about evaluating code but instead trying to get a > reasonable judgment as to whether or not python is the best choice for > what I am trying to do. I have not learned Python yet. In point of > fact, I have not, as yet learned any programming language much to my > dismay. > > I post the process I need below. > > So, here goes the work flow I need to support on my job. [problem cut] > Does anyone see a problem with Python doing this? Hi Ralph, This should be perfectly doable in Python. The majority of the popular web frameworks out there aren't exactly designed for newcomers, so you'll want to learn a bit of Python before tackling this. But I think all of the subproblems here sound perfectly doable. For example, one of the subproblems here: 7. The Python code (cgi script?) calls another application (server resident) that performs processing on the graphics file. may be a combination of the 'subprocess' python module to drive the external application: http://www.python.org/doc/lib/module-subprocess.html Just as counterpoint: actually, any good language and envrionment should probably do the trick. Python is appropriate, but so are other languages and frameworks. (Caveat: I do have my doubts about Java + J2EE because that environment seems too focused on low-level details...) I've heard good things about Ruby and its "Ruby On Rails" web framework, so if you have the time, you may want to look at that too. So if you do take a look at another language, and decide it fits you better, that's perfectly fine, and we won't ostracise you. *grin* The particular kind of control flow you're describing --- a multistage web application --- is actually not too fun to do from scratch. Thankfully, other people have worked on this problem, so you'll want to stand on their shoulders. For example, I've heard very good things about Turbogears and Django for web development: http://www.turbogears.org/ http://www.djangoproject.com/ I have to admit that I have not used either of them yet, but if I starting another web project in Python, those will be the frameworks I'd seriously look at. Good luck to you! From ml.cyresse at gmail.com Sun Apr 30 11:48:59 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 30 Apr 2006 21:48:59 +1200 Subject: [Tutor] Strange Question In-Reply-To: References: <44541180.50408@rochester.rr.com> Message-ID: Hi, It's certainly doable in Python; but as Danny said, you'll want a handle on Python before you launch into web frameworks. However, Python's a pretty easy language to pick up and run with.Just make sure you use a Python aware editor. Going by your email address, I found Vim to be pretty good with Python, once I figured out how to do folding. So much so, that I downloaded gVim for my windows box. If you're an Emacs guru, then I'm sure you'll be fine. :-) With regard to #7 - 7. The Python code (cgi script?) calls another application (server resident) that performs processing on the graphics file. You could actually do this within your Python code if you wanted, with the Python Imaging Library - http://www.pythonware.com/products/pil/ You may already have a suitable external app in mind, but I thought I'd mention it just in case. With regards to Python web frameworks, Django and Turbogears are the two front-runners, as Danny mentioned. Django is the more mature of the two, but Turbogears is pretty good as well, both have helpful Google Groups/mailing lists. I'm not hugely experienced in Python, but I managed to get up and running okay with both. It's easier to get Django working with Apache than Turbogears. Turbogears uses the Kid templating language, but can also use other templating languages like Cheetah. Turbogears is 4 separate packages combined, Cherrypy, SQLObject, Kid and Mochikit. Beyond that, I'm not too sure. I'm playing with Django at the moment, Turbogears 0.9 is still in alpha, last time I checked, which means a bit of tweaking of conf files to get working with mod_python, if you're familiar with Apache at all, and as I'm a Windows monkey, I find it a bit daunting, so hence Django, as it plays nicely. :) Good luck and I look forward to questions to this list. :) Regards, Liam Clarke On 4/30/06, Danny Yoo wrote: > > > > First, I think this is a wonderful list. I always see great advice and > > great attitudes about helping. > > > > My post is not about evaluating code but instead trying to get a > > reasonable judgment as to whether or not python is the best choice for > > what I am trying to do. I have not learned Python yet. In point of > > fact, I have not, as yet learned any programming language much to my > > dismay. > > > > I post the process I need below. > > > > So, here goes the work flow I need to support on my job. > > [problem cut] > > > Does anyone see a problem with Python doing this? > > Hi Ralph, > > This should be perfectly doable in Python. The majority of the popular > web frameworks out there aren't exactly designed for newcomers, so you'll > want to learn a bit of Python before tackling this. > > But I think all of the subproblems here sound perfectly doable. For > example, one of the subproblems here: > > 7. The Python code (cgi script?) calls another application (server > resident) that performs processing on the graphics file. > > may be a combination of the 'subprocess' python module to drive the > external application: > > http://www.python.org/doc/lib/module-subprocess.html > > > Just as counterpoint: actually, any good language and envrionment should > probably do the trick. Python is appropriate, but so are other languages > and frameworks. (Caveat: I do have my doubts about Java + J2EE because > that environment seems too focused on low-level details...) > > I've heard good things about Ruby and its "Ruby On Rails" web framework, > so if you have the time, you may want to look at that too. So if you do > take a look at another language, and decide it fits you better, that's > perfectly fine, and we won't ostracise you. *grin* > > The particular kind of control flow you're describing --- a multistage web > application --- is actually not too fun to do from scratch. Thankfully, > other people have worked on this problem, so you'll want to stand on their > shoulders. For example, I've heard very good things about Turbogears and > Django for web development: > > http://www.turbogears.org/ > > http://www.djangoproject.com/ > > I have to admit that I have not used either of them yet, but if I starting > another web project in Python, those will be the frameworks I'd seriously > look at. > > > Good luck to you! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Apr 30 14:07:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Apr 2006 08:07:59 -0400 Subject: [Tutor] Strange Question In-Reply-To: <44541180.50408@rochester.rr.com> References: <44541180.50408@rochester.rr.com> Message-ID: <4454A89F.9060900@tds.net> GNULinuxGeek wrote: > So, here goes the work flow I need to support on my job. > > 1. Person goes to a web page. > 2. The page allows them to retrieve a file from their local hard drive. > 3. They make one or two selections with check boxes or drop lists > that define things about image resolution and preferences. > 4. They enter their E-Mail address to allow the resultant file to be > sent back to them. > 5. They submit the graphics file (TIFF image) along with the > selections and the file is uploaded. > 6. The code on the server drops the file in a directory created from > the submitted file name. > 7. The Python code (cgi script?) calls another application (server > resident) that performs processing on the graphics file. > 8. The original file, a processed "proof" file and a raw bitmap file > are stored back in the created directory. > 9. The resultant proof file is sent back to them in an E-Mail message > for their approval. > 10. The person would then go back to another page and "OK" the file > and then the processed image would be sent to yet another E-Mail > address. > > Does anyone see a problem with Python doing this? Also, from my > knowledge position in programming and in Python (zero), should I attempt > this? Python can certainly do all of this. You should learn some basic Python programming from one of the beginner tutorials before you start on the web piece. Then start tackling each of the steps above. Python has a bewildering array of web application frameworks. At the risk of adding to the confusion I will say I think Django and TurboGears might be overkill for this application. What you have described above could be implemented in a couple of cgi programs or a simpler framework like CherryPy or Karrigell. Kent From alan.gauld at freenet.co.uk Sun Apr 30 16:28:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 30 Apr 2006 15:28:45 +0100 Subject: [Tutor] Strange Question References: <44541180.50408@rochester.rr.com> Message-ID: <009101c66c62$63557ea0$0c01a8c0@XPpro> > I have not, as yet learned any programming language much to my dismay. In that case python is a good starting point since it is easier to learn than most other languages. 1.. Person goes to a web page. 2.. The page allows them to retrieve a file from their local hard drive. 3.. They make one or two selections with check boxes or drop lists that define things about image resolution and preferences. 4.. They enter their E-Mail address to allow the resultant file to be sent back to them. 5.. They submit the graphics file (TIFF image) along with the selections and the file is uploaded. Up to thid point there is no Python involved its all pure HTML. 1.. The code on the server drops the file in a directory created from the submitted file name. 2.. The Python code (cgi script?) calls another application (server resident) that performs processing on the graphics file. 3.. The original file, a processed "proof" file and a raw bitmap file are stored back in the created directory. > The resultant proof file is sent back to them in an E-Mail message for their approval. This is all possible in Python through the use of some modules, cgi and PIL primarily. 1.. The person would then go back to another page and "OK" the file and then the processed image would be sent to yet another E-Mail address. Does anyone see a problem with Python doing this? Python should be absolutely fine for this job. Also, from my knowledge position in programming and in Python (zero), should I attempt this? It actually sounds like a very reasonable first project. You can build it in bits and start simple and add complexity as you go. The only word of caution is: take time tom walk before you run. In learning to program (in any language) you need to take time to learn the basics - like learning scales on a musical instrument. If you allow a few days (if working full-time - say 2 or 3 hours a day) or a few weeks (if its a "fit it in" job) before you start on the application itself. If you jump in too deep too soon you will only get frustrated and write an awful lot of clunky code. OTOH don't wait to become an expert - you'll wait forever! :-) And this list is good for helping these kinds of projects evolve. PS If the formatting of my mail is screwed up for a few days its coz I've just bought a new PC and I'm still 'breaking it in' (Intel Dual Core 3GHz, 2G RAM, 200GB HD, XP Pro for those who care or are curious...) HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060430/f77e2303/attachment.htm From alan.gauld at freenet.co.uk Sun Apr 30 16:41:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 30 Apr 2006 15:41:03 +0100 Subject: [Tutor] Strange Question References: <44541180.50408@rochester.rr.com> Message-ID: <009501c66c64$1b72de00$0c01a8c0@XPpro> > and frameworks. (Caveat: I do have my doubts about Java + J2EE > because that environment seems too focused on low-level details...) I hate Java as a language but I've been getting more involved with it as a Web tool and JSP/Struts is actually quite a powerful web development environment. Certainly Java could handle this task, but I'd never recommend it for a beginner as a first project. Whereas with Python (or Ruby) its fine. > The particular kind of control flow you're describing --- a > multistage web application --- is actually not too fun to do from > scratch. Personally I probably would build this directly using simple CGI. There are very few web pages and actions I personally think a vanilla CGI app is easier than one of the richer frameworks. > shoulders. For example, I've heard very good things about > Turbogears and Django for web development: These are great if you are building more complex web environments and want re-use, consistency of processing etc. And if the OP thinks he may be building a whole suite of these type appliications then they would be worth investigating. But if it's always going to be a simple uopload, process, email, site then CGI will be prettty easy. And when its the first time you do something its always 'fun'...its when you do it the second and third time that the fun wears off. Finally I think everyone should buiold at least one vanilla CGI app just so they understand what is really going on under all those framework classes etc... > http://www.turbogears.org/ > I have to admit that I have not used either of them yet, but if I > starting I'ver been playing with TurboGears - and an interesting contrast to the Java/Struts stuff! I'd definitely use TurboGears for any personal web server stuff, provided I could find a web server/ISP which could run it! But for large scale stuff I'd stick to struts. Possible using Jython instead of Java - but I haven't tried that yet... Alan g. From daniel at thewatkins.org.uk Sun Apr 30 17:34:57 2006 From: daniel at thewatkins.org.uk (Daniel Watkins) Date: Sun, 30 Apr 2006 16:34:57 +0100 Subject: [Tutor] Splitting strings into blocks Message-ID: <200604301635.09227.daniel@thewatkins.org.uk> Hi list, I'm currently working on a program to parse LaTeX style maths expressions and provide an answer. For example, I have the expression "2^\frac{1}{2}". I'm trying to work out a way to split this into it's most basic blocks of LaTeX (i.e. 2^ and \frac{1}{2}) while maintaining a record of the depth of the expression (i.e. (2^,0),(\frac{1}{2},1)). I will then process this list from the highest order downwards, feeding the deeper results progressively into shallower elements until all have been calculated. LaTeX allows me to legally express the previously stated expression as "{2^{\\frac{1}{2}}}". This makes it much easier to figure out where the units of LaTeX are located. The depth of any item can now be expressed as the number of unpaired opening or closing braces between the element and the start or end of the expression. I'm essentially looking for a way to split the string up along the braces, while recording the number of braces between the split and either end of the expression. Any help would be much appreciated. Cheers, Dan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 191 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060430/99b2962a/attachment.pgp