From alan.gauld@blueyonder.co.uk  Fri Aug  1 04:09:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  1 03:09:02 2003
Subject: [Tutor] Recursion help
References: <3F298E37.8070600@unixremedies.com> <2920.192.207.104.212.1059690117.squirrel@mail.harlekin-maus.com>
Message-ID: <005a01c357fb$d1ea8000$6401a8c0@xp>

> 
> You can look at it this way:
> printList((1,2,3))
>    prints (1,2,3)[0] which is 1
>    runs printList((1,2,3)[1:]) = printList((2,3))
>    now we're in printList((2,3))
>       prints (2,3)[0] which is 2
>       runs printList((2,3)[1:]) and so on ...
 

Thats a pretty good explanation Zak, mind if I steal it and 
add it to the tutor?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@blueyonder.co.uk  Fri Aug  1 04:40:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  1 03:40:01 2003
Subject: [Tutor] Recursion help
References: <3F298E37.8070600@unixremedies.com> <2920.192.207.104.212.1059690117.squirrel@mail.harlekin-maus.com>
Message-ID: <006101c35800$06f57620$6401a8c0@xp>

> You can look at it this way:
> printList((1,2,3))
>    prints (1,2,3)[0] which is 1
>    runs printList((1,2,3)[1:]) = printList((2,3))
>    now we're in printList((2,3))
>       prints (2,3)[0] which is 2
>       runs printList((2,3)[1:]) and so on ...

I modified it slightly and expanded it to completely describe the
function. I also added a brief explanation about using slicing 
[1:] to get the end of the list.

See what you think here:

http://www.freenetpages.co.uk/hp/alan.gauld/tutrecur.htm

HTH,

Alan G
without Guido's time machine...


From glingl@aon.at  Fri Aug  1 04:58:01 2003
From: glingl@aon.at (Gregor Lingl)
Date: Fri Aug  1 03:58:01 2003
Subject: [Tutor] Recursion help
References: <3F298E37.8070600@unixremedies.com>
Message-ID: <3F2A1DE8.5000501@aon.at>

Justin Heath schrieb:

> I am working thru some of the examples in the "Learning to Program" 
> tutorial. I am going thru the recusrion section and have gotten stumped. 

Hi Justin,
one of the keypoints to understand recursion is understanding function
calls. Let's consider a very simple NONrecursive example:

 >>> def printitem(item):
    print item
  
 >>> def myfun():
    printitem("Hello world!")
    printitem("Wow!")
  
 >>> myfun()
Hello world!
Wow!
 >>>

Here we have defined two functions. The second one, myfun calls
the first one, printitem, twice, with different arguments.

You can make this visible, by inserting print statements, which give you 
information
about entering and exiting the execution af a function:

 >>> def printitem(item):
    print "printitem(", item, ") entered."
    print item
    print "prititem(", item, ") exited."

   
 >>> printitem("Hi!")
printitem( Hi! ) entered.
Hi!
prititem( Hi! ) exited.
 >>> def myfun():
    print "Myfun entered."
    printitem("Hello world!")
    printitem("Wow!")
    print "Myfun exited."

   
 >>> myfun()
Myfun entered.
printitem( Hello world! ) entered.
Hello world!
prititem( Hello world! ) exited.
printitem( Wow! ) entered.
Wow!
prititem( Wow! ) exited.
Myfun exited.
 >>>

Observe, that here you have the original output, but additionally
some "meta"-output, giving information about what's gong on

Now, what concerns recursion, the difference is mainly that
we have a function calling not another one but itself, with new arguments.

But you can make visible what's going on in the same way, by inserting
those print-statements for tracing execution: (Please continue reading below
your code-snippet)

> Here is the code I have run below:
>
> def printList(L):
>    # if its empty do nothing
>    if not L: return
>    # if its a list call printList on 1st element
>    if type(L[0]) == type([]):
>        printList(L[0])
>    else: #no list so just print        print L[0]    # now process the 
> rest of L    printList(L[1:])
>
> myList=[1,2,3,4,5]
>
> printList(myList)
>
> The output is as follows:
> 1
> 2
> 3
> 4
> 5

Now we change your function, observing that there are two points
where the functino may be exited:

 >>> def printList(L):
    print "printList(", L, ") entered."
    # if its empty do nothing
    if not L:
                print "printList(", L, ") exited."
        return
    # if its a list call printList on 1st element
    if type(L[0]) == type([]):
        printList(L[0])
    else: #no list so just print
        print L[0]
    # now process the rest of L
    printList(L[1:])
    print "printList(", L, ") exited."
  
 >>> printList([1,2,3,4,5])
printList( [1, 2, 3, 4, 5] ) entered.
1
printList( [2, 3, 4, 5] ) entered.
2
printList( [3, 4, 5] ) entered.
3
printList( [4, 5] ) entered.
4
printList( [5] ) entered.
5
printList( [] ) entered.
printList( [] ) exited.
printList( [5] ) exited.
printList( [4, 5] ) exited.
printList( [3, 4, 5] ) exited.
printList( [2, 3, 4, 5] ) exited.
printList( [1, 2, 3, 4, 5] ) exited.

We can amend this, by using a variable calldepth, which
we increment with every new call of printList and which we
use to indent our meta-information by preceding our
output string with "   "*calldepth:

 >>> def printList(L, calldepth):
    print "   "*calldepth + "printList(", L, ") entered."
    # if its empty do nothing
    if not L:
                print "   "*calldepth + "printList(", L, ") exited."
        return
    # if its a list call printList on 1st element
    if type(L[0]) == type([]):
        printList(L[0], calldepth+1)
    else: #no list so just print
        print L[0]
    # now process the rest of L
    printList(L[1:], calldepth+1)
    print "   "*calldepth + "printList(", L, ") exited."

   
 >>> printList([1,2,3,4,5], 1)
   printList( [1, 2, 3, 4, 5] ) entered.
1
      printList( [2, 3, 4, 5] ) entered.
2
         printList( [3, 4, 5] ) entered.
3
            printList( [4, 5] ) entered.
4
               printList( [5] ) entered.
5
                  printList( [] ) entered.
                  printList( [] ) exited.
               printList( [5] ) exited.
            printList( [4, 5] ) exited.
         printList( [3, 4, 5] ) exited.
      printList( [2, 3, 4, 5] ) exited.
   printList( [1, 2, 3, 4, 5] ) exited.
 >>>

So you see, that each active instance of printList retains it's own
value of  L, as L is a local variable to the function printList

Now you may wonder and try to understand how this comes:

 >>> printList([1,[2,3,4],5], 1)
   printList( [1, [2, 3, 4], 5] ) entered.
1
      printList( [[2, 3, 4], 5] ) entered.
         printList( [2, 3, 4] ) entered.
2
            printList( [3, 4] ) entered.
3
               printList( [4] ) entered.
4
                  printList( [] ) entered.
                  printList( [] ) exited.
               printList( [4] ) exited.
            printList( [3, 4] ) exited.
         printList( [2, 3, 4] ) exited.
         printList( [5] ) entered.
5
            printList( [] ) entered.
            printList( [] ) exited.
         printList( [5] ) exited.
      printList( [[2, 3, 4], 5] ) exited.
   printList( [1, [2, 3, 4], 5] ) exited.
 >>>

Enough stuff to digest for now, I think. To that end play with it.
Regards,
Gregor





From klappnase@freenet.de  Fri Aug  1 05:12:02 2003
From: klappnase@freenet.de (klappnase)
Date: Fri Aug  1 04:12:02 2003
Subject: [Tutor] How to get messages from stderr
In-Reply-To: <3F294C59.5070803@ccvcorp.com>
References: <20030731021253.404a731a.klappnase@freenet.de>
 <Pine.A41.4.32.0307310346390.33464-100000@faust27-eth.rz.uni-frankfurt.de>
 <20030731111411.2285a507.klappnase@freenet.de>
 <3F294C59.5070803@ccvcorp.com>
Message-ID: <20030801101124.46a43180.klappnase@freenet.de>

On Thu, 31 Jul 2003 10:05:29 -0700
"Jeff Shannon" <jeff@ccvcorp.com> wrote:

> I believe that your problem may be with using read(), with no arguments. 
>  By default, read() will return everything up to end-of-file.  For a 
> pipe, EOF doesn't occur until the pipe is closed.  Therefore, 
> self.ppp.read() will block until the pipe is closed, i.e. the command 
> stops running.
> 
> Try calling read() with an argument multiple times, and assembling the 
> results yourself.  In one of my own programs, I needed to supply input 
> to an external command, and determined that that command would output 
> exactly 18 bytes of data before waiting for input, so I used this code:
> 
>     def _runcommand(self, command):
>         print command
>         i, o = os.popen4(command)
>         print o.read(18)
>         i.write(self.paramstring)
>         i.write('\n')
>         i.flush()
>         result = o.readlines()
>         return result
> 
> I couldn't just use read() or readlines(), because those calls would 
> hang waiting for EOF or EOL respectively, neither of which would happen 
> at the point I was interested in.
> 
Thanks for that hint!
Now I do get the messages from stderr, but somehow the child process gets extremely slowed down.
These are the functions I use.
What have I done wrong here?


	def normalize(self, ev):
		'''Starts "normalize -m" on all selected files.'''
		if self.tracklist.listbox.size() == 0:
			tkMessageBox.showerror(message=nofilesmsg)
		elif self.tracklist.listbox.size() == 1:
			tkMessageBox.showerror(message=normfailmsg)
		else:
			shallwenormalize = tkMessageBox.askokcancel(message=shallwenormalizemsg, title='phononormalizer')
			if shallwenormalize:
			        filelist = ''
				selectedfiles = self.tracklist.listbox.get(0, END)
				for i in range(len(selectedfiles)):
					filelist = filelist + ' ' + selectedfiles[i]
			        normalizecmd = 'normalize -m ' + filelist
				self.pp = popen2.Popen4(normalizecmd)
				print 'Phononormalizer: Starting process "normalize" at PID ' + str(self.pp.pid)
				self.ppp = self.pp.fromchild
				self.frame.after(1000, self.getmsg)


	def getmsg(self):
		if self.pp.poll() == -1:
			bb = self.ppp.read(100)
			print bb
            		self.frame.after(1000, self.getmsg)
		else:
			print 'Phonormalizer: finished'

With getmsg() I want to capture normalize's  output for a window with a progress meter, but with this function normalizing a few
small test files which normally takes about 2 or 3 seconds takes more than a minute.

Thanks for your patience with silly newbies like me

Michael


From Jan.Wilhelmsen@bilia.no  Fri Aug  1 05:26:02 2003
From: Jan.Wilhelmsen@bilia.no (Wilhelmsen Jan)
Date: Fri Aug  1 04:26:02 2003
Subject: [Tutor] Rounding up/down integer numbers!
Message-ID: <9DB3344EC407D311A0A500508B0963E401DE32EB@ex84701.cars.no.bilia.net>

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

------_=_NextPart_001_01C35806.36054930
Content-Type: text/plain

Hi!
 
I have the need to round up some numbers to the nearest 100. (01-49 down and
50-99 round up)
 
How do you do this most efficiently?
 
Ex:
 
8356440
Should be rounded down to:
8356400
and:
8356499
should be rounded up to:
8356500
 
So far I managed but what if:
 
8359980
Then the number should be rounded up to:
8360000
 
Can anyone give me a clue to this?
 
I think maybe I have to set up a range with split 100 and use a while syntax
 
But I'm pretty new to programming so I'm not sure how to do this
 
 
Thanks
 
Regards
 
Jan Wilhelmsen
IT-Technician
Bilia Personbil as
 


-------------------------------------------------------------------------------
This verifies that this e-mail has been scanned for virus and deemed virus-free 
according to F-secure Content Scanner 5.0
Fri, 1 Aug 2003 10:23:39 +0200 GMT
-------------------------------------------------------------------------------


------_=_NextPart_001_01C35806.36054930
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" xmlns:w=3D"urn:sc=
hemas-microsoft-com:office:word" xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C35817.2818C570">
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:HyphenationZone>21</w:HyphenationZone>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]-->
<style>
<!--
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
p.MsoAutoSig, li.MsoAutoSig, div.MsoAutoSig
	{margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";}
span.EpostStil17
	{mso-style-type:personal-compose;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:windowtext;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
@page Section1
	{size:595.3pt 841.9pt;
	margin:70.85pt 70.85pt 70.85pt 70.85pt;
	mso-header-margin:35.4pt;
	mso-footer-margin:35.4pt;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Vanlig tabell";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin:0cm;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DNO-BOK link=3Dblue vlink=3Dpurple style=3D'tab-interval:35.4pt=
'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span style=3D'font-size:1=
0.0pt;
font-family:Arial'>Hi!<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span style=3D'font-size:1=
0.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>I have the need to round =
up
some numbers to the nearest 100. (01-49 down and 50-99 <span class=3DGramE>=
round</span>
up)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>How do you do this most e=
fficiently?<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Ex:<o:p></o:p></span></fo=
nt></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8356440<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Should be rounded down to=
:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8356400<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3DArial><span =
lang=3DEN-GB
style=3D'font-size:10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>and</s=
pan></font></span><font
size=3D2 face=3DArial><span lang=3DEN-GB style=3D'font-size:10.0pt;font-fam=
ily:Arial;
mso-ansi-language:EN-GB'>:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8356499<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3DArial><span =
lang=3DEN-GB
style=3D'font-size:10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>should=
</span></font></span><font
size=3D2 face=3DArial><span lang=3DEN-GB style=3D'font-size:10.0pt;font-fam=
ily:Arial;
mso-ansi-language:EN-GB'> be rounded up to:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8356500<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>So far I managed but what=
 if:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8359980<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Then the number should be
rounded up to:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>8360000<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Can anyone give me a clue=
 to
this?<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>I think maybe I have to s=
et
up a range with split 100 and use a while syntax<o:p></o:p></span></font></=
p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>But I'm pretty new to
programming so I'm not sure how to do this<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Thanks<o:p></o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'>Regards<o:p></o:p></span>=
</font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span lang=3DEN-GB style=
=3D'font-size:
10.0pt;font-family:Arial;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span><=
/font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span lang=3D=
EN-GB
style=3D'font-size:12.0pt;mso-ansi-language:EN-GB;mso-no-proof:yes'>Jan
Wilhelmsen<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D2 face=3D"Times New Roman"><span lang=3D=
EN-GB
style=3D'font-size:10.0pt;mso-ansi-language:EN-GB;mso-no-proof:yes'>IT-Tech=
nician<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D2 face=3D"Times New Roman"><span lang=3D=
EN-GB
style=3D'font-size:10.0pt;mso-ansi-language:EN-GB;mso-no-proof:yes'>Bilia
Personbil as<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D3 face=3D"Times New Roman"><span lang=3DE=
N-GB
style=3D'font-size:12.0pt;mso-ansi-language:EN-GB'><o:p>&nbsp;</o:p></span>=
</font></p>

</div>

<FONT SIZE=3D3><BR>
<BR>
---------------------------------------------------------------------------=
----<BR>
This verifies that this e-mail has been scanned for virus and deemed virus-=
free <BR>
according to F-secure Content Scanner 5.0<BR>
Fri, 1 Aug 2003 10:23:39 +0200 GMT<BR>
---------------------------------------------------------------------------=
----<BR>
</FONT>
</body>

</html>

------_=_NextPart_001_01C35806.36054930--


From glingl@aon.at  Fri Aug  1 06:01:05 2003
From: glingl@aon.at (Gregor Lingl)
Date: Fri Aug  1 05:01:05 2003
Subject: [Tutor] Rounding up/down integer numbers!
References: <9DB3344EC407D311A0A500508B0963E401DE32EB@ex84701.cars.no.bilia.net>
Message-ID: <3F2A2CB7.8040207@aon.at>

Wilhelmsen Jan schrieb:

> Hi!
>
>  
>
> I have the need to round up some numbers to the nearest 100. (01-49 
> down and 50-99 round up)
>
>  
>
> How do you do this most efficiently?
>
>  
>
Python has a function round, which returns numbers of type double:

 >>> print round(1123.456789, 4)
1123.4568
 >>> print round(1123.456789, 2)
1123.46
 >>> print round(1123.456789, 0)
1123.0

This function has a wonderful magic property:

 >>> print round(1123.456789, -1)
1120.0
 >>> print round(1123.456789, -2)
1100.0

If you need an integer as a result use int to convert type:

 >>> print int(round(1123.456789, -2))
1100
 >>> print int(round(8359980, -2))
8360000

HTH, Gregor





> Ex:
>
>  
>
> 8356440
>
> Should be rounded down to:
>
> 8356400
>
> and:
>
> 8356499
>
> should be rounded up to:
>
> 8356500
>
>  
>
> So far I managed but what if:
>
>  
>
> 8359980
>
> Then the number should be rounded up to:
>
> 8360000
>
>  
>
> Can anyone give me a clue to this?
>
>  
>
> I think maybe I have to set up a range with split 100 and use a while 
> syntax
>
>  
>
> But I'm pretty new to programming so I'm not sure how to do this
>
>  
>
>  
>
> Thanks
>
>  
>
> Regards
>
>  
>
> Jan Wilhelmsen
>
> IT-Technician
>
> Bilia Personbil as
>
>  
>
>
>
> -------------------------------------------------------------------------------
> This verifies that this e-mail has been scanned for virus and deemed 
> virus-free
> according to F-secure Content Scanner 5.0
> Fri, 1 Aug 2003 10:23:39 +0200 GMT
> -------------------------------------------------------------------------------







From cybersamurai@mac.com  Fri Aug  1 10:14:15 2003
From: cybersamurai@mac.com (Luiz Siqueira Neto)
Date: Fri Aug  1 09:14:15 2003
Subject: [Tutor] why use *get*
Message-ID: <200308011015.07012.cybersamurai@mac.com>

I don't know why use *get*.

ex.
d = {'name':'foo'}

### all this instructions have the same result
d['name'] = d.get('name', 0) + 'bar'
d['name'] = d.get('name', 1) + 'bar'
d['name'] = d.get('name', 2) + 'bar'
d['name'] = d.get('name', 3) + 'bar'
d['name'] = += 'bar'

For what I use *x.get* ????


From justin@unixremedies.com  Fri Aug  1 10:44:02 2003
From: justin@unixremedies.com (Justin Heath)
Date: Fri Aug  1 09:44:02 2003
Subject: [Tutor] Recursion help
In-Reply-To: <3F2A1DE8.5000501@aon.at>
References: <3F298E37.8070600@unixremedies.com>
 <3F2A1DE8.5000501@aon.at>
Message-ID: <3F2A6970.2010309@unixremedies.com>

Gregor Lingl wrote:

> Justin Heath schrieb:
>
>> I am working thru some of the examples in the "Learning to Program" 
>> tutorial. I am going thru the recusrion section and have gotten stumped. 
>
>
> Hi Justin,
> one of the keypoints to understand recursion is understanding function
> calls. Let's consider a very simple NONrecursive example:
>
> >>> def printitem(item):
>    print item
>  
> >>> def myfun():
>    printitem("Hello world!")
>    printitem("Wow!")
>  
> >>> myfun()
> Hello world!
> Wow!
> >>>
>
> Here we have defined two functions. The second one, myfun calls
> the first one, printitem, twice, with different arguments.
>
> You can make this visible, by inserting print statements, which give 
> you information
> about entering and exiting the execution af a function:
>
> >>> def printitem(item):
>    print "printitem(", item, ") entered."
>    print item
>    print "prititem(", item, ") exited."
>
>   >>> printitem("Hi!")
> printitem( Hi! ) entered.
> Hi!
> prititem( Hi! ) exited.
> >>> def myfun():
>    print "Myfun entered."
>    printitem("Hello world!")
>    printitem("Wow!")
>    print "Myfun exited."
>
>   >>> myfun()
> Myfun entered.
> printitem( Hello world! ) entered.
> Hello world!
> prititem( Hello world! ) exited.
> printitem( Wow! ) entered.
> Wow!
> prititem( Wow! ) exited.
> Myfun exited.
> >>>
>
> Observe, that here you have the original output, but additionally
> some "meta"-output, giving information about what's gong on
>
> Now, what concerns recursion, the difference is mainly that
> we have a function calling not another one but itself, with new 
> arguments.
>
> But you can make visible what's going on in the same way, by inserting
> those print-statements for tracing execution: (Please continue reading 
> below
> your code-snippet)
>
>> Here is the code I have run below:
>>
>> def printList(L):
>>    # if its empty do nothing
>>    if not L: return
>>    # if its a list call printList on 1st element
>>    if type(L[0]) == type([]):
>>        printList(L[0])
>>    else: #no list so just print        print L[0]    # now process 
>> the rest of L    printList(L[1:])
>>
>> myList=[1,2,3,4,5]
>>
>> printList(myList)
>>
>> The output is as follows:
>> 1
>> 2
>> 3
>> 4
>> 5
>
>
> Now we change your function, observing that there are two points
> where the functino may be exited:
>
> >>> def printList(L):
>    print "printList(", L, ") entered."
>    # if its empty do nothing
>    if not L:
>                print "printList(", L, ") exited."
>        return
>    # if its a list call printList on 1st element
>    if type(L[0]) == type([]):
>        printList(L[0])
>    else: #no list so just print
>        print L[0]
>    # now process the rest of L
>    printList(L[1:])
>    print "printList(", L, ") exited."
>  
> >>> printList([1,2,3,4,5])
> printList( [1, 2, 3, 4, 5] ) entered.
> 1
> printList( [2, 3, 4, 5] ) entered.
> 2
> printList( [3, 4, 5] ) entered.
> 3
> printList( [4, 5] ) entered.
> 4
> printList( [5] ) entered.
> 5
> printList( [] ) entered.
> printList( [] ) exited.
> printList( [5] ) exited.
> printList( [4, 5] ) exited.
> printList( [3, 4, 5] ) exited.
> printList( [2, 3, 4, 5] ) exited.
> printList( [1, 2, 3, 4, 5] ) exited.
>
> We can amend this, by using a variable calldepth, which
> we increment with every new call of printList and which we
> use to indent our meta-information by preceding our
> output string with "   "*calldepth:
>
> >>> def printList(L, calldepth):
>    print "   "*calldepth + "printList(", L, ") entered."
>    # if its empty do nothing
>    if not L:
>                print "   "*calldepth + "printList(", L, ") exited."
>        return
>    # if its a list call printList on 1st element
>    if type(L[0]) == type([]):
>        printList(L[0], calldepth+1)
>    else: #no list so just print
>        print L[0]
>    # now process the rest of L
>    printList(L[1:], calldepth+1)
>    print "   "*calldepth + "printList(", L, ") exited."
>
>   >>> printList([1,2,3,4,5], 1)
>   printList( [1, 2, 3, 4, 5] ) entered.
> 1
>      printList( [2, 3, 4, 5] ) entered.
> 2
>         printList( [3, 4, 5] ) entered.
> 3
>            printList( [4, 5] ) entered.
> 4
>               printList( [5] ) entered.
> 5
>                  printList( [] ) entered.
>                  printList( [] ) exited.
>               printList( [5] ) exited.
>            printList( [4, 5] ) exited.
>         printList( [3, 4, 5] ) exited.
>      printList( [2, 3, 4, 5] ) exited.
>   printList( [1, 2, 3, 4, 5] ) exited.
> >>>
>
> So you see, that each active instance of printList retains it's own
> value of  L, as L is a local variable to the function printList
>
> Now you may wonder and try to understand how this comes:
>
> >>> printList([1,[2,3,4],5], 1)
>   printList( [1, [2, 3, 4], 5] ) entered.
> 1
>      printList( [[2, 3, 4], 5] ) entered.
>         printList( [2, 3, 4] ) entered.
> 2
>            printList( [3, 4] ) entered.
> 3
>               printList( [4] ) entered.
> 4
>                  printList( [] ) entered.
>                  printList( [] ) exited.
>               printList( [4] ) exited.
>            printList( [3, 4] ) exited.
>         printList( [2, 3, 4] ) exited.
>         printList( [5] ) entered.
> 5
>            printList( [] ) entered.
>            printList( [] ) exited.
>         printList( [5] ) exited.
>      printList( [[2, 3, 4], 5] ) exited.
>   printList( [1, [2, 3, 4], 5] ) exited.
> >>>
>
> Enough stuff to digest for now, I think. To that end play with it.
> Regards,
> Gregor
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Gregor,

I see your point. If I had chosen to print the list every time I would 
have seen the assignment when the funtioned 're-called" itself. I had 
actually added some "debugging" print statements but only within the 
if/else loops. I guess it goes to show that verbosity is a good thing.

Alos, thanks to you and everyone else for thier help. And unless I get 
my head around my next topic I may be chiming in again later. :-)

Thanks,
Justin




From Janssen@rz.uni-frankfurt.de  Fri Aug  1 11:18:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Fri Aug  1 10:18:02 2003
Subject: [Tutor] why use *get*
In-Reply-To: <200308011015.07012.cybersamurai@mac.com>
References: <200308011015.07012.cybersamurai@mac.com>
Message-ID: <Pine.A41.4.56.0308011600590.1500428@hermes-22.rz.uni-frankfurt.de>

On Fri, 1 Aug 2003, Luiz Siqueira Neto wrote:

> I don't know why use *get*.
>
> ex.
> d =3D {'name':'foo'}
>
> ### all this instructions have the same result
> d['name'] =3D d.get('name', 0) + 'bar'
> d['name'] =3D d.get('name', 1) + 'bar'
> d['name'] =3D d.get('name', 2) + 'bar'
> d['name'] =3D d.get('name', 3) + 'bar'
> d['name'] =3D +=3D 'bar'

PYTHONDOC/lib/typesmapping.html:
a.get(k[, x]) ---> a[k] if k in a, else x

since your dictionary d has a key "name" the default values 0; 1; 2 and 3
arn't used (otherwise would raise TypeError: unsupported operand type(s)
for +: 'int' and 'str'). d.get('name', 0) returns the value of d['name']
in this case. d.get('not_a_key_of_d', 0) returns 0.

> For what I use *x.get* ????

to avoid having to write (example made with a 'counter'):

if d.has_key('counter'):
   d['counter'] +=3D 1
else:
   d['counter'] =3D 1

# or
try: d['counter'] +=3D 1
except KeyError: d['counter'] =3D 1

Note that the later one isn't aquivalent to d.get() in terms of
internal behavior (effect is =E4quivalent). First example is =E4quivalent
to d.get(). Nevertheless use of d.get() might help you to write
cleaner code (because lesser levels of indentation).

regards
Michael



From mhansen@cso.atmel.com  Fri Aug  1 11:43:02 2003
From: mhansen@cso.atmel.com (Mike Hansen)
Date: Fri Aug  1 10:43:02 2003
Subject: [Tutor] Re: Unsure why won't work
In-Reply-To: <20030801000002.14091.97626.Mailman@mail.python.org>
References: <20030801000002.14091.97626.Mailman@mail.python.org>
Message-ID: <3F2A7C58.1020605@cso.atmel.com>

 >Date: Thu, 31 Jul 2003 13:02:53 -0700
 >From: "Jeff Shannon" <jeff@ccvcorp.com>
 >To: ebernert@crpud.net, python-tutor <tutor@python.org>
 >Subject: Re: [Tutor] Unsure why won't work

[...]

 >Also, due to the limitations of
 >HTTP, it's difficult to write a constantly-updating program -- the
 >protocol works on a file-based basis.  A web browser requests a file,
 >and typically cannot (properly) display the file until the entire
 >contents have arrived.  Since this program is continually sending new
 >output, you never send an entire "file" ... so even if a browser is able
 >to show a response, you'll have a single page which is constantly
 >growing, which is probably not the preferred way of doing this.  You
 >could perhaps have the program write a single-page snapshot of the file
 >and include a meta-refresh tag, which would tell the browser to reload
 >the file (thus grabbing a new snapshot) after a few seconds.

It is possible and not that difficult to write a constantly updating web 
page. A friend of mine works at an ISP. He has written Perl scripts that 
display log files to web pages that are constantly updating. i.e. new 
entries to the log file appear at the bottom of the page as they are 
being written to the log file. I believe the trick is to not close the 
file you are reading while you are pumping out it's contents to a web 
page. The web page looks like it's not finished loading. It will never 
be. I would need to look at the scripts to get more details.

I would think you would not want to perform this trick with more than 
one connection to the web server. It's probably fine for sys admin type 
tasks, but not for multi-user stuff.

Now, there's an issue with displaying HTML tables. In Microsoft Internet 
Explorer, it won't display a table until the entire table is received. 
Large tables take their sweet time displaying in MS IE.

Mike







From phate@rockriver.net  Fri Aug  1 11:52:02 2003
From: phate@rockriver.net (Michie DeBerry)
Date: Fri Aug  1 10:52:02 2003
Subject: [Tutor] Python Compiler
Message-ID: <200308010952.28835.phate@rockriver.net>

I was wondering if there is a program, for linux, that will look at a python 
script, and then generate a standard .exe file for windows. I have looked at 
py2exe, but it is for windows.
Any help here?
Michie


From justin@unixremedies.com  Fri Aug  1 12:41:02 2003
From: justin@unixremedies.com (Justin Heath)
Date: Fri Aug  1 11:41:02 2003
Subject: [Tutor] Classes, methods and self
Message-ID: <3F2A84B8.6060907@unixremedies.com>

I am going through some various class documentation (Learning to Program 
and Learning Python) and I cannot seem to understand why self is needed 
in a method declaration. I "believe" that I understand what self does 
(i.e. connects itself to the current object instance). However, what I 
do not understand is why you have to explicitly declare self in the 
argument list of a method. I hope that was clear. Can anyone clarify 
this for me?

Thanks again,
Justin




From bgailer@alum.rpi.edu  Fri Aug  1 13:25:05 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Fri Aug  1 12:25:05 2003
Subject: [Tutor] Classes, methods and self
In-Reply-To: <3F2A84B8.6060907@unixremedies.com>
Message-ID: <5.2.1.1.0.20030801102102.02ca69f0@66.28.54.253>

--=======54A65727=======
Content-Type: text/plain; x-avg-checked=avg-ok-6564133F; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 10:18 AM 8/1/2003 -0500, Justin Heath wrote:

>I am going through some various class documentation (Learning to Program 
>and Learning Python) and I cannot seem to understand why self is needed in 
>a method declaration. I "believe" that I understand what self does (i.e. 
>connects itself to the current object instance). However, what I do not 
>understand is why you have to explicitly declare self in the argument list 
>of a method. I hope that was clear. Can anyone clarify this for me?

class A:
   def foo(self,arg):
     print arg

a = A()
a.foo(3)

Python converts a.foo(3) into A.foo(a, 3), thus passing the instance as the 
first argument to the class method foo.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625

--=======54A65727=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6564133F
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003

--=======54A65727=======--



From pythontutor@venix.com  Fri Aug  1 13:33:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Aug  1 12:33:02 2003
Subject: [Tutor] Re: Unsure why won't work
In-Reply-To: <3F2A7C58.1020605@cso.atmel.com>
References: <20030801000002.14091.97626.Mailman@mail.python.org> <3F2A7C58.1020605@cso.atmel.com>
Message-ID: <3F2A9611.3030905@venix.com>

A "normal cgi" script called from a web server will not be
able to hold the file open while sending results.  The web server
sends the results to the browser after the cgi script has completed.

Mike Hansen wrote:

>  >Date: Thu, 31 Jul 2003 13:02:53 -0700
>  >From: "Jeff Shannon" <jeff@ccvcorp.com>
>  >To: ebernert@crpud.net, python-tutor <tutor@python.org>
>  >Subject: Re: [Tutor] Unsure why won't work
> 
> [...]
> 
>  >Also, due to the limitations of
>  >HTTP, it's difficult to write a constantly-updating program -- the
>  >protocol works on a file-based basis.  A web browser requests a file,
>  >and typically cannot (properly) display the file until the entire
>  >contents have arrived.  Since this program is continually sending new
>  >output, you never send an entire "file" ... so even if a browser is able
>  >to show a response, you'll have a single page which is constantly
>  >growing, which is probably not the preferred way of doing this.  You
>  >could perhaps have the program write a single-page snapshot of the file
>  >and include a meta-refresh tag, which would tell the browser to reload
>  >the file (thus grabbing a new snapshot) after a few seconds.
> 
> It is possible and not that difficult to write a constantly updating web 
> page. A friend of mine works at an ISP. He has written Perl scripts that 
> display log files to web pages that are constantly updating. i.e. new 
> entries to the log file appear at the bottom of the page as they are 
> being written to the log file. I believe the trick is to not close the 
> file you are reading while you are pumping out it's contents to a web 
> page. The web page looks like it's not finished loading. It will never 
> be. I would need to look at the scripts to get more details.
> 
> I would think you would not want to perform this trick with more than 
> one connection to the web server. It's probably fine for sys admin type 
> tasks, but not for multi-user stuff.
> 
> Now, there's an issue with displaying HTML tables. In Microsoft Internet 
> Explorer, it won't display a table until the entire table is received. 
> Large tables take their sweet time displaying in MS IE.
> 
> Mike
> 
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From pythontutor@venix.com  Fri Aug  1 13:59:01 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Aug  1 12:59:01 2003
Subject: [Tutor] Classes, methods and self
In-Reply-To: <3F2A84B8.6060907@unixremedies.com>
References: <3F2A84B8.6060907@unixremedies.com>
Message-ID: <3F2A9C06.4080707@venix.com>

http://www.amk.ca/python/writing/warts.html
Python Warts

I pasted the Andrew Kuchling's comments about using self below.  I believe
that Python's approach of explicit object references is preferable to
implicit object references, but neither is perfect.  Is there a third
alternative???

***********
Explicit self in Methods

It's been suggested that the requirement to use self. to access attributes within class methods is tolerable but awkward, and the implied this from C++ and Java would be better. Perhaps this is a matter of preference; my Java code is instantly 
recognizable by the constant explicit use of this.attribute all over the place. Many Java or C++ coding standards dictate that object attributes should have a special prefix (e.g. m_) to distinguish them from locals; perhaps those who forget self are 
doomed to reinvent it.

If self. is too much typing for you, you can use a shorter variable name instead of self:

def method (s, arg1, arg2=None):
     s.attr1 = arg1
     if arg2 is not None:
          s.other_meth(arg2)

Using s instead of self doesn't follow the normal Python coding conventions, but few people will have difficulty adapting to the change.

Justin Heath wrote:

> I am going through some various class documentation (Learning to Program 
> and Learning Python) and I cannot seem to understand why self is needed 
> in a method declaration. I "believe" that I understand what self does 
> (i.e. connects itself to the current object instance). However, what I 
> do not understand is why you have to explicitly declare self in the 
> argument list of a method. I hope that was clear. Can anyone clarify 
> this for me?
> 
> Thanks again,
> Justin
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From rick@niof.net  Fri Aug  1 14:22:02 2003
From: rick@niof.net (Rick Pasotto)
Date: Fri Aug  1 13:22:02 2003
Subject: [Tutor] pysqlite and sqlite_last_insert_rowid()
Message-ID: <20030801172603.GC17226@niof.net>

How do I get the last_insert_id using pysqlite? The table is defined
with an 'id integer primary key'.

-- 
"By definition, a government has no conscience.  Sometimes it has
 a policy, but nothing more." -- Albert Camus
    Rick Pasotto    rick@niof.net    http://www.niof.net


From ATrautman@perryjudds.com  Fri Aug  1 15:03:01 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Fri Aug  1 14:03:01 2003
Subject: [Tutor] pysqlite and sqlite_last_insert_rowid()
Message-ID: <06738462136C054B8F8872D69DA140DB010876@corp-exch-1.pjinet.com>

I cannot confirm this with the two databases you mention but the normal way
with SQL/Oracle is to complete the add with an update if needed and than
move last. If many users are the system move last and find the last item
added by that user.

Some systems allow update and will keep you on that current record. After
the update you should be able to see/read the id field in the current
recordset. If you use INSERT you will have to use the first method.

HTH,

Alan

-----Original Message-----
From: Rick Pasotto [mailto:rick@niof.net]
Sent: Friday, August 01, 2003 12:26 PM
To: tutor@python.org
Subject: [Tutor] pysqlite and sqlite_last_insert_rowid()


How do I get the last_insert_id using pysqlite? The table is defined
with an 'id integer primary key'.

-- 
"By definition, a government has no conscience.  Sometimes it has
 a policy, but nothing more." -- Albert Camus
    Rick Pasotto    rick@niof.net    http://www.niof.net

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


From jonathan.hayward@pobox.com  Fri Aug  1 15:13:02 2003
From: jonathan.hayward@pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug  1 14:13:02 2003
Subject: [Tutor] Bug with fork / socket from CGI
Message-ID: <3F2AAD87.1020104@pobox.com>

I'm trying to make a CGI script that, on first invocation, starts a 
daemon. Every invocation from then on queries the daemon via a socket.

As is, the first invocation hangs, and subsequent invocations give an 
error ('Bad file descriptor' refers to a socket.makefile() variable):

There was an error loading this page.
(9, 'Bad file descriptor')

Here's the multitasking object code. Any bugfixes or corrections welcome.

class multitasking_manager(ancestor):
     """Class to handle multithreading and multiprocessing material."""
     def __init__(self):
         ancestor.__init__(self)
         self.thread_specific_storage = {}
         self.thread_specific_storage_lock = thread.allocate_lock()
         self.is_in_check_and_appropriately_update_stored_information = 0
     def check_and_appropriately_update_stored_information(self):
         self.is_in_check_and_appropriately_update_stored_information = 1
         # Check if databases etc. should be updated, and if so perform
         # appropriate updates.
         self.is_in_check_and_appropriately_update_stored_information = 0
     def check_and_start_oracle(self):
         if not self.is_oracle_running():
             self.start_oracle()
     def get_page_from_oracle(self):
         self.check_and_start_oracle()
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sockIn = sock.makefile("r")
         sockOut = sock.makefile("wb")
         sock.close()
         try:
             sock.connect((configuration.get_search_server_ip(), \
               configuration.get_search_server_port()))
             for current_environment_key in os.environ.keys():
                 sockOut.write("environmental_variable " + \
                   current_environment_key + "\r\n")
                 cPickle.dump(os.environ[current_environment_key], sockOut)
             for cgi_key in cgi.FieldStorage().keys():
                 sockOut.write("cgi_value " + cgi_key + "\r\n")
                 cPickle.dump(cgi.FieldStorage[cgi_key])
             sockOut.write("\r\n")
             result = cPickle.load(sockIn)
             sockOut.close()
             sockIn.close()
         except socket.error, e:
             return "Content-type: text/html\n\n<h1>There was an error 
loading this page.</h1>" + str(e)
     def get_thread_specific_storage():
         thread_id = thread.get_ident()
         result = thread_specific_storage.get(thread_id)
         if thread_specific_storage is None:
             try:
                 thread_specific_storage_lock.acquire()
                 thread_specific_storaget[thread_id] = result = {}
             finally:
                 thread_specific_storage_lock.release()
         return result
     def is_oracle_running(self):
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         try:
             sock.connect((configuration.get_search_server_ip(), \
               configuration.get_search_server_port()))
             sock.close()
             return 1
         except socket.error:
             return 0
     def run_oracle(self):
         thread.start_new_thread(\
           self.check_and_appropriately_update_stored_information, ())
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind(("", configuration.get_search_server_port()))
         sock.listen(5)
         while 1:
             try:
                 newsocket, address = sock.accept()
                 thread.start_new_thread(self.run_oracle_thread, 
(newsocket, \
                   address))
             except socket.error:
                 sock.close()
                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                 sock.bind(("", configuration.get_search_server_port()))
                 sock.listen(5)
     def run_oracle_thread(sock, address):
         """Reads a CGI or other header variable alone on a line, format 
like
             cgi_value <HTML form element name>
             environmental_variable REMOTE_ADDR
         and then a pickled value. There is exactly one space between 
the two
         elements, and neither element may contain a space"""
         sockIn = sock.makefile("wb")
         sockOut = sock.makefile("r")
         sock.close()
         line = sockIn.readline()
         while line:
             if get_thread_specific_storage()["cgi"] == None:
                 get_thread_specific_storage()["cgi"] = {}
             if get_thread_specific_storage()["environmental_variables"] 
== \
               None:
 
get_thread_specific_storage()["environmental_variables"] = {}
             cgi = get_thread_specific_storage["cgi"]
             environmental_variables = \
               get_thread_specific_storage["environmental_variables"]
             line = re.sub("[\r\n]+", "", line)
             if line != "":
                 query_line = re.split("\s+", line)
                 input_type = query_line[0]
                 input_name = query_line[1]
                 if input_type == "cgi_value":
                     cgi[input_name] = cPickle.load(sockIn)
                 elif input_type == "environmental_variables":
                     environmental_variables[input_name] = 
cPickle.load(sockIn)
                 line = sockIn.readline()
             else:
                 generate_output()
                 print_output(sockOut)
         sockIn.close()
         sockOut.close()
     def start_oracle(self):
         try:
             first_pid = os.fork()
         except OSError, e:
             log_error("Failed to make first fork for oracle. Error: " + \
               e.strerror)
             return
         if first_pid == 0:
             os.chdir("/")
             os.setsid()
             os.umask(066)
             try:
                 second_pid = os.fork()
             except OSError, e:
                 log_error("Failed to make second fork for oracle. 
Error: " + \
                   e.strerror)
                 return
             if second_pid == 0:
                 self.run_oracle()
             else:
                 sys.exit(0)


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From jeff@ccvcorp.com  Fri Aug  1 15:15:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Aug  1 14:15:02 2003
Subject: [Tutor] global
References: <3F29C6A3.4050100@netzero.net> <3F29C9A1.9050508@ccvcorp.com> <3F29D645.5010103@netzero.net>
Message-ID: <3F2AAE3E.7030204@ccvcorp.com>

Kirk Bailey wrote:

 > Jeff Shannon wrote:
 >
 >> Kirk Bailey wrote:
 >>
 >>> Got a script that wants to bark. Early in the program I
 >>> define some defaults for certain variables to define state
 >>> (they are used as boolian flags, 1/0 stuff). Later, a
 >>> function referrs o one- and barks. Says it does not know
 >>> the variable- undefined. Hmmm, sure it is... Apparently
 >>> this function is not aware the variable is already defined.
 >>> How do I force a variable to be global so it will
 >>> automatically be available to the insiode structure of a
 >>> defined function without having to formally pass it as an
 >>> arguement?
 >>
 >> Presuming that this is within the same module, nothing needs
 >> to be done. However, rebinding a name that [supposedly] points
 >> to a global object can result in a problem like what you
 >> mention [...]
 >
 > Jeff, to conserve bandwidth, I have created a link on the website
 > that will accurately display the current script.
 >
 > http://www.tinylist.org/wikinehesa.txt

Okay, it looks to me like I was more-or-less right about your
problem.  Here's the relevant parts of your script:


# Flags to control things
A=0    # Anchor toggle flag
B=0    # Bold toggle flag
I=0    # Italic toggle flag
U=0    # underscore toggle flag

def htmlize(thing,A,B,I,U):    # this converts wikicode to html, for one 
line.
[...]
        if exists(thing,"'''"):
            if B:
                thing=string.replace(thing,"'''","<B>")
            else:
                thing=string.replace(thing,"'''","</B>"
            B=not B    # toggle B flag
        # I am concerned that this won't toggle within a line, only between
[...]
index=0                    # index is a pointer for lines in a list.
for line in finalrawpage:        # each line will be treated in the page
    finalrawpage[index]=htmlize(line,A,B,I,U) # line by line, gibve it 
the treatment!
    index=index+1            # incrementing the counter to point the 
next line


So, you have a global variable B.  When htmlize() is called, that
variable is passed into the function as a parameter.  Once inside
the function, you're calling that parameter by the same name as
the global variable, but it is in fact a separate entity (even
though it holds the same value).  Thus, the line 'B = not B' toggles
the value of the local (parameter) variable, which now becomes 1,
but it does not affect the global variable.  Thus, on your next
trip through htmlize(), B is *still* 0.

I presume that adding these as parameters was an attempt to fix the
problem you originally mentioned, where a variable was reported as
being undefined.  That's what would have happened if you didn't pass
the flags in as parameters, i.e. your parameter list was just

def htmlize(thing):  [...]

In this case, when Python loads your code and compiles it to bytecode,
it notices the assignment to B ('B= not B') inside your function. 
Since you assign to this name, it's assumed to be a local variable,
and it's given a place in the fast-locals namespace.  Note that this
happens at load-time.  When you actually *run* the function, you
come to the statement 'if B:'.  At this point, Python tries to load
a value for B; it recognizes that it's got a space in fast-locals,
but then finds no value for it there because you haven't assigned
anything to it within the function.  (There's a global B, but Python
won't look for it because it "knows" that this is supposed to be a
local variable.)  That's when you get your UnboundLocalError.

You can prevent that error by stating, within htmlize(), that B (and
the other flags) are global --

def htmlize(thing):
    global A, B, I, U
    [...]

Now Python knows that these are intended to be globals, and it won't
reserve that space for them in fast-locals.  When it gets to the
previously problematic 'if B:', it will properly look up (and find)
B in the global namespace, and when you assign to B it will know to
change the value of the global name instead of creating a new local
name.  Personally, I'd lean towards using a class here, and having
htmlize() be a method of that class and your flags be attributes, but
that's a matter of personal taste -- I'm a big fan of using objects and
not so happy about globals.

Incidentally, you're right about your mentioned concern -- if you have
two or more sets of ''' on a single line, your function as is will
replace all of them with the same tag (either start or end), rather than
alternating tags.  In order to properly handle multiple tags on the
same line, you'll need to do something a bit more complicated.  One
possibility would be to split the line on ''', and then reassemble it
with alternation between <B> and </B>.  You'd need to keep track of
just how many instances of ''' there were, however, and be careful to
not have a spurious tag at the end of the reassembled line -- but you'd
also need to be sure that, if the old line ends with ''', you put the
proper tag on the end of the new line.  All of this is less trivial than
it seems at first glance, but it certainly can be done if given a bit
of careful thought.

Jeff Shannon
Technician/Programmer
Credit International




From pythontutor@venix.com  Fri Aug  1 15:51:03 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Aug  1 14:51:03 2003
Subject: [Tutor] Bug with fork / socket from CGI
In-Reply-To: <3F2AAD87.1020104@pobox.com>
References: <3F2AAD87.1020104@pobox.com>
Message-ID: <3F2AB64B.1040705@venix.com>

I did not attempt to figure out your problem,  the cgitb module with
its traceback facility usually helps a great deal with debugging an
errant cgi script.

However, wouldn't it be simpler to use fastCGI or an equivalent connection
between the web server and the persistent process?

Jonathan Hayward http://JonathansCorner.com wrote:

> I'm trying to make a CGI script that, on first invocation, starts a 
> daemon. Every invocation from then on queries the daemon via a socket.
> 
> As is, the first invocation hangs, and subsequent invocations give an 
> error ('Bad file descriptor' refers to a socket.makefile() variable):
> 
> There was an error loading this page.
> (9, 'Bad file descriptor')
> 
> Here's the multitasking object code. Any bugfixes or corrections welcome.
> 
> class multitasking_manager(ancestor):
>     """Class to handle multithreading and multiprocessing material."""
>     def __init__(self):
>         ancestor.__init__(self)
>         self.thread_specific_storage = {}
>         self.thread_specific_storage_lock = thread.allocate_lock()
>         self.is_in_check_and_appropriately_update_stored_information = 0
>     def check_and_appropriately_update_stored_information(self):
>         self.is_in_check_and_appropriately_update_stored_information = 1
>         # Check if databases etc. should be updated, and if so perform
>         # appropriate updates.
>         self.is_in_check_and_appropriately_update_stored_information = 0
>     def check_and_start_oracle(self):
>         if not self.is_oracle_running():
>             self.start_oracle()
>     def get_page_from_oracle(self):
>         self.check_and_start_oracle()
>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         sockIn = sock.makefile("r")
>         sockOut = sock.makefile("wb")
>         sock.close()
>         try:
>             sock.connect((configuration.get_search_server_ip(), \
>               configuration.get_search_server_port()))
>             for current_environment_key in os.environ.keys():
>                 sockOut.write("environmental_variable " + \
>                   current_environment_key + "\r\n")
>                 cPickle.dump(os.environ[current_environment_key], sockOut)
>             for cgi_key in cgi.FieldStorage().keys():
>                 sockOut.write("cgi_value " + cgi_key + "\r\n")
>                 cPickle.dump(cgi.FieldStorage[cgi_key])
>             sockOut.write("\r\n")
>             result = cPickle.load(sockIn)
>             sockOut.close()
>             sockIn.close()
>         except socket.error, e:
>             return "Content-type: text/html\n\n<h1>There was an error 
> loading this page.</h1>" + str(e)
>     def get_thread_specific_storage():
>         thread_id = thread.get_ident()
>         result = thread_specific_storage.get(thread_id)
>         if thread_specific_storage is None:
>             try:
>                 thread_specific_storage_lock.acquire()
>                 thread_specific_storaget[thread_id] = result = {}
>             finally:
>                 thread_specific_storage_lock.release()
>         return result
>     def is_oracle_running(self):
>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         try:
>             sock.connect((configuration.get_search_server_ip(), \
>               configuration.get_search_server_port()))
>             sock.close()
>             return 1
>         except socket.error:
>             return 0
>     def run_oracle(self):
>         thread.start_new_thread(\
>           self.check_and_appropriately_update_stored_information, ())
>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>         sock.bind(("", configuration.get_search_server_port()))
>         sock.listen(5)
>         while 1:
>             try:
>                 newsocket, address = sock.accept()
>                 thread.start_new_thread(self.run_oracle_thread, 
> (newsocket, \
>                   address))
>             except socket.error:
>                 sock.close()
>                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>                 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>                 sock.bind(("", configuration.get_search_server_port()))
>                 sock.listen(5)
>     def run_oracle_thread(sock, address):
>         """Reads a CGI or other header variable alone on a line, format 
> like
>             cgi_value <HTML form element name>
>             environmental_variable REMOTE_ADDR
>         and then a pickled value. There is exactly one space between the 
> two
>         elements, and neither element may contain a space"""
>         sockIn = sock.makefile("wb")
>         sockOut = sock.makefile("r")
>         sock.close()
>         line = sockIn.readline()
>         while line:
>             if get_thread_specific_storage()["cgi"] == None:
>                 get_thread_specific_storage()["cgi"] = {}
>             if get_thread_specific_storage()["environmental_variables"] 
> == \
>               None:
> 
> get_thread_specific_storage()["environmental_variables"] = {}
>             cgi = get_thread_specific_storage["cgi"]
>             environmental_variables = \
>               get_thread_specific_storage["environmental_variables"]
>             line = re.sub("[\r\n]+", "", line)
>             if line != "":
>                 query_line = re.split("\s+", line)
>                 input_type = query_line[0]
>                 input_name = query_line[1]
>                 if input_type == "cgi_value":
>                     cgi[input_name] = cPickle.load(sockIn)
>                 elif input_type == "environmental_variables":
>                     environmental_variables[input_name] = 
> cPickle.load(sockIn)
>                 line = sockIn.readline()
>             else:
>                 generate_output()
>                 print_output(sockOut)
>         sockIn.close()
>         sockOut.close()
>     def start_oracle(self):
>         try:
>             first_pid = os.fork()
>         except OSError, e:
>             log_error("Failed to make first fork for oracle. Error: " + \
>               e.strerror)
>             return
>         if first_pid == 0:
>             os.chdir("/")
>             os.setsid()
>             os.umask(066)
>             try:
>                 second_pid = os.fork()
>             except OSError, e:
>                 log_error("Failed to make second fork for oracle. Error: 
> " + \
>                   e.strerror)
>                 return
>             if second_pid == 0:
>                 self.run_oracle()
>             else:
>                 sys.exit(0)
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From cybersamurai@mac.com  Fri Aug  1 15:52:01 2003
From: cybersamurai@mac.com (Luiz Siqueira Neto)
Date: Fri Aug  1 14:52:01 2003
Subject: [Tutor] Re: why use *get*
Message-ID: <200308011552.21504.cybersamurai@mac.com>

--Boundary-00=_lbrK/XJkLM6KIJs
Content-Type: text/plain;
  charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

Thanks.  :)
--Boundary-00=_lbrK/XJkLM6KIJs
Content-Type: message/rfc822;
  name="forwarded message"
Content-Transfer-Encoding: 8bit
Content-Description: Luiz Siqueira Neto <cybersamurai@mac.com>: why use *get*

From: Luiz Siqueira Neto <cybersamurai@mac.com>
Reply-To: cybersamurai@mac.com
Organization: CyberSamurai
To: tutor@python.org
Subject: why use *get*
Date: Fri, 1 Aug 2003 10:15:06 -0300
User-Agent: KMail/1.5
MIME-Version: 1.0
Content-Type: text/plain;
  charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Message-Id: <200308011015.07012.cybersamurai@mac.com>
Status: RO
X-Status: S
X-KMail-EncryptionState:  
X-KMail-SignatureState:  

I don't know why use *get*.

ex.
d = {'name':'foo'}

### all this instructions have the same result
d['name'] = d.get('name', 0) + 'bar'
d['name'] = d.get('name', 1) + 'bar'
d['name'] = d.get('name', 2) + 'bar'
d['name'] = d.get('name', 3) + 'bar'
d['name'] = += 'bar'

For what I use *x.get* ????
--Boundary-00=_lbrK/XJkLM6KIJs--



From dyoo@hkn.eecs.berkeley.edu  Fri Aug  1 16:22:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug  1 15:22:02 2003
Subject: [Tutor] Python Compiler   [cross compiling from Linux?]
In-Reply-To: <200308010952.28835.phate@rockriver.net>
Message-ID: <Pine.LNX.4.44.0308011137520.16679-100000@hkn.eecs.berkeley.edu>


On Fri, 1 Aug 2003, Michie DeBerry wrote:

> I was wondering if there is a program, for linux, that will look at a
> python script, and then generate a standard .exe file for windows. I
> have looked at py2exe, but it is for windows.

Hi Michie,


Yikes!

Doing a "cross-compiling" of a Windows .EXE on a Linux system is an
advanced topic.  I'm not sure if anyone here can help you with it. You may
want to ask on the comp.lang.python newsgroup and see if anyone else has
tried to do it.


There are a few pages out there that explain how to do a cross-compiling.
For example:

    http://rooster.stanford.edu/~ben/linux/cross.php

explains that the 'mingw32msvc' tools at:

    http://www.mingw.org/

may be able to help.  Perhaps there's a way of massaging something like
McMillan's Installer package:

    http://www.mcmillan-inc.com/install1.html

to use the mingw tools when it generates an executable.  There was a brief
discussion of using Installer on the Adonthell mailing lists:

    http://mail.gnu.org/archive/html/adonthell-devel/2003-01/msg00076.html

so that might be a viable way of doing this.



If you can't tell: I'm being very hesitant and handwavy about this because
I've never tried this before... *grin* Again, you may want to ask your
question on comp.lang.python; there should be people there who have more
cross-compiling experience there.



Good luck to you!



From logiplex@qwest.net  Fri Aug  1 16:25:03 2003
From: logiplex@qwest.net (Cliff Wells)
Date: Fri Aug  1 15:25:03 2003
Subject: [Tutor] Re: Tutor digest, Vol 1 #2622 - 13 msgs
In-Reply-To: <000c01c357cd$28d07c50$bc4c41db@VULCAN>
References: <20030731160006.11018.13659.Mailman@mail.python.org>
 <000c01c357cd$28d07c50$bc4c41db@VULCAN>
Message-ID: <1059765857.1469.76.camel@software1.logiplex.internal>

On Thu, 2003-07-31 at 18:35, G Kiran wrote:
> Hi,
> 
>     I am trying to limit no of threads i can spawn for a multi threaded
> socket server .
> 
> presently i do this by the following fragment of code
> 
> 
> maxthreads=40
> for ct in range(0,len(scanlist)-1):
>         th.append(checkport(scanlist[ct])
>         th[ct].start()
>         while  threading.activeCount() > maxthreads :  pass  ##### this is
> how i am limiting the no of threads
> 
> i am using the threading class fo my checkport function
> 
> is there any other way of doing it...rather than the endless loop which i
> feel wastes the processor time

The general method is to create a pool of threads that wait for work to
become available (for instance, from a Queue).  This has the advantage
of not only controlling the number of threads, but also eliminating the
overhead of starting a thread everytime some work becomes available.

For example:

import threading, Queue, time

work = Queue.Queue()

nthreads = 10

def consumer(n):
    while 1:
        job = work.get()
        if job is None:
            return
        print "thread %d" % n, job
        time.sleep(0.01) # arbitrary delay


def producer(iterations):
    for i in xrange(iterations):
        work.put(i) # some bogus work
        
    for i in xrange(nthreads):
        work.put(None) # kill the threads
        

if __name__ == '__main__':
    # start up a pool of 10 threads
    for i in range(nthreads):
        t = threading.Thread(target = consumer, args = (i,))
        t.start()
        
    # at this point the threads are all idle waiting
    # for work to do, let's give it to them
    producer(1000)


Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555



From logiplex@qwest.net  Fri Aug  1 16:37:01 2003
From: logiplex@qwest.net (Cliff Wells)
Date: Fri Aug  1 15:37:01 2003
Subject: [Tutor] global
In-Reply-To: <3F2AAE3E.7030204@ccvcorp.com>
References: <3F29C6A3.4050100@netzero.net> <3F29C9A1.9050508@ccvcorp.com>
 <3F29D645.5010103@netzero.net>  <3F2AAE3E.7030204@ccvcorp.com>
Message-ID: <1059766606.1469.84.camel@software1.logiplex.internal>

On Fri, 2003-08-01 at 11:15, Jeff Shannon wrote:
> Kirk Bailey wrote:

> # Flags to control things
> A=0    # Anchor toggle flag
> B=0    # Bold toggle flag
> I=0    # Italic toggle flag
> U=0    # underscore toggle flag

Just a suggestion:  rather than have a bunch of global variables, why
not put these in a dictionary and pass it around?  That neatly solves
the globals problem and makes your program a bit tidier:


flags = {
    'anchor': 0,
    'bold': 0,
    'italic': 0,
    'underscore': 0,
}


def htmlize(thing, flags):
    [...]
        if exists(thing, "'''"):
            if flags['bold']:
                thing = string.replace(thing, "'''", "<B>")
            else:
                thing = string.replace(thing, "'''", "</B>"
            flags['bold'] = not flags['bold'] 
    [...]


Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555



From alan.gauld@blueyonder.co.uk  Fri Aug  1 16:39:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  1 15:39:02 2003
Subject: [Tutor] why use *get*
References: <200308011015.07012.cybersamurai@mac.com>
Message-ID: <00b701c35864$921528e0$6401a8c0@xp>

> d = {'name':'foo'}
> 
> ### all this instructions have the same result
> d['name'] = d.get('name', 0) + 'bar'
> d['name'] = += 'bar'
> 
> For what I use *x.get* ????

Try

print d['sex']
print d.get('sex','male')

Now do you see a difference?

get() fetches the current contents or the default provided 
if the key does not exist. Thus it never fails and causes 
an error.

HTH,

Alan G.


From tim@johnsons-web.com  Fri Aug  1 16:41:20 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Fri Aug  1 15:41:20 2003
Subject: [Tutor] Python Compiler   [cross compiling from Linux?]
In-Reply-To: <Pine.LNX.4.44.0308011137520.16679-100000@hkn.eecs.berkeley.edu>
References: <200308010952.28835.phate@rockriver.net> <Pine.LNX.4.44.0308011137520.16679-100000@hkn.eecs.berkeley.edu>
Message-ID: <20030801194654.GF22826@johnsons-web.com>

* Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [030801 11:32]:
> 
> 
> On Fri, 1 Aug 2003, Michie DeBerry wrote:
> 
> > I was wondering if there is a program, for linux, that will look at a
> > python script, and then generate a standard .exe file for windows. I
> > have looked at py2exe, but it is for windows.
> 
> Hi Michie,
> 
> 
> Yikes!
> 
> Doing a "cross-compiling" of a Windows .EXE on a Linux system is an
> advanced topic.  I'm not sure if anyone here can help you with it. You may
> want to ask on the comp.lang.python newsgroup and see if anyone else has
> tried to do it.
> 
> 
> There are a few pages out there that explain how to do a cross-compiling.
> For example:
> 
>     http://rooster.stanford.edu/~ben/linux/cross.php
> 
> explains that the 'mingw32msvc' tools at:
> 
>     http://www.mingw.org/
> 
> may be able to help.  Perhaps there's a way of massaging something like
> McMillan's Installer package:
> 
>     http://www.mcmillan-inc.com/install1.html
> 
> to use the mingw tools when it generates an executable.  There was a brief
> discussion of using Installer on the Adonthell mailing lists:
> 
>     http://mail.gnu.org/archive/html/adonthell-devel/2003-01/msg00076.html
> 
> so that might be a viable way of doing this.
> 
> 
> 
> If you can't tell: I'm being very hesitant and handwavy about this because
> I've never tried this before... *grin* Again, you may want to ask your
> question on comp.lang.python; there should be people there who have more
> cross-compiling experience there.

  :-) You even scared Danny! If you were to use Win4Lin, then
      you would have Linux and Windows operating systems sharing
      the same file system at the same time. You would then be
      able to edit and test in Linux, using Linux tools, and then
      (on the same workstation), compile and deploy for windows.
      
      Is that something that might of interest to you?
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From alan.gauld@blueyonder.co.uk  Fri Aug  1 16:46:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  1 15:46:02 2003
Subject: [Tutor] Classes, methods and self
References: <3F2A84B8.6060907@unixremedies.com>
Message-ID: <00c801c35865$94555f70$6401a8c0@xp>

> and Learning Python) and I cannot seem to understand why self is
needed
> in a method declaration. I "believe" that I understand what self
does
> (i.e. connects itself to the current object instance).

Corrct.

> However, what I do not understand is why you have to explicitly
> declare self in the argument list of a method.

Because that's how Guido van Rossum designed the Python language.
Other languages (eg. Java, C++) let the compiler/interpreter do it
for you. However there are some avantages to explicit self, not
least because it helps make the fact that you are writing a method,
as opposed to a function, more obvious.

Using self inside the methods is also not needed in other languages
but again there are advantages to the Python approach in that it
becomes clear which variables are local to the method and which
are part of the object(and thus persist beyond the method execution)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From jonathan.hayward@pobox.com  Fri Aug  1 17:08:02 2003
From: jonathan.hayward@pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug  1 16:08:02 2003
Subject: GROT 239: Re: [Tutor] Bug with fork / socket from CGI
In-Reply-To: <3F2AB64B.1040705@venix.com>
References: <3F2AAD87.1020104@pobox.com> <3F2AB64B.1040705@venix.com>
Message-ID: <3F2AC869.2010007@pobox.com>

Lloyd Kvam wrote:

> I did not attempt to figure out your problem,  the cgitb module with
> its traceback facility usually helps a great deal with debugging an
> errant cgi script.

When I used cgitb, it gave errno 9, 'Bad file descriptor' to this line:

            sock.connect((configuration.get_search_server_ip(), \
              configuration.get_search_server_port()))

Evaluated, that comes to:

sock.connect(("127.0.0.1", 1374))

Cgitb has helped me know what I need to be using right, but it won't 
explain the socket concept I'm missing--that's why I e-mailed the list. 
Do you or anyone else on the list know what needs to be changed about 
the socket so the above line will be corrected?

TIA

>
> However, wouldn't it be simpler to use fastCGI or an equivalent 
> connection
> between the web server and the persistent process?

I looked in to it. That's great if I want to have my private server 
running things, but I want to have something that people can install PnP 
without repeating the extras I set up.

>
> Jonathan Hayward http://JonathansCorner.com wrote:
>
>> I'm trying to make a CGI script that, on first invocation, starts a 
>> daemon. Every invocation from then on queries the daemon via a socket.
>>
>> As is, the first invocation hangs, and subsequent invocations give an 
>> error ('Bad file descriptor' refers to a socket.makefile() variable):
>>
>> There was an error loading this page.
>> (9, 'Bad file descriptor')
>>
>> Here's the multitasking object code. Any bugfixes or corrections 
>> welcome.
>>
>> class multitasking_manager(ancestor):
>>     """Class to handle multithreading and multiprocessing material."""
>>     def __init__(self):
>>         ancestor.__init__(self)
>>         self.thread_specific_storage = {}
>>         self.thread_specific_storage_lock = thread.allocate_lock()
>>         self.is_in_check_and_appropriately_update_stored_information = 0
>>     def check_and_appropriately_update_stored_information(self):
>>         self.is_in_check_and_appropriately_update_stored_information = 1
>>         # Check if databases etc. should be updated, and if so perform
>>         # appropriate updates.
>>         self.is_in_check_and_appropriately_update_stored_information = 0
>>     def check_and_start_oracle(self):
>>         if not self.is_oracle_running():
>>             self.start_oracle()
>>     def get_page_from_oracle(self):
>>         self.check_and_start_oracle()
>>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>         sockIn = sock.makefile("r")
>>         sockOut = sock.makefile("wb")
>>         sock.close()
>>         try:
>>             sock.connect((configuration.get_search_server_ip(), \
>>               configuration.get_search_server_port()))
>>             for current_environment_key in os.environ.keys():
>>                 sockOut.write("environmental_variable " + \
>>                   current_environment_key + "\r\n")
>>                 cPickle.dump(os.environ[current_environment_key], 
>> sockOut)
>>             for cgi_key in cgi.FieldStorage().keys():
>>                 sockOut.write("cgi_value " + cgi_key + "\r\n")
>>                 cPickle.dump(cgi.FieldStorage[cgi_key])
>>             sockOut.write("\r\n")
>>             result = cPickle.load(sockIn)
>>             sockOut.close()
>>             sockIn.close()
>>         except socket.error, e:
>>             return "Content-type: text/html\n\n<h1>There was an error 
>> loading this page.</h1>" + str(e)
>>     def get_thread_specific_storage():
>>         thread_id = thread.get_ident()
>>         result = thread_specific_storage.get(thread_id)
>>         if thread_specific_storage is None:
>>             try:
>>                 thread_specific_storage_lock.acquire()
>>                 thread_specific_storaget[thread_id] = result = {}
>>             finally:
>>                 thread_specific_storage_lock.release()
>>         return result
>>     def is_oracle_running(self):
>>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>         try:
>>             sock.connect((configuration.get_search_server_ip(), \
>>               configuration.get_search_server_port()))
>>             sock.close()
>>             return 1
>>         except socket.error:
>>             return 0
>>     def run_oracle(self):
>>         thread.start_new_thread(\
>>           self.check_and_appropriately_update_stored_information, ())
>>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>>         sock.bind(("", configuration.get_search_server_port()))
>>         sock.listen(5)
>>         while 1:
>>             try:
>>                 newsocket, address = sock.accept()
>>                 thread.start_new_thread(self.run_oracle_thread, 
>> (newsocket, \
>>                   address))
>>             except socket.error:
>>                 sock.close()
>>                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>                 sock.setsockopt(socket.SOL_SOCKET, 
>> socket.SO_REUSEADDR, 1)
>>                 sock.bind(("", configuration.get_search_server_port()))
>>                 sock.listen(5)
>>     def run_oracle_thread(sock, address):
>>         """Reads a CGI or other header variable alone on a line, 
>> format like
>>             cgi_value <HTML form element name>
>>             environmental_variable REMOTE_ADDR
>>         and then a pickled value. There is exactly one space between 
>> the two
>>         elements, and neither element may contain a space"""
>>         sockIn = sock.makefile("wb")
>>         sockOut = sock.makefile("r")
>>         sock.close()
>>         line = sockIn.readline()
>>         while line:
>>             if get_thread_specific_storage()["cgi"] == None:
>>                 get_thread_specific_storage()["cgi"] = {}
>>             if 
>> get_thread_specific_storage()["environmental_variables"] == \
>>               None:
>>
>> get_thread_specific_storage()["environmental_variables"] = {}
>>             cgi = get_thread_specific_storage["cgi"]
>>             environmental_variables = \
>>               get_thread_specific_storage["environmental_variables"]
>>             line = re.sub("[\r\n]+", "", line)
>>             if line != "":
>>                 query_line = re.split("\s+", line)
>>                 input_type = query_line[0]
>>                 input_name = query_line[1]
>>                 if input_type == "cgi_value":
>>                     cgi[input_name] = cPickle.load(sockIn)
>>                 elif input_type == "environmental_variables":
>>                     environmental_variables[input_name] = 
>> cPickle.load(sockIn)
>>                 line = sockIn.readline()
>>             else:
>>                 generate_output()
>>                 print_output(sockOut)
>>         sockIn.close()
>>         sockOut.close()
>>     def start_oracle(self):
>>         try:
>>             first_pid = os.fork()
>>         except OSError, e:
>>             log_error("Failed to make first fork for oracle. Error: " 
>> + \
>>               e.strerror)
>>             return
>>         if first_pid == 0:
>>             os.chdir("/")
>>             os.setsid()
>>             os.umask(066)
>>             try:
>>                 second_pid = os.fork()
>>             except OSError, e:
>>                 log_error("Failed to make second fork for oracle. 
>> Error: " + \
>>                   e.strerror)
>>                 return
>>             if second_pid == 0:
>>                 self.run_oracle()
>>             else:
>>                 sys.exit(0)
>>
>>
>


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com




From pythontutor@venix.com  Fri Aug  1 18:08:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Aug  1 17:08:02 2003
Subject: GROT 239: Re: [Tutor] Bug with fork / socket from CGI
In-Reply-To: <3F2AC869.2010007@pobox.com>
References: <3F2AAD87.1020104@pobox.com> <3F2AB64B.1040705@venix.com> <3F2AC869.2010007@pobox.com>
Message-ID: <3F2AD688.6070100@venix.com>

 >>>         sock.close()
Looking at the source code, error 9 comes from a closedsocket object.
     class _closedsocket:
         def __getattr__(self, name):
             raise error(9, 'Bad file descriptor')

You can't close sock and then use it to make the connection.

Jonathan Hayward http://JonathansCorner.com wrote:

> Lloyd Kvam wrote:
> 
>> I did not attempt to figure out your problem,  the cgitb module with
>> its traceback facility usually helps a great deal with debugging an
>> errant cgi script.
> 
> 
> When I used cgitb, it gave errno 9, 'Bad file descriptor' to this line:
> 
>            sock.connect((configuration.get_search_server_ip(), \
>              configuration.get_search_server_port()))
> 
> Evaluated, that comes to:
> 
> sock.connect(("127.0.0.1", 1374))
> 
> Cgitb has helped me know what I need to be using right, but it won't 
> explain the socket concept I'm missing--that's why I e-mailed the list. 
> Do you or anyone else on the list know what needs to be changed about 
> the socket so the above line will be corrected?
> 
> TIA
> 
>>
>> However, wouldn't it be simpler to use fastCGI or an equivalent 
>> connection
>> between the web server and the persistent process?
> 
> 
> I looked in to it. That's great if I want to have my private server 
> running things, but I want to have something that people can install PnP 
> without repeating the extras I set up.
> 
>>
>>>     def get_page_from_oracle(self):
>>>         self.check_and_start_oracle()
>>>         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>>         sockIn = sock.makefile("r")
>>>         sockOut = sock.makefile("wb")
>>>         sock.close()
>>>         try:
>>>             sock.connect((configuration.get_search_server_ip(), \
>>>               configuration.get_search_server_port()))
>>>             for current_environment_key in os.environ.keys():
>>>                 sockOut.write("environmental_variable " + \
>>>                   current_environment_key + "\r\n")
>>>                 cPickle.dump(os.environ[current_environment_key], 
>>> sockOut)
>>>             for cgi_key in cgi.FieldStorage().keys():
>>>                 sockOut.write("cgi_value " + cgi_key + "\r\n")
>>>                 cPickle.dump(cgi.FieldStorage[cgi_key])
>>>             sockOut.write("\r\n")
>>>             result = cPickle.load(sockIn)
>>>             sockOut.close()
>>>             sockIn.close()
>>>         except socket.error, e:
>>>             return "Content-type: text/html\n\n<h1>There was an error 
>>> loading this page.</h1>" + str(e)
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From vijayram_groups@yahoo.com  Fri Aug  1 19:50:03 2003
From: vijayram_groups@yahoo.com (Vijayram Gopu)
Date: Fri Aug  1 18:50:03 2003
Subject: [Tutor] Problem
Message-ID: <20030801224932.94943.qmail@web10008.mail.yahoo.com>

--0-1143195001-1059778172=:94937
Content-Type: text/plain; charset=us-ascii

Hello,
 
 I want to write a script which should do the following things:
 
- Read email address from a file and place it in the To address bar.
- Print Hello in the Subject bar.
- Access a file from a directory and attach it to th email.
- Read a text file and copy the message in the text file and copy it in the message area of the email.
- Save it in the outlook box.
 
The outlook box then sends over the email to the email address specified.
 
Can I achieve these using Python scripting.. If yes how can we achieve it... I am very new to Python language.. practically know nothing about its syntax etc.
 
Can anybody suggest how to start it and how to achieve the above task.... I would greatly appreciate if anybody can help me in this regard..
 
Thankx,
 
Vijayram Gopu.
 


---------------------------------
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
--0-1143195001-1059778172=:94937
Content-Type: text/html; charset=us-ascii

<DIV>Hello,</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;I want to write a script which should do the following things:</DIV>
<DIV>&nbsp;</DIV>
<DIV>- Read email address from a file and place it in the To address bar.</DIV>
<DIV>- Print Hello in the Subject bar.</DIV>
<DIV>- Access a file from a directory and attach it to th email.</DIV>
<DIV>- Read a text file and copy the message in the text file and copy it in the message area of the email.</DIV>
<DIV>- Save it in the outlook box.</DIV>
<DIV>&nbsp;</DIV>
<DIV>The outlook box then sends over the email to the email address specified.</DIV>
<DIV>&nbsp;</DIV>
<DIV>Can I achieve these using Python scripting.. If yes how can we achieve it... I am very new to Python language.. practically know nothing about its syntax etc.</DIV>
<DIV>&nbsp;</DIV>
<DIV>Can anybody suggest how to start it and how to achieve the above task.... I would greatly appreciate if anybody can help me in this regard..</DIV>
<DIV>&nbsp;</DIV>
<DIV>Thankx,</DIV>
<DIV>&nbsp;</DIV>
<DIV>Vijayram Gopu.</DIV>
<DIV>&nbsp;</DIV><p><hr SIZE=1>
Do you Yahoo!?<br>
<a href="http://us.rd.yahoo.com/evt=10469/*http://sitebuilder.yahoo.com">Yahoo! SiteBuilder</a> - Free, easy-to-use web site design software
--0-1143195001-1059778172=:94937--


From jeff@ccvcorp.com  Fri Aug  1 20:09:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Aug  1 19:09:01 2003
Subject: [Tutor] Problem
References: <20030801224932.94943.qmail@web10008.mail.yahoo.com>
Message-ID: <3F2AF31D.7080906@ccvcorp.com>

Vijayram Gopu wrote:

> Hello,
>  
>  I want to write a script which should do the following things:
>  
> - Read email address from a file and place it in the To address bar.
> - Print Hello in the Subject bar.
> - Access a file from a directory and attach it to th email.
> - Read a text file and copy the message in the text file and copy it 
> in the message area of the email.
> - Save it in the outlook box.
>  
> The outlook box then sends over the email to the email address specified.
>  
> Can I achieve these using Python scripting.. If yes how can we achieve 
> it... I am very new to Python language.. practically know nothing 
> about its syntax etc.


If you need to get Outlook to send an email, then you'll need to look 
into PythonCOM.  Outlook can be loaded as a COM server and given 
instructions -- this is how VB/VBscript control Outlook (and many other 
applications, including the entire Office suite).  You'll need to look 
through the documentation for PythonCOM, which is part of the win32all 
package.  I'd also recommend trying to get your hands on a copy of 
"Python Programming on Win32", by Marc Hammond & Andy Robinson.  It has 
lots of examples of COM and Office scripting.  For specifics on how to 
direct Outlook, you'll need to look at the Visual Basic Help included 
with Outlook itself.  That will tell you how to control Outlook from VB; 
you'll need to translate this to Python yourself, but it's mostly 
straightforward (and the gotchas are discussed in the aforementioned book).

On the other hand, if you just need to assemble & send email, it's 
probably simpler to "roll your own" than it is to control Outlook, 
thanks to Python's "batteries included" library.  With the email package 
and the smtplib module, it's fairly straightforward to create & send email.

Jeff Shannon
Technician/Programmer
Credit International




From alan.gauld@blueyonder.co.uk  Fri Aug  1 20:21:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  1 19:21:02 2003
Subject: [Tutor] Problem
References: <20030801224932.94943.qmail@web10008.mail.yahoo.com>
Message-ID: <012801c35883$93d78140$6401a8c0@xp>

> - Read email address from a file and place it in the To address bar.

Needs text processing, depends on format of file but builtin string
methods may suffice. Failing that the regular expression module 're'
may be needed

> - Print Hello in the Subject bar.

Depends on the GUI toolkit and Operating System.

> - Access a file from a directory and attach it to th email.

Look at the  mime module

> - Read a text file and copy the message in the text file and
> copy it in the message area of the email.

I think this is the new email module

> - Save it in the outlook box.

Ah Outlook, not real email then... You need the winall package
to talk to COM.

> The outlook box then sends over the email to the email address
specified.

Easier done directly from Python using the email module but if
you must drive Outlook then its the winall package again.

> Can I achieve these using Python scripting..

yes

> If yes how can we achieve it...

See the modules cited above. - read their documentation and
learn how to use Python. If you already know a programming
language the standard included tutor is all you need.

> Can anybody suggest how to start it

Type python at a DOS prompt if using Windoze, or in an xterm on Linux.
Click the icon in a Mac...

Or try Danny yoo's tutorial on IDLE for any of them...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From mlong@datalong.com  Fri Aug  1 20:34:02 2003
From: mlong@datalong.com (Michael Long)
Date: Fri Aug  1 19:34:02 2003
Subject: [Tutor] Problem
Message-ID: <E19ijP6-0006S7-2l@server18.pronicsolutions.com>

I am currently doing something similar without the attachement. The
following should get you started.

import smptlib
from email.MIMETest import MIMEText
msg = "The is the message in the body of the email"
msg = MIMEText(msg)
msg['Subject'] = "This is the subject line"
msg['From'] = "me@mydomain.com" # you will need the smtp email address 
                                # of your outlook account
msg['To'] = "someone@somewhere.com"
s = smtplib.SMTP("myOutlookServer")
s.login("mylogin", "mypasswd")
s.sendmail("me@mydomain.com",["someone@somewhere.com"],msg.as_string())
s.quit

> 
> Hello,
>  
>  I want to write a script which should do the following things:
>  
> - Read email address from a file and place it in the To address bar.
> - Print Hello in the Subject bar.
> - Access a file from a directory and attach it to th email.
> - Read a text file and copy the message in the text file and copy it
in the message area of the email.
> - Save it in the outlook box.
>  
> The outlook box then sends over the email to the email address specified.
>  
> Can I achieve these using Python scripting.. If yes how can we achieve
it... I am very new to Python language.. practically know nothing about
its syntax etc.
>  
> Can anybody suggest how to start it and how to achieve the above
task.... I would greatly appreciate if anybody can help me in this regard..
>  
> Thankx,
>  
> Vijayram Gopu.
>  
> 
> 
> ---------------------------------
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free, easy-to-use web site design software
> 




From jlohman@cox.net  Sat Aug  2 00:38:02 2003
From: jlohman@cox.net (Jeff Lohman)
Date: Fri Aug  1 23:38:02 2003
Subject: [Tutor] Problem
In-Reply-To: <20030801224932.94943.qmail@web10008.mail.yahoo.com>
Message-ID: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>

This is a multi-part message in MIME format.

------=_NextPart_000_00B3_01C3586C.AFE41AE0
Content-Type: text/plain;
	charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Wait...isn't he just describing a SPAM program?

-Jeff
  -----Original Message-----
  From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Vijayram Gopu
  Sent: Friday, August 01, 2003 3:50 PM
  To: tutor@python.org
  Subject: [Tutor] Problem


  Hello,

   I want to write a script which should do the following things:

  - Read email address from a file and place it in the To address bar.
  - Print Hello in the Subject bar.
  - Access a file from a directory and attach it to th email.
  - Read a text file and copy the message in the text file and copy it in the message area of the
email.
  - Save it in the outlook box.

  The outlook box then sends over the email to the email address specified.

  Can I achieve these using Python scripting.. If yes how can we achieve it... I am very new to
Python language.. practically know nothing about its syntax etc.

  Can anybody suggest how to start it and how to achieve the above task.... I would greatly
appreciate if anybody can help me in this regard..

  Thankx,

  Vijayram Gopu.



------------------------------------------------------------------------------
  Do you Yahoo!?
  Yahoo! SiteBuilder - Free, easy-to-use web site design software

------=_NextPart_000_00B3_01C3586C.AFE41AE0
Content-Type: text/html;
	charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<META content=3D"MSHTML 6.00.2800.1126" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D062443603-02082003>Wait...isn't he just describing a SPAM=20
program?</SPAN></FONT></DIV>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D062443603-02082003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D062443603-02082003>-Jeff</SPAN></FONT></DIV>
<BLOCKQUOTE=20
style=3D"PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px =
solid">
  <DIV class=3DOutlookMessageHeader dir=3Dltr align=3Dleft><FONT =
face=3DTahoma=20
  size=3D2>-----Original Message-----<BR><B>From:</B> =
tutor-admin@python.org=20
  [mailto:tutor-admin@python.org]<B>On Behalf Of </B>Vijayram=20
  Gopu<BR><B>Sent:</B> Friday, August 01, 2003 3:50 PM<BR><B>To:</B>=20
  tutor@python.org<BR><B>Subject:</B> [Tutor] =
Problem<BR><BR></FONT></DIV>
  <DIV>Hello,</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>&nbsp;I want to write a script which should do the following=20
things:</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>- Read email address from a file and place it in the To address=20
bar.</DIV>
  <DIV>- Print Hello in the Subject bar.</DIV>
  <DIV>- Access a file from a directory and attach it to th email.</DIV>
  <DIV>- Read a text file and copy the message in the text file and copy =
it in=20
  the message area of the email.</DIV>
  <DIV>- Save it in the outlook box.</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>The outlook box then sends over the email to the email address=20
  specified.</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>Can I achieve these using Python scripting.. If yes how can we =
achieve=20
  it... I am very new to Python language.. practically know nothing =
about its=20
  syntax etc.</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>Can anybody suggest how to start it and how to achieve the above =
task....=20
  I would greatly appreciate if anybody can help me in this =
regard..</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>Thankx,</DIV>
  <DIV>&nbsp;</DIV>
  <DIV>Vijayram Gopu.</DIV>
  <DIV>&nbsp;</DIV>
  <P>
  <HR SIZE=3D1>
  Do you Yahoo!?<BR><A=20
  =
href=3D"http://us.rd.yahoo.com/evt=3D10469/*http://sitebuilder.yahoo.com"=
>Yahoo!=20
  SiteBuilder</A> - Free, easy-to-use web site design=20
software</BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_00B3_01C3586C.AFE41AE0--



From carroll@tjc.com  Sat Aug  2 00:41:18 2003
From: carroll@tjc.com (Terry Carroll)
Date: Fri Aug  1 23:41:18 2003
Subject: [Tutor] Which Python?
Message-ID: <Pine.LNX.4.44.0308012031530.4487-100000@violet.rahul.net>

I'm a Windows XP user, primarily (occasional Linux use).

I use Activestate's ActivePython, 2.2.2.  My major reason is that I 
used to use ActivePerl a lot, and when I decided to give Python a whirl, 
it seemed logical to use ActivePython.

Now that Python 2.3 is out, I'm looking ahead to when I'm going to cut 
over to 2.3, and I'm wondering: what are the reasons to install either 
ActivePython (when 2.3 becomes available) or the standard Windows Python 
from python.org?

Any opinions?

ActivePython:
 http://www.activestate.com/Products/ActivePython/

Python.org:
 http://www.python.org/2.3/

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982




From tbstep@tampabay.rr.com  Sat Aug  2 01:04:03 2003
From: tbstep@tampabay.rr.com (Todd Stephens)
Date: Sat Aug  2 00:04:03 2003
Subject: [Tutor] Problem
In-Reply-To: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
References: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
Message-ID: <200308020000.19607@toddloki>

On Friday 01 August 2003 11:37 pm, Jeff Lohman wrote:

> Wait...isn't he just describing a SPAM program?

That was my first thought.  Actually, since Outlook was specified, my first 
thought was 'how to mass-mail a virus', but I'm just a suspicious cynic :)

-- 
Todd Stephens



From olof.krantz@telia.com  Sat Aug  2 06:34:02 2003
From: olof.krantz@telia.com (Olof Krantz)
Date: Sat Aug  2 05:34:02 2003
Subject: [Tutor] Problem
In-Reply-To: <200308020000.19607@toddloki>
References: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
 <200308020000.19607@toddloki>
Message-ID: <1059816745.2636.0.camel@laptop.krantz.se>

Actually it was my first thought too...

On Sat, 2003-08-02 at 06:00, Todd Stephens wrote:
> On Friday 01 August 2003 11:37 pm, Jeff Lohman wrote:
> 
> > Wait...isn't he just describing a SPAM program?
> 
> That was my first thought.  Actually, since Outlook was specified, my first 
> thought was 'how to mass-mail a virus', but I'm just a suspicious cynic :)



From mwagman@charter.net  Sat Aug  2 09:12:01 2003
From: mwagman@charter.net (Mike Wagman)
Date: Sat Aug  2 08:12:01 2003
Subject: [Tutor] Problem
In-Reply-To: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
References: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
Message-ID: <1059826369.2432.1.camel@24-159-241-21.jvl.wi.charter.com>

If the file is a py2exe executable packaged in one file he is describing
a virus.

On Fri, 2003-08-01 at 22:37, Jeff Lohman wrote:
> Wait...isn't he just describing a SPAM program?
>  
> -Jeff
>         -----Original Message-----
>         From: tutor-admin@python.org [mailto:tutor-admin@python.org]On
>         Behalf Of Vijayram Gopu
>         Sent: Friday, August 01, 2003 3:50 PM
>         To: tutor@python.org
>         Subject: [Tutor] Problem
>         
>         
>         Hello,
>          
>          I want to write a script which should do the following
>         things:
>          
>         - Read email address from a file and place it in the To
>         address bar.
>         - Print Hello in the Subject bar.
>         - Access a file from a directory and attach it to th email.
>         - Read a text file and copy the message in the text file and
>         copy it in the message area of the email.
>         - Save it in the outlook box.
>          
>         The outlook box then sends over the email to the email address
>         specified.
>          
>         Can I achieve these using Python scripting.. If yes how can we
>         achieve it... I am very new to Python language.. practically
>         know nothing about its syntax etc.
>          
>         Can anybody suggest how to start it and how to achieve the
>         above task.... I would greatly appreciate if anybody can help
>         me in this regard..
>          
>         Thankx,
>          
>         Vijayram Gopu.
>          
>         
>         
>         ______________________________________________________________
>          Do you Yahoo!?
>         Yahoo! SiteBuilder - Free, easy-to-use web site design
>         software



From mwagman@charter.net  Sat Aug  2 09:14:02 2003
From: mwagman@charter.net (Mike Wagman)
Date: Sat Aug  2 08:14:02 2003
Subject: [Tutor] Email encryption
Message-ID: <1059826537.2431.5.camel@24-159-241-21.jvl.wi.charter.com>

I have been writing an app for my brother (so yes I am a hobbiest
programmer), He is a director of nursing, it generates some patient
related paperwork that he finds useful. However he would like to add an
email capability to the program so an employee somewhere else could send
him that information. 

I need to encrypt/decrypt information (files) by email can any one help
me.  



From pythontutor@venix.com  Sat Aug  2 09:38:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat Aug  2 08:38:02 2003
Subject: [Tutor] Email encryption
In-Reply-To: <1059826537.2431.5.camel@24-159-241-21.jvl.wi.charter.com>
References: <1059826537.2431.5.camel@24-159-241-21.jvl.wi.charter.com>
Message-ID: <3F2BB076.7010309@venix.com>

http://www.amk.ca/python/code/crypto.html
Python Cryptography Toolkit

This should have what you need.  The builtin python encryption is a
bit weak.

(I presume that dates back to US export controls on encryption.)

Mike Wagman wrote:

> I have been writing an app for my brother (so yes I am a hobbiest
> programmer), He is a director of nursing, it generates some patient
> related paperwork that he finds useful. However he would like to add an
> email capability to the program so an employee somewhere else could send
> him that information. 
> 
> I need to encrypt/decrypt information (files) by email can any one help
> me.  
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From goki75@vsnl.net  Sat Aug  2 09:43:01 2003
From: goki75@vsnl.net (G Kiran)
Date: Sat Aug  2 08:43:01 2003
Subject: [Tutor] No Console
Message-ID: <000101c358f3$8268cf70$a94c41db@VULCAN>

Hello,

 How do i write a python program which does not run in a console in windows

i mean want it to run it in background   in windows...

...i can't fork out a new process like we do in unix and end the parent
exiting the shell

thanx

-kiran



From jpaish@freenet.edmonton.ab.ca  Sat Aug  2 09:57:01 2003
From: jpaish@freenet.edmonton.ab.ca (Joseph Paish)
Date: Sat Aug  2 08:57:01 2003
Subject: [Tutor] is it possible to embed data inside a script?
In-Reply-To: <3F1B5B5B.7090302@netzero.net>
References: <03071907470600.01312@localhost.localdomain> <3F1B5B5B.7090302@netzero.net>
Message-ID: <03080206594600.01475@localhost.localdomain>

On Sunday 20 July 2003 21:17, Kirk Bailey wrote:
> Sure thing.
>
> domainname=3D"tinylist.org"
> password=3D"swordfish"
> id=3D"idiot1@netzero.net"
>
> simple enough, but wait, there's more!
>
> array1()=3D'2','3','3','4','4','4','5','5','5','5','6','6','6','6','6',=
'7','7
>','7','7','7','7',...
>
> (2dice, 6 sides, in a matrix. Use ramdom.choice to pick one of them.
> Weighted correctly for 2s6)
>
> These are simplistic examples, but sure, data is just data. You can ass=
ign
> it to any variable type in a declaration whenever you like.
>
> Now, when this means a LOT of data, thing can get boring and real easy =
to
> get mixed up in the programmer's mind. Ever see a program with several
> HUNDRED DATA statements, read by a READ statement? When you go in to ch=
ange
> something, it is EASY to get totally lost, espically when it is a progr=
am
> which does not number lines.
>
> Why  is it important to store a lot of data IN the program?

not really that important.  just trying to clear up a couple dozen short=20
scripts each of which has about 10 lines of data.  that way i can cut dow=
n on=20
the number of tiny files that i have built up over the years.

joe
=20


From pythontutor@venix.com  Sat Aug  2 10:02:03 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat Aug  2 09:02:03 2003
Subject: [Tutor] No Console
In-Reply-To: <000101c358f3$8268cf70$a94c41db@VULCAN>
References: <000101c358f3$8268cf70$a94c41db@VULCAN>
Message-ID: <3F2BB600.2020002@venix.com>

If you use the extension .pyw or explicitly use pythonw, rather than python
to execute the script, no window is created.  The normal windows behavior
(at least in NT,2K,XP) in a command file, should be to kick off the program
and then immediately continue execution within the command file.  Effectively,
your python script is in the background.  To make it a Windows Service, is
a bit more work, but well documented in "Python Programming on Win32".


G Kiran wrote:

> Hello,
> 
>  How do i write a python program which does not run in a console in windows
> 
> i mean want it to run it in background   in windows...
> 
> ...i can't fork out a new process like we do in unix and end the parent
> exiting the shell
> 
> thanx
> 
> -kiran
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From llazarre@yahoo.com  Sat Aug  2 13:39:01 2003
From: llazarre@yahoo.com (Levy Lazarre)
Date: Sat Aug  2 12:39:01 2003
Subject: [Tutor] Using a dictionary to keep a count
Message-ID: <20030802163759.13666.qmail@web40412.mail.yahoo.com>

Hello all,

I am trying to write a script that will read a log
file and count the number of times each CGI script has
been accessed by a particular site. I am using a
dictionary to keep the counts per script, but there
must be a logic error since the final counts are
wrong. Can somebody please point me to the right
direction? I can make it work using a List approach
but I believe that a dictionary will be more
efficient.

Here are the sample input file(access_log) and the
Python script(logParse.py):

############## access_log ####################### 
alpha.umn.edu --[24/Feb/1997:09:03:50 -0700] "POST
/cgi-bin/script1.cgi HTTP /
alpha.umn.edu --[24/Feb/1997:09:04:15 -0700] "POST
/cgi-bin/script1.cgi HTTP /
mcgraw.com --[24/Feb/1997:09:04:22 -0700] "POST
/cgi-bin/script2.cgi HTTP /
rohcs.ats.com --[24/Feb/1997:09:04:34 -0700] "POST
/cgi-bin/script2.cgi HTTP /
rohcs.ats.com --[24/Feb/1997:09:04:34 -0700] "POST
/cgi-bin/script1.cgi HTTP /
idg.com --[24/Feb/1997:09:05:35 -0700] "POST
/cgi-bin/script2.cgi HTTP /
##################################################

################################ logParse.py
######################################
# logParse.py
# Test program read a log file and track the number of
times some scripts have been accessed 
# by specific sites.
# This is the dictionary/dictionary approach.
###############

# This function is used to extract the script name and
the address from each line. Since the
# structure of the line is well defined, this can be
done without using regular expressions. 
# Sample line:
# alpha.umn.edu --[24/Feb/1997:09:03:50 -0700] "POST
/cgi-bin/script1.cgi HTTP /
   
def process_line(aline):
 	address = aline.split('--')[0].strip()  # split at
'--' and get first piece
 	rest = aline.split("POST")[1].strip()   # split at
'POST' to get the distal portion.
 	script = rest.split()[0]                # split that
piece at the whitespace before 'HTTP'
 	                                        # and the
script is the first fragment.
 	return (script, address)                # return
both elements in a tuple     

####################### Main Program
#######################

# Initialize a dictionary that will contain the
scripts as keys and the sites as values.
dict ={} 

# Read the file line by line and extract the script
name and the address.
for line in file('access_log'):
    script, address = process_line(line)   
    # Add the script to the dictionary as a key if not
already in there, otherwise just add
    # the address as a value in a dictionary for the
key:
    dict.setdefault(script, {})[address] = 1
    
    # if the address had already been seen for the
same key, we must increment its count:
    if address in dict[script].keys():
        dict[script][address] += 1

# Now print the dictionary to verify what we have
done:

for key in dict.keys():
    print key, " => "
    for value in dict[key].keys():
        print value,":", dict[key][value]
     
    print "\n"    
################################### End
###################################

Thanks,
Levy Lazarre        
                                     

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com


From shalehperry@comcast.net  Sat Aug  2 14:49:02 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Sat Aug  2 13:49:02 2003
Subject: [Tutor] Using a dictionary to keep a count
In-Reply-To: <20030802163759.13666.qmail@web40412.mail.yahoo.com>
References: <20030802163759.13666.qmail@web40412.mail.yahoo.com>
Message-ID: <200308021048.21501.shalehperry@comcast.net>

On Saturday 02 August 2003 09:37, Levy Lazarre wrote:
>     # Add the script to the dictionary as a key if not
> already in there, otherwise just add
>     # the address as a value in a dictionary for the
> key:
>     dict.setdefault(script, {})[address] = 1
>
>     # if the address had already been seen for the
> same key, we must increment its count:
>     if address in dict[script].keys():
>         dict[script][address] += 1
>

>>> d.setdefault('foo', {})['bar'] = 1
>>> if 'bar' in d['foo'].keys(): 
...     d['foo']['bar'] += 1
... 
>>> d
{'foo': {'bar': 2}}
>>> d.setdefault('foo', {})['bar'] = 1
>>> d
{'foo': {'bar': 1}}

note, every time your setdefault is called you are resetting the counter.



From sigurd@12move.de  Sat Aug  2 16:10:01 2003
From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Aug  2 15:10:01 2003
Subject: [Tutor] Using a dictionary to keep a count
In-Reply-To: <20030802163759.13666.qmail@web40412.mail.yahoo.com> (Levy
 Lazarre's message of "Sat, 2 Aug 2003 09:37:59 -0700 (PDT)")
References: <20030802163759.13666.qmail@web40412.mail.yahoo.com>
Message-ID: <m31xw3or6c.fsf@hamster.pflaesterer.de>

On  2 Aug 2003, Levy Lazarre <- llazarre@yahoo.com wrote:

> direction? I can make it work using a List approach
> but I believe that a dictionary will be more
> efficient.

That's right.

Three things:
(a) Please try to convince your email client to *not* break lines of
    source code.  They are hard to read

> Here are the sample input file(access_log) and the
> Python script(logParse.py):

[...]

> # Initialize a dictionary that will contain the
> scripts as keys and the sites as values.
> dict ={} 

(b) It is no good idea to shadow Python buildins; dict is a builtin
    command so better name your dictionary different (eg. dic)

> # Read the file line by line and extract the script
> name and the address.
> for line in file('access_log'):
>     script, address = process_line(line)   
>     # Add the script to the dictionary as a key if not
> already in there, otherwise just add
>     # the address as a value in a dictionary for the
> key:
>     dict.setdefault(script, {})[address] = 1

>     # if the address had already been seen for the
> same key, we must increment its count:
>     if address in dict[script].keys():
>         dict[script][address] += 1


I am not sure if you understand the method setdefault completely right.
With 
     d = {}
     d.setdefault('a',0)

you set the key `'a'' to zero if it doesn't already exists.  setdefault
is just a shorter way to write

   if d.has_key('a'):
       d['a'] += 1
   else:
       d['a'] = 1

With setdefault you could write

   d['a'] = d.setdefault('a',0) + 1


Completey that could be:

for line in file('access_log'):
    script, address = process_line(line)   
    dic[address] = dic.setdefault(address,0) + 1

(c) So a function to process log files and print the values could be
    written like that: 

def process_log_file(name):
    d = {}
    f = open(name)
    for line in f:
        script, address = process_line(line)
        d[address] = d.setdefault(address,0) + 1
    f.close()
    for (key, value) in d.items():
        print key, " => ", value


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list



From phthenry@earthlink.net  Sat Aug  2 20:10:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sat Aug  2 19:10:02 2003
Subject: [Tutor] discrepency when using  os.path.getsize(line)
Message-ID: <20030802231119.GA30037@localhost.localdomain>

When I use os.path.getsize, I come up with a different value than when
I use the linux command "du -sb". 

I am using these two commands in a script to backup. 

At the beginning of my script, I use:

du -sb /

in order to get the size of all the files on my hard drive. I get a
size that converts to 4.0 Gibabytes.

I then use 

find / > list

To get all the files on my hard drive. 

I then run this list through a module prun.py, in order to prune out
junk files. The paths that are pruned out go into their separate file,
called "exclude".

So now I have two files of path names. If I add up the size of the two
lists, it should equal the size from the "du -sb" command.

However, it does not. In fact, I get a difference that is as great as
+60 perecent when I test my script on a small directory. If I test the
script on my whole hard drive, I get a difference of -9 percent.

If I do a test run on a small directory, and check a CD to see that
all the files have made it to the CD, they have. So it seems that all
the files that are supposed to be backed up are getting backed up. 

It seems that the problem is that getting the size of each individul
file using os.path.getsize will yield a huge difference than when
using "du". 

Anybody have an idea of why this discrepency occurrs? 

Below is a snippet from the method that splits the "list" into 600 MB
size lists to burn to CDs. The object already has the size of the
"exclude" list, as well as the "directory_size" (the size using "du").
You can skip down to where I have commented 
# calculate difference between size in directory and the 
to see the problematic code.

Thanks

Paul

******************************************

    def __split_list(self):
        
        """
        Read from the list (the list of files), one line at a time.

        The script can write this line to the following files:

            1. The full list, if the file exists.

            2. The split list, if the file exists,

            3. The error list, if the file is not found.

        After each line is read, the size of the file is represents is calculated and added
        to 'size'. This size is also added to archive_size (see below).

        When the size is greater than the size able to fit on the CD, close the current 
        split list. Start a new split list. This technique should result in creating as
        many split lists (numbered), as there will be CDs burned.

        The CD size varies if the --append option is used. For the first CD, the size will 
        be the default size (such as 600), minus the size of the archive already on the CD.

        In addition to keeping track of the size of chunks of files for each
        CD, the method also keeps track of the archive_size, or the total size
        of all the files in the list. This size  plus the self.__exclude
        size should equal the self.__directory_size (the size of calculated by
        du -sb.




        """

        full_list = os.path.join(self.__write_dir, 'full_list')
        if self.__verbose:
            sys.stdout.write('Splitting the large files into chunks...\n')
        self.__log.message('Splitting the text file into chunks...')
        size = 0
        archive_size = 0
        list_counter = 0
        num_counter = 0
        list_counter = self.__disk  #  string counter
        num_counter = self.__disk  #  number counter
	list_counter = '%04d' % list_counter
        output = os.path.join(self.__write_dir, 'split_list.%s' % list_counter)
        full_list = os.path.join(self.__write_dir, 'full_list')
        errors = os.path.join(self.__write_dir, 'errors')
        read_obj = open(self.__list_of_files, 'r')
        write_split = open(output, 'w')
        write_full = open(full_list, 'a')
        write_errors = open(errors, 'w')
        write_errors.write('<file_exists_errors>\n')

        # don't write <disk num = "xx"> label for append files since it is already there.
        if not self.__append:
            write_full.write('<disk num = "%s">\n' % list_counter)

        write_full.write('<date date = "%s">\n' % self.__date_string)
        line_to_read = 1
        self.__log.message("""Script will read one line at a time from "%s"
It chops off the last newline, then treats the line of text like  file.
It gets the size of the file, and adds it to a counter.
When the counter is greater than the CD size, a new list is started.
All files are written to full_list.
""" % self.__list_of_files)
        while line_to_read:
            if num_counter - self.__disk == 0:
                this_cd_size = self.__first_cd_size
            else:
                this_cd_size = self.__cd_size
            line_to_read = read_obj.readline()
            line = line_to_read[:-1]
            file_exists = os.path.isfile(line)
            if not line:
                continue
            if file_exists:
                file_size = os.path.getsize(line)
                size += file_size
                archive_size += file_size
            else:
                file_size = 0
            if size/1000000 > this_cd_size:
                write_full.write('</date>\n' )
                write_full.write('</disk>\n' )
                list_counter = int(list_counter)
                list_counter += 1
                num_counter += 1
                list_counter = '%04d' % list_counter
                write_full.write('<disk num = "%s">\n' % list_counter)
                write_full.write('<date date = "%s">\n' % self.__date_string)
                write_split.close()
                output = os.path.join(self.__write_dir, 'split_list.%s' % list_counter)
                write_split = open(output, 'w')
                size = file_size
            write_split.write('%s\n' % line)
            write_full.write('%s\n' % line)
        write_full.write('</date>\n' )
        write_full.write('</disk>\n' )
        write_errors.write('</file_exists_errors>\n')
        write_full.close()
        read_obj.close()
        write_errors.close()


        # calculate difference between size in directory and the 
        # files excluded plus the files being backed up
        # difference should be close to zero
        ds = float(self.__directory_size)
        as = float(archive_size)
        es = float(self.__exclude_size)
        if ds != 0:
            the_diff = ds - (es + as)
            percentage_diff = the_diff/self.__directory_size
            percentage_diff = round(percentage_diff * 100)
            percentage_diff = int(percentage_diff)
            self.__log.message('There are %s pecentage less files in the archive than on the hard drive.\n' % 
                percentage_diff)
            if not self.__quiet:
                sys.stdout.write('There are %s pecentage less files in the archive than on the hard drive.\n' % 
                percentage_diff)
        else:
            self.__log.message('Disk size is 0. User probably choose not to calculate size\n')
    



-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************


From idiot1@netzero.net  Sat Aug  2 20:24:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Aug  2 19:24:01 2003
Subject: [Tutor] wiki madness- it's contagious, want to get infected?
Message-ID: <3F2C47EC.6040600@netzero.net>

ok, this means it's time for me to learn some re lore, I expect.

I am trying to write a wiki. I have a lot of basic functionality going, 
and the overall skeleton is there, and working. HALF of the page editor 
is even complete!

What is holding me  back is parsing the wikicode into html. SOME of this 
code uses unique flags, so can be swapped with a strong.replace 
statement for that-   in effect, a rule.

But some of this demands that a tag be replaced 2 different ways, 
turning on or off a function. For instance, "'''" (3 'singlequotes') not 
only turns ON bold print, it turns it off again- it is a state toggle.

Therefore, the guts of a page must be read through sequentially, 
previous state alters response to a detected tag.

This does not seem to lend itself to the use of any number of 
string.replace(page, searchtarget, replacementstring)
statements.

WORSE, established wikicode uses PART of one tag as another tag, so we 
have to do searches in a sequence, preserving state and intermediate 
results. For instance, "'''" toggles bold. But "''" toggles italics! 
Were you to go in and search for italica first, you would rip apart a 
lot of bold tags, and leave some leftover 'singlequotes', messing things 
up no small amount. Another: "----" is a size 2 HR. ----- is a size 3 
hr. Some fun, huh?

Anyone out there want to play? I have built a list for discussing this.
	http://www.tinylist.org/cgi-bin/TLwebform2.py?wiki-project
leads directly to the membership management form.

Also, note that there is an older wiki (piki) on the site.
	http://www.tinylist.org/cgi-bin/piki.py
An area there directly acessable from the front page leads to the 
project page(s). Anyone, feel free to dive in.

When up to snuff sufficently, this program will be released under the 
GNU GPL, $free$. This is not a for profit project, it is a for people 
project.



-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From rick@niof.net  Sat Aug  2 20:27:02 2003
From: rick@niof.net (Rick Pasotto)
Date: Sat Aug  2 19:27:02 2003
Subject: [Tutor] discrepency when using  os.path.getsize(line)
In-Reply-To: <20030802231119.GA30037@localhost.localdomain>
References: <20030802231119.GA30037@localhost.localdomain>
Message-ID: <20030802233145.GI17226@niof.net>

On Sat, Aug 02, 2003 at 07:11:19PM -0400, Paul Tremblay wrote:
> When I use os.path.getsize, I come up with a different value than when
> I use the linux command "du -sb". 
> 
> I am using these two commands in a script to backup. 
> 
> At the beginning of my script, I use:
> 
> du -sb /
> 
> in order to get the size of all the files on my hard drive. I get a
> size that converts to 4.0 Gibabytes.
> 
> I then use 
> 
> find / > list
> 
> To get all the files on my hard drive. 
> 
> I then run this list through a module prun.py, in order to prune out
> junk files. The paths that are pruned out go into their separate file,
> called "exclude".
> 
> So now I have two files of path names. If I add up the size of the two
> lists, it should equal the size from the "du -sb" command.
> 
> However, it does not. In fact, I get a difference that is as great as
> +60 perecent when I test my script on a small directory. If I test the
> script on my whole hard drive, I get a difference of -9 percent.
> 
> If I do a test run on a small directory, and check a CD to see that
> all the files have made it to the CD, they have. So it seems that all
> the files that are supposed to be backed up are getting backed up. 
> 
> It seems that the problem is that getting the size of each individul
> file using os.path.getsize will yield a huge difference than when
> using "du". 
> 
> Anybody have an idea of why this discrepency occurrs? 

Have you taken into account links -- both hard and soft?

Another thing to consider is that 'du' reports the actual disk usage so
if your disk blocks are 1k then eight little 128 byte files will total
only 1024 bytes but will actually use 8 * 1024 = 8192 bytes.

-- 
"Moderation in temper is always a virtue; but moderation in principle
 is always a vice." -- Thomas Paine, _The Rights of Man_ (1791)
    Rick Pasotto    rick@niof.net    http://www.niof.net


From idiot1@netzero.net  Sat Aug  2 22:46:11 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Aug  2 21:46:11 2003
Subject: [Tutor] wiki madness, an update
Message-ID: <3F2C62BD.7010505@netzero.net>

ok. Reader works except for the only part that's not trivial, the 
wikicode parser. This is a dummy function which simply spews back the 
ray body of the page, so I can test everything else.

Editor form works. Editor processing script works.

wikinehesa='talksnake'
link: http://www.tinylist.org/cgi-bin/wikinehesa.py

Defaults to front page if no page specified.

Link in footer leads to the editor page; submitting that form leads to 
the RESULT page, which aslo simply spews back the pageguts, tastefully 
sandwiched a header and footer.

Also note again we have a simple wiki working, called piki.
http://www.tinylist.org/cgi-bin/piki.py

They access THE SAME PAGE FILES so you can use the existing one to 
double check the experimental one.

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.




From clay@shirky.com  Sat Aug  2 23:57:01 2003
From: clay@shirky.com (Clay Shirky)
Date: Sat Aug  2 22:57:01 2003
Subject: [Tutor] Comments wanted on new Python introduction
In-Reply-To: <20030731225824.GA30757@nyman.amk.ca>
Message-ID: <BB51F02F.B65A%clay@shirky.com>

> A new set of introductory pages for python.org is being developed.
> The current draft of a revised version is at
> http://www.python.org/topics/learn/ .

I am learning Python, and this is certainly a better one-stop page for
learners than exists now, many thanks.

I do have two suggestions, though.

The first is that reading the Overview of Python is not really that helpful
in this context, and probably doesn't merit inclusion as the 0th item on the
list. The Overview is most useful for someone wondering "How does Python
differ from language X?", but there's a difference between wanting to learn
_about_ Python and wanting to learn Python itself, and anyone in the latter
camp has already satisfied themselves about the former.

The second suggestion is really a plea: More editorial judgment, please.

Right now, Python.org seems to have a Yahoo strategy in a Google world.
Yahoo bent over backwards to include everything they could find, and always
to return some search result, which was fine when things were sparse, but
lousy when things got crowded. Google works by *excluding* most stuff, and
strongly ranking the resulting subset.

Analogously, the problem I've had with Python beginner's guides is that
there are too many of them. Worse, I am, by definition, unqualified to be
able to evaluate them, so when I'm given an 8 item list of sites on the
"Python for Porgrammers" page, I am worse off than I was before. When I got
to Python.org, I didn't know Pthon; now I don't know Python *and* I don't
know where to start.

It would be great to get an opinionated and knowledgeable recommendation, a
sort of "We're including on this page everything we could find relevant to
the topic, but we're also recommending that non-programmers learning to
program using Python start out at site A, while those with some experience
programming start out at B."

You know this stuff far better than we do; we'd be grateful if you would
tell us what you think we should do, based on what you know and we don't.

-clay





From clay@shirky.com  Sat Aug  2 23:57:14 2003
From: clay@shirky.com (Clay Shirky)
Date: Sat Aug  2 22:57:14 2003
Subject: [Tutor] get as a way to operate on first occurrence of an element in a
 list?
In-Reply-To: <3F2C62BD.7010505@netzero.net>
Message-ID: <BB51E8AB.B657%clay@shirky.com>

This may be a perlish thought (am currently switching to python after 10
years of hacking perl), but there is an idiom I often use where I create a
blank dictionary, and then loop through a list of values that may repeat,
performing an action only on the first occurrence, then adding the value to
the dictionary, then skipping all subsequent appearances of that value by
doing the dictionary lookup.

This is a working version in python:

 for line in f:
     if line in seen_dict:
         pass
     else:
         print line,
         seen_dict[line] =3D 1

However, I had a thought that I might be able to use get on the seen_dict t=
o
do the same in a single pass, but this na=EFve attempt
       =20
 for line in f:
     if seen_dict.get(line, 1):
         print line,

fails because get assigns the default value to seen_dict[line] before the i=
f
test.

Is there a way to use get to test for a value, fail if it doesn't exist, an=
d
*then* assign a value to it? Or is my earlier and more verbose rendering th=
e
One Obvious Way?

thx,

-clay



From phthenry@earthlink.net  Sun Aug  3 00:29:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sat Aug  2 23:29:02 2003
Subject: [Tutor] discrepency when using  os.path.getsize(line)
In-Reply-To: <20030802233145.GI17226@niof.net>
References: <20030802231119.GA30037@localhost.localdomain> <20030802233145.GI17226@niof.net>
Message-ID: <20030803023116.GC30037@localhost.localdomain>

On Sat, Aug 02, 2003 at 07:31:45PM -0400, Rick Pasotto wrote:
> > 
> > It seems that the problem is that getting the size of each individul
> > file using os.path.getsize will yield a huge difference than when
> > using "du". 
> > 
> > Anybody have an idea of why this discrepency occurrs? 
> 
> Have you taken into account links -- both hard and soft?
> 
> Another thing to consider is that 'du' reports the actual disk usage so
> if your disk blocks are 1k then eight little 128 byte files will total
> only 1024 bytes but will actually use 8 * 1024 = 8192 bytes.
> 

Okay, that makes perfect sense. Although, I just ran:

du -sk => 3.9G

du -skL => 4.3G

I thought the "-L" flag dereferenced the links?

At any rate, it seems to me that there is not way I can use "du" as an
additonal test to see if I am backing up all my data. There is no way
to get around the byte size. Guess I'll have to scrap that bit of
code!

Thanks

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************


From idiot1@netzero.net  Sun Aug  3 02:42:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sun Aug  3 01:42:02 2003
Subject: [Tutor] definition question
Message-ID: <3F2CA05E.6000809@netzero.net>

I am writing a number of functions for my current project, and a thought 
occured to me: Are they objects?

No, I am not using class statements, but they are defined functions, you 
pass arguements, they sometimes return data, and they sure are useful 
for writing code later on! :-)

This oop stuff still sends me in odd directions and asking strange 
questions. And all the programming I have heretofore hammered in was 
procedural, so oop is indeed coming slow and very hard.

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From shalehperry@comcast.net  Sun Aug  3 03:45:13 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug  3 02:45:13 2003
Subject: [Tutor] definition question
In-Reply-To: <3F2CA05E.6000809@netzero.net>
References: <3F2CA05E.6000809@netzero.net>
Message-ID: <200308022343.49146.shalehperry@comcast.net>

On Saturday 02 August 2003 22:40, Kirk Bailey wrote:
> I am writing a number of functions for my current project, and a thought
> occured to me: Are they objects?
>
> No, I am not using class statements, but they are defined functions, you
> pass arguements, they sometimes return data, and they sure are useful
> for writing code later on! :-)
>
> This oop stuff still sends me in odd directions and asking strange
> questions. And all the programming I have heretofore hammered in was
> procedural, so oop is indeed coming slow and very hard.

oop implies you are using classes.

Basically OOP is designed around nouns (objects) and verbs (methods).

bob.kicks(jane) whereas the procedural guy thinks kick(bob, jane).



From shalehperry@comcast.net  Sun Aug  3 03:54:01 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug  3 02:54:01 2003
Subject: [Tutor] get as a way to operate on first occurrence of an element in a list?
In-Reply-To: <BB51E8AB.B657%clay@shirky.com>
References: <BB51E8AB.B657%clay@shirky.com>
Message-ID: <200308022353.00423.shalehperry@comcast.net>

>
> This is a working version in python:
>
>  for line in f:
>      if line in seen_dict:
>          pass
>      else:
>          print line,
>          seen_dict[line] = 1
>

why not use the following?

for line in f:
   if line not in seen_dict:
       print line,
       seen_dict[line] = 1

that seems to say what you mean in a more succinct way.



From alan.gauld@blueyonder.co.uk  Sun Aug  3 04:47:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 03:47:01 2003
Subject: [Tutor] Comments wanted on new Python introduction
References: <BB51F02F.B65A%clay@shirky.com>
Message-ID: <001c01c35993$5aa28210$6401a8c0@xp>

> The second suggestion is really a plea: More editorial judgment,
please.
> ...
> You know this stuff far better than we do; we'd be grateful if you
would
> tell us what you think we should do, based on what you know and we
don't.

I'm not sure that's a valid assumption. The folks running the
Python site can't really be expected to go through every
tutorial that gets written, they simply note their existence.

Even if they did beauty is very much in the eye of the beholder.
When learning Smalltalk I tried 4 different books/tutorials before
I eventually found one that worked for me. All of the others had
been strongly recommended by other programmers who thought
they were great...

The only tutorial that could (or should) realistically be
recommended on the web site is the official one IMHO. Its the
only one that carries an official stamp and gets updated
to keep it in step with new releases.

Even my own tutor is still aimed at v1.5.2. And some of the
translations of it haven't been updated since they were written.
They are still useful since its better to have an old tutor
in youur own language than a current one you can't read properly!
(Incidentally I have just started the major work of updating
my English version of the tutor to 2.3)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@blueyonder.co.uk  Sun Aug  3 04:57:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 03:57:02 2003
Subject: [Tutor] get as a way to operate on first occurrence of an element in a list?
References: <BB51E8AB.B657%clay@shirky.com>
Message-ID: <001201c35994$b848b370$6401a8c0@xp>

> for line in f:
>     if line in seen_dict:
>         pass
>     else:
>         print line,
>         seen_dict[line] = 1

IMHO Its better to let the test rewflect what you want 
rather than what you don't want...

if line not in seen_dict:
   print line
   seen_dict[line] = 1


Is there a way to use get to test for a value, fail if 
it doesn't exist, and *then* assign a value to it? 

NOpe, the whole point of get is that it fetches a value 
from the dictionary if it exists and returns the default 
if it doesn't. So it never fails. Its a get() not a set()...

>>> d = {}
>>> d.get(1,2)
2
>>> d[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 1
>>>

Notice although it gave me a value back for key 1 it 
did NOT create an entry for key 1 in d.

it's equivalent to:

def get(key, default)
  if key in d:
    return d[key]
  else: return default

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From goki75@vsnl.net  Sun Aug  3 05:12:07 2003
From: goki75@vsnl.net (G Kiran)
Date: Sun Aug  3 04:12:07 2003
Subject: [Tutor] Raw Sockets
Message-ID: <000301c35995$ff6abbd0$a84c41db@VULCAN>

Hi,

    Raw sockets are much misunderstod i guess.. python documentation does
not provide much on this...though it just about says that its implemented.
but similar calls to ones in unix donot work

Specifically what i need to know is that how do i recv data from a raw
socket...
My reqmt is to monitor all traffic coming from an physical interface like a
lan card in python.. without using any third party modules...with just
socket libraries can i recv all the data coming in?

even a lead...clue in this direction will be highly appreciated

thanx in advance



From roypython@hotmail.com  Sun Aug  3 07:53:05 2003
From: roypython@hotmail.com (roy ollis)
Date: Sun Aug  3 06:53:05 2003
Subject: [Tutor] Comments wanted on new Python introduction
Message-ID: <BAY2-F97u3fQtYdVzDp0000255d@hotmail.com>

<html><div style='background-color:'><DIV>
<P>as a true newbie i can say WHAT?&nbsp; 8 is too many?&nbsp; i think 8 isn't enough. different people understand different ways.&nbsp; remember for a true newbie you cant say "just like java,&nbsp; opposite of java, or compare it to java in any way.&nbsp; java is an unknown.&nbsp; it's like explaining the color blue to a blind man.&nbsp; perhaps selling shoes or cloths is better.&nbsp; if anything is a "one size fits all" it pretty much truly fits none.&nbsp; it may be an xxl size any can fit in, or elastic that can streatch over the largest size,&nbsp; but it's going to look good on very few.</P>
<P>the idea of a tutorial is to teach people, not to impress people. different people just understand in different ways.&nbsp; someone that uses alot of big words&nbsp;to them sound intelligent isn't really comunicating,&nbsp; thats a politician, not a teacher.&nbsp; a sucessfull teachers students will exceed the teacher,&nbsp; building on what they've been taught.&nbsp; at the point you get to a single tutorial, pretty much as good as anyone can get, you've hit your limits and progress is impossible.&nbsp; and by the way alans tutorial is great, so is the one in the edu section.&nbsp; i think the official one is going to be very good to as soon as i get to a level i can understand it.</P>
<P>and it is ironic that the statement "there are too many already" is in the statement "we neeed a new one"&nbsp;&nbsp; aka&nbsp; here's one more.&nbsp; but if you want reviews there has been a site up for a while&nbsp;&nbsp; python city.&nbsp;&nbsp;&nbsp; <A href="http://www.awaretek.com/plf.html">http://www.awaretek.com/plf.html</A>&nbsp;&nbsp;&nbsp; .&nbsp; i suspect there are more.&nbsp; just google it as you said if you want reviews.<BR><BR></P></DIV>
<DIV></DIV>&gt;From: "Alan Gauld" <ALAN.GAULD@BLUEYONDER.CO.UK>
<DIV></DIV>&gt;To: "Clay Shirky" <CLAY@SHIRKY.COM>,"A.M. Kuchling" <AMK@AMK.CA>,<TUTOR@PYTHON.ORG> 
<DIV></DIV>&gt;Subject: Re: [Tutor] Comments wanted on new Python introduction 
<DIV></DIV>&gt;Date: Sun, 3 Aug 2003 08:46:30 +0100 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; &gt; The second suggestion is really a plea: More editorial judgment, 
<DIV></DIV>&gt;please. 
<DIV></DIV>&gt; &gt; ... 
<DIV></DIV>&gt; &gt; You know this stuff far better than we do; we'd be grateful if you 
<DIV></DIV>&gt;would 
<DIV></DIV>&gt; &gt; tell us what you think we should do, based on what you know and we 
<DIV></DIV>&gt;don't. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;I'm not sure that's a valid assumption. The folks running the 
<DIV></DIV>&gt;Python site can't really be expected to go through every 
<DIV></DIV>&gt;tutorial that gets written, they simply note their existence. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Even if they did beauty is very much in the eye of the beholder. 
<DIV></DIV>&gt;When learning Smalltalk I tried 4 different books/tutorials before 
<DIV></DIV>&gt;I eventually found one that worked for me. All of the others had 
<DIV></DIV>&gt;been strongly recommended by other programmers who thought 
<DIV></DIV>&gt;they were great... 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;The only tutorial that could (or should) realistically be 
<DIV></DIV>&gt;recommended on the web site is the official one IMHO. Its the 
<DIV></DIV>&gt;only one that carries an official stamp and gets updated 
<DIV></DIV>&gt;to keep it in step with new releases. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Even my own tutor is still aimed at v1.5.2. And some of the 
<DIV></DIV>&gt;translations of it haven't been updated since they were written. 
<DIV></DIV>&gt;They are still useful since its better to have an old tutor 
<DIV></DIV>&gt;in youur own language than a current one you can't read properly! 
<DIV></DIV>&gt;(Incidentally I have just started the major work of updating 
<DIV></DIV>&gt;my English version of the tutor to 2.3) 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Alan G 
<DIV></DIV>&gt;Author of the Learn to Program web tutor 
<DIV></DIV>&gt;http://www.freenetpages.co.uk/hp/alan.gauld 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;_______________________________________________ 
<DIV></DIV>&gt;Tutor maillist - Tutor@python.org 
<DIV></DIV>&gt;http://mail.python.org/mailman/listinfo/tutor 
<DIV></DIV></div><br clear=all><hr>Help STOP SPAM with <a href="http://g.msn.com/8HMFENUS/2731??PS=">the new MSN 8 </a> and get 2 months FREE*</html>


From op73418@mail.telepac.pt  Sun Aug  3 07:55:02 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Sun Aug  3 06:55:02 2003
Subject: [Tutor] definition question
In-Reply-To: <3F2CA05E.6000809@netzero.net>
Message-ID: <DCEDLKJJJGHMCOCFGMGKEECDCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Kirk Bailey
> Sent: domingo, 3 de Agosto de 2003 6:41
> To: tutor@python.org
> Subject: [Tutor] definition question
>
>
> I am writing a number of functions for my current project,
> and a thought
> occured to me: Are they objects?
>

Everything in Python is an object, therefore a function is an object.
See http://effbot.org/guides/python-objects.htm

>>> def test(*args):
... 	print "Hello, %s!" % str(args)
...

Now, let us inspect what attributes does a function object have:

>>> for elem in dir(test):
... 	print elem
...
__call__
__class__
__delattr__
__dict__
__doc__
__get__
__getattribute__
__hash__
__init__
__module__
__name__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
func_closure
func_code
func_defaults
func_dict
func_doc
func_globals
func_name

In particular:

>>> print test.__class__
<type 'function'>
>>>

You can just continue to poke around function objects and try to see
what those attribuets stand up for -- Python is great for this kind of
exploratory learning.

As you can see a function object has a __call__ method. This is the
method you implement in your classes to make them behave like
functions, e.g.:

>>> class Test(object):
... 	def __init__(self):
... 		pass
... 	def __call__(self):
... 		return "I am %r." % self
...
>>> a = Test()
>>> print a()
I am <__main__.Test object at 0x010DFC50>.
>>>

One last tidbit: as of 2.3 you still cannot inherit from functions --
although, I don't know why would I want to do that anyway.

> This oop stuff still sends me in odd directions and asking strange
> questions. And all the programming I have heretofore
> hammered in was
> procedural, so oop is indeed coming slow and very hard.

Well, if you have any questions, just shoot them.

With my best regards,
G. Rodrigues



From op73418@mail.telepac.pt  Sun Aug  3 08:05:02 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Sun Aug  3 07:05:02 2003
Subject: [Tutor] Raw Sockets
In-Reply-To: <000301c35995$ff6abbd0$a84c41db@VULCAN>
Message-ID: <DCEDLKJJJGHMCOCFGMGKCECECBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> G Kiran
> Sent: sábado, 2 de Agosto de 2003 16:04
> To: python tutor
> Subject: [Tutor] Raw Sockets
>
>
> Hi,
>
>     Raw sockets are much misunderstod i guess.. python
> documentation does
> not provide much on this...though it just about says that
> its implemented.
> but similar calls to ones in unix donot work
>
> Specifically what i need to know is that how do i recv data
> from a raw
> socket...
> My reqmt is to monitor all traffic coming from an physical
> interface like a
> lan card in python.. without using any third party
> modules...with just
> socket libraries can i recv all the data coming in?
>
> even a lead...clue in this direction will be highly appreciated
>

The module socket and its documentation are your friend. Here I am
just going to fire up the interpreter and ask help for the socket
objects in the socket module (spelled socket.socket)

>>> help(socket.socket)
Help on class _socketobject in module socket:

class _socketobject(__builtin__.object)
 |  socket([family[, type[, proto]]]) -> socket object
 |
 |  Open a socket of the given type.  The family argument specifies
the
 |  address family; it defaults to AF_INET.  The type argument
specifies
 |  whether this is a stream (SOCK_STREAM, this is the default)
 |  or datagram (SOCK_DGRAM) socket.  The protocol argument defaults
to 0,
 |  specifying the default protocol.  Keyword arguments are accepted.
 |
 |  A socket object represents one endpoint of a network connection.
 |
 |  Methods of socket objects (keyword arguments not allowed):
 |
 |  accept() -- accept a connection, returning new socket and client
address
 |  bind(addr) -- bind the socket to a local address
 |  close() -- close the socket
 |  connect(addr) -- connect the socket to a remote address
 |  connect_ex(addr) -- connect, return an error code instead of an
exception
 |  dup() -- return a new socket object identical to the current one
[*]
 |  fileno() -- return underlying file descriptor
 |  getpeername() -- return remote address [*]
 |  getsockname() -- return local address
 |  getsockopt(level, optname[, buflen]) -- get socket options
 |  gettimeout() -- return timeout or None
 |  listen(n) -- start listening for incoming connections
 |  makefile([mode, [bufsize]]) -- return a file object for the socket
[*]
 |  recv(buflen[, flags]) -- receive data
 |  recvfrom(buflen[, flags]) -- receive data and sender's address
 |  sendall(data[, flags]) -- send all data
 |  send(data[, flags]) -- send data, may not send all of it
 |  sendto(data[, flags], addr) -- send data to a given address
 |  setblocking(0 | 1) -- set or clear the blocking I/O flag
 |  setsockopt(level, optname, value) -- set socket options
 |  settimeout(None | float) -- set or clear the timeout
 |  shutdown(how) -- shut down traffic in one or both directions

[rest snipped]

As you can see, there is a recv method for the socket object to fetch
data.

In the documentation, there is a How-to guide to sockets. You may want
to read it to get a feel for how things are done. Here I am just going
to post one of its examples:

 #create an INET, STREAMing socket
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 #now connect to the web server on port 80
 # - the normal http port
 s.connect(("www.mcmillan-inc.com", 80))

Now you can use the recv method on s to fetch data.

Hope that helped, more question just hurl them.
G. Rodrigues



From clickron@webtv.net  Sun Aug  3 11:23:02 2003
From: clickron@webtv.net (Ron A)
Date: Sun Aug  3 10:23:02 2003
Subject: [Tutor] string formatting problem
Message-ID: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net>

I have this in a little program , and when it prints it goes to another
line when it gets to the last part of the string. 

 print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b) 

It prints like this.
                
88   PN   1118   0.21 
   18.48

I only have 4 spaces between each. Why would it split like this, and how
do I fix it?

Ron A



From bgailer@alum.rpi.edu  Sun Aug  3 11:48:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sun Aug  3 10:48:02 2003
Subject: [Tutor] string formatting problem
In-Reply-To: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net>
Message-ID: <5.2.1.1.0.20030803084451.02b7fd90@66.28.54.253>

--=======44DBCF=======
Content-Type: text/plain; x-avg-checked=avg-ok-4A8548FE; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 10:22 AM 8/3/2003 -0400, Ron A wrote:

>I have this in a little program , and when it prints it goes to another
>line when it gets to the last part of the string.
>
>  print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b)
>
>It prints like this.
>
>88   PN   1118   0.21
>    18.48
>
>I only have 4 spaces between each. Why would it split like this, and how
>do I fix it?


Here's what I get:

 >>> a=88
 >>> x=1118
 >>> b=0.20999999999999999
 >>> z=[0, 0,.21]
 >>> print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b)
88  PN  1118   0.21   18.48

How is your program/data/environment different?

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625

--=======44DBCF=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4A8548FE
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003

--=======44DBCF=======--



From clickron@webtv.net  Sun Aug  3 12:07:01 2003
From: clickron@webtv.net (Ron A)
Date: Sun Aug  3 11:07:01 2003
Subject: [Tutor] Re: string formatting problem
Message-ID: <16623-3F2D24DD-211@storefull-2134.public.lawson.webtv.net>

Here's the whole little program

pn_qty = {} 
import string 
# Get print number and quantity & store in lists pn and qty def work(): 
    while 1: 
        wk = raw_input("print number ") 
        wk2 = raw_input("quantity ") 
        pn_qty[wk] = wk2 
        ans = raw_input("continue? y/n ") 
        if ans.upper() == "N": 
            print 
            break 
        elif ans == "": 
            continue 
#Print invoices 
def invoice(): 
    data = open("birch2.txt", "r") 
    for x in pn_qty.keys(): 
        while 1: 
            y = data.readline() 
            z = string.split(y, ',') 
            if x == z[0]: 
                a = int(pn_qty[x]) 
                b = float(z[2]) 
  print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b) 
                break 
            elif y == "": 
                print "Print number %s not in file, start again" % (x)
break 
                
    data.seek(0) 
    data.close() 
        
work() 
invoice() 
88   PN   1118   0.21 
   18.48



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Aug  3 12:10:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Aug  3 11:10:02 2003
Subject: [Tutor] Upgrading 2.2 to 2.3
In-Reply-To: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net>
References: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net>
Message-ID: <571571075296.20030803111524@columbus.rr.com>

I can't find any info on upgrading on python.org. Am I supposed to:

a) put 2.3 over 2.2 in the same folder?
b) uninstall 2.2 then install 2.3?
c) install 2.3 in a new folder (what happens to all my old
site-packages?) ?
d) something I hadn't thought of?

This is on Windows 2000 FWIW.

Alan



From amk@amk.ca  Sun Aug  3 12:12:02 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Sun Aug  3 11:12:02 2003
Subject: [Tutor] Re: string formatting problem
In-Reply-To: <16623-3F2D24DD-211@storefull-2134.public.lawson.webtv.net>
References: <16623-3F2D24DD-211@storefull-2134.public.lawson.webtv.net>
Message-ID: <20030803151402.GA11535@nyman.amk.ca>

On Sun, Aug 03, 2003 at 11:06:05AM -0400, Ron A wrote:
>            y = data.readline() 

.readline() leaves a newline on the end, so y is set to a string such as 
"1,2,3,4\n".

>            z = string.split(y, ',') 

This splits only on comma characters, so z is set to ['1', '2', '3', '4\n'].
If you print z[3], that string will include a newline.  

Simple fix: strip off the newline (and any other trailing whitespace) 
with .rstrip():

        y = data.readline().rstrip()

--amk                                                             (www.amk.ca)
If you're using anything besides US-ASCII, I *stringly* suggest Python 2.0.
      -- Uche Ogbuji (A fortuitous typo?), 29 Jan 2001


From clickron@webtv.net  Sun Aug  3 12:19:02 2003
From: clickron@webtv.net (Ron A)
Date: Sun Aug  3 11:19:02 2003
Subject: [Tutor] Re: string formatting problem
Message-ID: <16624-3F2D27BB-152@storefull-2134.public.lawson.webtv.net>

Thank you. Thank you. This was driving me nuts. I consider myself a
novice at this, but I knew it had to be something I just wasn't seeing.

Thanks once again.

Ron A



From gus.tabares@verizon.net  Sun Aug  3 12:49:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Sun Aug  3 11:49:01 2003
Subject: [Tutor] Re: Upgrading 2.2 to 2.3
Message-ID: <1059925826.23980.2.camel@blackbetty>

>a) put 2.3 over 2.2 in the same folder?
>b) uninstall 2.2 then install 2.3?
>c) install 2.3 in a new folder (what happens to all my old
>site-packages?) ?
>d) something I hadn't thought of?

Technically you can have 2.2 and 2.3 co-exist on the same machine on
Windows 2000. By default 2.3 is installed to C:\Python23. I've done it
to make sure none of my scripts are broken in 2.3 (they're not;). But in
the end I just uninstalled 2.2 and installed 2.3 along with the Win32
API extensions.


HTH,
-- 
/Gus



From alan.gauld@blueyonder.co.uk  Sun Aug  3 12:51:14 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 11:51:14 2003
Subject: [Tutor] definition question
References: <3F2CA05E.6000809@netzero.net>
Message-ID: <002e01c359d7$0b0ae550$6401a8c0@xp>

> I am writing a number of functions for my current project, and a
thought
> occured to me: Are they objects?

In Python they are objects. Python regards functions as
objects that can be passed around and that have attributes
and even methods.

>>> def foo():
...      'A silly function that does nothing'
...      print 'foo'
...
>>> foo.__doc__
A silly function that does nothing
>>> def bar(f,n):
...    for i in range(n): f()
...
>>> bar(foo,3)
foo
foo
foo
>>>

So we can pass foo as an object into bar, we can inspect its
doc string, and there are other attributes we could look at too.
In recent Pythons we can even subclass it:

class myFunc(foo):
   pass

Although how we would use that I'm struggling to think...

So yes a function is an object, but a special one in that it
is not instantiated from a class. BUT this is a very Pythonic
feature and in most languages a function is not an object.

In fact in Java, to do what we did with bar above you have to
define a class with a predetermined method (usually called
run or similar) and pass the class into bar:

>>> class doit:
...    def run(s)
...      print 'phony foo
...
>>> def bar2(c,n):
...   for i in range(n):
...     C().run()
...
>>> bar2(doit,3)
phony foo
phony foo
phony foo

Hopefully its clear that this is a cumbersome and restricted
way of doing things and treating functions as objects has
some big advantages. Significantly the purest of all OOP
languages, Smalltalk, also treats blocks of code as objects
to avoid just this kind of awkwardness.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@blueyonder.co.uk  Sun Aug  3 12:58:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 11:58:02 2003
Subject: [Tutor] Raw Sockets
References: <000301c35995$ff6abbd0$a84c41db@VULCAN>
Message-ID: <003a01c359d8$0633c550$6401a8c0@xp>

>     Raw sockets are much misunderstod i guess.. python documentation
does
> not provide much on this...though it just about says that its
implemented.
> but similar calls to ones in unix donot work

Most of the BSD socket interface works pretty much as is but only on
a limited(ie the most common) set of protocols.

> Specifically what i need to know is that how do i recv data from a
raw
> socket...

There is a tutorial on the Python site(by Gordon McMillan?) on using
sockets which shows how to do UDP and TCP/IP. I don't think ICMP is
supported?

> My reqmt is to monitor all traffic coming from an physical interface
like a
> lan card in python..

That would require monitoring ethernet packets which are below the
socket level interface. Probably you need to look at even lower
level libraries like ioctl etc. I confess never to having programmed
at ethernet level so can't help much there.

It will presumably be OS dependant but you mentioned Unix earlier
so I'll assume you are on a *nix system.

Alan G.



From alan.gauld@blueyonder.co.uk  Sun Aug  3 13:01:39 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 12:01:39 2003
Subject: [Tutor] definition question
References: <DCEDLKJJJGHMCOCFGMGKEECDCBAA.op73418@mail.telepac.pt>
Message-ID: <004001c359d8$602f81c0$6401a8c0@xp>

> One last tidbit: as of 2.3 you still cannot inherit from
functions --
> although, I don't know why would I want to do that anyway.

Ah, I stand corrcted then, but as I said in my earlier post
- I can't actually think of a case where I'd want to!
Maybe to add some kind of debugging support or something...?

Alan G.



From alan.gauld@blueyonder.co.uk  Sun Aug  3 13:06:10 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 12:06:10 2003
Subject: [Tutor] string formatting problem
References: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net>
Message-ID: <004701c359d9$266c6880$6401a8c0@xp>

>  print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b) 
> 
> It prints like this.
>                 
> 88   PN   1118   0.21 
>    18.48

Works ok for me, are you sure you don't accidentally have a 
number in front of the 0 in 0.2f? When I made it %60.2f I got 
the same pattern you get...

Alan G.


From alan.gauld@blueyonder.co.uk  Sun Aug  3 13:10:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 12:10:02 2003
Subject: [Tutor] Re: string formatting problem
References: <16623-3F2D24DD-211@storefull-2134.public.lawson.webtv.net>
Message-ID: <005301c359d9$a3535a70$6401a8c0@xp>

> def invoice(): 
>             y = data.readline() 
>             z = string.split(y, ',') 
>   print  "%s  PN  %s   %s   %0.2f" % (a, x, z[2], a*b) 

Ah, now z is a line split, How long is Z[2]? Does it have a 
lot of whitespace at the end? Try inserting a debugging 
statement:

print len(z[2])

You may need to use strip to get rid of excess spaces etc...

Alan G.



From alan.gauld@blueyonder.co.uk  Sun Aug  3 13:13:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Aug  3 12:13:01 2003
Subject: [Tutor] Upgrading 2.2 to 2.3
References: <26429-3F2D1AB2-745@storefull-2132.public.lawson.webtv.net> <571571075296.20030803111524@columbus.rr.com>
Message-ID: <005801c359da$0754dad0$6401a8c0@xp>

> I can't find any info on upgrading on python.org. Am I supposed to:
> 
> a) put 2.3 over 2.2 in the same folder?

You can do that but I'd probably advise against it.

> b) uninstall 2.2 then install 2.3?

Thats usually how I do it. The uninstall will leave your Python 
directory alone if it has locally defined packages added. 
So just reinstall in the same place.

> c) install 2.3 in a new folder (what happens to all my old
> site-packages?) ?

You can have two versions if you wish, just make sure you 
call the right one for your programs - check PATH order etc.

Alan G.


From tutor@python.org  Sun Aug  3 13:29:02 2003
From: tutor@python.org (Tim Peters)
Date: Sun Aug  3 12:29:02 2003
Subject: [Tutor] Upgrading 2.2 to 2.3
In-Reply-To: <571571075296.20030803111524@columbus.rr.com>
Message-ID: <LNBBLJKPBEHFEDALKOLCKEBOFBAB.tim.one@comcast.net>

[R. Alan Monroe]
> I can't find any info on upgrading on python.org. Am I supposed to:
>
> a) put 2.3 over 2.2 in the same folder?
> b) uninstall 2.2 then install 2.3?
> c) install 2.3 in a new folder (what happens to all my old
>    site-packages?) ?
> d) something I hadn't thought of?
>
> This is on Windows 2000 FWIW.

It varies across platforms.  On Windows (any flavor, Win9x, Win2K, etc), you
can have any number of different "minor" Python releases installed
simultaneously.  "minor" == the second digit, so, e.g., I have Python 2.2.1,
2.2.3, and 2.3 all installed on my Windows box.

Windows only allows .py files to be associated with one executable, though,
and the most recent Python you installed wins.  You can use the "Advanced"
options dialog in the installer to avoid associating file extensions.

Putting 2.3. over 2.2 in the same folder is a bad idea.  Don't try it.
Nobody tests it that way (I build the Windows installer for PythonLabs, so
you can believe me when I see it sure isn't tested here <wink>).

If you install 2.3 into a new directory, it doesn't matter whether you
uninstall 2.2 -- suit yourself.

In any case, anything in site-packages containing a C extension (a .pyd
file) is incompatible across minor releases on Windows:  an extension built
for 2.2.x cannot be used with 2.1.y or 2.3.z.  You'll need to install new
versions of extensions for use with 2.3.  This part of the story is worse
than it is on most other platforms, but the dirty details under the covers
that prevent extensions from working with multiple minor versions of Python
on Windows are the same dirty details that *allow* you to have any number of
minor Python releases installed simultaneously on Windows.  It's a tradeoff,
and one that may or may not have been made in the particular way you prefer.



From tutor@python.org  Sun Aug  3 13:40:01 2003
From: tutor@python.org (Tim Peters)
Date: Sun Aug  3 12:40:01 2003
Subject: [Tutor] Upgrading 2.2 to 2.3
In-Reply-To: <LNBBLJKPBEHFEDALKOLCKEBOFBAB.tim.one@comcast.net>
Message-ID: <LNBBLJKPBEHFEDALKOLCCEBPFBAB.tim.one@comcast.net>

[Tim]
> It varies across platforms.  On Windows (any flavor, Win9x, Win2K,
> etc), you can have any number of different "minor" Python releases
> installed simultaneously.  "minor" == the second digit, so, e.g., I
> have Python 2.2.1, 2.2.3, and 2.3 all installed on my Windows box.
              ^^^^^
That should have said 2.1.3; sorry!


From jim_938@hotmail.com  Sun Aug  3 14:16:13 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Sun Aug  3 13:16:13 2003
Subject: [Tutor] Ascii hex to binary
Message-ID: <Sea1-F9YoHyYGNTrzLH0000e656@hotmail.com>

Hello *

Can some please tell me how can i express an ASCII hexadecimal string in the 
binary form with python.

10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114

I want this string to be expressed in binary form.

Thanks in advance.

waiting for reply.

Regards

_________________________________________________________________
It's raining movies. Bollywood is flooded. 
http://server1.msn.co.in/features/augustmovies03/index.asp August has 
arrived!



From tutor@python.org  Sun Aug  3 14:24:02 2003
From: tutor@python.org (Tim Peters)
Date: Sun Aug  3 13:24:02 2003
Subject: [Tutor] Ascii hex to binary
In-Reply-To: <Sea1-F9YoHyYGNTrzLH0000e656@hotmail.com>
Message-ID: <LNBBLJKPBEHFEDALKOLCIECCFBAB.tim.one@comcast.net>

[Jimmy verma]
> Hello *
> Can some please tell me how can i express an ASCII hexadecimal
> string in the binary form with python.
>
> 10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D
> 965B1CD45E2114
>
> I want this string to be expressed in binary form.

Read the docs for binascii.unhexlify.  No, that wasn't obvious <wink>.


From clay@shirky.com  Sun Aug  3 15:28:02 2003
From: clay@shirky.com (Clay Shirky)
Date: Sun Aug  3 14:28:02 2003
Subject: [Tutor] get as a way to operate on first occurrence of an
 element in a list?
In-Reply-To: <001201c35994$b848b370$6401a8c0@xp>
Message-ID: <BB52CC37.B6B8%clay@shirky.com>

>> for line in f:
>>     if line in seen_dict:
>>         pass
>>     else:
>>         print line,
>>         seen_dict[line] = 1
> 
> IMHO Its better to let the test rewflect what you want
> rather than what you don't want...
> 
> if line not in seen_dict:
>  print line
>  seen_dict[line] = 1

Yes, this was Sean's advice too, and the form I'll adopt, many thanks.

> Is there a way to use get to test for a value, fail if
> it doesn't exist, and *then* assign a value to it?
> 
> NOpe, the whole point of get is that it fetches a value
> from the dictionary if it exists and returns the default
> if it doesn't. So it never fails. Its a get() not a set()...

This is what I find so interesting. Most of learning Python for me has been
simply understanding how its done here -- "here's how slices work" sorts of
things. But every now and again I hit something where I have to change the
way I think, from perlish to pythonic.

In perl, the inner loop I am replacing is:

    print unless $seen{$_}++;

Even setting aside the low-level syntax like $ and ;, there are *5* things
in that line that Python disallows: statement before conditional in in-line
blocks, unless as a synonym for not if, the unnamed $_ variable, post-test
incrementing, and auto-creating a variable by altering its value.

People who love perl love that sort of flexibility and density, and people
who hate perl hate the trickiness and unreadability that goes with it.

I, who have a love/hate relationship with perl, understand both points of
view, but am moving towards the latter, as I start sharing more code with
the outside world. After a period of playing around with python, I think I
may have switched over completely. I haven't written a line of perl in three
months, as I'm finding Python's legibility intoxicating...

-clay



From op73418@mail.telepac.pt  Sun Aug  3 16:24:01 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Sun Aug  3 15:24:01 2003
Subject: [Tutor] definition question
In-Reply-To: <004001c359d8$602f81c0$6401a8c0@xp>
Message-ID: <DCEDLKJJJGHMCOCFGMGKGECHCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Alan Gauld
>
> > One last tidbit: as of 2.3 you still cannot inherit from
> functions --
> > although, I don't know why would I want to do that anyway.
>
> Ah, I stand corrcted then, but as I said in my earlier post
> - I can't actually think of a case where I'd want to!
> Maybe to add some kind of debugging support or something...?
>

I don't have a use case either. All use cases I've met are solved
equally well by just handrolling your own callable class (e.g.
implementing __call__) since in Python we only care about protocol (is
it callable?) and not about type (is it a function? is it a method?).

With my best regards,
G. Rodrigues



From clickron@webtv.net  Sun Aug  3 16:39:02 2003
From: clickron@webtv.net (Ron A)
Date: Sun Aug  3 15:39:02 2003
Subject: [Tutor] Re: string formatting problem
Message-ID: <19840-3F2D649D-753@storefull-2137.public.lawson.webtv.net>

It works! When I removed the newline character everything worked fine.
Thanks

Ron A
********************************************
>This splits only on comma characters, so
> z is set to ['1', '2', '3', '4\n']. If you print
> z[3], that string will include a newline.  

>Simple fix: strip off the newline (and any
> other trailing whitespace) with .rstrip(): 



From idiot1@netzero.net  Sun Aug  3 16:50:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sun Aug  3 15:50:01 2003
Subject: [Tutor] definition question
In-Reply-To: <200308022343.49146.shalehperry@comcast.net>
References: <3F2CA05E.6000809@netzero.net> <200308022343.49146.shalehperry@comcast.net>
Message-ID: <3F2D673D.3000100@netzero.net>


Sean 'Shaleh' Perry wrote:

> On Saturday 02 August 2003 22:40, Kirk Bailey wrote:
> 
>>I am writing a number of functions for my current project, and a thought
>>occured to me: Are they objects?
>>
>>No, I am not using class statements, but they are defined functions, you
>>pass arguements, they sometimes return data, and they sure are useful
>>for writing code later on! :-)
>>
>>This oop stuff still sends me in odd directions and asking strange
>>questions. And all the programming I have heretofore hammered in was
>>procedural, so oop is indeed coming slow and very hard.
> 
> 
> oop implies you are using classes.
> 
> Basically OOP is designed around nouns (objects) and verbs (methods).
> 
> bob.kicks(jane) whereas the procedural guy thinks kick(bob, jane).
> 
>
Hmmm!  bob.kick() is a instance of the superclass KICK, or of BOB? The 
VERB is 'kick' of course.

I of course cut my teeth on procedural programming, and therefore tend 
to thing of getting a job done in a series of steps, the essense of 
procedural programming. Oddly enough, your example makes more sense than 
the kick(bob, jane)

Sean, yould you care to contribute to the oop section of my wiki at the 
tinylist site? http://www.tinylist.org/cgi-bin/piki.py/FrontPage


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

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From clay@shirky.com  Sun Aug  3 21:28:01 2003
From: clay@shirky.com (Clay Shirky)
Date: Sun Aug  3 20:28:01 2003
Subject: [Tutor] Comments wanted on new Python introduction
In-Reply-To: <001c01c35993$5aa28210$6401a8c0@xp>
Message-ID: <BB532099.B6E5%clay@shirky.com>

> I'm not sure that's a valid assumption. The folks running the
> Python site can't really be expected to go through every
> tutorial that gets written, they simply note their existence.

Sure, but as the number of tutorials grows, this strategy gets less helpful.

> Even if they did beauty is very much in the eye of the beholder.
> When learning Smalltalk I tried 4 different books/tutorials before
> I eventually found one that worked for me.

But if this is the strategy for python.org, why bother with a /learn page at
all? Surely the point of the page is to make recommendations, even if just
implicit ones by excluding most of the written material available on Python.

If you're going to have a page helping people find strategies work for them,
even one sentence about why a certain resource is included would do wonders.

> The only tutorial that could (or should) realistically be
> recommended on the web site is the official one IMHO. Its the
> only one that carries an official stamp and gets updated
> to keep it in step with new releases.

Ah ha!  This is *very* helpful, and in fact, I wish something like this was
on the /learn page:

"The most up to date tutorial for Python is always the the one that included
with the current version of Python. It is the only one that carries an
official stamp and gets updated to keep it in step with new releases." After
that, you could note why the additional tutorials are being included, by
noting what they offer that the tutorial does not.

Even something like that would be a big help.

-clay





From clay@shirky.com  Sun Aug  3 21:48:01 2003
From: clay@shirky.com (Clay Shirky)
Date: Sun Aug  3 20:48:01 2003
Subject: [Tutor] Comments wanted on new Python introduction
In-Reply-To: <BAY2-F97u3fQtYdVzDp0000255d@hotmail.com>
Message-ID: <BB53254D.B6E9%clay@shirky.com>

> as a true newbie i can say WHAT?  8 is too many?

Sorry, I wasn't clear enough before. 8 is a fine number, but it would be
helpful to have some indication as to a) why a given resource has made the
quality cut to be included on that page, and b) how any given resource
differs from the others.

-clay



From jburton@brio.com  Sun Aug  3 22:25:02 2003
From: jburton@brio.com (Jack Burton)
Date: Sun Aug  3 21:25:02 2003
Subject: [Tutor] Book Examples for "Python Programming with the Java Class librari
 es"?
Message-ID: <6B0172099B98D411B77E00D0B7B0E0DC03CD4317@briohq-ex2.brio.com>

Hello All,

This is my first post to this mailing list.  I just got my first Python book
"Python Programming with the Java Class Libraries" by Richard Hightower.

The book did not come with a cdrom and I have found no reference to a
website where the book examples can be downloaded from. 

Anyone have the book examples or know where I can get them so I will not
have to type in all examples?

Thanks,

Jack


From idiot1@netzero.net  Mon Aug  4 00:24:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sun Aug  3 23:24:01 2003
Subject: [Tutor] Regular Expression guru saught
Message-ID: <3F2DD19A.9080205@netzero.net>

This thing is just flat going to need a lot of re stuff, and I need 
therefore to ome up to speed on re.

We can discuss this on the list as a learning experience for the 
membership, or we can take ot off list toprovate correspondance, your 
choice. Anyone care to help me hammer re into the concrete skull I have 
mentioned now and then? Please indicate your preference-
( )- discuss on this list
( )- discuss off list, private correspondance
( )- (other, specify:________________________________)     :-)



end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.




From marc_barry@hotmail.com  Mon Aug  4 06:58:02 2003
From: marc_barry@hotmail.com (Marc Barry)
Date: Mon Aug  4 05:58:02 2003
Subject: [Tutor] Mutable String Question
Message-ID: <Sea2-F5hIP38GmvhZAi00031dd2@hotmail.com>

All:

Is there a mutable string type such as a string buffer in Python?  I know 
that string's in Python are immutable and therefore you cannot append to 
them.  It seems terribly inefficient to do something like the following:

#------

a_string = ""
word_list = ["My", "name", "is"]

for word in word_list:
	a_string = a_string + " " + word

print a_string

#------

I know that the above is a trivial example, but with the amount of text I am 
processing this could have a significant impact on performance.  Does anyone 
know of a better way to handle this?

Regards,

Marc

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963



From Don Arnold" <darnold02@sprynet.com  Mon Aug  4 07:34:01 2003
From: Don Arnold" <darnold02@sprynet.com (Don Arnold)
Date: Mon Aug  4 06:34:01 2003
Subject: [Tutor] Mutable String Question
References: <Sea2-F5hIP38GmvhZAi00031dd2@hotmail.com>
Message-ID: <01ac01c35a73$c3dbd9d0$de10ba3f@defaultcomp>

----- Original Message -----
From: "Marc Barry" <marc_barry@hotmail.com>
To: <tutor@python.org>
Sent: Monday, August 04, 2003 4:56 AM
Subject: [Tutor] Mutable String Question


> All:
>
> Is there a mutable string type such as a string buffer in Python?  I know
> that string's in Python are immutable and therefore you cannot append to
> them.  It seems terribly inefficient to do something like the following:
>
> #------
>
> a_string = ""
> word_list = ["My", "name", "is"]
>

Replace these 2 lines:

> for word in word_list:
> a_string = a_string + " " + word
>

with this one:

  a_string = ' '.join(word_list)   ## note that there's a space between the
quotes

> print a_string
>
> #------
>
> I know that the above is a trivial example, but with the amount of text I
am
> processing this could have a significant impact on performance.  Does
anyone
> know of a better way to handle this?
>
> Regards,
>
> Marc


HTH,
Don



From op73418@mail.telepac.pt  Mon Aug  4 07:56:35 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Mon Aug  4 06:56:35 2003
Subject: [Tutor] Mutable String Question
In-Reply-To: <Sea2-F5hIP38GmvhZAi00031dd2@hotmail.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKOECJCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Marc Barry
> Sent: segunda-feira, 4 de Agosto de 2003 10:57
> To: tutor@python.org
> Subject: [Tutor] Mutable String Question
>
>
> All:
>
> Is there a mutable string type such as a string buffer in
> Python?  I know
> that string's in Python are immutable and therefore you
> cannot append to
> them.  It seems terribly inefficient to do something like
> the following:
>
> #------
>
> a_string = ""
> word_list = ["My", "name", "is"]
>
> for word in word_list:
> 	a_string = a_string + " " + word
>
> print a_string
>
> #------
>
> I know that the above is a trivial example, but with the
> amount of text I am
> processing this could have a significant impact on
> performance.  Does anyone
> know of a better way to handle this?
>

As D. Arnold already replied, the Pythonic way to do this is to suff
your strings in a list and then use the join method as in:

>>> word_list = ["My", "name", "is"]
>>> print " ".join(word_list)
My name is
>>>


This way you avoid the quadratic behaviour of concatening via + (due
to allocation/deallocation I believe).

If you *really* want mutable strings then the closest in the standard
library that I can remember are the StringIO (cStringIO) and the mmap
modules. Somewhere someone is bound to have coded a mutable string
type for Python -- googling or the seraching in the vaults might turn
up something.

With my best regards,
G. Rodrigues



From R. Alan Monroe" <amonroe@columbus.rr.com  Mon Aug  4 08:00:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Mon Aug  4 07:00:02 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2DD19A.9080205@netzero.net>
References: <3F2DD19A.9080205@netzero.net>
Message-ID: <18128705786.20030804070333@columbus.rr.com>

> This thing is just flat going to need a lot of re stuff, and I need 
> therefore to ome up to speed on re.

> We can discuss this on the list as a learning experience for the 
> membership, or we can take ot off list toprovate correspondance, your 
> choice. Anyone care to help me hammer re into the concrete skull I have 

This site is worth a look:

http://perl.plover.com/Regex/article.html



From sigurd@12move.de  Mon Aug  4 11:52:01 2003
From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Aug  4 10:52:01 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2DD19A.9080205@netzero.net> (Kirk Bailey's message of "Sun,
 03 Aug 2003 23:23:06 -0400")
References: <3F2DD19A.9080205@netzero.net>
Message-ID: <m3fzkho4wf.fsf@hamster.pflaesterer.de>

On  4 Aug 2003, Kirk Bailey <- idiot1@netzero.net wrote:

> (x)- discuss on this list
> ( )- discuss off list, private correspondance
> ( )- (other, specify:________________________________)     :-)



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list



From ATrautman@perryjudds.com  Mon Aug  4 12:51:02 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Aug  4 11:51:02 2003
Subject: [Tutor] ASCII hex to binary
Message-ID: <06738462136C054B8F8872D69DA140DB01087F@corp-exch-1.pjinet.com>

Jimmy,

You have a two part problem. I'll try to include a description the step
needed to make a program that will work.
The first problem is splitting this long string into separate values
(parsing into discrete values in gobbledy gook).

The left function will allow you to grab the left most character which needs
to be looked at.

Ok confused?

Do you need the binary values for the sum or for each individual number? 

If its just the total grab each value convert it into its decimal equivalent
and add them together. Then just convert it to binary.

If separate values are needed I would put each position into a into a
dictionary probably with a decimal value. 

Then write a function that converts each to a binary value putting it back
in the dictionary. 

save the data as needed.

http://scholar.hw.ac.uk/site/computing/topic7.asp?outline=no

Has a nice description on how to convert to binary from decimal if that is
needed.

HTH,

Alan


Hello *

Can some please tell me how can i express an ASCII hexadecimal string in the

binary form with python.

10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD4
5E2114

I want this string to be expressed in binary form.

Thanks in advance.

waiting for reply.

Regards

_________________________________________________________________
It's raining movies. Bollywood is flooded. 
http://server1.msn.co.in/features/augustmovies03/index.asp August has 
arrived!


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


From RASTM2@aol.com  Mon Aug  4 13:38:02 2003
From: RASTM2@aol.com (RASTM2@aol.com)
Date: Mon Aug  4 12:38:02 2003
Subject: [Tutor] Pythonwin/View/Options/Format/APPLY Button won't APPLY
Message-ID: <14a.2264ca66.2c5fe58b@aol.com>

--part1_14a.2264ca66.2c5fe58b_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Hello Y'all,

Pythonwin23 #46
Win98(notSE)
Pythonwin - View Menu - Options - Format - 
"String with no terminator" - bgcolor

I went and done it. I thought I'd change the Default color for the editor's 
"String with no terminator" from Olive Drab ( because I can't see black thru 
it)
to a brighter color and now it's set on the Default background color of 
White.
The thing just won't APPLY because the APPLY Button won't "un grey".
The change shows up in the little preview changes window on the left 
any old how you like it, but it won't even go back to Olive. 

I don't get it.
I was huntin' around some of the files for a couple hours and looking for it 
in the help but nuthin.

Will some kind person tell me which config file I gotta hack to get any
kinda response from this setting. 

I know it's an exterior config file cuz I dumped the whole thing and 
downloaded
another one - yah I know, drastic - but I am a Newbie and I would hate to 
mess
up something else by hunt and peck.

Ray - Rastm2@aol.com

--part1_14a.2264ca66.2c5fe58b_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">Hello Y'all,<BR>
<BR>
Pythonwin23 #46<BR>
Win98(notSE)<BR>
Pythonwin - View Menu - Options - Format - <BR>
"String with no terminator" - bgcolor<BR>
<BR>
I went and done it. I thought I'd change the Default color for the editor's=20=
<BR>
"String with no terminator" from Olive Drab ( because I can't see black thru=
 it)<BR>
to a brighter color and now it's set on the Default background color of Whit=
e.<BR>
The thing just won't APPLY because the APPLY Button won't "un grey".<BR>
The change shows up in the little preview changes window on the left <BR>
any old how you like it, but it won't even go back to Olive. <BR>
<BR>
I don't get it.<BR>
I was huntin' around some of the files for a couple hours and looking for it=
 <BR>
in the help but nuthin.<BR>
<BR>
Will some kind person tell me which config file I gotta hack to get any<BR>
kinda response from this setting. <BR>
<BR>
I know it's an exterior config file cuz I dumped the whole thing and downloa=
ded<BR>
another one - yah I know, drastic - but I am a Newbie and I would hate to me=
ss<BR>
up something else by hunt and peck.<BR>
<BR>
Ray - Rastm2@aol.com</FONT></HTML>

--part1_14a.2264ca66.2c5fe58b_boundary--


From klappnase@freenet.de  Mon Aug  4 13:42:01 2003
From: klappnase@freenet.de (klappnase)
Date: Mon Aug  4 12:42:01 2003
Subject: [Tutor] popen2.Popen4 objects
Message-ID: <20030804184239.49247347.klappnase@freenet.de>

Hello,
I hope that I do not bother all of you too much with my dumb newbie questions,
here I have yet another one.

I want to run a shell command using a popen2.Popen4 object.

I use the following line:

     self.pp = popen2.Popen4(cmd)

Now I use self.pp.pid to capture the PID of the child process and self.pp.poll() to check whether the child process
has finished.

Seems to work all fine, however I found that after the child process has finished, the Popen4 instance
still persists:

>>>print self.pp
>>><popen2.Popen4 instance at 0x834d1fc>

I think it sould be removed somehow, but I don't know how to do that. I'd be very thankful for any help.

Michael


   


From dyoo@hkn.eecs.berkeley.edu  Mon Aug  4 14:28:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug  4 13:28:02 2003
Subject: [Tutor] Mutable String Question  [java.lang.StringBuffer -->
 Python List]
In-Reply-To: <DCEDLKJJJGHMCOCFGMGKOECJCBAA.op73418@mail.telepac.pt>
Message-ID: <Pine.LNX.4.44.0308041007340.14245-100000@hkn.eecs.berkeley.edu>


> As D. Arnold already replied, the Pythonic way to do this is to suff
> your strings in a list and then use the join method as in:
>
> >>> word_list = ["My", "name", "is"]
> >>> print " ".join(word_list)
> My name is
> >>>
>
> This way you avoid the quadratic behaviour of concatening via + (due to
> allocation/deallocation I believe).
>
> If you *really* want mutable strings then the closest in the standard
> library that I can remember are the StringIO (cStringIO) and the mmap
> modules. Somewhere someone is bound to have coded a mutable string type
> for Python -- googling or the seraching in the vaults might turn up
> something.



Hi everyone,


Alternatively, if we want to treat our string as a list of characters,
then we can turn a string into a list of characters.  *grin* Here's an
example:


###
>>> sentence = "Python is a good programming language"
>>> buffer = list(sentence)
>>> buffer
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'g', 'o',
'o', 'd', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', ' ',
'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
>>>
>>>
###



We've "exploded" our string into its constituent characters.  Bam!
*grin* Now that we have a list of characters, we can do simple list
manipulation:

###
>>> buffer[12:16] = list('great')                ## Slice assignment
>>> buffer
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'g', 'r',
'e', 'a', 't', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g',
' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
###


List mainpulation is something that we're already pretty familiar with, so
this should be easy going.  *grin* Once we're done with our manipulation,
we can go back from our list of characters back into a string:

###
>>> ''.join(buffer)
'Python is a great programming language'
###



For comparison, the equivalent code in Java looks something like this:


///
String sentence = "Java is a good programming language";
StringBuffer buffer = new StringBuffer(sentence);
buffer.replace(10, 14, "fairly ok");
sentence = buffer.toString();
///


It's good to know that there's not much conceptual difference here.  If we
really look into Java's StringBuffer class:

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html

it becomes more clear that a Java StringBuffer is pretty much a "sequence"
of characters.  And since Lists are built into Python, there's less of a
need for an explicit "string buffer" class in Python --- Lists are often
powerful enough to do the job.


If you have more questions, please feel free to ask.  I hope this helps!



From jeff@ccvcorp.com  Mon Aug  4 14:36:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 13:36:01 2003
Subject: [Tutor] Problem
References: <00b201c358a7$5c42f2e0$fdaa6544@cx826527a>
Message-ID: <3F2E99AE.1000309@ccvcorp.com>

Jeff Lohman wrote:

> Wait...isn't he just describing a SPAM program


While a program of this sort can definitely be used for spamming and for 
virus dissemination, it also has legitimate uses.  At the company I work 
for, I've written programs that automatically create reports and email 
them our clients, or that send email notification of some procedure's 
success or failure to interested parties.  These are, on a technical 
level, no different from a spam program, but as a matter of practical 
usage they are an important business tool that is strongly desired by 
the people who receive these emails.

The difference between a useful mailing list and a spam center is one of 
usage, not of type.  We have no evidence to suspect that the use that 
the O.P. has in mind is for spamming.  I'd hate to see a presumption of 
guilt and a withholding of information based on that presumption.  I 
strongly support freedom of expression, even when that expression could 
perhaps inconvenience someone else.  (Indeed, if you have freedom of 
speech only as long as you don't upset/offend someone, then you do not 
have freedom of speech.)  The correct way to deal with spam is to track 
down and punish abusers, not to attempt to prevent access to automated 
email technology.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Aug  4 15:01:14 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 14:01:14 2003
Subject: [Tutor] Regular Expression guru saught
References: <3F2DD19A.9080205@netzero.net>
Message-ID: <3F2E9F63.8040102@ccvcorp.com>

Kirk Bailey wrote:

> This thing is just flat going to need a lot of re stuff, and I need 
> therefore to ome up to speed on re. 


I'm not so sure that re's are quite what you want -- or at least, I'm 
not sure if re's are enough.

The problem with re's is that they're not very good at handling nested 
data structures.  It's often mentioned that re's are not appropriate for 
parsing HTML or XML because of this limitation, and I suspect that the 
same will apply to parsing your simple wiki code as well.  You could 
perhaps write re's that will handle the majority of likely cases, but 
(if I'm right) it's almost assured that eventually, someone will write a 
wiki page that can't be properly parsed with a re-based approach.  

It seems to me that you may be better off investigating a full 
lexer/parser, a la the HTMLParser or sgmllib standard library modules. 
 In fact, you may be able to use a lot of the code from HTMLParser.  It 
looks like this uses re's internally, to identify tags, but it does a 
lot more than just extracting re groups.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Aug  4 15:12:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 14:12:02 2003
Subject: [Tutor] popen2.Popen4 objects
References: <20030804184239.49247347.klappnase@freenet.de>
Message-ID: <3F2EA20A.1050404@ccvcorp.com>

klappnase wrote:

>Seems to work all fine, however I found that after the child process has finished, the Popen4 instance
>still persists:
>
>  
>
>>>>print self.pp
>>>><popen2.Popen4 instance at 0x834d1fc>
>>>>        
>>>>
>
>I think it sould be removed somehow, but I don't know how to do that. I'd be very thankful for any help.
>  
>

An object exists as long as there are references to it.  In most cases, 
that's a good thing -- for instance, there may be information about the 
terminated process that you want to get later.  However, if you're sure 
that you're done with it, you can remove the reference to it that you've 
saved.  You can do this in one of two ways.  You can set self.pp = None, 
which cause your Popen4 object to be decref'ed, which will presumably 
allow it to be garbage-collected (if this is the only reference to it). 
 Your parent object (self) will still have a pp attribute, but it will 
point to None.  You could also 'del self.pp', which removes the pp 
attribute completely (thus also decref'ing the Popen4 object and 
probably garbage-collecting it).  Which of these is preferable depends 
on what else you're doing with your parent object -- in the second case, 
attempting to reference self.pp will result in an AttributeError, while 
in the first case it yields None.  This could be useful for conditionals 
("if self.pp: do_something()").

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Aug  4 15:34:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 14:34:02 2003
Subject: [Tutor] definition question
References: <3F2CA05E.6000809@netzero.net> <200308022343.49146.shalehperry@comcast.net> <3F2D673D.3000100@netzero.net>
Message-ID: <3F2EA734.7020902@ccvcorp.com>

Kirk Bailey wrote:

> Sean 'Shaleh' Perry wrote:
>
>> Basically OOP is designed around nouns (objects) and verbs (methods).
>>
>> bob.kicks(jane) whereas the procedural guy thinks kick(bob, jane).
>>
> Hmmm!  bob.kick() is a instance of the superclass KICK, or of BOB? The 
> VERB is 'kick' of course. 


In this example, kick() is the verb, while bob (and presumably jane) are 
instances of some class.  We actually don't know what class bob is, nor 
does it matter.  We're presuming that bob knows how to kick, and that's 
all that's important.  Bob could be a person, or a horse, or a 
five-legged Rigellian land-squid -- as long as Bob knows how to respond 
to being told to kick(jane), it's all the same to us.  This is one of 
the advantages of OOP -- it makes it very easy if we determine later 
that Bob needs to change.

In a procedural world, when someone writes the function kick(bob, jane), 
he'll need to know about all the possible things that both Bob and Jane 
could be, and take every possible variation into account.  The problem 
here comes when it's discovered that an important possibility was left 
out -- at that point, kick() must be changed, and the new possibility 
factored in to the big list of possible combinations.  In contrast, an 
OOP approach means that, when a new possibility arises (that Rigellian 
land-squid is discovered), you can write a new class for that case, 
which knows how Rigellian land-squids kick, and *none* of the code that 
handles a person or a horse needs to change at all.  Jane probably 
doesn't care whether she's being kicked by a horse or by a land-squid, 
it's going to hurt either way!

Jeff Shannon
Technician/Programmer
Credit International




From zak@harlekin-maus.com  Mon Aug  4 16:32:01 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Mon Aug  4 15:32:01 2003
Subject: [Tutor] ASCII hex to binary
In-Reply-To: <06738462136C054B8F8872D69DA140DB01087F@corp-exch-1.pjinet.com>
References: <06738462136C054B8F8872D69DA140DB01087F@corp-exch-1.pjinet.com>
Message-ID: <1784.192.206.201.102.1060025478.squirrel@mail.harlekin-maus.com>

> Jimmy,
<various cuts below>
> If its just the total grab each value convert it into its decimal
> equivalent
> and add them together. Then just convert it to binary.
>
> If separate values are needed I would put each position into a
> dictionary probably with a decimal value.
>
> Then write a function that converts each to a binary value putting it back
> in the dictionary.
>
> Alan

>> Hello *
>>
>> Can some please tell me how can i express an ASCII hexadecimal string in
>> the binary form with python.
<SNIP!>
>> Thanks in advance.

You can also take advantage of the fact that a single hex value (0-F) can
be represented as a 4-digit binary number. Here's a highly obfuscated
version, which I wouldn't recommend including anywhere.

hex_to_bin = lambda s: ''.join(map(lambda c: [''.join(['01'[2**j & k > 0]
for k in range(16) for j in range(3, -1, -1)][i:i+4]) for i in range(0,
256, 4)][int(c, 16)], s))

I have this feeling that I can simplify it a bit by avoiding two joins,
but I've already put too much wasted effort into it. It's also not very
efficient, with lambda being used over and over again.

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em


From jeff@ccvcorp.com  Mon Aug  4 17:16:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 16:16:01 2003
Subject: [Tutor] ASCII hex to binary
References: <06738462136C054B8F8872D69DA140DB01087F@corp-exch-1.pjinet.com> <1784.192.206.201.102.1060025478.squirrel@mail.harlekin-maus.com>
Message-ID: <3F2EBF25.8090106@ccvcorp.com>

>
>
>>>Can some please tell me how can i express an ASCII hexadecimal string in
>>>the binary form with python.
>>>
>You can also take advantage of the fact that a single hex value (0-F) can
>be represented as a 4-digit binary number. Here's a highly obfuscated
>version, which I wouldn't recommend including anywhere.
>

A rather less-obfuscated version, using a dictionary instead of 
constructing the binary representations on the fly:

binhex = { '0': '0000', '1': '0001', '2': '0010', '3': '0011',
            '4': '0100', '5': '0101', '6': '0110', '7': '0111',
            '8': '1000', '9': '1001', 'A': '1010', 'B': '1011',
            'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'  }

def hex_to_bin(hexstring):
    inputlist = list(hextring.upper())
    outputlist = [binhex[x] for x in inputlist]
    return "".join(outputlist)

One could perhaps use the inner loop of the obfuscated version to 
construct the binhex dictionary, but I'd be just as happy typing it out 
-- it's much easier to understand what you're doing here when you can 
*see* what the dictionary lookup is returning.

Jeff Shannon
Technician/Programmer
Credit International




From absmythe@ucdavis.edu  Mon Aug  4 17:27:01 2003
From: absmythe@ucdavis.edu (ashleigh smythe)
Date: Mon Aug  4 16:27:01 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2DD19A.9080205@netzero.net>
References: <3F2DD19A.9080205@netzero.net>
Message-ID: <1060028759.5867.125.camel@nate.ucdavis.edu>

On Sun, 2003-08-03 at 20:23, Kirk Bailey wrote:
> This thing is just flat going to need a lot of re stuff, and I need 
> therefore to ome up to speed on re.
> 
> We can discuss this on the list as a learning experience for the 
> membership, or we can take ot off list toprovate correspondance, your 
> choice. Anyone care to help me hammer re into the concrete skull I have 
> mentioned now and then? Please indicate your preference-
> ( )- discuss on this list
> ( )- discuss off list, private correspondance
> ( )- (other, specify:________________________________)     :-)
> 

I'm a newbie and learning a lot about python by just following the
list.  So my vote goes to please keep it on the list! :)

Thanks,

Ashleigh



From klappnase@freenet.de  Mon Aug  4 20:00:04 2003
From: klappnase@freenet.de (klappnase)
Date: Mon Aug  4 19:00:04 2003
Subject: [Tutor] popen2.Popen4 objects
In-Reply-To: <3F2EA20A.1050404@ccvcorp.com>
References: <20030804184239.49247347.klappnase@freenet.de>
 <3F2EA20A.1050404@ccvcorp.com>
Message-ID: <20030805010105.33f6501e.klappnase@freenet.de>

Thank you so much!

Meanwhile I found another problem.
If I create an instance of Popen4 and want to get the PID of the child process with:

     self.pp = popen2.Popen4(cmd)
     cmdpid = self.pp.pid

the PID that is returned belongs not actually to the process that I am interested in, but to
a subshell and the PID I wanted is cmdpid + 1.
This is a problem if I want to abort the child process with

     os.kill(self.pp.pid, 9)

I found that the subshell is being killed but the child process is happily running on.
I might use instead

     os.kill(self.pp.pid+1, 9)

but I am not sure if I can rely on the PID of the child to be exactly the subshell's PID + 1.
I might use os.system("skill -KILL cmd") instead, but I thought there must be a "Python way" to do this.
Can anyone help with this problem?

Thanks in advance

Michael



From idiot1@netzero.net  Mon Aug  4 21:37:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Aug  4 20:37:02 2003
Subject: [Tutor] wikinehesa.py
Message-ID: <3F2EFBFF.10407@netzero.net>

ok, making some progress. Got it to parse lines, damndest way, but it 
parses. The idea of intermediate code came through for me. It parses it 
into <BR> (linebreak) tags fine. So it looks for 2 in a row and parses 
into a <P> tag. One alone is saved as a br tag. AS the other wiki seems 
to like to save some of them with an intermediate ' ', some of the lines 
insist on being <br> <br>, instead of <br><br>. Beats me, reading it is 
clear as mud.

If you are using html readers, that did not come through properly.

Here's the FrontPage:
	http://www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage

Here's the script:
	http://www.tinylist.org/wikinehesa.txt

I still need to find a way to toggle italic and bold on and off; 
wikicode uses the same marker for toggling the thing, and I am drawing a 
blank. Anyone with an inclination, take a look and make some suggesions 
please?



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.




From shalehperry@comcast.net  Mon Aug  4 22:13:01 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Mon Aug  4 21:13:01 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2E9F63.8040102@ccvcorp.com>
References: <3F2DD19A.9080205@netzero.net> <3F2E9F63.8040102@ccvcorp.com>
Message-ID: <200308041811.52976.shalehperry@comcast.net>

On Monday 04 August 2003 11:01, Jeff Shannon wrote:
> Kirk Bailey wrote:
> > This thing is just flat going to need a lot of re stuff, and I need
> > therefore to ome up to speed on re.
>
> I'm not so sure that re's are quite what you want -- or at least, I'm
> not sure if re's are enough.
>
> The problem with re's is that they're not very good at handling nested
> data structures.  It's often mentioned that re's are not appropriate for
> parsing HTML or XML because of this limitation, and I suspect that the
> same will apply to parsing your simple wiki code as well.  You could
> perhaps write re's that will handle the majority of likely cases, but
> (if I'm right) it's almost assured that eventually, someone will write a
> wiki page that can't be properly parsed with a re-based approach.
>

Indeed.  The book "Text Processing in Python" may be of value here.  Covers 
simple string methods, re's and real parsers.  For me it turned out to cover 
mostly stuff I already knew but for someone just getting into text processing 
it is likely to be pretty valuable.

Beyond that, Kirk as always an example is worth a thousand threads (-:



From carroll@tjc.com  Mon Aug  4 22:16:01 2003
From: carroll@tjc.com (Terry Carroll)
Date: Mon Aug  4 21:16:01 2003
Subject: [Tutor] ASCII hex to binary
In-Reply-To: <1784.192.206.201.102.1060025478.squirrel@mail.harlekin-maus.com>
Message-ID: <Pine.LNX.4.44.0308041814270.28264-100000@violet.rahul.net>

On Mon, 4 Aug 2003, Zak Arntson wrote:

> hex_to_bin = lambda s: ''.join(map(lambda c: [''.join(['01'[2**j & k > 0]
> for k in range(16) for j in range(3, -1, -1)][i:i+4]) for i in range(0,
> 256, 4)][int(c, 16)], s))

This almost makes me nostalgic for Perl.

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982



From idiot1@netzero.net  Mon Aug  4 22:22:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Aug  4 21:22:02 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <m3fzkho4wf.fsf@hamster.pflaesterer.de>
References: <3F2DD19A.9080205@netzero.net> <m3fzkho4wf.fsf@hamster.pflaesterer.de>
Message-ID: <3F2F067B.7030804@netzero.net>

ok, here's the rub;
I am writing a wiki. A wiki stores the body of a page in a flat text 
file. NO HTML. The markup ciode is a simplistic set, Alas, some of them 
use the SAME symbol series to turn a feature on, or off- it is a toggle.

SOME functions use the SAME tags to turn a function ON or OFF- it is a 
toggle.

For instance:
'''bold''' text -   BOLD is printed BOLD, appears in output as
<b>bold</b> text
''italic'' text - italic is printed in italics, as
<i>italic</i> text

Doing this with string.replace is just not cutting the mustard. Any advice?




Karl Pflästerer wrote:

> On  4 Aug 2003, Kirk Bailey <- idiot1@netzero.net wrote:
> 
> 
>>(x)- discuss on this list
>>( )- discuss off list, private correspondance
>>( )- (other, specify:________________________________)     :-)
> 
> 
> 
> 
>    Karl

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1@netzero.net  Mon Aug  4 22:27:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Aug  4 21:27:01 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <200308041811.52976.shalehperry@comcast.net>
References: <3F2DD19A.9080205@netzero.net> <3F2E9F63.8040102@ccvcorp.com> <200308041811.52976.shalehperry@comcast.net>
Message-ID: <3F2F07A9.5090109@netzero.net>

Well, as an example, here's the code of the moment:
	http;//www.tinylist.org/wikinehesa.txt
and here is the mostly working reader tself:
	http://www.tinylist.org/cgi-bin/wikinehesa.py
Works, reads, even  manages a somewhat crufty parsing into paragraphs, 
but need to handle the <b></b> and <i></i> matter.


Sean 'Shaleh' Perry wrote:

> On Monday 04 August 2003 11:01, Jeff Shannon wrote:
> 
>>Kirk Bailey wrote:
>>
>>>This thing is just flat going to need a lot of re stuff, and I need
>>>therefore to ome up to speed on re.
>>
>>I'm not so sure that re's are quite what you want -- or at least, I'm
>>not sure if re's are enough.
>>
>>The problem with re's is that they're not very good at handling nested
>>data structures.  It's often mentioned that re's are not appropriate for
>>parsing HTML or XML because of this limitation, and I suspect that the
>>same will apply to parsing your simple wiki code as well.  You could
>>perhaps write re's that will handle the majority of likely cases, but
>>(if I'm right) it's almost assured that eventually, someone will write a
>>wiki page that can't be properly parsed with a re-based approach.
>>
> 
> 
> Indeed.  The book "Text Processing in Python" may be of value here.  Covers 
> simple string methods, re's and real parsers.  For me it turned out to cover 
> mostly stuff I already knew but for someone just getting into text processing 
> it is likely to be pretty valuable.
> 
> Beyond that, Kirk as always an example is worth a thousand threads (-:
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From pan@uchicago.edu  Mon Aug  4 22:31:02 2003
From: pan@uchicago.edu (pan@uchicago.edu)
Date: Mon Aug  4 21:31:02 2003
Subject: [Tutor] name 'sys' is not defined ?
In-Reply-To: <20030803032902.15978.30717.Mailman@mail.python.org>
References: <20030803032902.15978.30717.Mailman@mail.python.org>
Message-ID: <1060047047.3f2f08c78d6ca@webmail.uchicago.edu>

I've encountered some bug(s) that's driving me crazy. A simple code as
follows:

[1] import sys
[2] cgiFolder=r'D:\pan\pc\prog\lang\py\mymod\cgi'
[3] if cgiFolder not in sys.path: sys.path.append(cgiFolder)

[4] import treeNode
[5] from treeNode import c_treeNode

gives me an error 

    NameError: name 'sys' is not defined

at line [3] when it is first executed, and then:

    ImportError: cannot import name c_treeNode

at line [5] if it runs the 2nd time (means, the 'sys' error
in the first run no longer exist).

I am pretty sure that the c_treeNode class in the treeNode.py file
exists and runs correctly.

What is weird is, the above code was executed nicely last week 
without any error. When I came back to the office after the weekend,
everything went wrong. 

I've been using python 2.2.1 with pythonwin. I thought something went
wrong with either of them so I uninstalled them and installed a new
version of 2.2.2 but the problem persists.

Anyone has any idea?

pan


From jeff@ccvcorp.com  Mon Aug  4 23:04:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Aug  4 22:04:02 2003
Subject: [Tutor] Regular Expression guru saught
References: <3F2DD19A.9080205@netzero.net> <m3fzkho4wf.fsf@hamster.pflaesterer.de> <3F2F067B.7030804@netzero.net>
Message-ID: <3F2F10BB.6090208@ccvcorp.com>

Kirk Bailey wrote:

> ok, here's the rub;
> I am writing a wiki. A wiki stores the body of a page in a flat text 
> file. NO HTML. The markup ciode is a simplistic set, Alas, some of 
> them use the SAME symbol series to turn a feature on, or off- it is a 
> toggle.
>
> SOME functions use the SAME tags to turn a function ON or OFF- it is a 
> toggle.
>
> For instance:
> '''bold''' text -   BOLD is printed BOLD, appears in output as
> <b>bold</b> text
> ''italic'' text - italic is printed in italics, as
> <i>italic</i> text 


A crude (untested pseudo-code) possibility:

bold = 0
tag = ["<B>", "</B>"]
text = file( ... ).read()
while text.find("'''") >= 0:
    text.replace("'''", tag[bold], 1)
    bold = not bold

This should go through the entire file, finding each instance of three 
single-quotes, and replacing *one* instance with a tag.  The tag in to 
use is chosen through use of a toggle variable, which is flipped after 
each replacement.

An obvious problem with this approach is that it searches through the 
entire length of the file on each pass.  For a long file with a bunch of 
tags at the end, this could be a real bottleneck.  An obvious 
optimization would be to use the results of text.find() to separate 
translated text from untranslated, something like:

complete = ''
while 1:
    index = text.find("'''")
    if index < 0:    break
    complete = '%s%s%s' % (complete, text[:index], tag[bold])
    index += len("'''")
    text = text[index:]
    bold = not bold

That'll still be slow, but at least you won't be searching the same 
sections of text over and over again.  And through judicious use of 
parameters and generalization, this could be converted into a function 
that could be run for each tag-type -- i.e., translate(wikicode, 
starttag, endtag).

This is not very smart.  It won't handle the unexpected well at all, and 
it doesn't ensure that each opening tag has a matching closing tag. 
 Obviously, if a wikicode is a substring of another code, you'll have to 
translate for the larger one first -- ''' must be done before '', for 
example.  There's probably other limitations too.  But it might be 
enough for a quick & dirty (but working) solution.

Jeff Shannon
Technician/Programmer
Credit International




From pan@uchicago.edu  Mon Aug  4 23:24:01 2003
From: pan@uchicago.edu (pan@uchicago.edu)
Date: Mon Aug  4 22:24:01 2003
Subject: [Tutor] Re: name 'sys' is not defined ?
In-Reply-To: <1060047047.3f2f08c78d6ca@webmail.uchicago.edu>
References: <20030803032902.15978.30717.Mailman@mail.python.org> <1060047047.3f2f08c78d6ca@webmail.uchicago.edu>
Message-ID: <1060050201.3f2f15193b06f@webmail.uchicago.edu>

I've figured out where it went wrong. It's an overlook... 
I apologize.

For whoever has lost some brain cells on this, here is the
stupid mistake I made:

In the treeNode.py file, from where I wanna import the class
c_treeNode, there are 3 lines of code same as the [1]~[3] below.
Somehow, I accidentally deleted the line [1] (import sys) in that
file. 


Apologize for 

Quoting pan@uchicago.edu:
> 
> I've encountered some bug(s) that's driving me crazy. A simple code as
> follows:
> 
> [1] import sys
> [2] cgiFolder=r'D:\pan\pc\prog\lang\py\mymod\cgi'
> [3] if cgiFolder not in sys.path: sys.path.append(cgiFolder)
> 
> [4] import treeNode
> [5] from treeNode import c_treeNode
> 
> gives me an error 
> 
>     NameError: name 'sys' is not defined
> 
> at line [3] when it is first executed, and then:
> 
>     ImportError: cannot import name c_treeNode
> 
> at line [5] if it runs the 2nd time (means, the 'sys' error
> in the first run no longer exist).
> 
> I am pretty sure that the c_treeNode class in the treeNode.py file
> exists and runs correctly.
> 
> What is weird is, the above code was executed nicely last week 
> without any error. When I came back to the office after the weekend,
> everything went wrong. 
> 
> I've been using python 2.2.1 with pythonwin. I thought something went
> wrong with either of them so I uninstalled them and installed a new
> version of 2.2.2 but the problem persists.
> 
> Anyone has any idea?
> 
> pan
> 




From shalehperry@comcast.net  Mon Aug  4 23:43:02 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Mon Aug  4 22:43:02 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2F07A9.5090109@netzero.net>
References: <3F2DD19A.9080205@netzero.net> <200308041811.52976.shalehperry@comcast.net> <3F2F07A9.5090109@netzero.net>
Message-ID: <200308041942.01366.shalehperry@comcast.net>

On Monday 04 August 2003 18:26, Kirk Bailey wrote:
> Well, as an example, here's the code of the moment:
> 	http;//www.tinylist.org/wikinehesa.txt
> and here is the mostly working reader tself:
> 	http://www.tinylist.org/cgi-bin/wikinehesa.py
> Works, reads, even  manages a somewhat crufty parsing into paragraphs,
> but need to handle the <b></b> and <i></i> matter.
>

look at htmlparser's code.  What you need is a state machine ......



From op73418@mail.telepac.pt  Tue Aug  5 08:48:02 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Tue Aug  5 07:48:02 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2F07A9.5090109@netzero.net>
Message-ID: <DCEDLKJJJGHMCOCFGMGKEECPCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Kirk Bailey
> Sent: terca-feira, 5 de Agosto de 2003 2:26
> To: tutor@python.org
> Subject: Re: [Tutor] Regular Expression guru saught
>
>
> Well, as an example, here's the code of the moment:
> 	http;//www.tinylist.org/wikinehesa.txt
> and here is the mostly working reader tself:
> 	http://www.tinylist.org/cgi-bin/wikinehesa.py
> Works, reads, even  manages a somewhat crufty parsing into
> paragraphs,
> but need to handle the <b></b> and <i></i> matter.
>


Re's can't, I repeat, can't parse text with structure, you need a full
parser (state machine) for it. They can be used however to tokenize
the text, e.g. recognize the tags

< some-text-here-excluding-<-and->->

And then feed these tokens into the parser.

D. Mertz has a book online about text processing that might suit you
just fine.

With my best regards,
G. Rodrigues



From jpollack@socrates.Berkeley.EDU  Tue Aug  5 09:25:03 2003
From: jpollack@socrates.Berkeley.EDU (jpollack@socrates.Berkeley.EDU)
Date: Tue Aug  5 08:25:03 2003
Subject: [Tutor] file question
Message-ID: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>

Hi everyone,

Is there a way to pull a specific line from a file without reading the
whole thing into memory with .readlines()?

I have a monstrous text file, but I can easily figure out the index
numbers of the particular line I need without having to read the whole
thing in?  Is there a quick way to do this?

I couldn't find anything in documentation specifically addressing this.


Thanks!
Joshua Pollack



From reggie@merfinllc.com  Tue Aug  5 09:38:01 2003
From: reggie@merfinllc.com (Reggie Dugard)
Date: Tue Aug  5 08:38:01 2003
Subject: [Tutor] file question
In-Reply-To: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
References: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
Message-ID: <1060087044.11408.11.camel@pika>

Joshua,

There's no direct way to get to a specific line in a file, but you can
do it without having to read in the entire file.  If you're using Python
2.3 you can do the following:

for line_number, line in enumerate(open('filename')):
    if line_number == desired_line:
        break
else:
    raise ValueError, 'File too short'

On Tue, 2003-08-05 at 05:24, jpollack@socrates.Berkeley.EDU wrote:
> Hi everyone,
> 
> Is there a way to pull a specific line from a file without reading the
> whole thing into memory with .readlines()?
> 
> I have a monstrous text file, but I can easily figure out the index
> numbers of the particular line I need without having to read the whole
> thing in?  Is there a quick way to do this?
> 
> I couldn't find anything in documentation specifically addressing this.
> 
> 
> Thanks!
> Joshua Pollack
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Reggie




From hillcino368@hotmail.com  Tue Aug  5 10:34:04 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Tue Aug  5 09:34:04 2003
Subject: [Tutor] Ascii hex to binary
Message-ID: <Law15-F72uBixT16sTT0000f24e@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_65c4_673f_62d1
Content-Type: text/plain; format=flowed


Hi, jimmy

Thanks for your inquiry.

You may want to try my base converter base  2 - 255  and fantastic number 
compresser.
def base(r1,r2,n) works well in python because of the arbitrary precision 
integers. It can
be converted to other languages that have the ascii set and precision up to 
256 places.
I use your request as an example in the comments of the code.

It is also attached.

Have fun in the facinating world of numbers.

>From: "Jimmy verma" <jim_938@hotmail.com>
>To: tutor@python.org
>Subject: [Tutor] Ascii hex to binary
>Date: Sun, 03 Aug 2003 22:44:53 +0530
>
>Hello *
>
>Can some please tell me how can i express an ASCII hexadecimal string in 
>the binary form with python.
>
>10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
>
>I want this string to be expressed in binary form.
>
>Thanks in advance.
>
>waiting for reply.


#               Convert from base A to base B for any base(radix) 2 - 255
#                                      Cino Hilliard
#                                        6/9/2003
# Usage: (>>> assumed) import cvbase. cvbase.b2b(r1,r2,num).
# Note num outside of base 10 must be in quotes. No error checking is 
provided. Eg.,
# cvbase.b2b(2,10,11222) will give a bad result since e is not allowed in 
base 2.

# Examples 1 set a to a value base 16 and convert to base 2 and back to base 
16.
# 
a='10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114'
# >>> cvbase.b2b(16,2,a)
# length before conversion  82
# 
10000101111110011000101110000010011111010101101011011000111110000001111111001101
# 
10110100010110001111100111001101001100110010100100001101100011000010000011111000
# 
10100100000010110100101111111100011100001001010110111111101111101110111010110111
# 
00011110101110010010010001101100101100101101100011100110101000101111000100001000
# 10100
# length after conversion  325
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length after converting back 82

# Example 2 convert a to base 255 and back to base 16,
# >>> cvbase.b2b(16,255,a)
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length before conversion 82
# JÅš+dR + +?+Śô;ë++vc v@?8ótx+-ŚŹ5S+z?+-  %Ä™   #This lost some in hotmail
# length avter conversion 41
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length after converting back 82
# notice the 50% compression of your data from base 16 to base 255?
# notice the 4 times increase of your data from base 16 to base 2?
# Going from base 10 to base 255 gives 41.6% compression.
# Try cvbase.b2b(10,255,((10**1000-1)/9)**2)
# keep in mind, we are compressing numbers, not text. Text is a different 
matter.
# However if you have a billion digits of Pi you want to transmit via modem 
to your
# girl friend, you will cut your phone expense by 58.4% by compressing and 
sending
# algorithm.
#                Have fun in the facinating world of numbers
#

def b2b(r1,r2,n):             #Convert n in base r1 to base r2 and back
    import string
    print n
    print "length before conversion ",len(str(n))
    x = base(r1,r2,n)
    print x
    print "length after conversion ",len(str(x))
    n = base(r2,r1,x)
    print n
    print "length after converting back ",len(str(n))

def base(r1,r2,num):       #This is the crown jewel of the routine where we
    import string          #use base 10 as a pivot to go from base r1 to r2.
    digits=""
    for j in range(0,10):               #We collect the ascii characters we 
want to use.
          digits = digits + chr(j+48)
    for j in range(10,36):
          digits = digits + chr(j+55)
    for j in range(36,52):
          digits = digits + chr(j-4)
    for j in range(52,59):
          digits = digits + chr(j+6)
    for j in range(59,224):
          digits = digits + chr(j+32)
    for j in range(224,256):
          digits = digits + chr(j-224)
    num1 = str(num)
    ln  = len(num1)
    dec = 0
    for j in range(ln):
          asci = string.index(digits,num1[j]) #Get the ascii code of num
          temp   = r1**(ln-j-1) #Get the decending powers of the decimal 
encoded
          dec += asci*temp      #Convert the num in r1 to decimal
    RDX = ""                    #Init the storage string
    j=-1
    dec2=dec
    while dec2:                 #get number of digits in decimal
         dec2 = dec2 / r2
         j = j+1
    while j >= 0:
          pwr = r2**j           #This is just going from base 10 to another 
base.
          Q   = dec // pwr      #converting the  decimal number to r2 which 
in effect
          dec = dec % pwr       #converting num in base r1 to a number in 
base r2.
          RDX = RDX + digits[Q]
#         RDX = RDX + str(Q)+","  #like Maple. Using this will allow any 
base conv.
          j-=1
    return RDX

_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail

------=_NextPart_000_65c4_673f_62d1
Content-Type: text/plain; name="cvbase.py"; format=flowed
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="cvbase.py"

#               Convert from base A to base B for any base(radix) 2 - 255
#                                 Cino Hilliard
#                                    6/9/2003
# Usage: (>>> assumed) import cvbase. cvbase.b2b(r1,r2,num).
# Note num outside of base 10 must be in quotes. No error checking is 
provided. Eg.,
# cvbase.b2b(2,10,11222) will give a bad result since e is not allowed in 
base 2.

# Examples 1 set a to a value base 16 and convert to base 2 and back to base 
16.
# 
a='10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114'
# >>> cvbase.b2b(16,2,a)
# length before conversion  82
# 
10000101111110011000101110000010011111010101101011011000111110000001111111001101
# 
10110100010110001111100111001101001100110010100100001101100011000010000011111000
# 
10100100000010110100101111111100011100001001010110111111101111101110111010110111
# 
00011110101110010010010001101100101100101101100011100110101000101111000100001000
# 10100
# length after conversion  325
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length after converting back 82

# Example 2 convert a to base 255 and back to base 16,
# >>> cvbase.b2b(16,255,a)
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length before conversion 82
# JÅš+dR + +?+Śô;ë++vc v@?8ótx+-ŚŹ5S+z?+-  %Ä™
# length avter conversion 41
# 
10BF31704FAB5B1F03F9B68B1F39A66521B1841F1481697F8E12B7F7DDD6E3D7248D965B1CD45E2114
# length after converting back 82
# notice the 50% compression of your data from base 16 to base 255?
# notice the 4 times increase of your data from base 16 to base 2?
# Going from base 10 to base 255 gives 41.6% compression.
# Try cvbase.b2b(10,255,((10**1000-1)/9)**2)
# keep in mind, we are compressing numbers, not text. Text is a different 
matter.
# However if you have a billion digits of Pi you want to transmit via modem 
to your
# girl friend, you will cut your phone expense by 58.4% by compressing and 
sending
# algorithm.
#                Have fun in the facinating world of numbers
#

def b2b(r1,r2,n):             #Convert n in base r1 to base r2 and back
    import string
    print n
    print "length before conversion ",len(str(n))
    x = base(r1,r2,n)
    print x
    print "length after conversion ",len(str(x))
    n = base(r2,r1,x)
    print n
    print "length after converting back ",len(str(n))

def base(r1,r2,num):       #This is the crown jewel of the routine where we
    import string          #use base 10 as a pivot to go from base r1 to r2.
    digits=""
    for j in range(0,10):        #We collect the ascii characters we want to 
use.
          digits = digits + chr(j+48)#We can use them all but will not be 
able to print
    for j in range(10,36):
          digits = digits + chr(j+55)
    for j in range(36,52):
          digits = digits + chr(j-4)
    for j in range(52,59):
          digits = digits + chr(j+6)
    for j in range(59,224):
          digits = digits + chr(j+32)
    for j in range(224,256):
          digits = digits + chr(j-224)
    num1 = str(num)               #the first few. The 48-255 as my 
selection.
    ln  = len(num1)
    dec = 0
    for j in range(ln):
          asci = string.index(digits,num1[j]) #Get the ascii code of num
          temp   = r1**(ln-j-1) #Get the decending powers of the decimal 
encoded
          dec += asci*temp      #Convert the num in r1 to decimal
    RDX = ""                    #Init the storage string
    j=-1
    dec2=dec
    while dec2:                 #get number of digits in decimal
         dec2 = dec2 / r2
         j = j+1
    while j >= 0:
          pwr = r2**j           #This is just going from base 10 to another 
base.
          Q   = dec // pwr      #converting the  decimal number to r2 which 
in effect
          dec = dec % pwr       #converting num in base r1 to a number in 
base r2.
          RDX = RDX + digits[Q]
#         RDX = RDX + str(Q)+","  #like Maple. Using this will allow any 
base conv.
          j-=1
    return RDX



------=_NextPart_000_65c4_673f_62d1--


From pythontutor@venix.com  Tue Aug  5 10:53:03 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue Aug  5 09:53:03 2003
Subject: [Tutor] file question
In-Reply-To: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
References: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
Message-ID: <3F2FB693.7090503@venix.com>

A typical text file has varying lenth lines.  Navigating to specific locations
in a file is based upon byte counts, not line counts.  However, if the lines
are a known size, you can use seek to go directly to the position in the file.

On windows, the file should be opened in binary mode.

f = file(name, 'rb')
position = line_length * line_index
f.seek(position)
the_data = f.read(line_length)

jpollack@socrates.Berkeley.EDU wrote:

> Hi everyone,
> 
> Is there a way to pull a specific line from a file without reading the
> whole thing into memory with .readlines()?
> 
> I have a monstrous text file, but I can easily figure out the index
> numbers of the particular line I need without having to read the whole
> thing in?  Is there a quick way to do this?
> 
> I couldn't find anything in documentation specifically addressing this.
> 
> 
> Thanks!
> Joshua Pollack
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582



From clay@shirky.com  Tue Aug  5 11:30:12 2003
From: clay@shirky.com (Clay Shirky)
Date: Tue Aug  5 10:30:12 2003
Subject: [Tutor] file question
In-Reply-To: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
Message-ID: <BB553563.B866%clay@shirky.com>

> 
> Hi everyone,
> 
> Is there a way to pull a specific line from a file without reading the
> whole thing into memory with .readlines()?

One simplistic way to do that would be to loop through the file and ignore
every line you don't want, grab the one you want, and then break.

---

test_file = "spam_and_eggs.txt"

i = 0
print_line = 100000

f = open(test_file)

for line in f: # assumes 2.2 or higher
    if i == print_line:
        print line,
        break
    i += 1

---

spam_and_eggs.txt is an 8 meg file of ~150K lines. The for line in
f/pass/break method runs markedly faster for lines near the top of the file
(in my setup, better than 3 times faster when print_line = 10,000), while
for lines at the end of the file, the speed is about the same (though the
for line in f method still doesn't read the file into memory.)

If you have more than one line you want to get, make an array of print_line
numbers, and break after the last one.

If you are likely to want to get the same lines later, after an f.close(),
you may want to consider memoizing the lines you retrieve, saving them in a
dict with the line number as the key, then checking that before going
through the file again.

And of course, there may well be ways of manipulating the file object more
directly. The above is just a simple way to avoid the memory problem.

-clay





From jmillr@umich.edu  Tue Aug  5 14:30:01 2003
From: jmillr@umich.edu (John Miller)
Date: Tue Aug  5 13:30:01 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <20030805135303.17043.15181.Mailman@mail.python.org>
Message-ID: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>

Sean 'Shaleh' Perry <shalehperry@comcast.net> wrote:

> look at htmlparser's code.  What you need is a state machine ......

"Rodrigues" <op73418@mail.telepac.pt> wrote:

> Re's can't, I repeat, can't parse text with structure, you need a full
> parser (state machine) for it. They can be used however to tokenize
> the text, e.g. recognize the tags

I wonder if someone could explain what is meant by a "state machine", 
(and why regular expressions are insufficient for the kind of parsing 
Kirk needs for his wiki...)? Thanks.

John Miller



From goki75@vsnl.net  Tue Aug  5 14:31:02 2003
From: goki75@vsnl.net (G Kiran)
Date: Tue Aug  5 13:31:02 2003
Subject: [Tutor] Popen
Message-ID: <001401c35b76$85c1e050$a74c41db@VULCAN>

the following is the code...
the b.read from the pipe doesnot return and blocks there itself...since
cmd.exe does not end on its own
is there a way to open a two way pipe...so i can send and "exit" command to
end the shell...or write and read without blocking?



import socket
import os

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",81))
s.listen(5)
conn,addr=s.accept()
cmd=""
while (1):
    onechar=conn.recv(1)
    if not(onechar== '\n'): cmd=cmd+onechar
    else:
        a=popen("\\windows\\system32\\cmd.exe "+cmd)
        result=b.read()
        conn.send(result)
        cmd=""



From dyoo@hkn.eecs.berkeley.edu  Tue Aug  5 16:50:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug  5 15:50:02 2003
Subject: [Tutor] file question   [line # lookup / anydbm]
In-Reply-To: <Pine.GSO.4.44.0308050520090.14410-100000@socrates.Berkeley.EDU>
Message-ID: <Pine.LNX.4.44.0308051230120.15545-100000@hkn.eecs.berkeley.edu>


On Tue, 5 Aug 2003 jpollack@socrates.Berkeley.EDU wrote:

> Hi everyone,
>
> Is there a way to pull a specific line from a file without reading the
> whole thing into memory with .readlines()?
>
> I have a monstrous text file, but I can easily figure out the index
> numbers of the particular line I need without having to read the whole
> thing in?  Is there a quick way to do this?
>
> I couldn't find anything in documentation specifically addressing this.


Hi Joshua,

A "preprocessing" approach here might work --- we can write a program that
takes your large text file, and transforms it into something that's easier
to search through.

One way we can preprocess the text file is to use the 'anydbm' library:

    http://www.python.org/doc/lib/module-anydbm.html


Anydbm gives us an object that, for most purposes, acts like a dictionary,
except it's stored on disk.  One way we can approach this problem might be
something like this:

###
from __future__ import generators
import anydbm

def createIndex(filename, index_filename):
    """Creates a new index, keyed by line number, of the given
    filename."""
    index = anydbm.open(index_filename, "c")
    for line_number, line in enumerate(open(filename)):
        index[str(line_number)] = line     ## keys can only be strings
                                           ## though...
    index.close()


def lookupLine(index, line_number):
    return index[str(line_number)]

def enumerate(sequence):
    """Compatibility function for Python < 2.3.  In Python 2.3, this is
    a builtin."""
    i = 0
    for x in sequence:
        yield i, x
        i = i + 1
###


Let's see if this works:

###
>>> createIndex("/usr/share/dict/words", 'index')
>>> index = anydbm.open('index')
>>> lookupLine(index, 0)
'A\n'
>>> lookupLine(index, 500)
'absconder\n'
>>> lookupLine(index, 42)
'abalone\n'
>>> lookupLine(index, 1999)
'actinomere\n'
>>> lookupLine(index, 2999)
'advisably\n'
>>> lookupLine(index, 10999)
'Aonian\n'
>>> lookupLine(index, 70999)
'floriculturally\n'
###

And now it's very easy to do arbitrary line lookup.  So the preprocessing
step --- creating the index --- can be done once, and once it's created,
we can do all our access with the dbm file.

The disadvantage of this approach is that the index file itself can become
quite large.  We can modify our approach so that it doesn't waste so much
space --- instead of saving the lines in our anydbm file, we can store the
byte positions where those lines appear.

But perhaps this is a bit overkill?  *grin*  Will this dbm approach work
ok for you?


Good luck!



From alex@gabuzomeu.net  Tue Aug  5 17:12:01 2003
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Tue Aug  5 16:12:01 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
Message-ID: <3F300F6B.8080409@gabuzomeu.net>

Hello,


John Miller wrote:

> "Rodrigues" <op73418@mail.telepac.pt> wrote:
>
>> Re's can't, I repeat, can't parse text with structure, you need a full
>> parser (state machine) for it. They can be used however to tokenize
>> the text, e.g. recognize the tags
>
> I wonder if someone could explain what is meant by a "state machine",

For more information about state machines, you may want to read this 
article:  "Charming Python: Using state machines".

    http://www-106.ibm.com/developerworks/linux/library/l-python-state.html

> (and why regular expressions are insufficient for the kind of parsing 
> Kirk needs for his wiki...)?

Wiki formatting can be nested (eg. a link in bold text in italics in a 
list item), which makes parsing more complex.

I wrote a wiki engine about a year ago. I used regexps with recursive 
parsing: first pick the largest blocks (eg. paragraphs), then in those 
blocks look for smaller pieces, etc. It worked, but the code is complex 
and difficult to maintain and extend, so I suspect this isn't the 
optimal strategy.


Cheers.

Alexandre






From mhansen@cso.atmel.com  Tue Aug  5 17:31:54 2003
From: mhansen@cso.atmel.com (Mike Hansen)
Date: Tue Aug  5 16:31:54 2003
Subject: [Tutor] SAX, Classes, ...(sorry long message)
Message-ID: <3F301403.5000104@cso.atmel.com>

As part of a bigger software project, I'll be transferring data from a 
old GDBM database into a PostGre database. I thought a good way of 
getting data out of the unreliable GDBM database and into the PostGre 
database was to extract the info out of GDBM as an XML doc, and import 
it into PostGre. No big problems getting the XML doc out of the GDBM 
database. It's about 17MB. In order to parse it, I'll need SAX instead 
of DOM.  Before I tackle that, I thought I'd get a better handle on 
classes and using SAX. I found a little cd XML document that looked good 
to play with.(see below)  I wrote a little, python program that uses SAX 
and parses the XML doc printing the element names and the characters 
found. That worked. Then I thought I'd make a little CD class, while 
parsing, load a cd into the class, then print the values from the class 
when the closing CD element is found. That's when the trouble starts. 
AttributeError: element_name(see below). Should I be posting this on the 
XML-SIG mail list? I'm still pretty new to Python. Also, has anyone seen 
examples of using SAX to load a database with some validation before you 
dump it into the database? The only examples I've run across are 
searching for things in the XML doc using SAX.

Thanks,

Mike

#!/usr/bin/env python

from xml.sax import make_parser, SAXException
from xml.sax.handler import ContentHandler

class CD(object):
    __slots__ = 
'title','artist','country','company','price','year','element_name'

    def displayCD(self):
        print "CD"
        print "TITLE: " + self.title
        print "ARTIST: " + self.artist
        print "COUNTRY: " + self.country
        print "COMPANY: " + self.company
        print "PRICE: %.2f" % (self.price)
        print "YEAR: %d" % (self.year)

class XContentHandler(ContentHandler):
    def startElement(self,name,attrs):
        if name=='CD':
            print "New CD\n"
            cd = CD()   # create a new CD object when CD start tag is found.
        elif name == 'TITLE':
            print "Title "
            cd.element_name = "title"
        elif name == "ARTIST":
            print "Artist "
            cd.element_name = "artist"
        elif name == "COUNTRY":
            print "Country "
            cd.element_name = "country"
        elif name == "COMPANY":
            print "Company "
            cd.element_name = "company"
        elif name == "PRICE":
            print "Price "
            cd.element_name = "price"
        elif name == "YEAR":
            print "Year "
            cd.element_name = "year"
        elif name == "CATALOG":
            print "CATALOG"
        else:
            print "ELEMENT NOT DEFINED"
           


    def endElement(self,name):
        if name=='CD':
            print "DONE WITH CD\n"
            cd.displayCD()  
        elif name == 'CATALOG':
            print "END OF DOCUMENT"

    def characters(self,chars):
        if cd.element_name == "title":

-----
BOOM...
AttributeError: element_name
Makes sense. def characters doesn't know about the CD object. How do I 
pass it in? Also, is there a better way to load the object than checking 
each element_name? Like cd."element_name" = chars?
-----
            cd.title = chars
        elif cd.element_name == "artist":
            cd.artist = chars
        elif cd.element_name == "country":
            cd.country = chars
        elif cd.element_name == "company":
            cd.company = chars
        elif cd.element_name == "price":
            cd.price = chars
        elif cd.element_name == "year":
            cd.year = chars
           
        print chars + "\n"


handler = XContentHandler()
parser = make_parser()
parser.setContentHandler(handler)
fh = open('C:/Documents and Settings/mhansen/Desktop/sample2.xml', 'r')
parser.parse(fh)
fh.close()

-----

<?xml version="1.0"?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR></YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Still got the blues</TITLE>
    <ARTIST>Gary Moore</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Virgin records</COMPANY>
    <PRICE>10.20</PRICE>
    <YEAR>1990</YEAR>
  </CD>
  <CD>
    <TITLE>Eros</TITLE>
    <ARTIST>Eros Ramazzotti</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>BMG</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1997</YEAR>
  </CD>
  <CD>
    <TITLE>Red</TITLE>
    <ARTIST>The Communards</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>London</COMPANY>
    <PRICE>7.80</PRICE>
    <YEAR>1987</YEAR>
  </CD>
  <CD>
    <TITLE>Unchain my heart</TITLE>
    <ARTIST>Joe Cocker</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>EMI</COMPANY>
    <PRICE>8.20</PRICE>
    <YEAR>1987</YEAR>
  </CD>
</CATALOG>  




From jeff@ccvcorp.com  Tue Aug  5 18:23:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Aug  5 17:23:02 2003
Subject: [Tutor] Popen
References: <001401c35b76$85c1e050$a74c41db@VULCAN>
Message-ID: <3F30205C.40806@ccvcorp.com>

G Kiran wrote:

>the following is the code...
>the b.read from the pipe doesnot return and blocks there itself...since
>cmd.exe does not end on its own
>is there a way to open a two way pipe...so i can send and "exit" command to
>end the shell...or write and read without blocking?
>

Sure -- look at the docs for os.popen2() [or popen3()/popen4()].  These 
will give you two (or three) pipe handles instead of just one -- a 
stdout handle like os.popen(), and also a stdin handle (and possibly a 
stderr() handle as well).

inp, outp = os.popen2("...")
inp.write('blah blah blah')
inp.flush()
result = outp.read()

You simply call the input handle's write() method; this will be 
interpreted by the pipe as coming from stdin.  You need to call flush() 
once you've written something, though, because this uses a buffered I/O 
model and the other end of the pipe may or may not receive input that 
hasn't been flush()ed.  When you're done, you can simply call close() on 
all of your I/O handles.

Be aware, however, that there's certain special programs that don't read 
from stdin.  For example, ssh and its relatives request passphrases 
directly from the tty device that they're connected to, rather than from 
stdin -- this prevents a number of password-snooping attacks, but adds 
some challenges to scripting.  (In this example, the solution is to use 
passphrase-less public-key authentication, but that's another story.)

Jeff Shannon
Technician/Programmer
Credit International




From idiot1@netzero.net  Tue Aug  5 21:32:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Tue Aug  5 20:32:01 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
Message-ID: <3F304C17.8030502@netzero.net>

oy vey...

A STATE MACHINE is in effect a computer. It is simulated in code. It is 
customized for the task at hand. A simple state machine would be a 
turing machine if it was 'turing complete'. A turing machine is the 
minimal machine which may be properly called 'a computer'.

I may run off screaming... I  hope someone, ANYONE, can provide some advice.

A state machine is a sequential process which remembers previous STATE, 
and this influences it's behavior. It is programmable, and acts like a 
special purpose computer- or a general purpose one. When it is tailored 
for it's goal task, it is very powerful for that,, and somewhat simpler 
than a general purpose state machine.

Mr Turing came  up with this back in 1936, and it is credited as being 
the first design for a 'electronic' computer, as it could be implemented 
in relays, or vaccum tubes. Mr Babbage's 19th century design was quite 
different, and exclusively baised on mechanical principles, not logical 
ones.

Here is a simple turing machine.
There is only one command, but several subcommands.

It has a memory field for the commands, and another for a data 'tape'. 
This is conceived of as an infinately long paper tape, and some means of 
writing marks to it, erasing marks, READING them, and moving the tape 
left or right one 'step' This could be implemented as a long row of 
bits, for instance, in a large (looped?) memory array-  or cells in a 
list, with the proper code to loop back to the beginning.

The command is stored in memory TWICE. One is read and executed if the 
CURRENT location in the TAPE is a 0, and the other one is read if the 
current location of the tape is a 1.

The command does one thing: it writes the data to the tape, and moves 
the tape one space to the left or the right. WHICH half of the command 
is read and executed is determined by the STATE of the tape cel being 
examined by the head. The command provides the address to be next 
executed; all the cpu logic does is store the data to address the 
program memory. The tape, implemented in electronics, would be a 1 bit 
memory chip addressed by a up/down counter with binary output, and 
someform oc clocking to step it up or down on count.

The commands are formatted as:

        0   |     1
<-> D ADDR | <-> D ADDR

This means DIRECTION (<=left, >=right), D(ATA) (0 or 1) and NEXT 
ADDRESS. The partial command under 0 is executed if TAPE is 0, and under 
1 is executed if TAPE is 1. You can implement a computer this simple in 
relay logic, if you have a large shipping crate of them. Half wave 
recrified AC for a clock source ought to work. The relays of course 
would want filtered DC. Some extra logic to assist in programming and 
preloading the tape is a major assett. Buck Roger's fans might dare to 
implement the design with these newfangled germanium 'transistor' thingies.

Numbers are stored on the tape as uniary numbers. ???


a zero is a 1.
a ONE is a 11.
a TWO is a 111.
a THREE is a 1111.

to add two numbers is simple. Put them next to one another, turn the 0 
between them into a 1, then trim off two 1 bits, and sit still someplace.

Here ia a program to do this:
First, using manaual control hardware, load the blank tape with:
"0000000000000000011011000000000000000000"
           ^
The caret indicates a place on the tape where the read/write head 
starts. If the tape is a loop, we don't care where it is to start, the 
program will loop it to the right until it encounters the beginning of 
the data field.

ADDR        0   |     1
      <-> D ADDR | <-> D ADDR
0000: >  0 0000 |  >  1 0001
0001: >  1 0002 |  >  1 0001
0002: <  0 0003 |  >  1 0002
0003:  X        |  <  0 0004
0004:  X        |  <  0 0005
0005: < 0 0005  |  >  1 0005
X= don't care, never seen.

oooo writes a zero to the sero, moves head to right. Executes oooo as 
next address.

when it encounters a 1, it writes a 1 to the tape (so it does not 
change) and executes 0001 as the next step.

0001 steps through the 1's, and when it finds the intermediate 0 turns 
it to a 1, then goes to 0002.

You can follow it from there. When the thing STAYS on 0005, it's done. 
Turn off the clock source and read the tape manually for the answer to 
the deep mystery of the sum of 2+2.

THAT is a turing machine. It is a complete computer, and can compute 
ANYTHING. Eventually. If you do not go insane first.

And is a complete pain in the ass.

That ends today's compsci knowledge lecture. Asprin may be purchased at 
the vending machine in the lobby.

I coded one in basic several years ago. I may do it in python. Now, I 
may have to.

Where's the scotch?


John Miller wrote:

> Sean 'Shaleh' Perry <shalehperry@comcast.net> wrote:
> 
>> look at htmlparser's code.  What you need is a state machine ......
> 
> 
> "Rodrigues" <op73418@mail.telepac.pt> wrote:
> 
>> Re's can't, I repeat, can't parse text with structure, you need a full
>> parser (state machine) for it. They can be used however to tokenize
>> the text, e.g. recognize the tags
> 
> 
> I wonder if someone could explain what is meant by a "state machine", 
> (and why regular expressions are insufficient for the kind of parsing 
> Kirk needs for his wiki...)? Thanks.
> 
> John Miller
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From gus.tabares@verizon.net  Tue Aug  5 21:53:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Tue Aug  5 20:53:01 2003
Subject: [Tutor] sys.path
Message-ID: <1060131275.30328.2.camel@blackbetty>

Hey all,

	I'm just curious if anyone else has noticed this in Python 2.3 under
Windows (2000). This may have been there in 2.2 and I just didn't notice
it:

>>> import sys, os
>>> for path in sys.path:
	if not os.path.exists(path):
		print path

C:\WINNT\system32\python23.zip
C:\Python23\lib\plat-win
>>>

What are these and if they do not exist why are they in sys.path? Anyone
know? Just curious..no big deal:)


-- 
/Gus



From rhseabrook@aacc.edu  Tue Aug  5 22:03:14 2003
From: rhseabrook@aacc.edu (Seabrook, Richard)
Date: Tue Aug  5 21:03:14 2003
Subject: [Tutor] what's a state machine?
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F7012907F8@AACC-MAIL.aacc.cc.md.us>



-----Original Message-----
From:	Kirk Bailey [mailto:idiot1@netzero.net]
Sent:	Tue 8/5/2003 8:30 PM
To:	tutor@python.org
Cc:=09
Subject:	Re: [Tutor] what's a state machine?
oy vey...

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D

Don't go off the deep end...  I think the point
of Sr. Rodrigues' remark about needing a state machine
was this:

The thing you're trying to match in a wiki is probably
more extensive than just a pattern of adjacent characters,
which is what regular expressions do best.  In fact, the
topics you want to retrieve will probably be represented
by ambiguous terms rather far apart in the context, relying
on the matching agent to remember what it has seen in=20
previous lines, sentences, paragraphs maybe, in order to=20
determine the meaning of terms presently being scanned.
That means you need a process that has a memory, a program
in high-level language, for which the Turing machine is the
bare-bones minimum archetype.
While regular expressions may come in handy for matching
specific words occasionally, your retrievals will probably
have to deal with multiple-word phrases and a good bit
of ambiguity.
Dick S.



From shalehperry@comcast.net  Tue Aug  5 22:11:02 2003
From: shalehperry@comcast.net (Sean 'Shaleh' Perry)
Date: Tue Aug  5 21:11:02 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <3F304C17.8030502@netzero.net>
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu> <3F304C17.8030502@netzero.net>
Message-ID: <200308051809.35091.shalehperry@comcast.net>

On Tuesday 05 August 2003 17:30, Kirk Bailey wrote:
> oy vey...
>
> A STATE MACHINE is in effect a computer. It is simulated in code. It is
> customized for the task at hand. A simple state machine would be a
> turing machine if it was 'turing complete'. A turing machine is the
> minimal machine which may be properly called 'a computer'.
>
> I may run off screaming... I  hope someone, ANYONE, can provide some
> advice.
>

And here you make the most common of programmer errors -- you make the 
solution too generic.

State machines can be quite simple and need not be something ultra-scary.

Basically you define states your parsing/program might take and what will 
cause the transition from state to state.  The advantage gained is that you 
now have context when you read the next piece of text to parse so you know 
what you expect to find.

let's pretend I am in state WANT_R_PARENS and the input stream looks like 
'blah)'.

does b get me out of WANT_R_PARENS? nope, let's store it instead.
does l? ...
a? ...
h? ...
)? ah, yes it does.  So now we have 'blah' and are ready to leave state 
WANT_R_PARENS.  Maybe this is a math app and instead of a string we would 
have expressions.

2 + (2+(3*2))

each time we hit the found R paren state we would compute the expression we 
just finished.

That's all a state machine is.

"Start in state BEGIN.  When the next token (aka character, symbol, etc) is a 
left paren enter state WANT_R_PARENT.  When a right paren is found compute 
the expression and return to the BEGIN state."

Now if we find some other state trigger before we satisfy WANT_R_PAREN then we 
have a parse error and need to handle it.

If the input was 2 + (2+(3*2()) for instance, we can only satisfy 
WANT_R_PARENT twice and will trigger an error.




From carroll@tjc.com  Tue Aug  5 22:46:21 2003
From: carroll@tjc.com (Terry Carroll)
Date: Tue Aug  5 21:46:21 2003
Subject: [Tutor] Graphical object browser?
Message-ID: <Pine.LNX.4.44.0308051840520.28264-100000@violet.rahul.net>

I'm trying to get started with the XML DOM interface, and am finding that 
I tend to get lost in the document object.

I've had this happen before on smaller scale, and worked through using 
dir(object) and dir(object.thing) and dir(object.thing[0].dohickie), etc. 
and it's kind of awkward.

I'm wondering if anyone can recommend any graphical way to browse a Python 
object.  I've found a couple but haven't tried then yet; I figured I'd ask 
for recommendations first, just in case the install might  screw something 
up.

So, any recommendations?

The two I've found are PTUI at http://starship.python.net/crew/zack/ptui/
and PyDebug at http://home.t-online.de/home/Ulrich.Herold/PyDIntro.htm


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982



From idiot1@netzero.net  Tue Aug  5 22:56:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Tue Aug  5 21:56:02 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <200308051809.35091.shalehperry@comcast.net>
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu> <3F304C17.8030502@netzero.net> <200308051809.35091.shalehperry@comcast.net>
Message-ID: <3F305FE1.8070904@netzero.net>

I think you are right, a state machine of some sort is the way to handle 
this task. This will demand writeng a number of functions, and saving 
state in some variables, or objects.

I think I shall lay in a generous supply of the Bushnell's Irish whiskey...

And drink deeply of the article pointed earlier on this list for IBM's 
state machine article. it is looking intresting! :-)


Sean 'Shaleh' Perry wrote:

> On Tuesday 05 August 2003 17:30, Kirk Bailey wrote:
> 
>>oy vey...
>>
>>A STATE MACHINE is in effect a computer. It is simulated in code. It is
>>customized for the task at hand. A simple state machine would be a
>>turing machine if it was 'turing complete'. A turing machine is the
>>minimal machine which may be properly called 'a computer'.
>>
>>I may run off screaming... I  hope someone, ANYONE, can provide some
>>advice.
>>
> 
> 
> And here you make the most common of programmer errors -- you make the 
> solution too generic.
> 
> State machines can be quite simple and need not be something ultra-scary.
> 
> Basically you define states your parsing/program might take and what will 
> cause the transition from state to state.  The advantage gained is that you 
> now have context when you read the next piece of text to parse so you know 
> what you expect to find.
> 
> let's pretend I am in state WANT_R_PARENS and the input stream looks like 
> 'blah)'.
> 
> does b get me out of WANT_R_PARENS? nope, let's store it instead.
> does l? ...
> a? ...
> h? ...
> )? ah, yes it does.  So now we have 'blah' and are ready to leave state 
> WANT_R_PARENS.  Maybe this is a math app and instead of a string we would 
> have expressions.
> 
> 2 + (2+(3*2))
> 
> each time we hit the found R paren state we would compute the expression we 
> just finished.
> 
> That's all a state machine is.
> 
> "Start in state BEGIN.  When the next token (aka character, symbol, etc) is a 
> left paren enter state WANT_R_PARENT.  When a right paren is found compute 
> the expression and return to the BEGIN state."
> 
> Now if we find some other state trigger before we satisfy WANT_R_PAREN then we 
> have a parse error and need to handle it.
> 
> If the input was 2 + (2+(3*2()) for instance, we can only satisfy 
> WANT_R_PARENT twice and will trigger an error.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From carroll@tjc.com  Tue Aug  5 23:17:16 2003
From: carroll@tjc.com (Terry Carroll)
Date: Tue Aug  5 22:17:16 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <3F305FE1.8070904@netzero.net>
Message-ID: <Pine.LNX.4.44.0308051914210.28264-100000@violet.rahul.net>

On Tue, 5 Aug 2003, Kirk Bailey wrote:

> I think you are right, a state machine of some sort is the way to handle 
> this task. This will demand writeng a number of functions, and saving 
> state in some variables, or objects.
> 
> I think I shall lay in a generous supply of the Bushnell's Irish whiskey...

You know,it occurs to me you're working in HTML.  It might be worthwhile 
to consider using XHTML, which is HTML expressed in XML, and then using an 
XML parser.  The SAX parser is an XML state machine, essentially.  The 
first couple chapters of the O'Reilley XML & Python book show how to use 
it, pretty clearly.

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982



From klhjhm@hotmail.com  Wed Aug  6 01:24:02 2003
From: klhjhm@hotmail.com (kamariah lamim)
Date: Wed Aug  6 00:24:02 2003
Subject: [Tutor] help on  string replacement in a file
Message-ID: <BAY1-F1397Mx5EuSwCG00016d25@hotmail.com>

Hi.
   I wrote a function to replace a string in a file.I used built-in replace( 
) to do that . However it failed to overwrite the old content of file with 
the new one. . Could someone trace this problem.the function is something 
like this:

lineseen=0
drot='0.678'
batchNo=1

def modify5File(drot,batchNo):
	global lineSeen
	updateFile=open('disper.501','rw')
	x=updateFile.readlines()
	for everyLine in x:
		lineSeen += 1
		if lineSeen == 10:
			string.replace(everyLine,'+0.2000000000d+00',drot,1)
		else:
			pass
	updateFile.close()

_________________________________________________________________
Using a handphone prepaid card? Reload your credit online! 
http://www.msn.com.my/reloadredir/default.asp



From steveng@pop.jaring.my  Wed Aug  6 02:56:02 2003
From: steveng@pop.jaring.my (Stephen Ng)
Date: Wed Aug  6 01:56:02 2003
Subject: [Tutor] floating point accuracy
Message-ID: <1060149292.8584.40.camel@nutek-1>

Hi!

I am a total newcomer to python so still trying to find out what its all
about.

I tried the following 2/5.0 and received 0.40000000000000002.

The 2 at the end makes me wonder whether this is normal and how accurate
floating point arithmetic is.

Stephen Ng



From thomi@thomi.imail.net.nz  Wed Aug  6 03:08:02 2003
From: thomi@thomi.imail.net.nz (Thomas Clive Richards)
Date: Wed Aug  6 02:08:02 2003
Subject: [Tutor] floating point accuracy
In-Reply-To: <1060149292.8584.40.camel@nutek-1>
References: <1060149292.8584.40.camel@nutek-1>
Message-ID: <20030806180700.2d59ccef.thomi@thomi.imail.net.nz>

Hi,


> 
> I tried the following 2/5.0 and received 0.40000000000000002.
> 

Even if you take that value at face value (and i suggest you don't),
that's accurate enough, isn't it? the difference between that and the
real answer is only 2 in 10,000,000,000,000,000 (two in ten million
billion, or (depending on where you come from, a trillion))...

I'd say that's pretty good!!

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From klappnase@freenet.de  Wed Aug  6 06:07:02 2003
From: klappnase@freenet.de (klappnase)
Date: Wed Aug  6 05:07:02 2003
Subject: [Tutor] help on  string replacement in a file
In-Reply-To: <BAY1-F1397Mx5EuSwCG00016d25@hotmail.com>
References: <BAY1-F1397Mx5EuSwCG00016d25@hotmail.com>
Message-ID: <20030806110739.4f338462.klappnase@freenet.de>

On Wed, 06 Aug 2003 12:22:34 +0800
"kamariah lamim" <klhjhm@hotmail.com> wrote:

> Hi.
>    I wrote a function to replace a string in a file.I used built-in replace( 
> ) to do that . However it failed to overwrite the old content of file with 
> the new one. . Could someone trace this problem.the function is something 
> like this:
> 
> lineseen=0
> drot='0.678'
> batchNo=1
> 
> def modify5File(drot,batchNo):
> 	global lineSeen
> 	updateFile=open('disper.501','rw')
> 	x=updateFile.readlines()
> 	for everyLine in x:
> 		lineSeen += 1
> 		if lineSeen == 10:
> 			string.replace(everyLine,'+0.2000000000d+00',drot,1)
> 		else:
> 			pass
> 	updateFile.close()
> 
Hi,

I am not sure about that, but I think you should use the fileinput module for that, like:

def modify5File():
    for line in fileinput.input(path-to-file, inplace=1):
        line = line.replace('+0.2000000000d+00', '0.678')
        sys.stdout.write(line)

This should replace every '+0.2000000000d+00' in the file with '0.678' .

Best regards

Michael


From op73418@mail.telepac.pt  Wed Aug  6 08:47:30 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Wed Aug  6 07:47:30 2003
Subject: [Tutor] help on  string replacement in a file
In-Reply-To: <BAY1-F1397Mx5EuSwCG00016d25@hotmail.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKCEDFCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> kamariah lamim
> Sent: quarta-feira, 6 de Agosto de 2003 5:23
> To: tutor@python.org
> Subject: [Tutor] help on string replacement in a file
>
>
> Hi.
>    I wrote a function to replace a string in a file.I used
> built-in replace(
> ) to do that . However it failed to overwrite the old
> content of file with
> the new one. . Could someone trace this problem.the
> function is something
> like this:
>
> lineseen=0
> drot='0.678'
> batchNo=1
>
> def modify5File(drot,batchNo):
> 	global lineSeen
> 	updateFile=open('disper.501','rw')
> 	x=updateFile.readlines()

Here, you read the contents of updateFile *into memory* as a list of
lines.

> 	for everyLine in x:
> 		lineSeen += 1
> 		if lineSeen == 10:
>
> string.replace(everyLine,'+0.2000000000d+00',drot,1)
> 		else:
> 			pass

Here, you replace the offending lines with new ones, but *only* in
your in-memory list of lines.

> 	updateFile.close()
>

Here, you close the file.

You forgot to write everything back to the file *in disk*.

Hope that gives you a start, with my best regards,
G. Rodrigues



From op73418@mail.telepac.pt  Wed Aug  6 09:09:01 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Wed Aug  6 08:09:01 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
Message-ID: <DCEDLKJJJGHMCOCFGMGKMEDFCBAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> John Miller
> Sent: terca-feira, 5 de Agosto de 2003 18:29
> To: tutor@python.org
> Subject: [Tutor] what's a state machine?
>
>
> Sean 'Shaleh' Perry <shalehperry@comcast.net> wrote:
>
> > look at htmlparser's code.  What you need is a state
> machine ......
>
> "Rodrigues" <op73418@mail.telepac.pt> wrote:
>
> > Re's can't, I repeat, can't parse text with structure,
> you need a full
> > parser (state machine) for it. They can be used however
> to tokenize
> > the text, e.g. recognize the tags
>
> I wonder if someone could explain what is meant by a "state
> machine",
> (and why regular expressions are insufficient for the kind
> of parsing
> Kirk needs for his wiki...)? Thanks.
>

Consider the following HTML-like text:

<p>
some text
<b>
more text
</b>
even more text
<p>
you guessed it: more text
</p>
and here's some more text
</p>

You want to catch pairs of corresponding tags <*>...</*>. But there's
no re that will do it (in all generality, that is) - either you'll
catch too much or too little. The problem is that this is a
*structured* text - there is a pair <p>...</p> nested inside the outer
<p>...</p> pair. In order to catch *corresponding* pairs of tags
<*>...</*> you have to know *how deep* you are to match the tags
correctly. This "level of depthness" is precisely the internal state
that needs to be kept each time and that re's do not have. re's view
all text as flat, no depthness.

Hope I have made myself explained,
G. Rodrigues



From cybersamurai@terra.com.br  Wed Aug  6 09:38:02 2003
From: cybersamurai@terra.com.br (=?iso-8859-1?Q?cybersamurai?=)
Date: Wed Aug  6 08:38:02 2003
Subject: [Tutor] =?iso-8859-1?Q?dial-up_from_Python?=
Message-ID: <HJ771Q$FCAB2FAB02F63ADC128B9A5576D2284C@terra.com.br>

--_=_XaM3_Bdry.1060173422.2A.34356.42.9800.52.42.1010.1113712389
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable

How to create a dial-up connection and use it from Python?
--_=_XaM3_Bdry.1060173422.2A.34356.42.9800.52.42.1010.1113712389
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable

<DIV>How to create a dial-up connection and use it from Python?</DIV>
--_=_XaM3_Bdry.1060173422.2A.34356.42.9800.52.42.1010.1113712389--



From godoy@metalab.unc.edu  Wed Aug  6 11:41:01 2003
From: godoy@metalab.unc.edu (Jorge Godoy)
Date: Wed Aug  6 10:41:01 2003
Subject: [Tutor] Passwords in Windows
Message-ID: <m3vftakg2g.fsf@ieee.org>

Hi!


How do you generate and validate passwords while using Windows? For
unices one can use the crypt module to accomplish both tasks, but it's
unavailable on Windows. 

Do you change your authentication methods to use another crypto
system? Which one provides the same easy way to handle passwords that
crypt does? Is it available on unices too? 


Thanks in advance,
-- 
Godoy.     <godoy@metalab.unc.edu>


From ATrautman@perryjudds.com  Wed Aug  6 13:15:02 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Wed Aug  6 12:15:02 2003
Subject: [Tutor] floating point accuracy
Message-ID: <06738462136C054B8F8872D69DA140DB010888@corp-exch-1.pjinet.com>

That is normal for all base 8 cpu's (almost all made). The only method to be
highly precise is to do longhand division (ie.. subtract many times) using
integers or to purchase a large scale vector-based cpu machine $$$$. You
just happened to pick a really simple to reproduce example.

It has nothing to do with the language used, although some languages hide
this fact from you, it is just a hardware based limitation.

HTH,
Alan

-----Original Message-----
From: Stephen Ng [mailto:steveng@pop.jaring.my]
Sent: Wednesday, August 06, 2003 12:55 AM
To: tutor@python.org
Subject: [Tutor] floating point accuracy


Hi!

I am a total newcomer to python so still trying to find out what its all
about.

I tried the following 2/5.0 and received 0.40000000000000002.

The 2 at the end makes me wonder whether this is normal and how accurate
floating point arithmetic is.

Stephen Ng


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


From missive@hotmail.com  Wed Aug  6 13:54:02 2003
From: missive@hotmail.com (Lee Harr)
Date: Wed Aug  6 12:54:02 2003
Subject: [Tutor] Re: sys.path
Message-ID: <BAY2-F73CHJr1Wtyi670000c7e1@hotmail.com>

>        I'm just curious if anyone else has noticed this in Python 2.3 
>under
>Windows (2000). This may have been there in 2.2 and I just didn't notice
>it:
>
>>>>import sys, os
>>>>for path in sys.path:
>        if not os.path.exists(path):
>                print path
>
>C:\WINNT\system32\python23.zip
>C:\Python23\lib\plat-win
>>>>
>
>What are these and if they do not exist why are they in sys.path? Anyone
>know? Just curious..no big deal:)
>


Importing from zip files is new in 2.3.  I think it makes it easier to 
install
python on systems with limited resources (think embedded systems,
PDAs, etc)

I am not sure what plat-win is, but I assume it is platform-specific modules
related to running in windows.  Maybe that folder was there in 2.2 because
you had used it for a while and had installed some things in that folder.
It may get created the first time you try to install there...

I guess the import mechanism is smart enough to just skip over those
elements in sys.path that do not exist.

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. 
http://join.msn.com/?page=features/junkmail



From dyoo@hkn.eecs.berkeley.edu  Wed Aug  6 15:10:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug  6 14:10:03 2003
Subject: [Tutor] floating point accuracy  [working with Fractions]
In-Reply-To: <06738462136C054B8F8872D69DA140DB010888@corp-exch-1.pjinet.com>
Message-ID: <Pine.LNX.4.44.0308060957580.30056-100000@hkn.eecs.berkeley.edu>


On Wed, 6 Aug 2003, Alan Trautman wrote:

> You just happened to pick a really simple to reproduce example.
>
> It has nothing to do with the language used, although some languages
> hide this fact from you, it is just a hardware based limitation.


But even vector machines will probably have a hard time if they use
floating point notation.  This isn't a hardware problem as much as it is a
representation problem.

Most programmers have chosen a form of number representation that
guarantees efficient computation, at the expense of not being able to
represent all numbers precisely. This representation is called "floating
point", named because the computer stores as many digits of a number as it
can ("mantissa"), followed by the position of the decimal point
("exponent").

The problem with this representation is that it's inexact --- it only
stores a limited number of digits.  The Python Tutorial touches on this
issue:

    http://www.python.org/doc/current/tut/node14.html



That being said, nothing stops us from representing fractions if we're
willing to do a little work.  Here's a really hacky implementation of a
Fraction class:


###
class Fraction:
    def __init__(self, n, d=1):
        """Creates a new fraction with numerator n and denominator d"""
        self.n = n
        self.d = d
        self.reduce()

    def reduce(self):
        """Reduces a fraction."""
        g = gcd(self.n, self.d)
        self.n, self.d = (self.n / g,  self.d / g)

    def __add__(self, other):
        """Adds two Fractions."""
        return self.__class__(self.n * other.d + other.n * self.d,
                              self.d * other.d)

    def __sub__(self, other):
        """Subtracts two Fractions."""
        return self.__class__(self.n * other.d - other.n * self.d,
                              self.d * other.d)

    def __mul__(self, other):
        """Multiplies two Fractions."""
        return self.__class__(self.n * other.n, self.d * other.d)

    def __div__(self, other):
        """Divides two Fractions."""
        return self.__class__(self.n * other.d, self.d * other.n)

    def __str__(self):
        """Returns a nicely formatted string of our Fraction."""
        return "(%d / %d)" % (self.n, self.d)

    def __repr__(self):
        return "Fraction(%d, %d)" % (self.n, self.d)



def gcd(x, y):
    """Returns the greatest common denominator of x and y."""
    if y == 0: return x
    return gcd(y, x % y)
###



Let's see if it works ok:

###
>>> x = Fraction(2) / Fraction(5)
>>> print x
(2 / 5)
>>> x + x
Fraction(4, 5)
>>> x * x
Fraction(4, 25)
>>> x / x
Fraction(1, 1)
>>> x + Fraction(4,7)
Fraction(34, 35)
###


The above code is NOT meant to be used in a production environment.
*grin* I just hacked it up to show that doing rational math is perfectly
possible in Python.  There's a more serious PEP that discusses the pros
and cons of adding real Rationals:

    http://www.python.org/peps/pep-0239.html

and perhaps in the future it will become a standard type, just like
complex numbers.



Please feel free to ask questions about this.  Hope this helps!



From RASTM2@aol.com  Wed Aug  6 17:34:42 2003
From: RASTM2@aol.com (RASTM2@aol.com)
Date: Wed Aug  6 16:34:42 2003
Subject: [Tutor] Options - Format -  "String with no terminator" - bgcolor
Message-ID: <6b.16ab677d.2c62bf53@aol.com>

--part1_6b.16ab677d.2c62bf53_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Hello Y'all,

Pythonwin23 #46
Win98(notSE)
Pythonwin - View Menu - Options - Format - 
"String with no terminator" - bgcolor

I went and done it. I thought I'd change the Default color for the editor's 
"String with no terminator" from Olive Drab ( because I can't see black thru 
it)
to a brighter color and now it's set on the Default background color of 
White.
The thing just won't APPLY because the APPLY Button won't "un grey".
The change shows up in the little preview changes window on the left 
any old how you like it, but it won't even go back to Olive. 

I don't get it.
I was huntin' around some of the files for a couple hours and looking for it 
in the help but nuthin.

Will some kind person tell me which config file I gotta hack to get any
kinda response from this setting. 

I know it's an exterior config file cuz I dumped the whole thing and 
downloaded
another one - yah I know, drastic - but I am a Newbie and I would hate to 
mess
up something else by hunt and peck.

Ray - Rastm2@aol.com

--part1_6b.16ab677d.2c62bf53_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">Hello Y'all,<BR>
<BR>
Pythonwin23 #46<BR>
Win98(notSE)<BR>
Pythonwin - View Menu - Options - Format - <BR>
"String with no terminator" - bgcolor<BR>
<BR>
I went and done it. I thought I'd change the Default color for the editor's=20=
<BR>
"String with no terminator" from Olive Drab ( because I can't see black thru=
 it)<BR>
to a brighter color and now it's set on the Default background color of Whit=
e.<BR>
The thing just won't APPLY because the APPLY Button won't "un grey".<BR>
The change shows up in the little preview changes window on the left <BR>
any old how you like it, but it won't even go back to Olive. <BR>
<BR>
I don't get it.<BR>
I was huntin' around some of the files for a couple hours and looking for it=
 <BR>
in the help but nuthin.<BR>
<BR>
Will some kind person tell me which config file I gotta hack to get any<BR>
kinda response from this setting. <BR>
<BR>
I know it's an exterior config file cuz I dumped the whole thing and downloa=
ded<BR>
another one - yah I know, drastic - but I am a Newbie and I would hate to me=
ss<BR>
up something else by hunt and peck.<BR>
<BR>
Ray - Rastm2@aol.com<BR>
</FONT></HTML>
--part1_6b.16ab677d.2c62bf53_boundary--


From alan.gauld@blueyonder.co.uk  Wed Aug  6 18:09:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 17:09:01 2003
Subject: [Tutor] what's a state machine?
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu> <3F304C17.8030502@netzero.net>
Message-ID: <007001c35c5e$a84ff740$6401a8c0@xp>

Kirk wrote a fine description of state machine theory...

> THAT is a turing machine. It is a complete computer, and can compute
> ANYTHING. Eventually. If you do not go insane first.
>
> And is a complete pain in the ass.

To which I add that while Turing complete state machines are
hard dedicated purpose state machines are both very easy to
build, easy to maintain and extremely performant. This is
the reason why most large scale real-time systems are built
as state machines. Its also why a complete methodology and
notation exists to document such machines - its called SDL
- The Specification and Design Language, and is used to design
almost all modern telephone exchanges, air-traffic control
systems, railway control systems, factory control etc etc.

The secret is to model the machine as a big table:

Current State|Event|Action|Next State

You then define numeric values(or hash keys) for each state
and each event, load pointers/rferences to functions into
the action column and set of a loop that looks something
like this:

while True:
   EventID = getEvent()  # figure out how to get the events!
   try:
      StateTable[myState][EventID].Action()
      myState = StateTable[myState][EventID].nextState
   except:  # handle an error

Another strategy is that the Action should return nextState
but that prevents you from reusing action functions...

Now adding states, events or actions becomes a relatively simple
table build issue. And that can be done from a text file at startup...

Alan G.



From alan.gauld@blueyonder.co.uk  Wed Aug  6 18:09:16 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 17:09:16 2003
Subject: [Tutor] Graphical object browser?
References: <Pine.LNX.4.44.0308051840520.28264-100000@violet.rahul.net>
Message-ID: <007901c35c5e$f0295e30$6401a8c0@xp>

Pytonwin has both a COM object browser and Python object
browser built in.

They seemed to work OK on the few cases I've used them.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


----- Original Message -----
From: "Terry Carroll" <carroll@tjc.com>
To: <tutor@python.org>
Sent: Wednesday, August 06, 2003 2:45 AM
Subject: [Tutor] Graphical object browser?


> I'm trying to get started with the XML DOM interface, and am finding
that
> I tend to get lost in the document object.
>
> I've had this happen before on smaller scale, and worked through
using
> dir(object) and dir(object.thing) and dir(object.thing[0].dohickie),
etc.
> and it's kind of awkward.
>
> I'm wondering if anyone can recommend any graphical way to browse a
Python
> object.  I've found a couple but haven't tried then yet; I figured
I'd ask
> for recommendations first, just in case the install might  screw
something
> up.
>
> So, any recommendations?
>
> The two I've found are PTUI at
http://starship.python.net/crew/zack/ptui/
> and PyDebug at
http://home.t-online.de/home/Ulrich.Herold/PyDIntro.htm
>
>
> --
> Terry Carroll        |   "I say to you that the VCR is to the
American
> Santa Clara, CA      |   film producer and the American public as
the
> carroll@tjc.com      |   Boston strangler is to the woman home
alone."
>                      |       Jack Valenti, MPAA President
> Modell delendus est  |       Testimony before Congress, 1982
>
>
>
>
>



From klappnase@8ung.at  Wed Aug  6 18:10:05 2003
From: klappnase@8ung.at (Michael Lange)
Date: Wed Aug  6 17:10:05 2003
Subject: [Tutor] How to get messages from stderr
In-Reply-To: <3F294C59.5070803@ccvcorp.com>
References: <20030731021253.404a731a.klappnase@freenet.de>
 <Pine.A41.4.32.0307310346390.33464-100000@faust27-eth.rz.uni-frankfurt.de>
 <20030731111411.2285a507.klappnase@freenet.de>
 <3F294C59.5070803@ccvcorp.com>
Message-ID: <20030801022012.37113474.klappnase@8ung.at>

On Thu, 31 Jul 2003 10:05:29 -0700
"Jeff Shannon" <jeff@ccvcorp.com> wrote:

> I believe that your problem may be with using read(), with no arguments. 
>  By default, read() will return everything up to end-of-file.  For a 
> pipe, EOF doesn't occur until the pipe is closed.  Therefore, 
> self.ppp.read() will block until the pipe is closed, i.e. the command 
> stops running.
> 
> Try calling read() with an argument multiple times, and assembling the 
> results yourself.  In one of my own programs, I needed to supply input 
> to an external command, and determined that that command would output 
> exactly 18 bytes of data before waiting for input, so I used this code:
> 
>     def _runcommand(self, command):
>         print command
>         i, o = os.popen4(command)
>         print o.read(18)
>         i.write(self.paramstring)
>         i.write('\n')
>         i.flush()
>         result = o.readlines()
>         return result
> 
> I couldn't just use read() or readlines(), because those calls would 
> hang waiting for EOF or EOL respectively, neither of which would happen 
> at the point I was interested in.
> 
Thanks for that hint!
Now I do get the messages from stderr, but somehow the child process gets extremely slowed down.
What have I done wrong here?


	def normalize(self, ev):
		'''Starts "normalize -m" on all selected files.'''
		if self.tracklist.listbox.size() == 0:
			tkMessageBox.showerror(message=nofilesmsg)
		elif self.tracklist.listbox.size() == 1:
			tkMessageBox.showerror(message=normfailmsg)
		else:
			shallwenormalize = tkMessageBox.askokcancel(message=shallwenormalizemsg, title='phononormalizer')
			if shallwenormalize:
			        filelist = ''
				selectedfiles = self.tracklist.listbox.get(0, END)
				for i in range(len(selectedfiles)):
					filelist = filelist + ' ' + selectedfiles[i]
			        normalizecmd = 'normalize -m ' + filelist
				self.pp = popen2.Popen4(normalizecmd)
				print 'Phononormalizer: Starting process "normalize" at PID ' + str(self.pp.pid)
				self.ppp = self.pp.fromchild
				self.frame.after(1000, self.getmsg)


	def getmsg(self):
		if self.pp.poll() == -1:
			bb = self.ppp.read(100)
			print bb
            		self.frame.after(1000, self.getmsg)
		else:
			print 'Phonormalizer: finished'

With getmsg() I want to capture normalize's  output for a window with a progress meter, but with this function normalizing a few
test files which normally takes about 2 or 3 seconds takes more than a minute.

Thanks for your patience with silly newbies like me

Michael


From amk@amk.ca  Wed Aug  6 18:10:17 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Wed Aug  6 17:10:17 2003
Subject: [Tutor] why use *get*
In-Reply-To: <200308011015.07012.cybersamurai@mac.com>
References: <200308011015.07012.cybersamurai@mac.com>
Message-ID: <20030801132630.GA22514@vail.asti-usa.com>

On Fri, Aug 01, 2003 at 10:15:06AM -0300, Luiz Siqueira Neto wrote:
> d = {'name':'foo'}
> 
> ### all this instructions have the same result
> d['name'] = d.get('name', 0) + 'bar'

.get() makes a difference when you're accessing a key that *isn't* in the 
dictionary; in that case it returns the value of its second argument.

d['title'] raises a KeyError exception.
d.get('title', 'Untitled') returns the string "Untitled".

This is useful when you want to get a value from a dictionary but
don't want to crash if the key isn't there, e.g. if processing
e-mails, you don't want to stop with a KeyError if a message lacks a
'Subject' header.

--amk
Things are getting out of control; even *I* can't play this many games at once!
      -- The Doctor, in "Ghost Light"


From fards@earthlink.net  Wed Aug  6 18:10:34 2003
From: fards@earthlink.net (Seyed Fard)
Date: Wed Aug  6 17:10:34 2003
Subject: [Tutor] python22
Message-ID: <MDEEJCJPNMNONNLDFLLFGEOLCAAA.fards@earthlink.net>

This is a multi-part message in MIME format.

------=_NextPart_000_0000_01C35822.F08FE3C0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello.
I have python22 installed.
I am able to use IDLE (GUI) to RUN SCRIPTS.
I can also RUN saved files from a MS DOS command line window.
I don't know what the PYTHON(command line) window that is available in
PYTHON22 drag down menu used for. when I open this command line it starts
with >>> and I can not run saved programs with it.how this command line
used?
thank you

------=_NextPart_000_0000_01C35822.F08FE3C0
Content-Type: application/ms-tnef;
	name="winmail.dat"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename="winmail.dat"

eJ8+IhIPAQaQCAAEAAAAAAABAAEAAQeQBgAIAAAA5AQAAAAAAADoAAEIgAcAGAAAAElQTS5NaWNy
b3NvZnQgTWFpbC5Ob3RlADEIAQ2ABAACAAAAAgACAAEGgAMADgAAANMHCAABAAsAMQAAAAUAJAEB
A5AGAMgFAAAlAAAACwACAAEAAAALACMAAAAAAAMAJgAAAAAACwApAAAAAAADADYAAAAAAB4AcAAB
AAAACQAAAHB5dGhvbjIyAAAAAAIBcQABAAAAFgAAAAHDWER3JLyMJPUv4UhFpO9gq7vMHZ4AAAIB
HQwBAAAAGQAAAFNNVFA6RkFSRFNARUFSVEhMSU5LLk5FVAAAAAALAAEOAAAAAEAABg4AvqBsRFjD
AQIBCg4BAAAAGAAAAAAAAADpNbj0HKPDRJKfNetlR0cWwoAAAAsAHw4BAAAAAgEJEAEAAACNAQAA
iQEAAAUCAABMWkZ1HxNo0QMACgByY3BnMTI1FjIA+Atgbg4QMDMzTwH3AqQD4wIAY2gKwHOwZXQw
IAcTAoB9CoGSdgiQd2sLgGQ0DGAOYwBQCwMLtSBIZWxNCQAuCqIKgEkgEPB2QGUgcHl0aAIgMvQy
IAuAcwGQE/AJgBQnHGFtFqACYBTgdG8gAnURICBJRExFICAoR1VJKRciUlUCTgYAQ1JJUFRTrRQn
YwORB0BzGGRzFMH4ZCBmAxAHkQNSFqAF0mxETwXwBaBtA4Ea0GzPC4AU4APwEoBvdxQnHTDkbicF
QGtuHUAc8BDwBwVAFSAU4FBZVEhP/E4oHDoYMB0EHuEewQQA/RagdgtwC2AW8guAHyUVYdBkcmFn
HeF3A6AHgNxudRdSGtEFsC4ekQnw8ReQIG9wJIEVICFBHDt+aQVAFbEAIAQgA/AVICB+PicwFqAc
gRmkHmAFQHL2dQOgGpRwA2AJwBawJsW9JkAuFTAg0iVOI8I/FDThIPFuayB5CGAUNBHhAgAtQAAA
AAsAAYAIIAYAAAAAAMAAAAAAAABGAAAAAAOFAAAAAAAAAwADgAggBgAAAAAAwAAAAAAAAEYAAAAA
EIUAAAAAAAADAAeACCAGAAAAAADAAAAAAAAARgAAAABShQAAJ2oBAB4ACYAIIAYAAAAAAMAAAAAA
AABGAAAAAFSFAAABAAAABAAAADkuMAAeAAqACCAGAAAAAADAAAAAAAAARgAAAAA2hQAAAQAAAAEA
AAAAAAAAHgALgAggBgAAAAAAwAAAAAAAAEYAAAAAN4UAAAEAAAABAAAAAAAAAB4ADIAIIAYAAAAA
AMAAAAAAAABGAAAAADiFAAABAAAAAQAAAAAAAAALAA2ACCAGAAAAAADAAAAAAAAARgAAAACChQAA
AQAAAAsAOoAIIAYAAAAAAMAAAAAAAABGAAAAAA6FAAAAAAAAAwA8gAggBgAAAAAAwAAAAAAAAEYA
AAAAEYUAAAAAAAADAD2ACCAGAAAAAADAAAAAAAAARgAAAAAYhQAAAAAAAAMAWoAIIAYAAAAAAMAA
AAAAAABGAAAAAAGFAAAAAAAACwBrgAggBgAAAAAAwAAAAAAAAEYAAAAABoUAAAAAAAACAfgPAQAA
ABAAAADpNbj0HKPDRJKfNetlR0cWAgH6DwEAAAAQAAAA6TW49Byjw0SSnzXrZUdHFgIB+w8BAAAA
cwAAAAAAAAA4obsQBeUQGqG7CAArKlbCAABQU1RQUlguRExMAAAAAAAAAABOSVRB+b+4AQCqADfZ
bgAAAEM6XFdJTkRPV1NcQXBwbGljYXRpb24gRGF0YVxNaWNyb3NvZnRcT3V0bG9va1xvdXRsb29r
LnBzdAAAAwD+DwUAAAADAA00/TcAAAIBfwABAAAAMwAAADxNREVFSkNKUE5NTk9OTkxERkxMRkdF
T0xDQUFBLmZhcmRzQGVhcnRobGluay5uZXQ+AAADAAYQ76XDbQMABxAkAQAAAwAQEAAAAAADABEQ
AAAAAB4ACBABAAAAZQAAAEhFTExPSUhBVkVQWVRIT04yMklOU1RBTExFRElBTUFCTEVUT1VTRUlE
TEUoR1VJKVRPUlVOU0NSSVBUU0lDQU5BTFNPUlVOU0FWRURGSUxFU0ZST01BTVNET1NDT01NQU5E
TEkAAAAAuis=

------=_NextPart_000_0000_01C35822.F08FE3C0--



From tlo@alias.com  Wed Aug  6 18:11:05 2003
From: tlo@alias.com (Terence Lo)
Date: Wed Aug  6 17:11:05 2003
Subject: [Tutor] outputting dictionary key/value pairs
Message-ID: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>

hi,

 supoose i create a dictionary of the form:

dict = {"d1": "a", "d2": "b", "d3": "c"}

why is it that when i loop through the dictionary,

eg.

for k,v in dict.items():
	print k,v


the dictionary items aren't output in the order they appear in the
dictionary.  they seem to be returned in an arbitrary order.

is there a quick way to loop through the dict and output the contents in
order?  namely  d1 .. d2.. d3 ?

thx in advance.

t



From Roeland.Rengelink@chello.nl  Wed Aug  6 18:11:21 2003
From: Roeland.Rengelink@chello.nl (Roeland Rengelink)
Date: Wed Aug  6 17:11:21 2003
Subject: [Tutor] Mutable String Question
In-Reply-To: <Sea2-F5hIP38GmvhZAi00031dd2@hotmail.com>
References: <Sea2-F5hIP38GmvhZAi00031dd2@hotmail.com>
Message-ID: <1060024571.1941.13.camel@linux.local>

Hi Marc,

Probably the easiest string 'buffer' is the list, combined with the
string method 'join'

Your example:


>>> word_list = ['My', 'name', 'is']
>>> a_string = ' '.join(word_list)
>>> a_string
'My name is'

The method join is called on a separator (in this case a space ' '), and
takes a list of string as an argument. The new string contains all the
strings from the list, sepated by the separator.

Hope this helps,

Roeland 

On Mon, 2003-08-04 at 02:56, Marc Barry wrote:
> All:
> 
> Is there a mutable string type such as a string buffer in Python?  I know 
> that string's in Python are immutable and therefore you cannot append to 
> them.  It seems terribly inefficient to do something like the following:
> 
> #------
> 
> a_string = ""
> word_list = ["My", "name", "is"]
> 
> for word in word_list:
> 	a_string = a_string + " " + word
> 
> print a_string
> 
> #------
> 
> I know that the above is a trivial example, but with the amount of text I am 
> processing this could have a significant impact on performance.  Does anyone 
> know of a better way to handle this?
> 
> Regards,
> 
> Marc
> 
> _________________________________________________________________
> Protect your PC - get McAfee.com VirusScan Online  
> http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From amk@amk.ca  Wed Aug  6 18:11:31 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Wed Aug  6 17:11:31 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2DD19A.9080205@netzero.net>
References: <3F2DD19A.9080205@netzero.net>
Message-ID: <20030804115206.GA28576@vail.asti-usa.com>

On Sun, Aug 03, 2003 at 11:23:06PM -0400, Kirk Bailey wrote:
> This thing is just flat going to need a lot of re stuff, and I need 
> therefore to ome up to speed on re.

Try reading http://www.amk.ca/python/howto/regex/ .

--amk
ACHILLES: 'Tis but early days.
      -- _Troilus and Cressida_, IV, v



From amk@amk.ca  Wed Aug  6 18:11:39 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Wed Aug  6 17:11:39 2003
Subject: [Tutor] Comments wanted on new Python introduction
In-Reply-To: <BB53254D.B6E9%clay@shirky.com>
References: <BAY2-F97u3fQtYdVzDp0000255d@hotmail.com> <BB53254D.B6E9%clay@shirky.com>
Message-ID: <20030804121849.GC28576@vail.asti-usa.com>

On Sun, Aug 03, 2003 at 08:47:09PM -0400, Clay Shirky wrote:
> Sorry, I wasn't clear enough before. 8 is a fine number, but it would be
> helpful to have some indication as to a) why a given resource has made the
> quality cut to be included on that page, and b) how any given resource
> differs from the others.

The problem is that I'm not a newbie any more, and neither are any
other of the python.org maintainers.  I can read a tutorial and detect
a bad one by spotting factual errors, but can't detect a good one;
maybe a tutorial moves too quickly or assumes existing programming
knowledge, but I may miss that.

Pointing to the Python tutorial first is probably a good idea (though
sometimes people complain that it's too mathematically-oriented) so
I'll make that change.

--amk
ROSALIND: Beauty provoketh thieves sooner than gold.
      -- _As You Like It_, I, iii



From amk@amk.ca  Wed Aug  6 18:11:46 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Wed Aug  6 17:11:46 2003
Subject: [Tutor] Comments wanted on new Python introduction
In-Reply-To: <BB51F02F.B65A%clay@shirky.com>
References: <20030731225824.GA30757@nyman.amk.ca> <BB51F02F.B65A%clay@shirky.com>
Message-ID: <20030804125920.GD28576@vail.asti-usa.com>

On Sat, Aug 02, 2003 at 10:48:15PM -0400, Clay Shirky wrote:
> Right now, Python.org seems to have a Yahoo strategy in a Google world.

A good observation.  In the mid-90s the goal was to link to
*everything* from python.org: every article about Python, every
project that used it, every company we heard about.

(This is also why the O'Reilly _Programming Python_ book is so large;
it might have been the only Python book to see print, so Mark Lutz
tried to pack everything that might possibly be of interest into the book.)

Unfortunately, this meant that python.org collected lots of cruft that
was never properly updated; /topics/learn is part of an effort to discard 
old material and freshen up the site.

--amk


From amk@amk.ca  Wed Aug  6 18:11:52 2003
From: amk@amk.ca (A.M. Kuchling)
Date: Wed Aug  6 17:11:52 2003
Subject: [Tutor] Email encryption
In-Reply-To: <1059826537.2431.5.camel@24-159-241-21.jvl.wi.charter.com>
References: <1059826537.2431.5.camel@24-159-241-21.jvl.wi.charter.com>
Message-ID: <20030804131017.GB2020@vail.asti-usa.com>

On Sat, Aug 02, 2003 at 07:15:37AM -0500, Mike Wagman wrote:
> I need to encrypt/decrypt information (files) by email can any one help
> me.  

It's not quite clear what you're asking for.  Are you asking to send
encrypted e-mail from Python code?  There are two commonly-used
formats for encrypted e-mail, OpenPGP (used by GnuPG, PGP, and
PGP-derived programs) and S/MIME (Mozilla Mail, Outlook, most other
e-mail programs).  

To generate OpenPGP, you can install GnuPG, which is a command-line
program, and invoke it from Python using os.popen() or the popen2
module.  

To generate S/MIME, see http://www.post1.com/home/ngps/m2/howto.smime.html

If you want to do something else, such as encrypting files using a key
received via e-mail, you'll have to explain what it is.

--amk
I'm as truthful, honest, and about as boring as they come.
      -- Mel, in "The Ultimate Foe"


From levy.lazarre@mfms.com  Wed Aug  6 18:11:59 2003
From: levy.lazarre@mfms.com (Levy Lazarre)
Date: Wed Aug  6 17:11:59 2003
Subject: [Tutor] Re: Using a dictionary to keep a count
Message-ID: <97709E9D34F6D1119BE400A0C99DD96703B1416E@MFMSEXCH>

On Sat, 02 Aug 2003 21:07:41 +0200,   sigurd@12move.de  wrote:  

>(c) So a function to process log files and print the values could be
>    written like that: 

>def process_log_file(name):
>    d = {}
>    f = open(name)
>    for line in f:
>        script, address = process_line(line)
>        d[address] = d.setdefault(address,0) + 1
>    f.close()
>    for (key, value) in d.items():
>        print key, " => ", value

Thanks for the clarification and suggestion, however this approach doesn't
work for it doesn't create the intended dictionary of dictionaries
structure.
What I needed was the count per script per site, something like:
dic =  {
       '/cgi-bin/script1.cgi' => {
                                       'alpha.umn.edu' => 2,
                                       'rohcs.ats.com' => 2
                                        },
      '/cgi-bin/script2.cgi' => {
                                       'rohcs.ats.com' => 1,
                                       'idg.com' => 1
                                       }
 }

The following approach using exceptions seems to work:
###############################################
dic ={} 

# Read the file line by line and extract the script name and the address.
f = file('access_log')
for line in f :
    script, address = process_line(line)   
    try:             
      dic[script]                       # Has this script already been seen?
    except KeyError:     
      dic[script] = {}                  # first time script is seen, set
empty dict for it 
      
    try:      
      dic[script][address] += 1         # Has this address already been seen
for this script?
                                                  # if so, increment its
count
    except KeyError:    
       dic[script][address] = 1         # first time address seen for this
script, count = 1
f.close()
# Now print the dictionary to verify what we have done:

for key in dic.keys():
    print key, " => "
    for value in dic[key].keys():
        print value+":", dic[key][value]
     
    print "\n"    
#############################################################
Any comments? Is this a bad style? I was trying to make the code shorter
with setdefault(), but it appears very difficult to use with nested
structures.

Thanks,
Levy Lazarre
llazarre@yahoo.com


Confidentiality Notice: 
This is a transmission from a Winter Haven Hospital facility.  This message and any attached documents may be confidential and contain information protected by state and federal medical privacy statutes.  They are intended only for the use of the addressee.  If you are not the intended recipient, any disclosure, copying, or distribution of this information is strictly prohibited.  If you received this transmission in error, please accept our apologies and notify the sender.

This Outbound Message has been scanned for Viruses and objectionable content by McAfee WebShield.




From vibrations@cetlink.net  Wed Aug  6 18:12:06 2003
From: vibrations@cetlink.net (SGD)
Date: Wed Aug  6 17:12:06 2003
Subject: [Tutor] Executing an executable with commandline options
Message-ID: <000001c35bc9$f17d7130$ae34c6d1@whiterhino2>

This is a multi-part message in MIME format.

------=_NextPart_000_0001_01C35BA8.6A6BD130
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

Hello,
 
I'm coding a launcher for my favorite game and don't understand how two
execute an executable with command line options passed to it when the
run game icon is clicked.
 
To be exact this is what I what to do;
 
hl.exe -console -dev (among other commands)
 
Can you help?
 
Thanks,
Steven
 

------=_NextPart_000_0001_01C35BA8.6A6BD130
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C35BA8.57EA92D0">
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]-->
<style>
<!--
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
span.EmailStyle17
	{mso-style-type:personal-compose;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:windowtext;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin:0in;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Hello,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>I&#8217;m coding a launcher for my favorite game and =
don&#8217;t
understand how two execute an executable with command line options =
passed to it
when the run game icon is clicked.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>To be exact this is what I what to =
do;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>hl.exe &#8211;console &#8211;dev (among other =
commands)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Can you help?<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Thanks,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Steven<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

</div>

</body>

</html>

------=_NextPart_000_0001_01C35BA8.6A6BD130--



From alan.gauld@blueyonder.co.uk  Wed Aug  6 18:13:14 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 17:13:14 2003
Subject: [Tutor] dial-up from Python
References: <HJ771Q$FCAB2FAB02F63ADC128B9A5576D2284C@terra.com.br>
Message-ID: <009501c35c5f$42c151c0$6401a8c0@xp>

Which operating system?
Thee are several ways depending on OS. 

Alan G.

----- Original Message ----- 
From: "cybersamurai" <cybersamurai@terra.com.br>
To: "tutor" <tutor@python.org>
Sent: Wednesday, August 06, 2003 1:37 PM
Subject: [Tutor] dial-up from Python


How to create a dial-up connection and use it from Python?


From alan.gauld at blueyonder.co.uk  Wed Aug  6 23:35:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 17:57:31 2003
Subject: [Tutor] python22
References: <MDEEJCJPNMNONNLDFLLFGEOLCAAA.fards@earthlink.net>
Message-ID: <00b701c35c62$aa087fe0$6401a8c0@xp>

> I don't know what the PYTHON(command line) window that is available
in
> PYTHON22 drag down menu used for. when I open this command line it
starts
> with >>> and I can not run saved programs with it.how this command
line
> used?

In the same way you use the >>> prompt within the IDLE Shell window.
You can type Python commands in to experiment with ideas before
committing them to a script.

So you can do things like:

>>> 45+67*23/4.8

and get an answer

or
>>> import time
>>> time.sleep(5)

and so on.

In the early days of python IDLE did not exist. The command
window version was the only one you could use for this sort of work.
In fact I still use it more often than I do IDLE.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From pcarey at lexmark.com  Wed Aug  6 18:19:46 2003
From: pcarey at lexmark.com (pcarey@lexmark.com)
Date: Wed Aug  6 18:01:12 2003
Subject: [Tutor] what's a state machine?
Message-ID: <OFDAD6BBC6.67C1A7DE-ON85256D7A.0074CBEC@lexmark.com>



>The secret is to model the machine as a big table:
>
>Current State|Event|Action|Next State
>
>You then define numeric values(or hash keys) for each state
>and each event, load pointers/rferences to functions into
>the action column and set of a loop that looks something
>like this:

This is fascinating stuff. Are there textbooks devoted to this kind of
topic? If so, can you recommend any?

Thank you,

PETE






"Alan Gauld" <alan.gauld@blueyonder.co.uk>@python.org on 08/06/2003
05:06:51 PM

Sent by:    tutor-admin@python.org


To:    "Kirk Bailey" <idiot1@netzero.net>, <tutor@python.org>
cc:

Subject:    Re: [Tutor] what's a state machine?


Kirk wrote a fine description of state machine theory...

> THAT is a turing machine. It is a complete computer, and can compute
> ANYTHING. Eventually. If you do not go insane first.
>
> And is a complete pain in the ass.

To which I add that while Turing complete state machines are
hard dedicated purpose state machines are both very easy to
build, easy to maintain and extremely performant. This is
the reason why most large scale real-time systems are built
as state machines. Its also why a complete methodology and
notation exists to document such machines - its called SDL
- The Specification and Design Language, and is used to design
almost all modern telephone exchanges, air-traffic control
systems, railway control systems, factory control etc etc.

The secret is to model the machine as a big table:

Current State|Event|Action|Next State

You then define numeric values(or hash keys) for each state
and each event, load pointers/rferences to functions into
the action column and set of a loop that looks something
like this:

while True:
   EventID = getEvent()  # figure out how to get the events!
   try:
      StateTable[myState][EventID].Action()
      myState = StateTable[myState][EventID].nextState
   except:  # handle an error

Another strategy is that the Action should return nextState
but that prevents you from reusing action functions...

Now adding states, events or actions becomes a relatively simple
table build issue. And that can be done from a text file at startup...

Alan G.


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





From missive at hotmail.com  Wed Aug  6 22:41:58 2003
From: missive at hotmail.com (Lee Harr)
Date: Wed Aug  6 18:01:19 2003
Subject: [Tutor] Re: python22
Message-ID: <BAY2-F44C0aorS4VJ0a0000d692@hotmail.com>

>I have python22 installed.
>I am able to use IDLE (GUI) to RUN SCRIPTS.
>I can also RUN saved files from a MS DOS command line window.
>I don't know what the PYTHON(command line) window that is available in
>PYTHON22 drag down menu used for. when I open this command line it starts
>with >>> and I can not run saved programs with it.how this command line
>used?
>

It is pretty much the same thing as you would get by choosing
Run -> Python Shell
from the IDLE window.

It is the Python interactive interpreter. You can type python
statements at that >>> prompt.

You can run programs from that prompt... but you have to
import them first.

Let's say you have a file foo.py

#foo.py
def bar(n):
    print n

if __name__ == '__main__':
    bar('module was run, not imported')

#end foo.py

If I run the program:
>python foo.py
module was run, not imported


But then you could in your Python Shell...

>>>import foo
>>>foo.bar('a test')
a test


Of course, foo.py needs to be on your sys.path for that to work....

_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE* 
http://join.msn.com/?page=features/junkmail


From alan.gauld at blueyonder.co.uk  Thu Aug  7 00:08:05 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 18:08:00 2003
Subject: [Tutor] what's a state machine?
References: <OFDAD6BBC6.67C1A7DE-ON85256D7A.0074CBEC@lexmark.com>
Message-ID: <000401c35c67$36506090$6401a8c0@xp>

> >The secret is to model the machine as a big table:
> >
> >Current State|Event|Action|Next State
> >
>
> This is fascinating stuff. Are there textbooks devoted to this kind
of
> topic? If so, can you recommend any?
>

Yes several. Depends how theoretical you want to go
- state/automata theory, Mealy/Moore machines etc...

For a fairly straightforward discussion of real time systems including
a table driven state machine you could try

Title: Intro to Real-Time Software design
Auth:  Allworth & Zobel
Pub:   MacMillan

Dunno if its still in print but you can probably get it second
hand from Amazon if not.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Thu Aug  7 00:14:02 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 18:13:59 2003
Subject: [Tutor] what's a state machine?
References: <OFDAD6BBC6.67C1A7DE-ON85256D7A.0074CBEC@lexmark.com>
Message-ID: <000b01c35c68$0b3c4800$6401a8c0@xp>

> >The secret is to model the machine as a big table:
> >
> >Current State|Event|Action|Next State

> This is fascinating stuff. 

It is indeed. I meant to mention that it is theoretically possible 
to model any system as a state machine since at a trival level 
every software program can have the states:

Initialising
Running
Stopping

At this level the system while running is just a traditional event 
loop as used in GUI systems. Thus any GUI application can be 
designed using tools like SDL, and built using state techniques.
For example a modal dialog represents a state, during which only 
a limited set of events are permitted...

In batch processing states could include such things as
DatabaseOpen(or FileOpen)
ReadingData
ProcessingData

etc
In this case the program sends itself events whhich are 
processed according to current state...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From missive at hotmail.com  Wed Aug  6 22:33:58 2003
From: missive at hotmail.com (Lee Harr)
Date: Wed Aug  6 18:14:57 2003
Subject: [Tutor] Re: Executing an executable with commandline options
Message-ID: <BAY2-F864kVOxWULKop0000d69b@hotmail.com>

>I'm coding a launcher for my favorite game and don't understand how two
>execute an executable with command line options passed to it when the
>run game icon is clicked.
>
>To be exact this is what I what to do;
>
>hl.exe -console -dev (among other commands)
>


import os
os.system('hl.exe -console -dev')


might do the trick.

btw... the html that came along with your post was about
ten times the size of your message... and that's generally
considered rude.  :o)

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE* 
http://join.msn.com/?page=features/virus


From bgailer at alum.rpi.edu  Wed Aug  6 16:15:11 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed Aug  6 18:16:10 2003
Subject: [Tutor] python22
In-Reply-To: <MDEEJCJPNMNONNLDFLLFGEOLCAAA.fards@earthlink.net>
Message-ID: <5.2.1.1.0.20030806151225.02b85b38@66.28.54.253>

At 11:49 AM 8/1/2003 -0400, Seyed Fard wrote:

>I have python22 installed.
>I am able to use IDLE (GUI) to RUN SCRIPTS.
>I can also RUN saved files from a MS DOS command line window.
>I don't know what the PYTHON(command line) window that is available in
>PYTHON22 drag down menu used for. when I open this command line it starts
>with >>> and I can not run saved programs with it.how this command line used?

This gives you the interpreter in interactive mode. You can type statements 
and expressions and get immediate results. You can import scripts, and if 
they are not restricted to running under if __name__ == '__main__' they 
will execute just as if you had RUN them from a MS DOS command line window.

Do read up on import to understand all the ramifications.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From logiplex at qwest.net  Wed Aug  6 16:38:48 2003
From: logiplex at qwest.net (Cliff Wells)
Date: Wed Aug  6 18:38:55 2003
Subject: [Tutor] outputting dictionary key/value pairs
In-Reply-To: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>
References: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>
Message-ID: <1060209528.2207.241.camel@software1.logiplex.internal>

On Fri, 2003-08-01 at 09:18, Terence Lo wrote:
> hi,
> 
>  supoose i create a dictionary of the form:
> 
> dict = {"d1": "a", "d2": "b", "d3": "c"}

Don't use dict as a variable name.  It shadows a builtin.

>>> dict
<type 'dict'>

> why is it that when i loop through the dictionary,
> 
> eg.
> 
> for k,v in dict.items():
> 	print k,v
> 
> 
> the dictionary items aren't output in the order they appear in the
> dictionary.  they seem to be returned in an arbitrary order.

It isn't arbitrary, but for all practical purposes, it might as well
be.  Dictionaries are hash-tables, which means the key (i.e. the index)
is mathematically generated in such a way to distribute the keys evenly
and avoid collisions (two keys having the same hash value).

You can try this yourself:

>>> hash
<built-in function hash>
>>> hash('a')
-468864544
>>> hash('b')
-340864157
>>> hash('c')
-212863774

As you can see, the value of the key has little to do with its relative
value after hashing.

Hashes for integers are the same as the integer (hash(100) == 100), but
that is an implementation detail and could change without warning.

Basically, in the dictionary you define above, the string "d1" is never
actually stored anywhere, rather, the hash value of the string "d1" is
used as the index.  Whenever you request dict['d1'], Python looks up
dict[hash('d1')], and returns whatever value is stored there.

You can search on Google for more information on hash tables if you
like.

> is there a quick way to loop through the dict and output the contents in
> order?  namely  d1 .. d2.. d3 ?

Not really.  You can do things like:

>>> d = {"d1": "a", "d2": "b", "d3": "c"}
>>> sorted = d.items()
>>> sorted.sort()
>>> for k, v in sorted:
...     print k, v
...
d1 a
d2 b
d3 c
>>>


Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555


From jonathan.hayward at pobox.com  Wed Aug  6 23:48:14 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Wed Aug  6 18:42:08 2003
Subject: [Tutor] Sockets, again
Message-ID: <3F31779E.1020906@pobox.com>

I've got past the problem I'd noticed earlier (source: I opened the 
output socket-file "r" and the input socket-file "wb", and that's why I 
had the bad file descriptor. Oof.).

I want the client to encode its environmental and CGI data, feed a blank 
line or other end-of-input indicator, and get a webpage back. My current 
problem is that the script hangs, possibly stuck in an infinite loop, or 
more probably deadlocked on input. Or that's my best guess; I hope I'm 
missing something very simple again. The server seems to be giving the 
client a steady stream of either newlines or nulls.

So the client opens up with a query like:

    environment_variable REMOTE_HOST
    [Pickling of "127.0.0.1"]
    cgi page_mode
    [Pickling of a page mode]
    @@END_OF_QUERY@@

Then the server would think a bit and send back a pickled webpage. 
(Using cPickle is overkill now, but I want to leave a couple of doors 
open to things that might be useful later.)

Any help would be appreciated. This is the interface code I have now for 
the client:

    def get_page_from_oracle(self):
        self.check_and_start_oracle()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect((configuration.get_search_server_ip(), \
              configuration.get_search_server_port()))
            sockIn = sock.makefile("rb")
            sockOut = sock.makefile("wb")
            for current_environment_key in os.environ.keys():
                sockOut.write("environmental_variable " + \
                  current_environment_key + "\r\n")
                cPickle.dump(os.environ[current_environment_key], sockOut)
            for cgi_key in cgi.FieldStorage().keys():
                sockOut.write("cgi_value " + cgi_key + "\r\n")
                cPickle.dump(cgi.FieldStorage[cgi_key])
            sockOut.write(configuration.get_query_terminator() + "\r\n")
            sockOut.write("\r\n")
            #result = cPickle.load(sockIn)
            result = sockIn.readline()
            sock.close()
            sockIn.close()
            sockOut.close()
            #return "Content-type: text/html\n\nget_page_from_oracle"
            return result
        except socket.error, e:
            return "Content-type: text/html\n\n<h1>There was an error 
loading this page.</h1>" + str(e)

And the server:

    def handle_oracle_query(self, sock, address):
        """Reads a CGI or other header variable alone on a line, format like
            cgi_value <HTML form element name>
            environmental_variable REMOTE_ADDR
        and then a pickled value. There is exactly one space between the two
        elements, and neither element may contain a space"""
        sockIn = sock.makefile("rb")
        sockOut = sock.makefile("wb")
        line = sockIn.readline()
        should_continue = 1
        while should_continue:
            if not self.get_thread_specific_storage().has_key("cgi"):
                self.get_thread_specific_storage()["cgi"] = None
            if not self.get_thread_specific_storage().has_key( \
              "environmental_variables"):
                
self.get_thread_specific_storage()["environmental_variables"] \
                  = None
            if self.get_thread_specific_storage()["cgi"] == None:
                self.get_thread_specific_storage()["cgi"] = {}
            if 
self.get_thread_specific_storage()["environmental_variables"] \
              == None:
                
self.get_thread_specific_storage()["environmental_variables"] \
                  = {}
            cgi = self.get_thread_specific_storage()["cgi"]
            environmental_variables = \
              self.get_thread_specific_storage()["environmental_variables"]
            line = re.sub("[\r\n]+", "", line)
            query_line = re.split("\s+", line)
            if len(query_line) == 2:
                input_type = query_line[0]
                input_name = query_line[1]
                if input_type == "cgi_value":
                    cgi[input_name] = cPickle.load(sockIn)
                elif input_type == "environmental_variables":
                    environmental_variables[input_name] = 
cPickle.load(sockIn)
            else:
                should_continue = 0
            line = sockIn.readline()
        generate_output()
        print_output(sockOut)
        sockOut.write("\r\n")
        sock.close()
        sockIn.close()
        sockOut.close()

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From amonroe at columbus.rr.com  Wed Aug  6 19:47:56 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed Aug  6 18:43:08 2003
Subject: [Tutor] what's a state machine?
In-Reply-To: <007001c35c5e$a84ff740$6401a8c0@xp>
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>
	<3F304C17.8030502@netzero.net> <007001c35c5e$a84ff740$6401a8c0@xp>
Message-ID: <83243768911.20030806184756@columbus.rr.com>

> The secret is to model the machine as a big table:

> Current State|Event|Action|Next State

> You then define numeric values(or hash keys) for each state
> and each event, load pointers/rferences to functions into
> the action column

Does that work when you have multiple concurrent states, like
simultaneouly Walking and ChewingGum at the same time?

Alan


From jeff at ccvcorp.com  Wed Aug  6 16:49:46 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Wed Aug  6 18:48:53 2003
Subject: [Tutor] what's a state machine?
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu>	<3F304C17.8030502@netzero.net>
	<007001c35c5e$a84ff740$6401a8c0@xp>
	<83243768911.20030806184756@columbus.rr.com>
Message-ID: <3F31860A.5090600@ccvcorp.com>

R. Alan Monroe wrote:

>>You then define numeric values(or hash keys) for each state
>>and each event, load pointers/rferences to functions into
>>the action column
>>    
>>
>
>Does that work when you have multiple concurrent states, like
>simultaneouly Walking and ChewingGum at the same time?
>  
>

Yes, if you define a states walking, chewing_gum, and 
walking_and_chewing_gum.  Any valid combination of other states can be 
seen as a single state itself.  This could lead to a combinatoric 
explosion in the number of possible states, and may not be the most 
efficient way to implement the state machine, but it can be done.

Jeff Shannon
Technician/Programmer
Credit International



From tbstep at tampabay.rr.com  Wed Aug  6 18:36:17 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Wed Aug  6 18:54:29 2003
Subject: [Tutor] python22
In-Reply-To: <MDEEJCJPNMNONNLDFLLFGEOLCAAA.fards@earthlink.net>
References: <MDEEJCJPNMNONNLDFLLFGEOLCAAA.fards@earthlink.net>
Message-ID: <200308061736.17299@toddloki>

On Friday 01 August 2003 11:49 am, Seyed Fard wrote:
> Hello.
> I have python22 installed.
> I am able to use IDLE (GUI) to RUN SCRIPTS.
> I can also RUN saved files from a MS DOS command line window.
> I don't know what the PYTHON(command line) window that is available in
> PYTHON22 drag down menu used for. when I open this command line it starts
> with >>> and I can not run saved programs with it.how this command line
> used?
> thank you

The interactive prompt can be used for testing out functions and the like 
before inserting into your program.  You can define and then call a function 
from the interactive prompt, whereas if you were coding a program in a text 
editor, you would have to save it and run it just to see if your function 
worked.  At least, that is what I use it for.

-- 
Todd Stephens


From alan.gauld at blueyonder.co.uk  Thu Aug  7 01:16:56 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug  6 19:16:51 2003
Subject: [Tutor] what's a state machine?
References: <51CCFC50-C76A-11D7-BFF8-00039303967A@umich.edu><3F304C17.8030502@netzero.net>
	<007001c35c5e$a84ff740$6401a8c0@xp>
	<83243768911.20030806184756@columbus.rr.com>
Message-ID: <004201c35c70$d4688ce0$6401a8c0@xp>

> > You then define numeric values(or hash keys) for each state
> > and each event, load pointers/rferences to functions into
> > the action column
> 
> Does that work when you have multiple concurrent states, like
> simultaneouly Walking and ChewingGum at the same time?

There are two approaches to this problem.

1) Combining states, eg of walking-with-gum

So you then get:

chewing-gum-still
walking-without-gum
walking-with-gum

etc

This can quickly escalate to an unmanageable "state explosion"
so ...

2) Use "nested states", which implies a second state machine(table)
inside the first. This works OK up to about 3 levels then it gets 
messy. But then again if you really have that amount of nested 
state its going to be messy no matter how you build it!

Nested states is the approach advocated in UML, using Harel charts 
to represent the nested states.

Most real world situations are covered by two state levels plus 
a combined state model for the inner cases. A combination of 
(1) and (2)...

Alan G.

From carroll at tjc.com  Wed Aug  6 17:57:59 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug  6 19:58:03 2003
Subject: [Tutor] outputting dictionary key/value pairs
In-Reply-To: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>
Message-ID: <Pine.LNX.4.44.0308061657170.17963-100000@mauve.rahul.net>

On Fri, 1 Aug 2003, Terence Lo wrote:

>  supoose i create a dictionary of the form:
> 
> dict = {"d1": "a", "d2": "b", "d3": "c"}
> 
> why is it that when i loop through the dictionary,
> 
> eg.
> 
> for k,v in dict.items():
> 	print k,v
> 
> 
> the dictionary items aren't output in the order they appear in the
> dictionary.  they seem to be returned in an arbitrary order.

Yep. that's the way dictionaries work.
 
> is there a quick way to loop through the dict and output the contents in
> order?  namely  d1 .. d2.. d3 ?

Try this:

keylist = dict.keys()
keylist.sort()
for k in keylist:
    print k, dict[k]

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From zak at harlekin-maus.com  Wed Aug  6 18:21:36 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Wed Aug  6 20:21:41 2003
Subject: [Tutor] outputting dictionary key/value pairs
In-Reply-To: <Pine.LNX.4.44.0308061657170.17963-100000@mauve.rahul.net>
References: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>
	<Pine.LNX.4.44.0308061657170.17963-100000@mauve.rahul.net>
Message-ID: <4031.192.207.104.210.1060215696.squirrel@mail.harlekin-maus.com>

>> is there a quick way to loop through the dict and output the contents in
>> order?  namely  d1 .. d2.. d3 ?
>
> Try this:
>
> keylist = dict.keys()
> keylist.sort()
> for k in keylist:
>     print k, dict[k]
>
> --
> Terry Carroll        |   "I say to you that the VCR is to the American

Here's an alternative approach, if you'd like to keep a sorted list of
keys and values around. This approach is, though, of dubious use.

###
>>> d = {'d1':'a', 'd2':'b', 'd3':'c'}
>>> d_list = [(k, v) for k, v in d.items()]
>>> d_list.sort()

>>> print d_list
[('d1', 'a'), ('d2', 'b'), ('d3', 'c')]

>>> for d_tuple in d_list:
        print d_tuple[0], d_tuple[1]

d1 a
d2 b
d3 c
###

Also, I'd like to point out that you shouldn't be using 'dict' as a
variable name, since it's already defined in Python

###
>>> dict
<type 'dict'>
###

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From sigurd at 12move.de  Thu Aug  7 03:29:38 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Aug  6 20:31:46 2003
Subject: [Tutor] Re: Using a dictionary to keep a count
In-Reply-To: <97709E9D34F6D1119BE400A0C99DD96703B1416E@MFMSEXCH> (Levy
	Lazarre's message of "Mon, 4 Aug 2003 10:55:42 -0400")
References: <97709E9D34F6D1119BE400A0C99DD96703B1416E@MFMSEXCH>
Message-ID: <m3llu6z612.fsf@hamster.pflaesterer.de>

On  4 Aug 2003, Levy Lazarre <- levy.lazarre@mfms.com wrote:

> Thanks for the clarification and suggestion, however this approach doesn't
> work for it doesn't create the intended dictionary of dictionaries
> structure.

Sorry I overlooked that need.

[...]

> The following approach using exceptions seems to work:
> ###############################################
> dic ={} 

Try to avoid global variables whenever possible.


[Code with try/except]

> Any comments? Is this a bad style? I was trying to make the code shorter
> with setdefault(), but it appears very difficult to use with nested
> structures.

No code with try/except is most of the times good style.  Here is an
example how your desire could be achieved with setdefault.

def process_log_file(name):
    d = {}
    f = open(name)
    for line in f:
        script, address = process_line(line)
        d.setdefault(script, {})
        d[script][address] = d[script].setdefault(address,0) + 1
    f.close()
    for (key, value) in d.items():
        print key , '=>'
        for (subkey, subvalue) in value.items():
            print ' ' * len(key + '=<'), subkey, ': ', subvalue


You could write the assignment in one line but I wouldn't recommend it
(unless you like unreadable code):

def process_log_file(name):
    d = {}
    f = open(name)
    for line in f:
        script, address = process_line(line)
        d[script][address] = d.setdefault(script, {}).setdefault(address,0) + 1
    f.close()
    for (key, value) in d.items():
        print key , '=>'
        for (subkey, subvalue) in value.items():
            print ' ' * len(key + '=<'), subkey, ': ', subvalue



You could separate the printing part in the above function but I didn't
do that because the format is very specific.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From carroll at tjc.com  Wed Aug  6 19:15:57 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug  6 21:16:05 2003
Subject: [Tutor] Graphical object browser?
In-Reply-To: <007901c35c5e$f0295e30$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0308061814020.17963-100000@mauve.rahul.net>

On Wed, 6 Aug 2003, Alan Gauld wrote:

> Pytonwin has both a COM object browser and Python object
> browser built in.
> 
> They seemed to work OK on the few cases I've used them.

Thanks; this is helpful.  It's a little awkward, but a big step up from 
the command line.  Best of all, it's already installed.

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From idiot1 at netzero.net  Wed Aug  6 22:17:14 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Aug  6 21:19:23 2003
Subject: [Tutor] wiki project update
Message-ID: <3F31A89A.5090804@netzero.net>

Well, reading The Wiki Way, there were some good ideas in there. One of 
them is that there is no hard and fast wiki code set, just a generally 
followed convention. When I used DIFFERENT tage to start and end bold 
and italic tags, it works fine. The current experimental version is 
doing this on the FrontPage only, and is working on those words so tagged.
http://www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage
There's losts more, and other, and a parser engine is really about all 
that will work for me. This is a hack at best, a kludge, payhaps a Bag 
On The Side, not a solution.

On a more positive note, is is doing Section colored headers, page 
headers and footers, inserting all the right information in them, and 
the editor is working just primo. It even looks rather nice. But the 
engine is the real project, the toughnut.


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Wed Aug  6 22:26:49 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Aug  6 21:28:28 2003
Subject: [Tutor] 2 functions- are they state machines?
Message-ID: <3F31AAD9.3020604@netzero.net>

These attack a subset of the task.

# This one turns wikiwords into http links
def createwikilinks(line):	# is this a state machine?
	line=string.split(line)
	index=0
	for word in line:
		if wikiname(word):	# ware wordwrap!
			word='<a \
href=http://www.'+domainname+'/cgi-bin/wikinehesa.py/'+\
word+'">'+word+'</a>'
			line[index]=word
			index=index+1
	line-string.join(line)
	return line
	
# this one determines if a word is a wikiword.
def iswikiname(word):			# is this a state machine?
	transitions=0			# counts transitions
	prior=0				# maintains priorletterstate
	caps='ABCDEFGHIJKLMNOPQRSTUVWXYZ' # defines capital letter.
	for letter in word:		# check each letter 4 capitals
		if letter in caps: 	# if this letter is a cap;
			if prior==0:	# if the last was not a cap,
				prior=1	# note a cap was just processed
			else:			# if the last was a cap,
				pass		# noop prior already set
		else:		# if the current letter is not a cap;
			if prior==1: 	# if the last one was a cap;
				transitions=transitions+1 # a transition
				prior=0	# note this letter was not a cap
			else:			# but if not...
				pass		# shine it on...
	if transitions>1:			# 2+ is a wikiword
		return 1			# return a logical YES
	else:					#
		return 0			# return a logical NO















-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From steveng at pop.jaring.my  Thu Aug  7 03:52:12 2003
From: steveng at pop.jaring.my (Stephen Ng)
Date: Wed Aug  6 22:52:13 2003
Subject: [Tutor] floating point accuracy
In-Reply-To: <06738462136C054B8F8872D69DA140DB010888@corp-exch-1.pjinet.com>
References: <06738462136C054B8F8872D69DA140DB010888@corp-exch-1.pjinet.com>
Message-ID: <1060224715.10886.48.camel@nutek-1>

Hi!

Thanks for the info.

I guess I'll have to be careful when using floating point operations.

Stephen Ng

On Thu, 2003-08-07 at 00:13, Alan Trautman wrote:
> That is normal for all base 8 cpu's (almost all made). The only method to be
> highly precise is to do longhand division (ie.. subtract many times) using
> integers or to purchase a large scale vector-based cpu machine $$$$. You
> just happened to pick a really simple to reproduce example.
> 
> It has nothing to do with the language used, although some languages hide
> this fact from you, it is just a hardware based limitation.
> 
> HTH,
> Alan
> 
> -----Original Message-----
> From: Stephen Ng [mailto:steveng@pop.jaring.my]
> Sent: Wednesday, August 06, 2003 12:55 AM
> To: tutor@python.org
> Subject: [Tutor] floating point accuracy
> 
> 
> Hi!
> 
> I am a total newcomer to python so still trying to find out what its all
> about.
> 
> I tried the following 2/5.0 and received 0.40000000000000002.
> 
> The 2 at the end makes me wonder whether this is normal and how accurate
> floating point arithmetic is.
> 
> Stephen Ng
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From magnus at thinkware.se  Thu Aug  7 19:01:24 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Aug  7 11:54:29 2003
Subject: [Tutor] Regular Expression guru saught
In-Reply-To: <3F2F067B.7030804@netzero.net>
References: <m3fzkho4wf.fsf@hamster.pflaesterer.de>
	<3F2DD19A.9080205@netzero.net>
	<m3fzkho4wf.fsf@hamster.pflaesterer.de>
Message-ID: <5.2.1.1.0.20030807180014.022f3e88@www.thinkware.se>

At 21:20 2003-08-04 -0400, Kirk Bailey wrote:
>I am writing a wiki. A wiki stores the body of a page in a flat text file. 
>NO HTML. The markup ciode is a simplistic set, Alas, some of them use the 
>SAME symbol series to turn a feature on, or off- it is a toggle.

Consider using docutils.

There are also several python wikis out there, such as
MoinMoin and ZWiki. Have a look at their source code!


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From bgailer at alum.rpi.edu  Thu Aug  7 11:32:21 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu Aug  7 12:41:03 2003
Subject: [Tutor] Executing an executable with commandline options
In-Reply-To: <000001c35bc9$f17d7130$ae34c6d1@whiterhino2>
Message-ID: <5.2.1.1.0.20030807102134.01d4ca10@66.28.54.253>

Skipped content of type multipart/alternative-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From bgailer at alum.rpi.edu  Thu Aug  7 12:37:46 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu Aug  7 13:39:22 2003
Subject: [Tutor] outputting dictionary key/value pairs
In-Reply-To: <003601c35848$96c8d6a0$8d411dc6@ms.aliaswavefront.com>
Message-ID: <5.2.1.1.0.20030807113029.02bd2008@66.28.54.253>

At 12:18 PM 8/1/2003 -0400, Terence Lo wrote:
>supoose i create a dictionary dict = {"d1": "a", "d2": "b", "d3": "c"}
>when i loop through the dictionary,
>for k,v in dict.items():
>         print k,v
>the dictionary items aren't output in the order they appear in the
>dictionary.  they seem to be returned in an arbitrary order.

Dictionaries are stored using some kind of binary tree that manages the 
hashed values of its keys. There is no attempt at maintaining any order.

>is there a quick way to loop through the dict and output the contents in
>order?  namely  d1 .. d2.. d3 ?

keys = dict.keys()
keys.sort()
for k in keys:
     print k, dict[k]

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From alan.gauld at blueyonder.co.uk  Thu Aug  7 22:27:29 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Aug  7 16:27:14 2003
Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2643
References: <E19knDX-0004it-00@mail.python.org>
Message-ID: <003901c35d22$53178f30$6401a8c0@xp>

Sorry Kirk,

Without the formatting I couldn't even be sure how the code
was supposed to look, let alone tell if it was a state machine.

Alan G.

----- Original Message -----
From: <tutor-request@python.org>
To: <tutor@python.org>
Sent: Thursday, August 07, 2003 5:02 PM
Subject: Tutor Digest, Vol 1, Issue 2643


> Send Tutor mailing list submissions to
> tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> tutor-request@python.org
>
> You can reach the person managing the list at
> tutor-owner@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>


----------------------------------------------------------------------
----------


> Today's Topics:
>
>    1. Re: python22 (Todd Stephens)
>    2. Re: what's a state machine? (Alan Gauld)
>    3. Re: outputting dictionary key/value pairs (Terry Carroll)
>    4. Re: outputting dictionary key/value pairs (Zak Arntson)
>    5. Re: Re: Using a dictionary to keep a count (Karl Pfl?sterer )
>    6. Re: Graphical object browser? (Terry Carroll)
>    7. wiki project update (Kirk Bailey)
>    8. 2 functions- are they state machines? (Kirk Bailey)
>    9. RE: floating point accuracy (Stephen Ng)
>   10. Re: Regular Expression guru saught (Magnus Lyck?)
>


----------------------------------------------------------------------
----------


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


From alan.gauld at blueyonder.co.uk  Thu Aug  7 22:28:48 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Aug  7 16:29:15 2003
Subject: Fw: [Tutor] dial-up from Python
Message-ID: <003e01c35d22$81c83a00$6401a8c0@xp>

Forwarding to the list for perusal now we know the OS...

Alan G
----- Original Message -----
From: "Luiz Siqueira Neto" <cybersamurai@terra.com.br>
To: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
Sent: Thursday, August 07, 2003 12:10 PM
Subject: Re: [Tutor] dial-up from Python


> I need make this in W95/98 and WNT/2000.
>
> Thanks about help me.  : )
>
> ----- Original Message -----
> From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> To: "cybersamurai" <cybersamurai@terra.com.br>; "tutor"
<tutor@python.org>
> Sent: Wednesday, August 06, 2003 6:11 PM
> Subject: Re: [Tutor] dial-up from Python
>
>
> > Which operating system?
> > Thee are several ways depending on OS.
> >
> > Alan G.
> >
> > ----- Original Message -----
> > From: "cybersamurai" <cybersamurai@terra.com.br>
> > To: "tutor" <tutor@python.org>
> > Sent: Wednesday, August 06, 2003 1:37 PM
> > Subject: [Tutor] dial-up from Python
> >
> >
> > How to create a dial-up connection and use it from Python?
> >
> > Esta mensagem foi verificada pelo E-mail Protegido Terra.
> > Scan engine: VirusScan / Atualizado em 06/08/2003 / Vers?o: 1.3.13
> > Proteja o seu e-mail Terra:
http://www.emailprotegido.terra.com.br/
> >
>


From magnus at thinkware.se  Fri Aug  8 00:43:32 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Aug  7 17:46:08 2003
Subject: [Tutor] sys.path
In-Reply-To: <1060131275.30328.2.camel@blackbetty>
Message-ID: <5.2.1.1.0.20030807230407.02313d28@www.thinkware.se>

At 20:54 2003-08-05 -0400, Gus Tabares wrote:
>C:\WINNT\system32\python23.zip
>C:\Python23\lib\plat-win
> >>>
>
>What are these and if they do not exist why are they in sys.path? Anyone
>know? Just curious..no big deal:)

This is new in Python 2.3. I hadn't observed this, or heard about it,
so I'm speculating below...

I assume the first has to do with the new feature of zipped python
modules, see http://www.python.org/doc/current/whatsnew/node5.html
and http://www.python.org/peps/pep-0273.html

For the latter, see http://www.python.org/doc/essays/packages.html
I assume all platforms now check a plat-<my platform> directory,
which might or might not exist, depending on whether it's needed or
not.




--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From idiot1 at netzero.net  Thu Aug  7 19:54:59 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug  7 19:17:54 2003
Subject: [Tutor] is this a state machine?
Message-ID: <3F32D8C3.5000204@netzero.net>

BTW, it works.

def iswikiword(word):				# test to see is a wikiword
	caps='ABCDEFGHIJKLMNOPQRSTUVWXYZ'	# define capitalletters
	prior=0					# set inital state for flags
	count=0					# wikiwords have 2+transitions
	for letter in word:			# examine each letter
		if letter in caps:		# if it IS a capital letter,
			prior=1			# store that state
		else:					# and if not,
			if prior==1:		# but the previous one WAS,
				prior=0		# reset the flag,
				count=count+1	# anc count the transition!
			else:				# otherwise,
				pass 			# chill out.
	if count > 1:				# ok, the results are in;
		return 1				# if there are 2+, itis.
	else:						# and if not,
		return 0				# say so.



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.




From idiot1 at netzero.net  Thu Aug  7 21:24:03 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug  7 20:24:07 2003
Subject: [Tutor] further wikinessismlogy
Message-ID: <3F32EDA3.5030503@netzero.net>

OK, got some stuff to toss out for fun and amusement:

BEWARE WORD WRAP!

# follows is a function/object/thingie that determines if a word
# is a WikiWord. WikiWords are to be treated as LINKS to pages, and
# are constructed as 2 words runtogether (like that was) with the First
# Letter Of Each word RUNTOGETHER. ALL CAPITAL words are NOT to be treated
# as wikiwords. Therefore, it must preserve some sense of prior state...
# I *THINK* the following is a (simple?) state machine...
def iswikiword(word):				# test to see is a wikiword
	caps='ABCDEFGHIJKLMNOPQRSTUVWXYZ'	# define capitalletters
	prior=0					# set inital state for flags
	count=0					# wikiwords have 2+ transitions-count!
	for letter in word:			# examine each letter
		if letter in caps:		# if it IS a capital letter,
			prior=1			# store that state
		else:					# and if not,
			if prior==1:		# but the previous one WAS,
				prior=0		# reset the flag,
				count=count+1	# anc count the transition!
			else:				# otherwise,
				pass 			# chill out.
	if count > 1:				# ok, the results are in;
		return 1				# if there are 2+, it is. Say so.
	else:						# and if not,
		return 0				# say so.
#
# now we bend string.find into a tool to generate boolian logic values.
# in python, a 0 (ZERO) is a 'no', and ANY OTHER VALUE is a 'yes'
def isin(str,substr):		# this thing is a general tool.
	return 1+string.find(str,substr)	# it returns a logical 1 or 0
#
#
# now we can use it in other tools.
def ishyperlink(word):		# uses previous to detect a hyperlink
	if isin(word,'http://'): # makes top level code simper to read
		return 1
	else:
		return 0
#
#
# we use this tool to create wikilinks- html links in the wiki to
# a specific page in the wiki.
def makewikilink(word):		# makes wikiwords into hyperlinks to the wiki
	link='a \
href="'+webprefix+domainname+'/cgi-bin/wikinehesa.py/'+word+'">'+word+'</a>'
	return link		# look out, word wrap!
#
#
# But some links go elsewhere, and are structured differently.
# these already contain the web prefix needed IN THEM, so we do not add
# it. Instead, we exault it so it will work.
# oh- as a security precaution, we removed <anglebrackets> prior to this.
def makehyperlink(word):	# this converts url's into working links.
	link='<a href="'+word+'">'+word+'</a>'
	return link
#
#
This wiki WILL see the light of day. Someday.

Giggling insanely in the family compscilab, I remain;


         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From jim_938 at hotmail.com  Fri Aug  8 07:36:11 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Thu Aug  7 21:06:45 2003
Subject: [Tutor] strings matching problem
Message-ID: <Sea1-F124XSRdZqou2V000005cc@hotmail.com>

Hello !

First of all thanks to everyone on the list for giving consideration to my 
problems. With the help of the tutor mailing list i am really learning a lot 
about programming in python.

I have a small problem for now also.

I have a few names like a name followed by hash(#) and then a no. which 
indicates the repeated  occurance of the name.

Like .abc ,  .abc#1 ,  .abc#2

I want that if i encounter such kind of name then it should be converted to  
.abc

I think that this can be done with re.compile and some kind of match with 
re.match

But i am not sure what is the best way to do this.

Your suggestion will be welcomed by me.

Thanks a lot.

Regards,

Jim

_________________________________________________________________
The Six Sigma edge. Give it to your business. 
http://server1.msn.co.in/features/6sigma Stay ahead!


From dyoo at hkn.eecs.berkeley.edu  Thu Aug  7 19:17:42 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Aug  7 21:17:48 2003
Subject: [Tutor] is this a state machine? [designing a program to detect
	WikiWords]
In-Reply-To: <3F32D8C3.5000204@netzero.net>
Message-ID: <Pine.LNX.4.44.0308071632430.7862-100000@hkn.eecs.berkeley.edu>



On Thu, 7 Aug 2003, Kirk Bailey wrote:

> def iswikiword(word):				# test to see is a wikiword
> 	caps='ABCDEFGHIJKLMNOPQRSTUVWXYZ'	# define capitalletters
> 	prior=0					# set inital state for flags
> 	count=0					# wikiwords have 2+transitions
> 	for letter in word:			# examine each letter
> 		if letter in caps:		# if it IS a capital letter,
> 			prior=1			# store that state
> 		else:					# and if not,
> 			if prior==1:		# but the previous one WAS,
> 				prior=0		# reset the flag,
> 				count=count+1	# anc count the transition!
> 			else:				# otherwise,
> 				pass 			# chill out.
> 	if count > 1:				# ok, the results are in;
> 		return 1				# if there are 2+, itis.
> 	else:						# and if not,
> 		return 0				# say so.


[Warning: case study of using finite state machines to recognize
WikiWords.]


Hi Kirk,



Let's define what a "wiki word" is in English, before defining it in code.
According to:

    """It is a concatenation of words (of two or more letters each)
    without white space between them, and with the first letter (only) of
    each component word capitalized."""

    http://c2.com/cgi/wiki?WikiWords


The code above will work for a lot of cases, but will break on something
like this:

###
>>> iswikiword("ThisIsNOTAWikiWord")
1
###


A finite state machine is also not allowed to do counting, so the 'count'
variable in the function will disqualify it from being a finite state
machine.




We can imagine a finite state machine to recognize WikiWords that might
look like this:


                   capital?
          START --------------> On1stCapitalLetter
                                      |
                                      |
                                      | lowercase?
                                      |
                                      |
                                      | <--------+
                                      |          |
                                      |          | lowercase?
                                      |          |
                                      V          |
                                  FirstWord -----+
                                      |
                                      |
                                      | capital?
                                      |
                                      |
                                      V
                        +---> OnAnotherCapitalLetter
                        |             |
                        |             |
                        |             | lowercase?
                        |             |
                        |             |
                        |             | <---------+
              capital?  |             |           |
                        |             |           | lowercase?
                        |             |           |
                        |             V           |
                        |       **ANOTHERWORD ----+
                        |             |
                        |             |
                        |             |
                        +-------------+



This looks suspiciously like a flow diagram, for which I apologize: it's
hard drawing circles in ASCII, so I've omitted them.  *grin*


The diagram above has 5 states:

    [START, On1stCapitalLetter, FirstWord, OnAnotherCapitalLetter,
     ANOTHERWORD]


Whew.  That's a mouthful.  Let's shorten the names slightly:

    [START, On1st, FirstWord, OnAnother, ANOTHERWORD]


I've labeled the state that we start on as "START".  We jump from state to
state, depending if the next letter is uppercase or lowercase --- and if
we ever "fall off" the machine, then the word definitely isn't a Wiki
Word.  Think of it as a board game.


If it's a board game, how do we win?  How do we know if we are recognizing
a WikiWord?  Well, if we're on the ANOTHERWORD state by the time we're at
the end of our word, we'll consider that to be a WikiWord: that's the goal
of any word that wants to have the Wiki nature.



Before we put down any Python code, let's try it out on something like
"WikiWord":


------

time   state   next letter   comments
----   -----   -----------   --------

 1     START       W          'W' is capitalized, so we jump to
                              On1stCapitalLetter

 2     On1st       i          'i' is lowercased, so we jump to Firstword

 3     FirstWord   k          'k' is lowercased.  There's an "lowercase?"
                              arrow that points back to FirstWord, so we
                              jump back to FirstWord.

 4     FirstWord   i          Ditto.

 5     FirstWord   W          Ok, we've seen another capital.

 6     OnAnother   o          Yeah, now we can jump onto ANOTHERWORD!

 7     ANOTHERWORD r          ... but we can't celebrate until we finish
                              reading the rest of our input!

 8     ANOTHERWORD d          Almost there.

 9     ANOTHERWORD            Done!  And yes, 'WikiWord' is a WikiWord

------


Once we try a few words against our game board, we'll probably feel more
comfortable that it's doing the right thing.  Now to implement it in
Python!  *grin*



The diagram above is easy for us humans to trace, but not so convenient
for computers.  Let's make it slightly easier by "redrawing" that diagram
as a table:


                    capital?      lowercase?
-----------------------------------------------
START        |      On1st          FAIL
On1st        |      FAIL           FirstWord
FirstWord    |      OnAnother      FirstWord
OnAnother    |      FAIL           ANOTHERWORD
ANOTHERWORD  |      OnAnother      ANOTHERWORD
FAIL         |      FAIL           FAIL


I've sneaked in one more state, a "FAIL" state that catches the situation
when we "fall" off the diagram.  Think of it as a black hole for failed
WikiWords.


If we want to be concise, we can do another renaming of the states of our
machine, from words to numbers.  Let's do that.


      capital?   lowercase?
--------------------------
0   |    1           5
1   |    5           2
2   |    3           2
3   |    5           4
4   |    3           4
5   |    5           5



And something like this is easy to represent as a list:

###
>>> transitions = [[1, 5],
...                [5, 2],
...                [3, 2],
...                [5, 4],
...                [3, 4],
...                [5, 5]]
###



And now, we can write something that uses this table to jump around our
state diagram:

###
def isWikiWord(word):
    """Code to demonstrate a Finite State Machine that recognizes
       WikiWords."""
    SUCCESS_STATE = 4
    TRANSITIONS = [[1, 5],
                   [5, 2],
                   [3, 2],
                   [5, 4],
                   [3, 4],
                   [5, 5]]
    current_state = 0
    for letter in word:
        if letter.upper() == letter:
            current_state = TRANSITIONS[current_state][0]
        else:
            current_state = TRANSITIONS[current_state][1]
    return current_state == SUCCESS_STATE
###


The code itself is simple --- if completely nonobvious.  *grin* The real
complexity of the code has been hidden by our transition state table, but
the actual running of the code is pretty tame.


But does it work?

###
>>> isWikiWord("WikiWord")
1
>>> isWikiWord("WikiWordS")
0
>>> isWikiWord("The")
0
>>> isWikiWord("TheS")
0
>>> isWikiWord("SeeMe")
1
>>> [(word, isWikiWord(word))
...  for word in '''WikiWords is a MixedCase "word"
...                 which is useful in identifying
...                 and linking WikiPages'''.split()]
[('WikiWords', 1), ('is', 0), ('a', 0),
 ('MixedCase', 1), ('"word"', 0), ('which', 0),
 ('is', 0), ('useful', 0), ('in', 0),
 ('identifying', 0), ('and', 0), ('linking', 0),
 ('WikiPages', 1)]
###




One very cute thing about finite state machines is that they can be
transformed into regular expressions.  That is, we can first draw a
diagram, and then calculate an equivalent regular expression that does the
same work as the finite state machine.


The process is slightly involved, and this post is too way long as it is.
*grin* But here's the end result of the transformation:

###
>>> regex = re.compile('''
...     [A-Z][a-z]+
...     [A-Z][a-z]
...     ([A-Z][a-z] | [a-z])*
...     ''', re.VERBOSE)
>>> regex.match('Wiki')
>>> regex.match('WikiWord')
<_sre.SRE_Match object at 0x8168128>
>>> regex.match('WikiWordsAreNeat')
<_sre.SRE_Match object at 0x8126060>
>>> regex.match('FooBAR')
>>> regex.match('FooB')
>>> regex.match('FooBar')
<_sre.SRE_Match object at 0x8168128>
###


If you're interested in this sort of stuff, you may want to look through
"Introduction to the Theory of Computation":

    http://www-math.mit.edu/~sipser/book.html


It's a pricey book, but awesome in its presentation of these ideas.



I hope this helps!


From idiot1 at netzero.net  Thu Aug  7 22:44:50 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug  7 21:44:53 2003
Subject: [Tutor] arg...
Message-ID: <3F330092.5000301@netzero.net>

This is getting fustrating. Not that I'm going to give up- perish the thought- 
but it's fustrating.

ok. Nothing bombs. isolated parts work in idle. But it fails to convert 
wikiwords to links, and also fails to convert to active html links http url's.

Sigh.. oh well, Rome was not burned in a day...

Here's the wiki:
http;//www.tinylist.org/wikinehesa.py/SandBox

Here's the sourcecode of the moment:
http://www.tinylist.org/cgi-bin/wikinehesa.py/SandBox



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Thu Aug  7 22:52:22 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug  7 21:51:57 2003
Subject: [Tutor] is this a state machine? [designing a program to detect
	WikiWords]
In-Reply-To: <Pine.LNX.4.44.0308071632430.7862-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308071632430.7862-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F330256.3040109@netzero.net>


Again I am impressed by my own ignorance of my craft. And by the wisdom of my 
betters.

Danny Yoo wrote:

> 
> On Thu, 7 Aug 2003, Kirk Bailey wrote:
> 
> 
>>def iswikiword(word):				# test to see is a wikiword
>>	caps='ABCDEFGHIJKLMNOPQRSTUVWXYZ'	# define capitalletters
>>	prior=0					# set inital state for flags
>>	count=0					# wikiwords have 2+transitions
>>	for letter in word:			# examine each letter
>>		if letter in caps:		# if it IS a capital letter,
>>			prior=1			# store that state
>>		else:					# and if not,
>>			if prior==1:		# but the previous one WAS,
>>				prior=0		# reset the flag,
>>				count=count+1	# anc count the transition!
>>			else:				# otherwise,
>>				pass 			# chill out.
>>	if count > 1:				# ok, the results are in;
>>		return 1				# if there are 2+, itis.
>>	else:						# and if not,
>>		return 0				# say so.
> 
> 
> 
> [Warning: case study of using finite state machines to recognize
> WikiWords.]
> 
> 
> Hi Kirk,
> 
> 
> 
> Let's define what a "wiki word" is in English, before defining it in code.
> According to:
> 
>     """It is a concatenation of words (of two or more letters each)
>     without white space between them, and with the first letter (only) of
>     each component word capitalized."""
> 
>     http://c2.com/cgi/wiki?WikiWords
> 
> 
> The code above will work for a lot of cases, but will break on something
> like this:
> 
> ###
> 
>>>>iswikiword("ThisIsNOTAWikiWord")
> 
> 1
> ###
> 
> 
> A finite state machine is also not allowed to do counting, so the 'count'
> variable in the function will disqualify it from being a finite state
> machine.
> 
> 
> 
> 
> We can imagine a finite state machine to recognize WikiWords that might
> look like this:
> 
> 
>                    capital?
>           START --------------> On1stCapitalLetter
>                                       |
>                                       |
>                                       | lowercase?
>                                       |
>                                       |
>                                       | <--------+
>                                       |          |
>                                       |          | lowercase?
>                                       |          |
>                                       V          |
>                                   FirstWord -----+
>                                       |
>                                       |
>                                       | capital?
>                                       |
>                                       |
>                                       V
>                         +---> OnAnotherCapitalLetter
>                         |             |
>                         |             |
>                         |             | lowercase?
>                         |             |
>                         |             |
>                         |             | <---------+
>               capital?  |             |           |
>                         |             |           | lowercase?
>                         |             |           |
>                         |             V           |
>                         |       **ANOTHERWORD ----+
>                         |             |
>                         |             |
>                         |             |
>                         +-------------+
> 
> 
> 
> This looks suspiciously like a flow diagram, for which I apologize: it's
> hard drawing circles in ASCII, so I've omitted them.  *grin*
> 
> 
> The diagram above has 5 states:
> 
>     [START, On1stCapitalLetter, FirstWord, OnAnotherCapitalLetter,
>      ANOTHERWORD]
> 
> 
> Whew.  That's a mouthful.  Let's shorten the names slightly:
> 
>     [START, On1st, FirstWord, OnAnother, ANOTHERWORD]
> 
> 
> I've labeled the state that we start on as "START".  We jump from state to
> state, depending if the next letter is uppercase or lowercase --- and if
> we ever "fall off" the machine, then the word definitely isn't a Wiki
> Word.  Think of it as a board game.
> 
> 
> If it's a board game, how do we win?  How do we know if we are recognizing
> a WikiWord?  Well, if we're on the ANOTHERWORD state by the time we're at
> the end of our word, we'll consider that to be a WikiWord: that's the goal
> of any word that wants to have the Wiki nature.
> 
> 
> 
> Before we put down any Python code, let's try it out on something like
> "WikiWord":
> 
> 
> ------
> 
> time   state   next letter   comments
> ----   -----   -----------   --------
> 
>  1     START       W          'W' is capitalized, so we jump to
>                               On1stCapitalLetter
> 
>  2     On1st       i          'i' is lowercased, so we jump to Firstword
> 
>  3     FirstWord   k          'k' is lowercased.  There's an "lowercase?"
>                               arrow that points back to FirstWord, so we
>                               jump back to FirstWord.
> 
>  4     FirstWord   i          Ditto.
> 
>  5     FirstWord   W          Ok, we've seen another capital.
> 
>  6     OnAnother   o          Yeah, now we can jump onto ANOTHERWORD!
> 
>  7     ANOTHERWORD r          ... but we can't celebrate until we finish
>                               reading the rest of our input!
> 
>  8     ANOTHERWORD d          Almost there.
> 
>  9     ANOTHERWORD            Done!  And yes, 'WikiWord' is a WikiWord
> 
> ------
> 
> 
> Once we try a few words against our game board, we'll probably feel more
> comfortable that it's doing the right thing.  Now to implement it in
> Python!  *grin*
> 
> 
> 
> The diagram above is easy for us humans to trace, but not so convenient
> for computers.  Let's make it slightly easier by "redrawing" that diagram
> as a table:
> 
> 
>                     capital?      lowercase?
> -----------------------------------------------
> START        |      On1st          FAIL
> On1st        |      FAIL           FirstWord
> FirstWord    |      OnAnother      FirstWord
> OnAnother    |      FAIL           ANOTHERWORD
> ANOTHERWORD  |      OnAnother      ANOTHERWORD
> FAIL         |      FAIL           FAIL
> 
> 
> I've sneaked in one more state, a "FAIL" state that catches the situation
> when we "fall" off the diagram.  Think of it as a black hole for failed
> WikiWords.
> 
> 
> If we want to be concise, we can do another renaming of the states of our
> machine, from words to numbers.  Let's do that.
> 
> 
>       capital?   lowercase?
> --------------------------
> 0   |    1           5
> 1   |    5           2
> 2   |    3           2
> 3   |    5           4
> 4   |    3           4
> 5   |    5           5
> 
> 
> 
> And something like this is easy to represent as a list:
> 
> ###
> 
>>>>transitions = [[1, 5],
> 
> ...                [5, 2],
> ...                [3, 2],
> ...                [5, 4],
> ...                [3, 4],
> ...                [5, 5]]
> ###
> 
> 
> 
> And now, we can write something that uses this table to jump around our
> state diagram:
> 
> ###
> def isWikiWord(word):
>     """Code to demonstrate a Finite State Machine that recognizes
>        WikiWords."""
>     SUCCESS_STATE = 4
>     TRANSITIONS = [[1, 5],
>                    [5, 2],
>                    [3, 2],
>                    [5, 4],
>                    [3, 4],
>                    [5, 5]]
>     current_state = 0
>     for letter in word:
>         if letter.upper() == letter:
>             current_state = TRANSITIONS[current_state][0]
>         else:
>             current_state = TRANSITIONS[current_state][1]
>     return current_state == SUCCESS_STATE
> ###
> 
> 
> The code itself is simple --- if completely nonobvious.  *grin* The real
> complexity of the code has been hidden by our transition state table, but
> the actual running of the code is pretty tame.
> 
> 
> But does it work?
> 
> ###
> 
>>>>isWikiWord("WikiWord")
> 
> 1
> 
>>>>isWikiWord("WikiWordS")
> 
> 0
> 
>>>>isWikiWord("The")
> 
> 0
> 
>>>>isWikiWord("TheS")
> 
> 0
> 
>>>>isWikiWord("SeeMe")
> 
> 1
> 
>>>>[(word, isWikiWord(word))
> 
> ...  for word in '''WikiWords is a MixedCase "word"
> ...                 which is useful in identifying
> ...                 and linking WikiPages'''.split()]
> [('WikiWords', 1), ('is', 0), ('a', 0),
>  ('MixedCase', 1), ('"word"', 0), ('which', 0),
>  ('is', 0), ('useful', 0), ('in', 0),
>  ('identifying', 0), ('and', 0), ('linking', 0),
>  ('WikiPages', 1)]
> ###
> 
> 
> 
> 
> One very cute thing about finite state machines is that they can be
> transformed into regular expressions.  That is, we can first draw a
> diagram, and then calculate an equivalent regular expression that does the
> same work as the finite state machine.
> 
> 
> The process is slightly involved, and this post is too way long as it is.
> *grin* But here's the end result of the transformation:
> 
> ###
> 
>>>>regex = re.compile('''
> 
> ...     [A-Z][a-z]+
> ...     [A-Z][a-z]
> ...     ([A-Z][a-z] | [a-z])*
> ...     ''', re.VERBOSE)
> 
>>>>regex.match('Wiki')
>>>>regex.match('WikiWord')
> 
> <_sre.SRE_Match object at 0x8168128>
> 
>>>>regex.match('WikiWordsAreNeat')
> 
> <_sre.SRE_Match object at 0x8126060>
> 
>>>>regex.match('FooBAR')
>>>>regex.match('FooB')
>>>>regex.match('FooBar')
> 
> <_sre.SRE_Match object at 0x8168128>
> ###
> 
> 
> If you're interested in this sort of stuff, you may want to look through
> "Introduction to the Theory of Computation":
> 
>     http://www-math.mit.edu/~sipser/book.html
> 
> 
> It's a pricey book, but awesome in its presentation of these ideas.
> 
> 
> 
> I hope this helps!
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From clay at shirky.com  Thu Aug  7 23:08:15 2003
From: clay at shirky.com (Clay Shirky)
Date: Thu Aug  7 22:08:21 2003
Subject: [Tutor] strings matching problem
In-Reply-To: <Sea1-F124XSRdZqou2V000005cc@hotmail.com>
Message-ID: <BB587E4F.BAB4%clay@shirky.com>

> Hello !
> 
> First of all thanks to everyone on the list for giving consideration to my
> problems. With the help of the tutor mailing list i am really learning a lot
> about programming in python.
> 
> I have a small problem for now also.
> 
> I have a few names like a name followed by hash(#) and then a no. which
> indicates the repeated  occurance of the name.
> 
> Like .abc ,  .abc#1 ,  .abc#2
> 
> I want that if i encounter such kind of name then it should be converted to
> .abc
> 
> I think that this can be done with re.compile and some kind of match with
> re.match

You'd rather do re.sub (substitution) than re.match, and you only need to
use re.compile if you are doing a *lot* of matches and speed is an issue, so
if its just a one-off renaming of a few hundred files, you can skip
re.compile.

Here's a sample using re.sub

# dummy file list
file_list = [ "spam.abc", "eggs.abc#1", "spam_eggs.abc#2" ]

import re # import the regular expression module

for f in file_list:
    new_f = re.sub("abc#\d+$", "abc", f) # sub "abc# + digits" with abc
    print f, "->", new_f

Note that the regular expression, abc#\d+$, is pretty narrowly tailored to
the example you gave. Its "abc followed by a hash mark followed by one or
more digits, to the end of the string", so if the pattern is more general,
like sometimes theres a hash but no number, or characters after the numbers,
or the string after the hash can include letters, you will need to change
the regular expression.

-clay


From amonroe at columbus.rr.com  Thu Aug  7 23:27:45 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu Aug  7 22:23:10 2003
Subject: [Tutor] Python cross-compiler for 16 bit Motorla cpus?
In-Reply-To: <BB587E4F.BAB4%clay@shirky.com>
References: <BB587E4F.BAB4%clay@shirky.com>
Message-ID: <8610412382.20030807222745@columbus.rr.com>

>> Hello !
>> 
>> First of all thanks to everyone on the list for giving consideration to my
>> problems. With the help of the tutor mailing list i am really learning a lot
>> about programming in python.
>> 
>> I have a small problem for now also.
>> 
>> I have a few names like a name followed by hash(#) and then a no. which
>> indicates the repeated  occurance of the name.
>> 
>> Like .abc ,  .abc#1 ,  .abc#2
>> 
>> I want that if i encounter such kind of name then it should be converted to
>> .abc
>> 
>> I think that this can be done with re.compile and some kind of match with
>> re.match

> You'd rather do re.sub (substitution) than re.match, and you only need to
> use re.compile if you are doing a *lot* of matches and speed is an issue, so
> if its just a one-off renaming of a few hundred files, you can skip
> re.compile.

> Here's a sample using re.sub
Is there a Python cross-compiler for 16 bit Motorla cpus?

I googled for:
python Motorola 68HCS12
and got no results...

The reason I ask:
http://www.xgamestation.com/

Alan


From amonroe at columbus.rr.com  Thu Aug  7 23:33:42 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu Aug  7 22:29:05 2003
Subject: [Tutor] Python cross-compiler for 16 bit Motorla cpus?
In-Reply-To: <8610412382.20030807222745@columbus.rr.com>
References: <BB587E4F.BAB4%clay@shirky.com>
	<8610412382.20030807222745@columbus.rr.com>
Message-ID: <19010768744.20030807223342@columbus.rr.com>

> Is there a Python cross-compiler for 16 bit Motorla cpus?
Apologies for inadvertenly including an earlier, completely unrelated
message... (note to self: hit ctrl+home before sending!)

Alan


From idiot1 at netzero.net  Fri Aug  8 00:30:29 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug  7 23:30:34 2003
Subject: [Tutor] wiki madness
Message-ID: <3F331955.7050805@netzero.net>

Improving. Wrong,but better.

Works, sort of. still got problems, but DIFFERENT problems. Take a look:
the wiki:
http://www.tinylist.org/cgi-bin/wikinehesa.py

the sourcecode:
http://www.tinylist.org/wikinehesa.txt

The asprin:
(link not available...)

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From shalehperry at comcast.net  Fri Aug  8 00:31:56 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Fri Aug  8 02:32:31 2003
Subject: [Tutor] wiki madness
In-Reply-To: <3F331955.7050805@netzero.net>
References: <3F331955.7050805@netzero.net>
Message-ID: <200308072331.56143.shalehperry@comcast.net>

On Thursday 07 August 2003 20:30, Kirk Bailey wrote:
> Improving. Wrong,but better.
>

comments:

* no need to define caps, just use string.ascii_uppercase (and lowercase is 
there too)

* why not define ishyperlink() using string.startswith()?
or perhaps something from the urllib module?

* wordsplit() doesn't actually split, more like strips.  You could write that 
function as:

for char in word:
    if char not in punctuation:
        newword += char # or 1.5 style newword = newword + char
    else:
        extras = extras + char
    return words, extras

* style comment.  I like to use the formatting operator instead of lots of 
string math.

link = '<a href="%s">%s</a>' % (word, word) # instead of
link = '<a href="' + word + '">' + word + '</a>'

while discussing style, this is python, feel free to use some whitespace.  
Your code reads like a bourne again shell coder.

* parseline() is begging for a list and a loop.  Also, you are not parsing the 
line.  parsing is breaking down into tokens and performing actions with the 
tokens.

* marking main() with the python idiom of:

if __name__ == '__main__':
   # code

would be a good best practice to follow.  Also lets you load any of yourt 
python apps as modules for other python apps.

Sorry, did not run it to help you debug it.  Just wanted to pass on some style 
ideas for the other readers.


From alan.gauld at blueyonder.co.uk  Fri Aug  8 09:01:16 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  8 03:00:48 2003
Subject: [Tutor] strings matching problem
References: <Sea1-F124XSRdZqou2V000005cc@hotmail.com>
Message-ID: <008301c35d7a$dc80aec0$6401a8c0@xp>

> Like .abc ,  .abc#1 ,  .abc#2
>
> I want that if i encounter such kind of name then it should be
converted to
> .abc

string.split('#') will do that for you:

>>> print 'abc#2'.split('#')[0]
'abc'

Alan G.



From arkamir at softhome.net  Fri Aug  8 11:27:29 2003
From: arkamir at softhome.net (arkamir@softhome.net)
Date: Fri Aug  8 12:27:33 2003
Subject: [Tutor] example help
In-Reply-To: <E19l9hm-0007aE-00@mail.python.org> 
References: <E19l9hm-0007aE-00@mail.python.org>
Message-ID: <courier.3F33CF71.00006945@softhome.net>

Hey im knew to programing and i got these examples out of the book THE QUICK 
PYTHON GUIDE. I understand all the other examples but these 2 just stump me. 
Can anyone help explain them to me?? 

This example gives the factorial of a number 

def fact(n):
  r=1
  while n >0:
     r=r*n
     n=n-1
  return r 

This one calculates a number (x) to a number (Y) which has an initial 
setting to 2 

def power(x, y=2):
  r=1
  while y>0:
     r=r*x
     y=y-1
  return r
thanks 

From jonathan.hayward at pobox.com  Fri Aug  8 18:32:44 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug  8 12:32:48 2003
Subject: [Tutor] re question
Message-ID: <3F33D0AC.70408@pobox.com>

I'm trying to use regexps to find the contents of all foo tags. So, if I 
gave the procedure I'm working on an HTML document and asked for 
"strong" tags, it would return a list of strings enclosed in <strong> 
</strong> in the original.

I'm having trouble with the re; at the moment the re seems to return 
only the first instance. What am I doing wrong?

    def get_tag_contents_internal(self, tag, file_contents):
        result = []
        # At present only matches first occurrence. Regexp should be 
worked on.
        my_re = re.compile(".*?(<" + tag + ".*?>(.*?)</" + tag + \
          ".*?>.*?)+.*?", re.IGNORECASE)
        if my_re.match(file_contents) != None:
            result = my_re.match(file_contents(group(2))
        return result

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From alex at gabuzomeu.net  Fri Aug  8 20:10:00 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Fri Aug  8 13:06:19 2003
Subject: [Tutor] re question
In-Reply-To: <3F33D0AC.70408@pobox.com>
References: <3F33D0AC.70408@pobox.com>
Message-ID: <3F33D968.8020902@gabuzomeu.net>

Hello Jonathan,


Jonathan Hayward http://JonathansCorner.com wrote:
> I'm trying to use regexps to find the contents of all foo tags. So, if I 
> gave the procedure I'm working on an HTML document and asked for 
> "strong" tags, it would return a list of strings enclosed in <strong> 
> </strong> in the original.
> 
> I'm having trouble with the re; at the moment the re seems to return 
> only the first instance. What am I doing wrong?
> 
>    def get_tag_contents_internal(self, tag, file_contents):
>        result = []
>        # At present only matches first occurrence. Regexp should be 
> worked on.
>        my_re = re.compile(".*?(<" + tag + ".*?>(.*?)</" + tag + \
>          ".*?>.*?)+.*?", re.IGNORECASE)

To retrieve all matches, you can use findall(). Also, your expression 
may be matching too much. Here is an example that seems to work:

 >>> import re
 >>> s = """text text <strong>this is strong</strong> text <strong>this 
is strong too</strong>"""
 >>> tag = "strong"
 >>> pattern = re.compile("<%s.*?>(.*?)</%s.*?>" % (tag, tag))
 >>> pattern.findall(s)
['this is strong', 'this is strong too']


To extract data from HTML files, you may also want to look at the 
'HTMLParser', 'htmllib' and 'sgmllib' modules:

	http://www.python.org/doc/current/lib/markup.html


Cheers.

Alexandre




From clay at shirky.com  Fri Aug  8 14:06:18 2003
From: clay at shirky.com (Clay Shirky)
Date: Fri Aug  8 13:06:28 2003
Subject: [Tutor] example help
In-Reply-To: <courier.3F33CF71.00006945@softhome.net>
Message-ID: <BB5950CA.BB43%clay@shirky.com>

> def fact(n):
> r=1
> while n >0:
>    r=r*n
>    n=n-1
> return r 

This takes a user-defined number, n, and says that as long as n is greater
than 0, the function should set r to r * n, reduce n by one, and check again
to see if the new value of n is greater than 0.

So if you set an n of 3, the loop would go:

3 is grater than 0:
    r = 1 * 3 # r is now 3
    n = 3 - 1 # n is now 2

2 is greater than 0:
    r = 3 * 2 # the new r times the new n, which is 6
    n = 2 - 1 # n is now 1

1 is greater than 0:
    r = 6 * 1 # the new r times the new n, which is still 6
    n = 1 - 1 # n is no 0

0 is NOT greater than zero:
    return r

So feeding the function an n of 3 returns an r of 6, which is the value of
3! (3 factorial.)

The power function works the same way, set a new r, reduce n by one, and
re-check to make sure n still passes the while test.

-clay





From zak at harlekin-maus.com  Fri Aug  8 11:10:37 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Fri Aug  8 13:10:41 2003
Subject: [Tutor] example help
In-Reply-To: <courier.3F33CF71.00006945@softhome.net>
References: <E19l9hm-0007aE-00@mail.python.org>
	<courier.3F33CF71.00006945@softhome.net>
Message-ID: <1543.192.207.104.210.1060362637.squirrel@mail.harlekin-maus.com>

> Hey im knew to programing and i got these examples out of the book THE
> QUICK
> PYTHON GUIDE.
>
> This example gives the factorial of a number
>
> def fact(n):
>   r=1
>   while n >0:
>      r=r*n
>      n=n-1
>   return r

The best thing to do is to walk through the routine with a handy variable
value chart. Here's an example for fact(4). Before we start, we know that
4! = 4 * 3 * 2 * 1 = 24. So hopefully, that's what we get on the
walkthrough.

fact(4)
r      n      notes
-      -      -----
1      4      at line 2, r=1
4      4      at line 4, r=r*n
4      3      at line 5, n=n-1
now we go back to line 3, n > 0, so we stay in the while loop
12     3      r = r*n
12     2      n = n-1
back to line 3
24     2      r = r*n
24     1      n = n-1
back to line 3
24     1      r = r*n
24     0      n = n-1
back to line 3, n > 0 ? NO! n is equal to zero, not greater than, so we
kick out of the while loop
24     0      return r

return 24

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From tpc at csua.berkeley.edu  Fri Aug  8 11:11:46 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Aug  8 13:12:04 2003
Subject: [Tutor] re question
In-Reply-To: <3F33D0AC.70408@pobox.com>
Message-ID: <20030808100924.C16066-100000@localhost.name>


hello Jonathan, you should use re.findall as re.match only returns the
first instance.  By the way I would recommend the htmllib.HTMLParser
module instead of reinventing the wheel.

On Fri, 8 Aug 2003, Jonathan Hayward http://JonathansCorner.com wrote:

> I'm trying to use regexps to find the contents of all foo tags. So, if I
> gave the procedure I'm working on an HTML document and asked for
> "strong" tags, it would return a list of strings enclosed in <strong>
> </strong> in the original.
>
> I'm having trouble with the re; at the moment the re seems to return
> only the first instance. What am I doing wrong?
>
>     def get_tag_contents_internal(self, tag, file_contents):
>         result = []
>         # At present only matches first occurrence. Regexp should be
> worked on.
>         my_re = re.compile(".*?(<" + tag + ".*?>(.*?)</" + tag + \
>           ".*?>.*?)+.*?", re.IGNORECASE)
>         if my_re.match(file_contents) != None:
>             result = my_re.match(file_contents(group(2))
>         return result
>
> --
> ++ Jonathan Hayward, jonathan.hayward@pobox.com
> ** To see an award-winning website with stories, essays, artwork,
> ** games, and a four-dimensional maze, why not visit my home page?
> ** All of this is waiting for you at http://JonathansCorner.com
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From knguyen at seri.co.uk  Fri Aug  8 19:42:06 2003
From: knguyen at seri.co.uk (Khai Nguyen)
Date: Fri Aug  8 13:42:25 2003
Subject: [Tutor] Executing an executable with commandline options
Message-ID: <341710540F08E34498A057DEE04DAAD7EE16C0@ex1.seri.co.uk>

Bob, 
 
I think he ask about some thing else.  Could be interesting ...  
 
For example you start an win application which normally show you a
dialogue, and wait, if you don't need to change anyconfiguration like
chose which game to start with you still have to hit the RUN button so
that the application can run!
 
 
"How to start such an application in python" is what I understand he
want to ask here.  Am I right.? if I misunderstood, would it be possible
to use python to write a script for starting the applic\game I
describe?(WINNT or windows2000 ope.). 
 
 
DOS batch file or a short cut link only brings you to the
dialogue\interface where it waits for you to hit return button.  Apart
from Macro applic (using cursor and key pad memory), slow sometime
trouble, I could not think other way.  With python maybe? But, how?
 
Kind regard
 
ntk 
 
 -Original Message-----
From: Bob Gailer [mailto:bgailer@alum.rpi.edu] 
Sent: Thursday, August 07, 2003 5:32 PM
To: SGD; tutor@python.org
Subject: Re: [Tutor] Executing an executable with commandline options



At 11:21 PM 8/5/2003 -0400, SGD wrote:


I'm coding a launcher for my favorite game and dont understand how two
execute an executable with command line options passed to it when the
run game icon is clicked. To be exact this is what I what to do;

hl.exe -console -dev (among other commands)


Since you did not tell us which operating system, I'll assume you are
running Windows, and that you are referring to icons that appear in a
folder or on the desktop.. (With *x YMMV). 

Option 1 - If you have not already done so, create a shortcut to the
executable. Open its properties, and add the options after the exe in
the Target text box. Then double click the shortcut.

Option 2 - create a .bat or .cmd file with the desired command and
double click that.


Bob Gailer
bgailer@alum.rpi.edu
303 442 2625




*****************************************************************************
The information contained in this email and in any attachments 
may be privileged and confidential.  
The information is designated solely for the attention and use of 
the intended recipient(s).  
If you are not the intended recipient(s), please be aware that any 
disclosure, copying, distribution or use of the contents of this 
information is prohibited. 
If you have received this email in error, please notify the sender 
by telephone or email immediately.
*****************************************************************************

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030808/c7dd0234/attachment.htm
From jeff at ccvcorp.com  Fri Aug  8 12:28:18 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Aug  8 14:27:32 2003
Subject: [Tutor] re question
References: <20030808100924.C16066-100000@localhost.name>
Message-ID: <3F33EBC2.5020405@ccvcorp.com>

tpc@csua.berkeley.edu wrote:

>hello Jonathan, you should use re.findall as re.match only returns the
>first instance.  By the way I would recommend the htmllib.HTMLParser
>module instead of reinventing the wheel.
>

Indeed, it's not just reinventing the wheel.  Regular expressions, by 
themselves, are insufficient to do proper HTML parsing, because re's 
don't remember state and can't deal with nested/branched data structures 
(which HTML/XML/SGML are).  As someone else pointed out, you're likely 
to grab too much, or not enough.  Anybody seriously trying to do 
anything with HTML should be using HTMLParser, *not* re.

Jeff Shannon
Technician/Programmer
Credit International



From justin at unixremedies.com  Fri Aug  8 15:41:04 2003
From: justin at unixremedies.com (Justin Heath)
Date: Fri Aug  8 15:55:55 2003
Subject: [Tutor] Windows software reporting
Message-ID: <3F33FCD0.10402@unixremedies.com>

All,

I am currently writing a program that queries Linux, Solaris boxes for 
installed software and software versions and comparing this information 
against a database. It appears this could be useful to our Windows guys 
as well. My question is how to get this information on a Windows box. 
Currently for Linux I am using os.popen("rpm -qa", "r"), for example. 
Any suggestions?

Thanks,
Justin



From gus.tabares at verizon.net  Fri Aug  8 17:01:48 2003
From: gus.tabares at verizon.net (Gus Tabares)
Date: Fri Aug  8 16:03:28 2003
Subject: [Tutor] Windows software reporting
In-Reply-To: <3F33FCD0.10402@unixremedies.com>
References: <3F33FCD0.10402@unixremedies.com>
Message-ID: <oprtlq9ae1blxpqj@outgoing.verizon.net>

On Fri, 08 Aug 2003 14:41:04 -0500, Justin Heath <justin@unixremedies.com> 
wrote:

> All,
>
> I am currently writing a program that queries Linux, Solaris boxes for 
> installed software and software versions and comparing this information 
> against a database. It appears this could be useful to our Windows guys 
> as well. My question is how to get this information on a Windows box. 
> Currently for Linux I am using os.popen("rpm -qa", "r"), for example. Any 
> suggestions?
>
> Thanks,
> Justin
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


One possibility is to use Mark Hammonds Win32 API extensions and query the 
registry? Seems like a semi-decent idea. Hope this helps anyways...


/Gus

From harrisonfthomasjr at comcast.net  Fri Aug  8 14:13:56 2003
From: harrisonfthomasjr at comcast.net (Harrison Thomas)
Date: Fri Aug  8 16:13:29 2003
Subject: [Tutor] What happened to the Subject line?
In-Reply-To: <E19lDLC-000864-00@mail.python.org>
Message-ID: <JNELICAENPFFBHHOHOKMOEGECMAA.harrisonfthomasjr@comcast.net>



Earlier this week the subject line stopped listing the number of messages. I
use this to prioritize my reading of the list. Could we have it reinstated?

Thanks
Harrison


From jonathan.hayward at pobox.com  Fri Aug  8 22:17:04 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug  8 16:17:09 2003
Subject: [Tutor] re question
In-Reply-To: <3F33EBC2.5020405@ccvcorp.com>
References: <20030808100924.C16066-100000@localhost.name>
	<3F33EBC2.5020405@ccvcorp.com>
Message-ID: <3F340540.6060106@pobox.com>

Jeff Shannon wrote:

> tpc@csua.berkeley.edu wrote:
>
>> hello Jonathan, you should use re.findall as re.match only returns the
>> first instance.  By the way I would recommend the htmllib.HTMLParser
>> module instead of reinventing the wheel.
>>
>
> Indeed, it's not just reinventing the wheel.  Regular expressions, by 
> themselves, are insufficient to do proper HTML parsing, because re's 
> don't remember state and can't deal with nested/branched data 
> structures (which HTML/XML/SGML are).  As someone else pointed out, 
> you're likely to grab too much, or not enough.  Anybody seriously 
> trying to do anything with HTML should be using HTMLParser, *not* re.
>
Hmm...

I looked through the library docs on this, and tried to do it with re's 
because figuring out how to use HTMLParser looked like more work than 
using re's -- 3 hours' documentation search to avoid one hour of 
reinventing the wheel.

What I'd like to do is:

Find all instances of such-and-such between two tags (for which I've 
received a helpful response).
Strip out all (or possibly all-but-whitelist) tags from an HTML page 
(substitute "" for "<.*?>" over multiple lines?).
Iterate over links / images and selectively change the targets / sources 
(which would take me a lot of troubleshooting to do with RE).

Possibly other things; I'm not trying to compete with HTMLParser but get 
some basic functionality. I'd welcome suggestions on how to do this with 
HTMLParser.

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From BranimirP at cpas.com  Fri Aug  8 17:25:48 2003
From: BranimirP at cpas.com (Branimir Petrovic)
Date: Fri Aug  8 16:26:23 2003
Subject: [Tutor] Windows software reporting
Message-ID: <33678E78A2DD4D418396703A750048D45E67BC@RIKER>

> -----Original Message-----
> From: Justin Heath [mailto:justin@unixremedies.com]
> Sent: Friday, August 08, 2003 3:41 PM
> To: tutor@python.org
> Subject: [Tutor] Windows software reporting
> 
> 
> All,
> 
> I am currently writing a program that queries Linux, Solaris 
> boxes for 
> installed software and software versions and comparing this 
> information 
> against a database. It appears this could be useful to our 
> Windows guys 
> as well. My question is how to get this information on a Windows box. 
> Currently for Linux I am using os.popen("rpm -qa", "r"), for example. 

Have a look at project that does exactly that but is unfortunately done all 
in JScript (except one lone VB script class):

	http://poormanssms.sourceforge.net/

If it for any reason you can not/will not use this already done tested
and working solution, then have a look at SoftwareMeteringCLS.vbs either
among project files or here:

	http://www.interclasse.com/scripts/SoftwareMeteringCLS.php

to see how to do it, then use the "right tool for the right task"...

Be warned though that should you base your solution on WMI (and DCOM) as 
I did with mine, you might eventually be in for unpleasant surprise sooner 
or later (hint: late RPC DCOM vulnerability and ill fated MS03-026 security 
patch... I have little doubt that M$ will not manage to mess up either WMI 
or the DCOM on which it relies on security grounds if not for any other).

Branimir 

From jeff at ccvcorp.com  Fri Aug  8 15:40:14 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Aug  8 17:39:28 2003
Subject: [Tutor] re question
References: <20030808100924.C16066-100000@localhost.name>	<3F33EBC2.5020405@ccvcorp.com>
	<3F340540.6060106@pobox.com>
Message-ID: <3F3418BE.1000505@ccvcorp.com>

Jonathan Hayward http://JonathansCorner.com wrote:

> Jeff Shannon wrote:
>
>> tpc@csua.berkeley.edu wrote:
>>
>>> hello Jonathan, you should use re.findall as re.match only returns the
>>> first instance.  By the way I would recommend the htmllib.HTMLParser
>>> module instead of reinventing the wheel.
>>>
>>
>> Indeed, it's not just reinventing the wheel.  Regular expressions, by 
>> themselves, are insufficient to do proper HTML parsing, because re's 
>> don't remember state and can't deal with nested/branched data 
>> structures (which HTML/XML/SGML are).  As someone else pointed out, 
>> you're likely to grab too much, or not enough.  Anybody seriously 
>> trying to do anything with HTML should be using HTMLParser, *not* re.
>>
> Hmm...
>
> I looked through the library docs on this, and tried to do it with 
> re's because figuring out how to use HTMLParser looked like more work 
> than using re's -- 3 hours' documentation search to avoid one hour of 
> reinventing the wheel. 


Depending on just how limited your needs are, you *might* be able to get 
away with just using re's -- but you might also get bitten.

> What I'd like to do is:
>
> Find all instances of such-and-such between two tags (for which I've 
> received a helpful response). 


This is trickier than it sounds.  Look at the string

"This is <strong>bad</strong>.  Very <strong>bad</strong>."

Within this string, there are *three* instances of something that's 
between paired tags -- "bad", twice, and this:

"bad</strong>.  Very <strong>bad"

A regular expression will have difficulty distinguishing between these. 
 Of course, you'll immediately thing, just match the closest one!  That 
doesn't work either, though.  Consider a nested list --

<ol>
<li>
    <ol><li>One</li><li>Two</li></ol>
</li>
<li>One, again</li>
</ol>

Here, if you're set to match the first closing tag you see, then the 
<ol> from the outer list will be matched with the </ol> from the inner 
list.  Not good.

In fact, there is no way to construct a normal RE that can work right 
for both of these cases.  In order to do that, you need a proper parser, 
which will include a state machine.  HTMLParser can handle both of these 
cases with no problems.

> Strip out all (or possibly all-but-whitelist) tags from an HTML page 
> (substitute "" for "<.*?>" over multiple lines?). 


This could be done with RE's, provided that you're not worried about 
preserving the meaning of the tag.  You're throwing away the 
tree-structure of your data, so the limitations of REs don't apply.

> Iterate over links / images and selectively change the targets / 
> sources (which would take me a lot of troubleshooting to do with RE). 


This could possibly work, too -- an <img src="..."> tag is complete in 
and of itself, and therefore can be safely recognized by a RE.  You 
could work out a RE that would identify the contents of the src 
attribute, and substitute it with some transformed version of itself. 
 Similarly, you could identify and modify the href attribute of an <a> 
tag -- but you could not safely identify the text between <a> and </a>, 
because REs can't properly capture the necessary level of structure.

> Possibly other things; I'm not trying to compete with HTMLParser but 
> get some basic functionality. I'd welcome suggestions on how to do 
> this with HTMLParser. 


Depending on how basic your functionality is (i.e., if you know for 
absolute certain that you will *never* have nested tags), you may be 
able to get away with REs -- after all, if you're firing a gun across 
the room, the path of the bullet might as well be straight.  But if 
you're firing artillery, then you can't make that simplification.  And 
even when you're firing across the room... if the shot ends up going out 
the window, then suddenly you're in a whole different paradigm and your 
simplification won't work, and may cause a whole heap of unexpected 
problems.

(I've never needed to parse HTML myself, so I haven't looked into how to 
use HTMLParser, and I can't offer specific code to help with your 
problems.  I've just picked up enough about parsing in general to know 
that REs alone are not up to the task.)

Jeff Shannon
Technician/Programmer
Credit International



From Niurkav1 at aol.com  Thu Aug  7 10:13:46 2003
From: Niurkav1 at aol.com (Niurkav1@aol.com)
Date: Fri Aug  8 17:44:50 2003
Subject: [Tutor] (no subject)
Message-ID: <73.33aef175.2c63aa8a@aol.com>

How do I use Python on Linux? I dont know if I even have the source code, so 
please email me at phasma999@hotmail.com
thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030807/29623511/attachment.htm
From alan.gauld at blueyonder.co.uk  Sat Aug  9 00:06:22 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Aug  8 18:05:45 2003
Subject: [Tutor] Windows software reporting
References: <3F33FCD0.10402@unixremedies.com>
Message-ID: <00de01c35df9$4d899d10$6401a8c0@xp>

> as well. My question is how to get this information on a Windows
box.
> Currently for Linux I am using os.popen("rpm -qa", "r"), for
example.

OK, First you are only picking up rpm installed packages as it
is - On Solaris particularly a lot of software does not use rpm
for installs.

Now to Windows, I don't know of any way to do this in windows
except to examine the registry. There are APIs to do that in
the winall package but you'll need to do some research to find
which keys you need to check to see whats been installed. And
like the rpm solution it will only find those installed the
official way. Single file executables just copied into a
folder will be invisible.

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  Fri Aug  8 16:42:57 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug  8 18:43:02 2003
Subject: [Tutor] re question
In-Reply-To: <3F340540.6060106@pobox.com>
Message-ID: <Pine.LNX.4.44.0308081522210.8778-100000@hkn.eecs.berkeley.edu>



Hi Jonathan,




> Find all instances of such-and-such between two tags (for which I've
> received a helpful response).

I actually prefer using SGMLParser over HTMLParser.  SGMLParser has some
documentation here:

    http://www.python.org/doc/lib/module-sgmllib.html

but examples can't hurt.  *grin* Here's a small example of a program that
pays attention to italics:


###
>>> import sgmllib
>>> class MyParser(sgmllib.SGMLParser):
...     def __init__(self):
...         sgmllib.SGMLParser.__init__(self)
...         self.in_italic = 0
...         self.italicized_words = []
...     def start_i(self, attributes):
...         self.in_italic = 1
...     def end_i(self):
...         self.in_italic = 0
...     def handle_data(self, data):
...         if self.in_italic:
...             self.italicized_words.append(data)
...     def getItalics(self):
...         return self.italicized_words
...
>>> p = MyParser()
>>> p.feed("""Hello, this is a bit of <i>italicized</i> text.
... <i>hello</i> world!""")
>>> p.getItalics()
['italicized', 'hello']
###



> Strip out all (or possibly all-but-whitelist) tags from an HTML page
> (substitute "" for "<.*?>" over multiple lines?).

We can do this by redefining our parser not to do anything except pay
attention to handle_data():

###
>>> def strip_html(text):
...     class silly_parser(sgmllib.SGMLParser):
...         def __init__(self):
...             sgmllib.SGMLParser.__init__(self)
...             self.text = []
...         def handle_data(self, data):
...             self.text.append(data)
...         def get_text(self):
...             return self.text
...     p = silly_parser()
...     p.feed(text)
...     return ''.join(p.get_text())
...
>>> strip_html("""<html><body><p>Hello, this is <b>bolded</b>
...               test!</p></body></html""")
'Hello, this is bolded\n              test!'
###


Note: we can adjust this parser to be a little more discriminating on the
kinds of tags it ignores (all-but-whitelist?) by working with the
handle_starttag() method.



> Iterate over links / images and selectively change the targets / sources
> (which would take me a lot of troubleshooting to do with RE).
>
> Possibly other things; I'm not trying to compete with HTMLParser but get
> some basic functionality. I'd welcome suggestions on how to do this with
> HTMLParser.


With the examples above, you should be able to retarget them to do the
other tasks in quick order.  These are the sort of things where SGMLParser
really shines --- it's worth learning how to use it well.


If you run into problems, please feel free to email the Tutor list again,
and we can talk about SGMLParser in more depth.  Good luck!


From shalehperry at comcast.net  Fri Aug  8 17:29:52 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Fri Aug  8 19:30:28 2003
Subject: [Tutor] What happened to the Subject line?
In-Reply-To: <JNELICAENPFFBHHOHOKMOEGECMAA.harrisonfthomasjr@comcast.net>
References: <JNELICAENPFFBHHOHOKMOEGECMAA.harrisonfthomasjr@comcast.net>
Message-ID: <200308081629.52087.shalehperry@comcast.net>

On Friday 08 August 2003 13:13, Harrison Thomas wrote:
> Earlier this week the subject line stopped listing the number of messages.
> I use this to prioritize my reading of the list. Could we have it
> reinstated?
>

eh? my subjects have always been:

'[Tutor] some subject'


From jeff at ccvcorp.com  Fri Aug  8 17:37:06 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Aug  8 19:36:23 2003
Subject: [Tutor] What happened to the Subject line?
References: <JNELICAENPFFBHHOHOKMOEGECMAA.harrisonfthomasjr@comcast.net>
	<200308081629.52087.shalehperry@comcast.net>
Message-ID: <3F343422.8090105@ccvcorp.com>

Sean 'Shaleh' Perry wrote:

>On Friday 08 August 2003 13:13, Harrison Thomas wrote:
>  
>
>>Earlier this week the subject line stopped listing the number of messages.
>>I use this to prioritize my reading of the list. Could we have it
>>reinstated?
>>
>>    
>>
>
>eh? my subjects have always been:
>
>'[Tutor] some subject'
>  
>

I believe that the O.P. is referring to the digest format.  Other 
mailing lists that I read in digest form have stopped mentioning the 
number of messages in the subject, so I'm presuming that the same change 
happened here.

Jeff Shannon
Technician/Programmer
Credit International



From idiot1 at netzero.net  Fri Aug  8 20:49:57 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug  8 19:50:03 2003
Subject: [Tutor] wiki madness
In-Reply-To: <200308072331.56143.shalehperry@comcast.net>
References: <3F331955.7050805@netzero.net>
	<200308072331.56143.shalehperry@comcast.net>
Message-ID: <3F343725.5030003@netzero.net>



Sean 'Shaleh' Perry wrote:

> On Thursday 07 August 2003 20:30, Kirk Bailey wrote:
> 
>>Improving. Wrong,but better.
>>
> 
> 
> comments:
> 
> * no need to define caps, just use string.ascii_uppercase (and lowercase is 
> there too)
> 
> * why not define ishyperlink() using string.startswith()?
> or perhaps something from the urllib module?
>
1. nosuchfunction listed in the string module docs. Please advise.
2. must study on urllib module before commenting further.

> * wordsplit() doesn't actually split, more like strips.  You could write that 
> function as:
> 
> for char in word:
>     if char not in punctuation:
>         newword += char # or 1.5 style newword = newword + char
>     else:
>         extras = extras + char
>     return words, extras
> 
> * style comment.  I like to use the formatting operator instead of lots of 
> string math.
> 
> link = '<a href="%s">%s</a>' % (word, word) # instead of
> link = '<a href="' + word + '">' + word + '</a>'
> 
> while discussing style, this is python, feel free to use some whitespace.  
> Your code reads like a bourne again shell coder.
> 
MY GAWHD! :-)

> * parseline() is begging for a list and a loop.  Also, you are not parsing the 
> line.  parsing is breaking down into tokens and performing actions with the 
> tokens.

Seems like a good idea. take current material and inclose in a loop. Turn line 
into a list and walk the list with the parser.
> 
> * marking main() with the python idiom of:
> 
> if __name__ == '__main__':
>    # code
> 
> would be a good best practice to follow.  Also lets you load any of your 
> python apps as modules for other python apps.
> 
> Sorry, did not run it to help you debug it.  Just wanted to pass on some style 
> ideas for the other readers.
>
It runs. Works ALMOST right. ALMOST. if any punctuation is immediately following 
the word, it tends to get included, and ought not. Must study on it further to 
see what must change. Thanks for the comentary and advice.

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

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From dyoo at hkn.eecs.berkeley.edu  Fri Aug  8 18:09:27 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug  8 20:09:38 2003
Subject: [Tutor] What happened to the Subject line?   [Upgraded Mailman
	software]
In-Reply-To: <3F343422.8090105@ccvcorp.com>
Message-ID: <Pine.LNX.4.44.0308081659460.29424-100000@hkn.eecs.berkeley.edu>



On Fri, 8 Aug 2003, Jeff Shannon wrote:

> I believe that the O.P. is referring to the digest format.  Other
> mailing lists that I read in digest form have stopped mentioning the
> number of messages in the subject, so I'm presuming that the same change
> happened here.


Hi Harrison,


Yes, we've just updated our software here to use Mailman 2.1.2.  After the
upgrade, the subject line format of the digests have changed slightly.  I
feel slightly incompetent today: I haven't been able to figure out yet how
to configure things so that it redisplays the message count in each
digest.  My apologies!


I'll email the mailman folks later tonight to see if the feature was
removed on accident, and if so, if it's a good idea to bring it back.


Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Fri Aug  8 18:14:47 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug  8 20:14:56 2003
Subject: [Tutor] (no subject)
In-Reply-To: <73.33aef175.2c63aa8a@aol.com>
Message-ID: <Pine.LNX.4.44.0308081710070.29424-100000@hkn.eecs.berkeley.edu>



On Thu, 7 Aug 2003 Niurkav1@aol.com wrote:

> How do I use Python on Linux? I dont know if I even have the source
> code

Hi Niurkav1,


Welcome aboard!  Let's do a quick check to see if Python is already
installed on your Linux system.  Try:

    $ which python

at your command prompt line, and tell us how your system responds to this.


If you have Python installed, then you're all set!  If you're running a
Red Hat-based system, for example, since it comes installed by default,
you shouldn't need to do anything else to install Python.

If not, you may need to do a little more work, but it's not too difficult:
most Python distributions comes with a package-management system to ease
installation difficulties.


If you're trying to learn how to use Python, you may want to look at the
Beginners Guide to Python:

    http://python.org/topics/learn


Talk to you later!


From jeff at ccvcorp.com  Fri Aug  8 18:30:31 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Aug  8 20:30:15 2003
Subject: [Tutor] wiki madness
References: <3F331955.7050805@netzero.net>	<200308072331.56143.shalehperry@comcast.net>
	<3F343725.5030003@netzero.net>
Message-ID: <3F3440A7.1000403@ccvcorp.com>

Kirk Bailey wrote:

>> * no need to define caps, just use string.ascii_uppercase (and 
>> lowercase is there too)
>>
> 1. nosuchfunction listed in the string module docs. Please advise.


 >>> import string
 >>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
 >>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 >>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
 >>>

They're data (strings), not functions, so they'd probably be listed in a 
different part of the docs.

Jeff Shannon
Technician/Programmer
Credit International



From carroll at tjc.com  Fri Aug  8 20:48:28 2003
From: carroll at tjc.com (Terry Carroll)
Date: Fri Aug  8 22:48:34 2003
Subject: [Tutor] (no subject)
In-Reply-To: <Pine.LNX.4.44.0308081710070.29424-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0308081944500.32411-100000@mauve.rahul.net>

On Fri, 8 Aug 2003, Danny Yoo wrote:

> Welcome aboard!  Let's do a quick check to see if Python is already
> installed on your Linux system.  Try:
> 
>     $ which python
> 
> at your command prompt line, and tell us how your system responds to this.
> 
> If you have Python installed, then you're all set!  If you're running a
> Red Hat-based system, for example, since it comes installed by default,
> you shouldn't need to do anything else to install Python.

I'd also add a tip I picked up here; some Linuxes (Red Hat?) depend on
Python 1.5, so "python" may give you the old Python 1.5:

  % python
  Python 1.5.2 (#1, Jan 31 2003, 11:01:49)  [GCC 2.96 20000731 (Red 
  Hat Linux 7.22 on linux-i386
  Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
  >>>

Many of these sites install a more current version of Python as "python2":

  % python2
  Python 2.1.1 (#1, Feb 11 2003, 14:49:19)
  [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-108.7.2)] on linux2
  Type "copyright", "credits" or "license" for more information.
  >>>


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From shalehperry at comcast.net  Fri Aug  8 22:03:25 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Sat Aug  9 00:04:00 2003
Subject: [Tutor] wiki madness
In-Reply-To: <3F3440A7.1000403@ccvcorp.com>
References: <3F331955.7050805@netzero.net> <3F343725.5030003@netzero.net>
	<3F3440A7.1000403@ccvcorp.com>
Message-ID: <200308082103.25397.shalehperry@comcast.net>

On Friday 08 August 2003 17:30, Jeff Shannon wrote:
> Kirk Bailey wrote:
> >> * no need to define caps, just use string.ascii_uppercase (and
> >> lowercase is there too)
> >
> > 1. nosuchfunction listed in the string module docs. Please advise.
> >
>  >>> import string
>  >>> string.ascii_lowercase
>
> 'abcdefghijklmnopqrstuvwxyz'
>
> They're data (strings), not functions, so they'd probably be listed in a
> different part of the docs.
>

he's referring to startswith().  This is a method of strings and was added in 
the 2.x series. so you have:

url = 'ftp://foo.com/'
if url.startswith('http://'):
   # must be http
elif url.startswith('ftp://'):
   # must be ftp

you can mimic this with slicing.

if url[:6] == 'ftp://':
  # must be ftp


From mwagman at charter.net  Sat Aug  9 05:36:37 2003
From: mwagman at charter.net (Mike Wagman)
Date: Sat Aug  9 00:36:38 2003
Subject: [Tutor] Creating Folders on Desktop
Message-ID: <1060403922.2440.1.camel@24-159-241-21.jvl.wi.charter.com>

I find myself writing my own installer for a python program I have
written. Is there a way under windows to add a link to a folder to the
desktop using python code.

 Thanks
 Mike


From RASTM2 at aol.com  Sat Aug  9 03:15:47 2003
From: RASTM2 at aol.com (RASTM2@aol.com)
Date: Sat Aug  9 02:15:55 2003
Subject: [Tutor] Re: Tutor Digest, Vol 1, Issue 2646
Message-ID: <1ca.ef7a410.2c65eb93@aol.com>


Johnathan H said,

> Can anyone help explain them to me?? 
> 
> This example gives the factorial of a number 
> 
> def fact(n):
>  r=1
>  while n >0:
>    r=r*n
>    n=n-1
>  return r 
> 
line code          # Literally spoken   
1)    def fact(n):         # define a function called fact and let me be
                         # able to set one of the variables called "n"
2)      r = 1         #  this variable "r" is set to 1 every time we call 
fact(n) into play   
                             
3)      while n>0: # so long as this statement is true, "n greater than 0" ,
                           # do the indented lines next, otherwise pass the 
indented lines 
4)          r=r*n   # make my new "r" value equal to my old "r" value times 
                             #the value of "n", then
5)          n=n-1  # make my new "n" value equal to my old "n" value  minus 1
                          # then check the while statement again since this 
is the last 
                          # indented line of the while block, 
                          # if it's still true then do this block again
    
6)       return r      # we reach this statement when n is no longer greater 
than 0 
                         # n must be equal or less than 0
                     # so the value that is currently in r gets "return"ed 
                         # in this case, since you are in the interpreter 
window, 
                         # this will print the value of r after the function 
call fact(n)
>>> fact(5)
120

which is 5*4*3*2*1 = 120

If we call fact(5), then the first time thru the while loop r = 1 and n = 5
since n(5) is greater than 0, we get to go to line 4) 
this is where r picks up it's first new value. r = r * n is really 5 = 1 * 5
But you say how can r have two values? This is not the math I learned in 
school!
This statement is really the result of a great short cut for convienience.
It stems from something like,
c = b + a
b = c 
...but please don't think like this!
r = r * n will make so much sense to you after a while that I ashamed to show 
you
that last bit. 
You should try to follow the fact(n) code all the way through, now.
This will give you great insite as to how the power(x,y=2) works.
What I will say about that one is that you can call it lots of ways.
Try power(2), then power(2,3), then power(2,4).... and so on for a hint.
The "y=2" part is a default value for "y". This means that if you don't give 
the
function a "y" value it will always use a 2. 


Good Luck. Johnathan
I hope you enjoy programming, Python, and the good folks of the Tutor list.
Ray St. Marie
Rastm2@<removethistoreachme>users.sourceforge.net 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030809/1b5a307c/attachment.htm
From alan.gauld at blueyonder.co.uk  Sat Aug  9 10:37:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Aug  9 04:36:47 2003
Subject: [Tutor] What happened to the Subject line?
References: <JNELICAENPFFBHHOHOKMOEGECMAA.harrisonfthomasjr@comcast.net>
	<200308081629.52087.shalehperry@comcast.net>
Message-ID: <010401c35e51$7a22aa80$6401a8c0@xp>


> On Friday 08 August 2003 13:13, Harrison Thomas wrote:
> > Earlier this week the subject line stopped listing the number of
messages.
> > I use this to prioritize my reading of the list. Could we have it
> > reinstated?
> >
>
> eh? my subjects have always been:
>
> '[Tutor] some subject'

He's talking about the tutor digest Sean. It used to say

'Tutor Digest, Vol 1, Issue 1234, 13 messages'

I think the message count dissapeared at the same time
the "Issue Number" appeared but maybe I just never
noticed the Issue nuimber before...

Anyway, I agree with Harison, it was useful and it
would be good to get it back!

Alan G.



From alex at gabuzomeu.net  Sat Aug  9 14:08:52 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Sat Aug  9 07:08:54 2003
Subject: [Tutor] re question
In-Reply-To: <3F340540.6060106@pobox.com>
References: <20030808100924.C16066-100000@localhost.name>	<3F33EBC2.5020405@ccvcorp.com>
	<3F340540.6060106@pobox.com>
Message-ID: <3F34D644.80403@gabuzomeu.net>

Hello,


Jonathan Hayward wrote:

> I looked through the library docs on this, and tried to do it with 
> re's because figuring out how to use HTMLParser looked like more work 
> than using re's -- 3 hours' documentation search to avoid one hour of 
> reinventing the wheel. 

Here is an example I wrote yesterday night to test the HTMLParser 
module. (This module seems to have been added in Python 2.2. Now we have 
two parsers for HTML code: "HTMLParser.HTMLParser" and 
"htmllib.HTMLParser".)

###
from HTMLParser import HTMLParser

class CustomParser(HTMLParser):
    def __init__(self):
        self.inStrong = False
        self.payload = []
        HTMLParser.__init__(self)

    def parse(self, text):
        self.reset()
        self.feed(text)

    def handle_starttag(self, tag, attr):
        if tag == "strong":
            self.inStrong = True

    def handle_endtag(self, tag):
        if tag == "strong":
            self.inStrong = False

    def handle_data(self, data):
        if self.inStrong:
            self.payload.append(data)

if __name__ == "__main__":
    s = """text text <strong>this is strong</strong> text <strong>this 
is strong too</strong>"""
    p = CustomParser()
    p.parse(s)
    print p.payload
###


Cheers.

Alexandre





From jonathan.hayward at pobox.com  Sat Aug  9 17:58:25 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug  9 11:58:29 2003
Subject: [Tutor] HTMLParser clarification: Thanks
Message-ID: <3F351A21.6070808@pobox.com>

Danny, Alexandre--thanks to your clarification, I now have a clear 
concept that I didn't get from the library docs.

Looking forward to working from your replies,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From idiot1 at netzero.net  Sat Aug  9 17:07:40 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug  9 16:07:58 2003
Subject: [Tutor] wiki madness
In-Reply-To: <3F3440A7.1000403@ccvcorp.com>
References: <3F331955.7050805@netzero.net>	<200308072331.56143.shalehperry@comcast.net>	<3F343725.5030003@netzero.net>
	<3F3440A7.1000403@ccvcorp.com>
Message-ID: <3F35548C.4080007@netzero.net>

in 1.6.2 string.lowercase and string.uppercase exist, but
not string.punctuation.

 >>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
 >>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 >>> string.punctuation
Traceback (innermost last):
   File "<stdin>", line 1, in ?
AttributeError: punctuation
 >>> string.punctuation
Traceback (innermost last):
   File "<stdin>", line 1, in ?
AttributeError: punctuation


Jeff Shannon wrote:

> Kirk Bailey wrote:
> 
>>> * no need to define caps, just use string.ascii_uppercase (and 
>>> lowercase is there too)
>>>
>> 1. nosuchfunction listed in the string module docs. Please advise.
> 
> 
> 
>  >>> import string
>  >>> string.ascii_lowercase
> 'abcdefghijklmnopqrstuvwxyz'
>  >>> string.ascii_uppercase
> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>  >>> string.punctuation
> '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>  >>>
> 
> They're data (strings), not functions, so they'd probably be listed in a 
> different part of the docs.
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Sat Aug  9 17:23:06 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug  9 16:23:25 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus
Message-ID: <3F35582A.8070108@netzero.net>

It's SOOO close, and still SOOO screwed up.
code of the hour:
http://www.tinylist.org/wikinehesa.txt
what it results in:
http://www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage

Introducing the code to convert wikiwords and http links into live tags mulched 
it. Remove that, and it works- but no live tags to click. sigh...

And to compare the page, you can view the same page with another wikiengine on 
the site, same sourcefile.

http;//www.tinylist.org/cgi-bin/piki.py

BOTH engines default to 'FrontPage' if none is specified.



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Sat Aug  9 19:01:59 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug  9 18:01:59 2003
Subject: [Tutor] class blast
Message-ID: <3F356F57.6030501@netzero.net>

OK, I wrote a couple of things:
def isin(str,substr):                           # this thing is a general tool.
         return 1+string.find(str,substr)        # it returns a logical 1 or 0
#                                               # for use in an IF statement.
#
def ishyperlink(word):                          # uses previous to detect a 
hyperlink
         return isin(word,'http://')             # if the target is in the word,

isin can be used to provide this functionality in the definition of other words.

Going back to the object/class chaos, I recall that objects have attributes and 
methods that can be the same in instances of a class( in fact, normally they ARE 
the same, only the data differ). But the data is different.

What I was doing was in effect creating a parent class and an instance of the 
class, with required data for it's operation hard coded into the definition.

Am I drilling in a dry hole here? Was the sound of a candle flaring into light 
over my head?

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From glingl at aon.at  Sun Aug 10 01:43:00 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sat Aug  9 18:40:58 2003
Subject: [Tutor] Re: example help
References: <E19lDLC-000864-02@mail.python.org>
Message-ID: <3F3578F4.8030502@aon.at>

tutor-request@python.org schrieb:

>Today's Topics:
>
>   1. example help (arkamir@softhome.net)
>
>Hey im knew to programing and i got these examples out of the book THE QUICK 
>PYTHON GUIDE. I understand all the other examples but these 2 just stump me. 
>Can anyone help explain them to me?? 
>
>This example gives the factorial of a number 
>
>def fact(n):
>  r=1
>  while n >0:
>     r=r*n
>     n=n-1
>  return r 
>  
>
....

Hi arkamir!

I'd like to show you how you can find for yourself out HOW a program
works. (You'll run into similar situations probably rather often  ... ;-) )

1. Start IDLE
2. Put your fact - function in a python-source file and run it.
3. Now you can calculate for example
 >>> fact(4)
24
 >>>
4. Keep Editor-Window with the fact-source open.
5. Click Menu-Entry Debug-Debugger
- the Debug Control Window appears
- Click check-boxes  Locals and Source (if not already selected)
6. Go back to the Python-Shell-window. Ther now is written:
[DEBUG ON]
 >>>
7. Enter now fact(4) again and type <Enter>
The action of the debugger starts.
Now you should proceed using only the Step-Button. After 2 Clicks
def fact(n):
in the source window should be highlighted and in the lower "locals"-section
of the debugger window you can observe the value of n, namely 4.
 From now on you can execute fact(4) Step by Step.
After two more Steps the statement r =1 will be executed and the actual 
value
of r will be displayed in the "Locals"-section (namely 1).
Proceed Step ba Step and observe the execution of the function line by line
and the corresponding changes of the values of the local variables.
8. Eventually (if the condition n==0 gets True) the statement
    return r
has to be executed. At this moment r has the value 24.
In order not to step into the4 sourcecode of IDLE itself it's wise to Click
Go which finishes the execution of writing fact(4) to the IDLE shell.
24 appears there.

If you like to learn about the execution of functions this way, try it 
our with
your power function and with different arguments.

Regards, Gregor





From idiot1 at netzero.net  Sat Aug  9 19:43:34 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug  9 18:43:33 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus
In-Reply-To: <3F35582A.8070108@netzero.net>
References: <3F35582A.8070108@netzero.net>
Message-ID: <3F357916.1040703@netzero.net>

Well, it's improved. Not right, but better.

Now you get layout ok, and it is still converting words into links or into 
wikiwords. USUALLY they are right. It is throwing some noise in the process I 
cannot understand. This puzzles me.

here are the links.
sourcecode:
http://www.tinylist.org/wikinehesa.txt

It's operational output:
http://www.tinylist.org/cgi-bin/wikinehesa.py

ANYONE, please take a look and tell me when to shoot this thing.
And where. WHERE is of particular intrest, SOMETHING here DESPERATELY needs a 
bullet.


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From clickron at webtv.net  Sat Aug  9 23:49:55 2003
From: clickron at webtv.net (Ron A)
Date: Sat Aug  9 22:49:59 2003
Subject: [Tutor] using debug
Message-ID: <29740-3F35B2D3-8325@storefull-2131.public.lawson.webtv.net>

Is there anywhere that tells how to use debug. I clicked on it, but I
don't have any idea how to use it. I have python 2.2 and windows 98.

Ron A


From python at rcn.com  Sun Aug 10 00:51:32 2003
From: python at rcn.com (Raymond Hettinger)
Date: Sat Aug  9 23:55:32 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus
References: <3F35582A.8070108@netzero.net> <3F357916.1040703@netzero.net>
Message-ID: <004d01c35ef2$b095a6c0$e841fea9@oemcomputer>


----- Original Message ----- 
From: "Kirk Bailey" <idiot1@netzero.net>
Cc: <tutor@python.org>
Sent: Saturday, August 09, 2003 6:43 PM
Subject: Re: [Tutor] wiki madness grows one you like a brain fungus



> Now you get layout ok, and it is still converting words into links or into 
> wikiwords. USUALLY they are right. It is throwing some noise in the process I 
> cannot understand. This puzzles me.
> 
> here are the links.
> sourcecode:
> http://www.tinylist.org/wikinehesa.txt
 . . .
> ANYONE, please take a look and tell me when to shoot this thing.
> And where. WHERE is of particular intrest, SOMETHING here DESPERATELY needs a 
> bullet.

Here's a compact, faster version of iswikiword():

    import re
    wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search
    def iswikiword(word, wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search):
        return wikiword(word) is not None


For Py2.3, the "in" keyword works just like your isin() function:

    if 'http://' in word: 

In wordsplit(), there is a bug -- you meant to return (newword, extras)
instead of (word, extras).  Also, building the strings through
character appends is very slow -- use str.join instead.  
Also, the search runs faster if "punctuation" is kept in a dictionary.

Overall, the code is fairly compact and nice.
Considering using docstrings instead of prolific comments on every line.
The code will look *much* more beautiful.


Raymond Hettinger




> 
> 
> -- 
> 
> end
> 
> Cheers!
>          Kirk D Bailey



#################################################################
#################################################################
#################################################################
#####
#####
#####
#################################################################
#################################################################
#################################################################

From dyoo at hkn.eecs.berkeley.edu  Sun Aug 10 03:53:26 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 10 05:53:32 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus  [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <004d01c35ef2$b095a6c0$e841fea9@oemcomputer>
Message-ID: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>


> Here's a compact, faster version of iswikiword():
>
>     import re
>     wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search
>     def iswikiword(word, wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search):
>         return wikiword(word) is not None

Hi Raymond and Kirk,


The regular expression is too lenient: the second word needs to be at
least two characters long.  For example,

    TeX

isn't considered a WikiWord, but your regular expression

    [A-Z][^A-Z]+[A-Z]

will match it.

There's one other problem: we need to introduce "anchors" that guarantee
that we won't try to hunt for WikiWords within our word.  That is, we
definitely want to avoid matching:

    thisIsAnEmbeddedsentence

But this is easy to fix: for our real regular expression, we can use '^'
and '$' to mark the beginning and ending of our pattern.  Alternatively,
we can use the '\b' word-break metapattern.


I wrote a rambling post a while back:

    http://mail.python.org/pipermail/tutor/2003-August/024579.html

where, at the end, I had calculated an alternative regular expression:

    [A-Z][a-z]+
    [A-Z][a-z]
    ([A-Z][a-z] | [a-z])*

If we look at it in a twisted way, it even makes a kind of sense.  But now
that I think about it more, there's a conceptually much simpler one:

    ([A-Z][a-z]+){2,}

which concisely says "two or more capitalized words".  This just goes to
show that too much education threatens to obscure simple solutions.
*grin*


With this in mind, here is a modified iswikiword() that should be more
strict:

###
def iswikiword(word):
    regex = re.compile(r'''
                       \b                 ## beginning break,
                       ([A-Z][a-z]+){2,}  ## at least two capitalized
                                          ## words,
                       \b                 ## and an ending break.
                       ''', re.VERBOSE)
    return regex.match(word)
###



Let's see how it works:

###
>>> iswikiword('TeX')
>>> iswikiword('WikiWord')
<_sre.SRE_Match object at 0x2028e0>
>>> iswikiword('WikiWordS')
>>> iswikiword('thisIsEmbedded?')
>>>
###



Kirk, your main processing loop:

###
for rawline in page:
    line = string.split(rawline,' ')
    ...
    for word in line:
        if iswikiword(word):
            ...
###

is doing too much work.  It's possible to do all the substitutions at once
by using re.sub(), the substitution function.  Here's a concrete example:


###
>>> wiki_regex = re.compile(r'\b([A-Z][a-z]+){2,}\b')
>>> def processWikiMatch(match):
...     '''Given a match object of a WikiWord, returns a link to that
...        WikiWord.'''
...     return makewikilink(match.group(0))
...
>>> def makewikilink(word):
...     '''proxy function; replace this with real function'''
...     return '<a href="">%s</a>' % word
...
>>> result = wiki_regex.sub(processWikiMatch,
...                         '''
... This is a test of feeding a WikiWorded sentence
... into a RegularExpression, using a
... SubstitutionFunction.  Cool, huh?''')
>>> print result

This is a test of feeding a <a href="">WikiWorded</a> sentence
into a <a href="">RegularExpression</a>, using a
<a href="">SubstitutionFunction</a>.  Cool, huh?
###


re.sub() here can optionally taking a "subsitution" function, rather than
just a simple string!  This is something that isn't as well known as it
deserves to be.


Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 10 04:13:31 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 10 06:13:34 2003
Subject: [Tutor] using debug
In-Reply-To: <29740-3F35B2D3-8325@storefull-2131.public.lawson.webtv.net>
Message-ID: <Pine.LNX.4.44.0308100305470.2703-100000@hkn.eecs.berkeley.edu>



On Sat, 9 Aug 2003, Ron A wrote:

> Is there anywhere that tells how to use debug. I clicked on it, but I
> don't have any idea how to use it. I have python 2.2 and windows 98.

Hi Ron,

Please forgive me for the silly statement that follows: I'm not quite sure
I understand what you mean when you're saying "debug".  I usually use it
as a verb, but you're definitely using it as a noun, that is, something
that can be clicked and executed.  Hmmm...


Are you talking about DOS's DEBUG.EXE utility?  If so, that's definitely
not a part of Python.  DEBUG.EXE is a low-level utility that can be used
to do hex editing, but I don't believe it's really used much by casual
programmers these days.


Can you clarify a little more what you're trying to do?  Are you trying to
learn Python, or are you trying to debug a program that you've written?


Best of wishes!


From magnus at thinkware.se  Sun Aug 10 14:25:25 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Aug 10 07:18:09 2003
Subject: [Tutor] Graphical object browser?
In-Reply-To: <Pine.LNX.4.44.0308051840520.28264-100000@violet.rahul.net>
Message-ID: <5.2.1.1.0.20030810132308.020e8e28@www.thinkware.se>

At 18:45 2003-08-05 -0700, Terry Carroll wrote:
>I'm wondering if anyone can recommend any graphical way to browse a Python
>object.  I've found a couple but haven't tried then yet; I figured I'd ask
>for recommendations first, just in case the install might  screw something
>up.

You could have a look at PyCrust! It's included in the
wxPython GUI toolkit. See www.wxpython.org


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From clickron at webtv.net  Sun Aug 10 10:41:33 2003
From: clickron at webtv.net (Ron A)
Date: Sun Aug 10 09:41:38 2003
Subject: [Tutor] Re: using debug
Message-ID: <2671-3F364B8D-218@storefull-2135.public.lawson.webtv.net>

In IDLE there's

-- file  edit  debug  windows  help --

That's the debug I meant. I'm a very casual user, and it's probably not
for me.
I thought it might be something simple that would help debug a program
if I was having a problem.

Ron A


From missive at hotmail.com  Sun Aug 10 15:08:22 2003
From: missive at hotmail.com (Lee Harr)
Date: Sun Aug 10 10:08:57 2003
Subject: [Tutor] Re: using debug
Message-ID: <BAY2-F105htHaRYsO1j000179af@hotmail.com>

>I thought it might be something simple that would help debug a program
>if I was having a problem.
>


I tend to use the "insert print statements around the areas that are giving 
me
problems" style of debugging, but some people prefer the debugger.  You
should try it and see if it works for you.

Here is a quick start:

start IDLE
click File -> New Window
enter a simple program to test the debugger...  let's use this:

# simple.py
for x in range(10):
    print x
    z = 5 * x
    print z
# end simple.py

save the program
click Debug -> Debugger
click Run -> Run Module

To go through your program one statement at a time...
click Step

Now you can follow along in the Debug Control window as your
program runs. You may also want to choose the Source checkbox
so that the current line will be highlighted in the program source
window.

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE* 
http://join.msn.com/?page=features/virus


From idiot1 at netzero.net  Sun Aug 10 12:58:51 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 10 11:58:56 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus
In-Reply-To: <004d01c35ef2$b095a6c0$e841fea9@oemcomputer>
References: <3F35582A.8070108@netzero.net> <3F357916.1040703@netzero.net>
	<004d01c35ef2$b095a6c0$e841fea9@oemcomputer>
Message-ID: <3F366BBB.2060000@netzero.net>



Raymond Hettinger wrote:
> ----- Original Message ----- 
> From: "Kirk Bailey" <idiot1@netzero.net>
> Cc: <tutor@python.org>
> Sent: Saturday, August 09, 2003 6:43 PM
> Subject: Re: [Tutor] wiki madness grows one you like a brain fungus
> 
> 
> 
> 
>>Now you get layout ok, and it is still converting words into links or into 
>>wikiwords. USUALLY they are right. It is throwing some noise in the process I 
>>cannot understand. This puzzles me.
>>
>>here are the links.
>>sourcecode:
>>http://www.tinylist.org/wikinehesa.txt
> 
>  . . .
> 
>>ANYONE, please take a look and tell me when to shoot this thing.
>>And where. WHERE is of particular intrest, SOMETHING here DESPERATELY needs a 
>>bullet.
> 
> 
> Here's a compact, faster version of iswikiword():
> 
>     import re
>     wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search
>     def iswikiword(word, wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search):
>         return wikiword(word) is not None
> 
Know why I wrote it that way?

Cause I don' comprehend re worth a damn is why. Thanks for the words of power. I 
will try it.
> 
> For Py2.3, the "in" keyword works just like your isin() function:
> 
Hoa about 1.5.2? OLd server, alas. Due for upgrade REAL SOON NOW...

>     if 'http://' in word: 
> 
> In wordsplit(), there is a bug -- you meant to return (newword, extras)
> instead of (word, extras).  Also, building the strings through
> character appends is very slow -- use str.join instead.  
> Also, the search runs faster if "punctuation" is kept in a dictionary.
>
oops... wil fix soonest.

> Overall, the code is fairly compact and nice.
My blushes sir, thank you! :-)
> Considering using docstrings instead of prolific comments on every line.
> The code will look *much* more beautiful.
Hmmmm...

At least I comment generously. You want to look at the inspiration, piki?
Wonder guy, but Martin don' comment worth a tinker's scream in hell. That sort 
of programming is, um, mysterious. Rather, that sort of MINDSET is a mystery.

> 
> 
> Raymond Hettinger
> 
> 
> 
> 
> 
>>
>>-- 
>>
>>end
>>
>>Cheers!
>>         Kirk D Bailey
> 
> 
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Sun Aug 10 13:07:37 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 10 12:07:29 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus  [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F366DC9.5000905@netzero.net>

`Lo Dan, how's tricks?

Dan, when I get a grip on re and how it works, and the many tricks it can play, 
I will write stuff in it. My prob is it is as clear as mud to me.

I accept the suggestions and code. But understanding them is another matter.

mayhaps we should start a thread on 'INTRODUCTION TO RE'? Anyone intrested can 
hop in and participate in the confusion?

Danny Yoo wrote:

>>Here's a compact, faster version of iswikiword():
>>
>>    import re
>>    wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search
>>    def iswikiword(word, wikiword = re.compile('[A-Z][^A-Z]+[A-Z]').search):
>>        return wikiword(word) is not None
> 
> 
> Hi Raymond and Kirk,
> 
> 
> The regular expression is too lenient: the second word needs to be at
> least two characters long.  For example,
> 
>     TeX
> 
> isn't considered a WikiWord, but your regular expression
> 
>     [A-Z][^A-Z]+[A-Z]
> 
> will match it.
> 
> There's one other problem: we need to introduce "anchors" that guarantee
> that we won't try to hunt for WikiWords within our word.  That is, we
> definitely want to avoid matching:
> 
>     thisIsAnEmbeddedsentence
> 
> But this is easy to fix: for our real regular expression, we can use '^'
> and '$' to mark the beginning and ending of our pattern.  Alternatively,
> we can use the '\b' word-break metapattern.
> 
> 
> I wrote a rambling post a while back:
> 
>     http://mail.python.org/pipermail/tutor/2003-August/024579.html
> 
> where, at the end, I had calculated an alternative regular expression:
> 
>     [A-Z][a-z]+
>     [A-Z][a-z]
>     ([A-Z][a-z] | [a-z])*
> 
> If we look at it in a twisted way, it even makes a kind of sense.  But now
> that I think about it more, there's a conceptually much simpler one:
> 
>     ([A-Z][a-z]+){2,}
> 
> which concisely says "two or more capitalized words".  This just goes to
> show that too much education threatens to obscure simple solutions.
> *grin*
> 
> 
> With this in mind, here is a modified iswikiword() that should be more
> strict:
> 
> ###
> def iswikiword(word):
>     regex = re.compile(r'''
>                        \b                 ## beginning break,
>                        ([A-Z][a-z]+){2,}  ## at least two capitalized
>                                           ## words,
>                        \b                 ## and an ending break.
>                        ''', re.VERBOSE)
>     return regex.match(word)
> ###
> 
> 
> 
> Let's see how it works:
> 
> ###
> 
>>>>iswikiword('TeX')
>>>>iswikiword('WikiWord')
> 
> <_sre.SRE_Match object at 0x2028e0>
> 
>>>>iswikiword('WikiWordS')
>>>>iswikiword('thisIsEmbedded?')
>>>>
> 
> ###
> 
> 
> 
> Kirk, your main processing loop:
> 
> ###
> for rawline in page:
>     line = string.split(rawline,' ')
>     ...
>     for word in line:
>         if iswikiword(word):
>             ...
> ###
> 
> is doing too much work.  It's possible to do all the substitutions at once
> by using re.sub(), the substitution function.  Here's a concrete example:
> 
> 
> ###
> 
>>>>wiki_regex = re.compile(r'\b([A-Z][a-z]+){2,}\b')
>>>>def processWikiMatch(match):
> 
> ...     '''Given a match object of a WikiWord, returns a link to that
> ...        WikiWord.'''
> ...     return makewikilink(match.group(0))
> ...
> 
>>>>def makewikilink(word):
> 
> ...     '''proxy function; replace this with real function'''
> ...     return '<a href="">%s</a>' % word
> ...
> 
>>>>result = wiki_regex.sub(processWikiMatch,
> 
> ...                         '''
> ... This is a test of feeding a WikiWorded sentence
> ... into a RegularExpression, using a
> ... SubstitutionFunction.  Cool, huh?''')
> 
>>>>print result
> 
> 
> This is a test of feeding a <a href="">WikiWorded</a> sentence
> into a <a href="">RegularExpression</a>, using a
> <a href="">SubstitutionFunction</a>.  Cool, huh?
> ###
> 
> 
> re.sub() here can optionally taking a "subsitution" function, rather than
> just a simple string!  This is something that isn't as well known as it
> deserves to be.
> 
> 
> Hope this helps!
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From glingl at aon.at  Sun Aug 10 21:32:10 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sun Aug 10 14:30:08 2003
Subject: [Tutor] Re: using debug
References: <2671-3F364B8D-218@storefull-2135.public.lawson.webtv.net>
Message-ID: <3F368FAA.1090109@aon.at>

Ron A schrieb:

>In IDLE there's
>
>-- file  edit  debug  windows  help --
>  
>
Hi Ron!
Is it only incidentally, that you ask this, while I've posted
a detailed Step by Step description of getting started with
"debug" only few hours before your posting as a reply to
example help?

If so, you can find it here:
http://mail.python.org/pipermail/tutor/2003-August/024619.html
Try it out!

The original request, containing the code of fact and power was:

http://mail.python.org/pipermail/tutor/2003-August/024586.html

Regards, Gregor Lingl

>That's the debug I meant. I'm a very casual user, and it's probably not
>for me.
>I thought it might be something simple that would help debug a program
>if I was having a problem.
>
>Ron A
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>





From andi at buxach.de  Sun Aug 10 21:01:58 2003
From: andi at buxach.de (Andreas Zwinkau)
Date: Sun Aug 10 15:09:30 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus
In-Reply-To: <3F35582A.8070108@netzero.net>
References: <3F35582A.8070108@netzero.net>
Message-ID: <20030810200158.700e8056.andi@buxach.de>

Nice Wiki so far Kirk

I wrote a Wiki in PHP and i mostly used regular expressions for the
changes. This can be done easily in Python as well. If you want to check
out it, then visit my website or download the source directly from:
http://andi.dasstellenwirinsinternet.de/doc/tipiwiki.tar.gz

Then regular expressions could be used by copy&paste them, but i highly
recommend to learn re. They are so damn usefull.

mfg
Andreas Zwinkau
 | web: andi.dasstellenwirinsinternet.de
 | mail: andi@buxach.de
 | jabber: beza1e1@amessage.de

From magnus at thinkware.se  Mon Aug 11 00:34:48 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Aug 10 17:27:30 2003
Subject: [Tutor] Windows software reporting
In-Reply-To: <3F33FCD0.10402@unixremedies.com>
Message-ID: <5.2.1.1.0.20030810232546.05269188@www.thinkware.se>

At 14:41 2003-08-08 -0500, Justin Heath wrote:
>Any suggestions?

An extremely rough and simple approach is to list the
contents of the Windows program directory. Something
like:

   os.popen('dir %ProgramFiles%').readlines()

Whether you use a directory listing, or the registry, it's
not easy to make it sophisticated. As far as I can see, the
registry settings for software installs don't follow any
standards that will help you get application names and
versions in any consistent way.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From llazarre at yahoo.com  Sun Aug 10 15:31:18 2003
From: llazarre at yahoo.com (Levy Lazarre)
Date: Sun Aug 10 17:31:52 2003
Subject: [Tutor] Re: Using a dictionary to keep a count
Message-ID: <20030810213118.13208.qmail@web40404.mail.yahoo.com>

On Thu, 07 Aug 2003 sigurd@12move.de (Karl Pfl?sterer
) wrote:

>You could write the assignment in one line but I
>wouldn't recommend it
>(unless you like unreadable code):

>        d[script][address] = d.setdefault(script, 
>          {}).setdefault(address,0) + 1

Thanks, Karl. This worked fine. Now I understand how
to make a nested call to setdefault(). I was having
trouble with the syntax.
I did the equivalent in Perl:
d->{script}{address}++ ;

Again, thanks for the clarification.
Levy

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From magnus at thinkware.se  Mon Aug 11 00:49:58 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Aug 10 17:42:39 2003
Subject: [Tutor] Python versions on Linux
In-Reply-To: <Pine.LNX.4.44.0308081944500.32411-100000@mauve.rahul.net>
References: <Pine.LNX.4.44.0308081710070.29424-100000@hkn.eecs.berkeley.edu>
Message-ID: <5.2.1.1.0.20030810234617.0526e580@www.thinkware.se>

At 19:48 2003-08-08 -0700, Terry Carroll wrote:
>I'd also add a tip I picked up here; some Linuxes (Red Hat?) depend on
>Python 1.5, so "python" may give you the old Python 1.5:

If so, it's probably a good idea to upgrade your Linux distribution.
Last time I looked, the current versions of RedHat used Python 2.2.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From mwagman at charter.net  Mon Aug 11 00:59:30 2003
From: mwagman at charter.net (Mike Wagman)
Date: Sun Aug 10 19:59:33 2003
Subject: [Tutor] Py2exe help
Message-ID: <1060560111.2868.1.camel@24-159-241-21.jvl.wi.charter.com>

On a windows 98 system I need to modify the icon created using Py2exe.
The icon editors I am using are not reading the icon on the exe right.
Can anyone help me with that.


From mwagman at charter.net  Mon Aug 11 01:19:12 2003
From: mwagman at charter.net (Mike Wagman)
Date: Sun Aug 10 20:19:14 2003
Subject: [Tutor] py2exe icon issue
Message-ID: <1060561290.2446.0.camel@24-159-241-21.jvl.wi.charter.com>

Never mind I found the solution. Found an icon editor that could read a
Py2exe file.


From joanna9765 at yahoo.com  Sun Aug 10 18:35:32 2003
From: joanna9765 at yahoo.com (Joanna Ingrahm)
Date: Sun Aug 10 20:35:36 2003
Subject: [Tutor] using python to start and stop a program
Message-ID: <20030811003532.33693.qmail@web80703.mail.yahoo.com>

I have a program that I have to start using the win32
comand line. to stop it I use ctrl+c.
Now I tried to do that using python but still have
problems with it.
I can start the program and receive the pid of it
using: 

os.spawnl(os.P_NOWAIT,...

but then how can I use that information to terminate
the process again? I tried to write it in a file and
read it again but couldn't get it to work.
Appreciate any help!
Johanna

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From shalehperry at comcast.net  Sun Aug 10 19:06:43 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug 10 21:07:19 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F366DC9.5000905@netzero.net>
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>
	<3F366DC9.5000905@netzero.net>
Message-ID: <200308101806.43261.shalehperry@comcast.net>

On Sunday 10 August 2003 09:07, Kirk Bailey wrote:
> `Lo Dan, how's tricks?
>
> Dan, when I get a grip on re and how it works, and the many tricks it can
> play, I will write stuff in it. My prob is it is as clear as mud to me.
>
> I accept the suggestions and code. But understanding them is another
> matter.
>
> mayhaps we should start a thread on 'INTRODUCTION TO RE'? Anyone intrested
> can hop in and participate in the confusion?
>

don't walk, run to your local bookstore and purchase O'Reilly's outstanding 
book "Mastering Regular Expressions".  Take a week and give it a good read.  
Every day after that will be a more productive one. Honest.

Yes it focuses on languages other than Python.  But in the end everyone uses a 
variant of Perl5 regex.  Read for the way of thinking and the regex syntax, 
just ignore the icky $%@&*.


From clickron at webtv.net  Mon Aug 11 00:47:54 2003
From: clickron at webtv.net (Ron A)
Date: Sun Aug 10 23:47:59 2003
Subject: [Tutor] Re: using debug
Message-ID: <23271-3F3711EA-1809@storefull-2137.public.lawson.webtv.net>

Thanks for all the info. I'll give it a try tomorrow.

Ron A


From carroll at tjc.com  Sun Aug 10 23:04:17 2003
From: carroll at tjc.com (Terry Carroll)
Date: Mon Aug 11 01:04:22 2003
Subject: [Tutor] Python versions on Linux
In-Reply-To: <5.2.1.1.0.20030810234617.0526e580@www.thinkware.se>
Message-ID: <Pine.LNX.4.44.0308102203420.32411-100000@mauve.rahul.net>

On Sun, 10 Aug 2003, Magnus Lyck? wrote:

> At 19:48 2003-08-08 -0700, Terry Carroll wrote:
> >I'd also add a tip I picked up here; some Linuxes (Red Hat?) depend on
> >Python 1.5, so "python" may give you the old Python 1.5:
> 
> If so, it's probably a good idea to upgrade your Linux distribution.

Sure, if it's your Linux distribution.  In this case, it's my ISP's.

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From glingl at aon.at  Mon Aug 11 14:05:52 2003
From: glingl at aon.at (Gregor Lingl)
Date: Mon Aug 11 07:03:46 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>	<3F366DC9.5000905@netzero.net>
	<200308101806.43261.shalehperry@comcast.net>
Message-ID: <3F377890.1060903@aon.at>

Sean 'Shaleh' Perry schrieb:

>>mayhaps we should start a thread on 'INTRODUCTION TO RE'? Anyone intrested
>>can hop in and participate in the confusion?
>>
>>    
>>
>
>don't walk, run to your local bookstore and purchase O'Reilly's outstanding 
>book "Mastering Regular Expressions".  Take a week and give it a good read.  
>Every day after that will be a more productive one. Honest.
>
>Yes it focuses on languages other than Python. 
>

Hi!
Maybe Kirk should consider to buy David Mertz new "Textprocessing an 
Python". It focuses on
Python, has a large chapter on regular expressions and much material on 
other internet-related
issues of text processing. You can find the book's description, table of 
contents and more than
80 pages of a sample chapter in pdf-format here:

http://www.awprofessional.com/isapi/product_id~%7B5F1EAF18-40C5-4C46-9AC4-9CEF74BC3F0C%7D/catalog/product.asp

Hmmm, a bit long this url, it was the 3. entry of the results of a 
google-search for:
Addison Wesley David Mertz Text processing

Could very well meet the requirements of someone trying to reinvent and 
amend the wiki.
Regards, Gregor



> But in the end everyone uses a 
>variant of Perl5 regex.  Read for the way of thinking and the regex syntax, 
>just ignore the icky $%@&*.
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>





From idiot1 at netzero.net  Mon Aug 11 09:05:04 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 11 08:04:57 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F377890.1060903@aon.at>
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>	<3F366DC9.5000905@netzero.net>	<200308101806.43261.shalehperry@comcast.net>
	<3F377890.1060903@aon.at>
Message-ID: <3F378670.8010507@netzero.net>

Worth a look. As my car just had a corinary, I'm going to purchase 1 ONE 1 book 
only for now. The price Ford motor Company charges for one of those drop into 
the fuel tank pump/gauge sender modules is completely INSANE. Probably drive it 
home late this afternoon.

Gregor Lingl wrote:

> Sean 'Shaleh' Perry schrieb:
> 
>>> mayhaps we should start a thread on 'INTRODUCTION TO RE'? Anyone 
>>> intrested
>>> can hop in and participate in the confusion?
>>>
>>>   
>>
>>
>> don't walk, run to your local bookstore and purchase O'Reilly's 
>> outstanding book "Mastering Regular Expressions".  Take a week and 
>> give it a good read.  Every day after that will be a more productive 
>> one. Honest.
>>
>> Yes it focuses on languages other than Python.
> 
> 
> Hi!
> Maybe Kirk should consider to buy David Mertz new "Textprocessing an 
> Python". It focuses on
> Python, has a large chapter on regular expressions and much material on 
> other internet-related
> issues of text processing. You can find the book's description, table of 
> contents and more than
> 80 pages of a sample chapter in pdf-format here:
> 
> http://www.awprofessional.com/isapi/product_id~%7B5F1EAF18-40C5-4C46-9AC4-9CEF74BC3F0C%7D/catalog/product.asp 
> 
> 
> Hmmm, a bit long this url, it was the 3. entry of the results of a 
> google-search for:
> Addison Wesley David Mertz Text processing
> 
> Could very well meet the requirements of someone trying to reinvent and 
> amend the wiki.
> Regards, Gregor
> 
> 
> 
>> But in the end everyone uses a variant of Perl5 regex.  Read for the 
>> way of thinking and the regex syntax, just ignore the icky $%@&*.
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>  
>>
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From just4info at serrati.net  Mon Aug 11 15:39:23 2003
From: just4info at serrati.net (just4info)
Date: Mon Aug 11 08:37:23 2003
Subject: [Tutor] TypeError
Message-ID: <3F378E7B.8040402@serrati.net>

hi.

i?m programming in oo languages (java, ada) some years and now i 
experimenting with python.

general things are no problem, but oo is a litte bit tricky :-)

i?ve two files: dummy.py an call.py

in dummy.py there is a class Dummy -->

class Dummy:

     def call_me():
         x = "Hello"
         return x

     def call_me_2():
         return "Yes"

an call.py imports the class -->

import dummy

you = dummy.Dummy()

print "\n"
print you.call_me()
print "\n"
print you.call_me_2()
print "\n"

in my eyes it should be correct syntax, but ich got the following error:

Traceback (most recent call last):
   File 
"C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
line 301, in RunScript
     exec codeObject in __main__.__dict__
   File "C:\Dokumente und Einstellungen\suess\Desktop\call.py", line 6, in ?
     print you.call_me()
TypeError: call_me() takes no arguments (1 given)

i used pythonwin (activestate python 2.2).

what?s wrong?

thanks in advance

mats





From bgailer at alum.rpi.edu  Mon Aug 11 07:48:46 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon Aug 11 08:50:27 2003
Subject: [Tutor] TypeError
In-Reply-To: <3F378E7B.8040402@serrati.net>
Message-ID: <5.2.1.1.0.20030811063854.02bfe4a8@66.28.54.253>

At 02:39 PM 8/11/2003 +0200, just4info wrote:
>i?m programming in oo languages (java, ada) some years and now i 
>experimenting with python.
>general things are no problem, but oo is a litte bit tricky :-)
>
>i?ve two files: dummy.py an call.py
>
>in dummy.py there is a class Dummy -->
>
>class Dummy:
>
>     def call_me():
>         x = "Hello"
>         return x
>
>     def call_me_2():
>         return "Yes"
>
>an call.py imports the class -->
>
>import dummy
>
>you = dummy.Dummy()
>
>print "\n"
>print you.call_me()
>print "\n"
>print you.call_me_2()
>print "\n"
>
>in my eyes it should be correct syntax, but ich got the following error:
>
>Traceback (most recent call last):
>   File 
> "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
> line 301, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Dokumente und Einstellungen\suess\Desktop\call.py", line 6, in ?
>     print you.call_me()
>TypeError: call_me() takes no arguments (1 given)
>
>i used pythonwin (activestate python 2.2).

Instance methods (call_me, call_me_2) are called with the instance as the 
first parameter. Thus the method definition must provide a parameter to 
receive the instance. Change:
     def call_me():
to:
     def call_me(self):
and likewise change:
     def call_me_2():
to:
     def call_me_2(self):

self is not a keyword, it is just customary Pythonese to use "self". How 
might one take advantage of this? Consider:
class Dummy:
     def save(self, value):
         self.x = value
     def recall(self):
         return self.x
import dummy

you = dummy.Dummy()
you.save("Green Stamps")
you2 = dummy.Dummy()
you2.save("Time in a bottle")
print you.recall(),you2.recall()

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From clay at shirky.com  Mon Aug 11 11:36:33 2003
From: clay at shirky.com (Clay Shirky)
Date: Mon Aug 11 10:36:39 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F377890.1060903@aon.at>
Message-ID: <BB5D2231.BD08%clay@shirky.com>

> Maybe Kirk should consider to buy David Mertz new "Textprocessing an
> Python".

+1 this (instead of Mastering Regular Expressions.)

The problem with Friedl's book, and the culture of regexes in general, is
that it leads to applying regexes to problems better worked out with any
thing from splits() to formal parsers.

As jwz put it "A lot of people, when they have a problem, think 'I know,
I'll use regular expressions!' Now they have two problems."

-clay


From as1116522 at sapo.pt  Mon Aug 11 17:13:24 2003
From: as1116522 at sapo.pt (as1116522)
Date: Mon Aug 11 11:13:31 2003
Subject: [Tutor] Displaying characters
Message-ID: <1060614804.3f37b294cf856@webmail.sapo.pt>


Hi, is there any way to display portuguese characters 
like: "?", "?", "?" in windows command line? 

___________________________________________________________________

O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m!
Clique em: http://antivirus.sapo.pt


From clay at shirky.com  Mon Aug 11 12:19:26 2003
From: clay at shirky.com (Clay Shirky)
Date: Mon Aug 11 11:19:28 2003
Subject: [Tutor] Flow control question.
In-Reply-To: <3F377890.1060903@aon.at>
Message-ID: <BB5D2C3E.BD0E%clay@shirky.com>

As an exercise, I am writing a MAC address tester. It takes a collection of
possible MAC addresses, compares them to a test case, and outputs matches,
doesn't match, and errors for strings that cant be valid MAC addresses.

On these errors, I return with 0, then, in the "check addresses" loop, I try
to 'continue' if the return value is 0, but it isn't working.

The code is

def bad_address(address, error):
    print address, "not a valid MAC address:", error, "..."

def test_mac(mac):
    address_list = []
    elements = re.split('[\:\-\.]', mac)
    if len(elements) == 1:
        bad_address( mac, "No valid seperator...")
        return 0
    if len(elements) != 6:
        bad_address( mac, "Need 6 two-hex-digit numbers...")
        return 0
        
    for element in elements:
        num = long(element, 16)
        if num >= 256:
            bad_address(mac, "Numeric element above 256")
            return 0
        else:
            address_list.append(element)
            
    hex_num = "".join(address_list)
    return long(hex_num, 16)

    
for new_address in new_addresses:
    if new_address == 0: continue # I want to skip the next test
    if test_mac(new_address) == test_mac(orig_address):
        print new_address, "matches", orig_address
    else:
        print new_address, "doesn't match..."

And when I run it against a test list, every address that fails generates
two errors, both a bad_address() error and a "doesn't match" error from the
for loop below.

How can I make the for loop skip the second if test if the return is after a
bad_address() call?

-clay


From idiot1 at netzero.net  Mon Aug 11 13:17:26 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 11 12:17:30 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <BB5D2231.BD08%clay@shirky.com>
References: <BB5D2231.BD08%clay@shirky.com>
Message-ID: <3F37C196.6010107@netzero.net>

IN fact, I did indeed just place an order with amazon for 'Textprocessing in 
Python" as it is language specific, addresses re rather well according to opion 
and review, and also covers other non re aspects of mangling text in the 
language of choice.

With any luck, it will even contain some silly skits and jokes in the examples, 
although that's hoping for a bit much. As for dead parrots, all mine are alive, 
and one is shitting on my sholder right now.

Um, or is that SITTING?

nope... oh, well, it needed changing anyway. Let's go, tinybird...


Clay Shirky wrote:

>>Maybe Kirk should consider to buy David Mertz new "Textprocessing an
>>Python".
> 
> 
> +1 this (instead of Mastering Regular Expressions.)
> 
> The problem with Friedl's book, and the culture of regexes in general, is
> that it leads to applying regexes to problems better worked out with any
> thing from splits() to formal parsers.
> 
> As jwz put it "A lot of people, when they have a problem, think 'I know,
> I'll use regular expressions!' Now they have two problems."
> 
> -clay
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From james.mccarney at cgi.com  Mon Aug 11 13:16:44 2003
From: james.mccarney at cgi.com (James McCarney)
Date: Mon Aug 11 12:19:27 2003
Subject: [Tutor] Python 2.3 build and configuration issues (Tkinter problem)
In-Reply-To: <E19mASw-0001fz-01@mail.python.org>
Message-ID: <000001c36023$f53bba80$5681a60a@GMC203608>

Hi all,

Hope this is not OT; it is after all a Python question...

I snagged the 2.3 source and compiled it for Linux. My kernel and
compiler are rather old, but there were no troubles, except for the
Tkinter module. 

The error message tells me that the Python I am using cannot find Tk. I
have a much older version of Python (1.5.?), and the Tkinter module
works fine there. Have others experienced this trouble? Is it because I
need to upgrade to a higher version of Tk (however, I think I am running
higher than 8.1 right now.)

Any insights appreciated,
James Alexander McCarney, Consultant, CGI Group Inc.
James.McCarney@CGI.com
 
CONFIDENTIALITY NOTICE: Proprietary/Confidential Information belonging
to CGI Group Inc. and its affiliates may be contained in this message.
If you are not a recipient indicated or intended in this message (or
responsible for delivery of this message to such person), or you think
for any reason that this message may have been addressed to you in
error, you may not use or copy or deliver this message to anyone else.
In such case, you should destroy this message and are asked to notify
the sender by reply email.


From alex at gabuzomeu.net  Mon Aug 11 20:17:58 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Mon Aug 11 13:17:59 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F377890.1060903@aon.at>
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>	<3F366DC9.5000905@netzero.net>	<200308101806.43261.shalehperry@comcast.net>
	<3F377890.1060903@aon.at>
Message-ID: <3F37CFC6.2050405@gabuzomeu.net>



Gregor Lingl wrote:

> Maybe Kirk should consider to buy David Mertz new "Textprocessing an 
> Python". It focuses on
> Python, has a large chapter on regular expressions and much material 
> on other internet-related
> issues of text processing. You can find the book's description, table 
> of contents and more than
> 80 pages of a sample chapter in pdf-format here:
>
> http://www.awprofessional.com/isapi/product_id~%7B5F1EAF18-40C5-4C46-9AC4-9CEF74BC3F0C%7D/catalog/product.asp

The text of this book -- or large parts of it -- is also available in 
text format on the author's Web site:

    http://gnosis.cx/TPiP/


Cheers.

Alexandre




From amk at asti-usa.com  Mon Aug 11 15:17:35 2003
From: amk at asti-usa.com (A.M. Kuchling)
Date: Mon Aug 11 14:18:21 2003
Subject: [Tutor] Flow control question.
In-Reply-To: <BB5D2C3E.BD0E%clay@shirky.com>
References: <3F377890.1060903@aon.at> <BB5D2C3E.BD0E%clay@shirky.com>
Message-ID: <20030811181735.GD16765@vail.asti-usa.com>

On Mon, Aug 11, 2003 at 11:19:26AM -0400, Clay Shirky wrote:
> for new_address in new_addresses:
>     if new_address == 0: continue # I want to skip the next test
>     if test_mac(new_address) == test_mac(orig_address):
>         print new_address, "matches", orig_address
>     else:
>         print new_address, "doesn't match..."

I'm a bit confused; is some code not included in your post that sets
elements of the new_addresses list to 0?  It looks to me like
new_address is some string 'aa:bb:cc:...' and you want to continue if
test_mac() returns 0, so the loop would be:

for new_address in new_addresses:
    result = test_mac(new_address)
    if new_address == 0: 
         continue # I want to skip the next test
    if result == test_mac(orig_address):
        print new_address, "matches", orig_address
    else:
        print new_address, "doesn't match..."

If your original code is what you want, then perhaps the problem is
that new_address is being set to the string '0'; '0' looks just
like the number 0 if you print it, but won't compare as equal.  Try printing
repr(new_address), or type(new_address), to check this.

--amk                                            (www.amk.ca)
RICHARD: Deep malice makes too deep incision.
      -- _Richard II_, I, i

From jeff at ccvcorp.com  Mon Aug 11 12:34:35 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 11 14:39:05 2003
Subject: [Tutor] Flow control question.
References: <BB5D2C3E.BD0E%clay@shirky.com>
Message-ID: <3F37E1BB.2060207@ccvcorp.com>

Clay Shirky wrote:

>On these errors, I return with 0, then, in the "check addresses" loop, I try
>to 'continue' if the return value is 0, but it isn't working.
>
[...]

>for new_address in new_addresses:
>    if new_address == 0: continue # I want to skip the next test
>    if test_mac(new_address) == test_mac(orig_address):
>        print new_address, "matches", orig_address
>    else:
>        print new_address, "doesn't match..."
>

I'm not entirely certain what you're after, here.  Your description 
doesn't seem to match the code, and I'm not sure whether the confusion 
is yours or mine. ;)  Anyhow, as best as I can tell...

Your first if statement, above

    if new_address == 0: continue # I want to skip the next test


Simply tests to see if the address that was fed in is equal to zero. 
 Now, at this point, you haven't run test_mac() on it;  you're simply 
looking to see if the potential MAC address is equal to zero.  I'd 
expect that your potential address should be a string, and thus will 
never be equal to zero, so I'm not sure what the intent here is.  Did 
you mean to compare the result of test_mac(new_address), perhaps?

At any rate, there's a couple of ways to skip the second if statement 
depending on what happens here.  Probably the simplest is to move the 
second test a level in -- put it in the else clause of the first if 
statement.  Actually, since you're not doing anything if the first test 
is true, then you can just reverse the sense of that test and have that 
test control the second one --

    if new_address != 0:     # Not equal, instead of equal, no continue
        if test_mac(new_address) == test_mac(orig_address):
            print new_address, "matches", orig_address
        else:
            print new_address, "doesn't match..."


As a minor point, consider that, if new_address is indeed equal to zero, 
it evaluates to a boolean false all by itself, and if it's *not* equal 
to zero (or the empty string, or the empty list, or None), then it 
evaluates to true all by itself.  Thus, the line

    if new_address != 0:

is in practice equivalent to

    if new_address:

and that second form is the preferred one.   (Note, also, that all of 
this applies regardless of whether the intent was to test new_address 
itself, or the result of test_mac(new_address) -- it's the same 
principle either way.)

If you *did* intend for the first test to be against the result of 
test_mac(), then you might be better off running that function only once 
and saving the result --

for new_address in new_addresses:
    result = test_mac(new_address)
    if result:
        if result == test_mac(orig_address):
            print new_address, "matches", orig_address
        else:
            print new_address, "doesn't match..."

This avoids the duplicate effort of running test_mac(new_address) twice.

Jeff Shannon
Technician/Programmer
Credit International



From clay at shirky.com  Mon Aug 11 16:27:19 2003
From: clay at shirky.com (Clay Shirky)
Date: Mon Aug 11 15:27:29 2003
Subject: [Tutor] Flow control question.
In-Reply-To: <20030811181735.GD16765@vail.asti-usa.com>
Message-ID: <BB5D6657.BD3C%clay@shirky.com>

> I'm a bit confused;

No, I was confused.

> for new_address in new_addresses:
>   result = test_mac(new_address)
>   if new_address == 0:
>        continue # I want to skip the next test

/me slaps head

Thanks -- I forgot I didn't call test_mac until the equivalence test,
meaning there was no return value to test in the first place.

Many thanks.

-clay
 


From alan.gauld at blueyonder.co.uk  Mon Aug 11 21:43:56 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 11 15:43:43 2003
Subject: [Tutor] Re: using debug
References: <2671-3F364B8D-218@storefull-2135.public.lawson.webtv.net>
Message-ID: <002501c36040$e7658770$6401a8c0@xp>

> In IDLE there's
>
> -- file  edit  debug  windows  help --
>
> That's the debug I meant. I'm a very casual user, and it's probably
not
> for me.

Actually it probably is, but as you've discovered documents for
beginners are scarse. If its of any help my book(the paper version)
contains a chapter on debugging which has a section on using the
Python debugger pdb. Most of that applies to the IDLE debugger too.

Problem is you need a copy of my book - maybe your local library?

> I thought it might be something simple that would help debug a
program
> if I was having a problem.

Thats exactly what it does.
You can set a "Breakpoint" which forces the program to stop every time
it reaches that line. So if you set it on the first line inside a loop
the program will stop and you can examine your variable values etc.

There is a "Watch" window for making that easy...

Debuggers are wonderful tools which can become addictive. Thats
why my book recommends that you use them as a last resort after
plain print statements fail to work. Otherwise you can end up
relying on them for every little buglet. But for the hard ones
a debugger is invaluable...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Mon Aug 11 21:46:43 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 11 15:46:29 2003
Subject: [Tutor] Re: using debug
References: <BAY2-F105htHaRYsO1j000179af@hotmail.com>
Message-ID: <003001c36041$4a8ad8a0$6401a8c0@xp>

> To go through your program one statement at a time...
> click Step

Usally you want "Step Over" otherwise you wind up stepping through 
the source code for the Python library, which while educational, 
doesn't get your problem solved!!

Only use Step when you specifically want to step into a function 
you have written yourself, or you think may be faulty.

THe "Step Out of" button is useful too when you get it wrong and 
find yourself staring at strange code...

Alan G.

From alan.gauld at blueyonder.co.uk  Mon Aug 11 21:54:56 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 11 15:54:47 2003
Subject: [Tutor] Flow control question.
References: <BB5D2C3E.BD0E%clay@shirky.com>
Message-ID: <006101c36042$70a33cc0$6401a8c0@xp>

> And when I run it against a test list, every address that fails
generates
> two errors, both a bad_address() error and a "doesn't match" error
from the
> for loop below.
>
> How can I make the for loop skip the second if test if the return is
after a
> bad_address() call?

I'm not sure thats the ptroblem BUT you don't shjow where orig_address
is set.  If the tet for orig_address fails for any reason - not a
string,
or formatting say, the first if will fail and you will get the 'bad
address report... But without seing the oroig_address bit I can't say
more than that.

Alan G.


From holysmoke at amaltaas.biz  Tue Aug 12 03:29:27 2003
From: holysmoke at amaltaas.biz (Sukrit K Mehra)
Date: Mon Aug 11 16:56:50 2003
Subject: [Tutor] [Long]General Questions
Message-ID: <20030811205927.GA664@Joss>

Hi Pythoners,

I am new to programming and in need of some advice. 

Background:
I have a system adminstration background. I want to learn *programming*.
I just read "How to think like a computer scientist: Python".

Computer Science:
How do I go about learning the following, keeping in mind I have no exams to
pass, using python.
a Algorithms
b Data Structures

After these what else could be nearly as practically rewarding?

Engineering:
I want to be productive asap and I believe I need these python skills
- Threads
- Unix Sys Calls
- Reg Ex
- Network Programming
- Wxpython/ gtk-python
- CGI
- Web Clients 
- DataBase connectivity

What would a smallish project in which I could use most of these skills
(I thought of a mail client but it's boring and it's ... boring; I learn
faster when I am *NOT* writing programs that compute factorials of
numbers.)

Ulimate Goals:
- To learn to think in terms of OO/procedural paradigms as need be.
- Develop good *progamming* skill so as to pick up any resume building
language like Java, C, C++ Visual Basic, Php, whatever.

Projects:
I have been trying to learn programming in vain for a long time now. I
never get beneath the surface of it because I never find anything to do.
Can anyone recommend me to some project where I can apprentice? I should
head for sourceforge? That has never works! Finding a project isn't
easy, atleast it has been difficult for me. 

thanks for your time.

From godoy at metalab.unc.edu  Mon Aug 11 18:58:34 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Mon Aug 11 17:02:01 2003
Subject: [Tutor] Displaying characters
In-Reply-To: <1060614804.3f37b294cf856@webmail.sapo.pt> (as1116522@sapo.pt's
	message of "Mon, 11 Aug 2003 16:13:24 +0100 (WEST)")
References: <1060614804.3f37b294cf856@webmail.sapo.pt>
Message-ID: <m3fzk7x66d.fsf@ieee.org>

as1116522 <as1116522@sapo.pt> writes:

> Hi, is there any way to display portuguese characters 
> like: "?", "?", "?" in windows command line? 

I just print them and it works.

In Windows, Linux and FreeBSD. It is also true for wxPython
applications. 


Some silly phrases:

>>> print 'Ol?! Como est?o as coisas a? em Portugal?'
Ol?! Como est?o as coisas a? em Portugal?
>>> print 'Aqui no Brasil est?o muito frias. O inverno est? bem severo.'
Aqui no Brasil est?o muito frias. O inverno est? bem severo.
>>> print 'Espero que os exemplos tenham ajudado. Uma palavra com "?": ma??.'
Espero que os exemplos tenham ajudado. Uma palavra com "?": ma??.
>>>


See you, 
-- 
Godoy.     <godoy@metalab.unc.edu>

From idiot1 at netzero.net  Mon Aug 11 19:57:57 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 11 18:58:03 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F37CFC6.2050405@gabuzomeu.net>
References: <Pine.LNX.4.44.0308100212390.2703-100000@hkn.eecs.berkeley.edu>	<3F366DC9.5000905@netzero.net>	<200308101806.43261.shalehperry@comcast.net>	<3F377890.1060903@aon.at>
	<3F37CFC6.2050405@gabuzomeu.net>
Message-ID: <3F381F75.5080202@netzero.net>

Glad you told me AFTER I ordered it! :-) otherwise, I might have been tempted to 
NOT order it- and miss the parts he did NOT put on the web. But I will content 
myself to read it until the deadtrees version arrives.

Alexandre Ratti wrote:
> 
> 
> Gregor Lingl wrote:
> 
>> Maybe Kirk should consider to buy David Mertz new "Textprocessing an 
>> Python". It focuses on
>> Python, has a large chapter on regular expressions and much material 
>> on other internet-related
>> issues of text processing. You can find the book's description, table 
>> of contents and more than
>> 80 pages of a sample chapter in pdf-format here:
>>
>> http://www.awprofessional.com/isapi/product_id~%7B5F1EAF18-40C5-4C46-9AC4-9CEF74BC3F0C%7D/catalog/product.asp 
>>
> 
> 
> The text of this book -- or large parts of it -- is also available in 
> text format on the author's Web site:
> 
>    http://gnosis.cx/TPiP/
> 
> 
> Cheers.
> 
> Alexandre
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Mon Aug 11 20:34:15 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 11 19:34:21 2003
Subject: [Tutor] [Long]General Questions
In-Reply-To: <20030811205927.GA664@Joss>
References: <20030811205927.GA664@Joss>
Message-ID: <3F3827F7.3090306@netzero.net>

Ya know, I daresay writing this letter took a little brass; this gent has more 
experience and education than I do in the field, but he is intrested in 
programming basics, and I'm pretty basic sure enough... ;-)



1. Download and install IDLE from the site. You will be playing with
    it a lot from now on.

2. Bookmark the site's main documentation page. I predict you will
    be using it a lot while using python.

3. Try stuff. It's ok to mess up, be WRONG, have stuff blow up.

4. Take up reading eveything you can as a hobby.

5. Hang around this list a lot. :-)

Look at other people's works. SIMPLE things are less confusing. For instance, I 
learned about turning strings into numbers into strings so I could write a 
hitcounter for websites; now my sites use it for their counters. Simple, basic, 
but a useful skill more important programs will use later on.

Sukrit K Mehra wrote:

> Hi Pythoners,
> 
> I am new to programming and in need of some advice. 
> 
> Background:
> I have a system adminstration background. I want to learn *programming*.
> I just read "How to think like a computer scientist: Python".
>
A computer is a box that follows a plan. But you knew this, right?

A program is a plan. programs either control machines, or pure data. When they 
control machines, they do it by reading and writing data- and in between, they 
do intresting things with it. If you grok algebra and such, you have a beginning.

For instance, to calculate the content volume of a pipe.
You need the inside diameter of the pipe, the length, and the knowledge of the 
volume formula.

The formula is V=(pi*(R^2))*L

To actually do useful work, this needs to be surrounded with some stuff to GET 
the information from the user, and DELIVER the result.


#!/usr/bin/python
# The above line MUST point at the python interpeter in YOUR server!
pi='3.1415926'			# we need this later to crunch the numbers.
print				# print program header
print 'PIPEVOLUME v:1.0.0'
print				# prints a blank line to space things out.
print 'what is the length of the pipe in meters?', # comma supresses newline
length=input()
print 'what is the radiius of the pipe in meters?'
radius=input()
volume=((radius*radius)*pi)*length
print				# prints a blank line to seperate the answer
#				# to majke it easier to read the screen.
print 'The volume of the specified pipe is ',volume,' meters^3.'

this is in the flow of:

setup>prompt>input>crunch>output>terminate (implicit in the language)

which is a fairly good broad outline for many programs.

This is procedural programming, not object programming. I know what must be done 
to generate a valid answer, and build a process to set up the tools the program 
needs, and then interact with the user, crunch, and deliver the result.

I could have created a function, as:
def sqr(r):
	sq=r*r
	return sq
and then used it in another defined function:

def volume(r,l):
	volume=(sqr(r)*3.1415925)*l
	return volume
then the program would look like:

#!/usr/bin/python
# The above line MUST point at the python interpeter in YOUR server!
pi='3.1415926'			# we need this later to crunch the numbers.
def sqr(r):
	sq=r*r
	return sq
#
def volume(r,l):
	volume=(sqr(r)*3.1415925)*l
	return volume
#
print				# print program header
print 'PIPEVOLUME v:1.0.0'
print				# prints a blank line to space things out.
print 'what is the length of the pipe in meters?', # comma supresses newline
length=input()
print 'what is the radiius of the pipe in meters?'
radius=input()
#
print				# prints a blank line to seperate the answer
#				# to majke it easier to read the screen.
print 'The volume of the specified pipe is ',volume(radius,length),' meters^3.'
print
In effect, I just invented two entirely new commands in python, the applied 
them. In python, functions always end in (roundbrackets) even if the function 
does not need any arguements pased to it.

return simply means ou are telling the function to say something, and what it is 
to say.

Suppose you had this function:
def hello():
	return 'Hello world!'

 >> >hello()
'Hello world!'
 >> >print hello()
Heello world!
 >> >

Dig? Of course, it can be A LOT more complex than this. your new function can be 
a complete subprogram in itself, in effect a SUBROUTINE, and it can invoke other 
such things in it's definition, as long as they exist already when your function 
executes. YOU CANNOT INVOKE SOMETHING THAT DOES NOT EXIST YET.



> Computer Science:
> How do I go about learning the following, keeping in mind I have no exams to
> pass, using python.
> a Algorithms
> b Data Structures
> 
> After these what else could be nearly as practically rewarding?
> 
> Engineering:
> I want to be productive asap and I believe I need these python skills
> - Threads
> - Unix Sys Calls
actually, try the os module for the details.
> - Reg Ex
> - Network Programming
Hmmm, LAN stuff? WAN? TCP/IP stack stuff?
> - Wxpython/ gtk-python
> - CGI
When you grok cgi, you will de delighted with how wonderful the cgi module is to 
use. Try creating a simple form of some sort, and record the input in a text 
file for later examination. I did this some time back when I wrote a weblog.
> - Web Clients 
Um, what sort?
> - DataBase connectivity
bd hash tables, freeform databases, what?
> 
> What would a smallish project in which I could use most of these skills
> (I thought of a mail client but it's boring and it's ... boring; I learn
> faster when I am *NOT* writing programs that compute factorials of
> numbers.)
Well, what is NOT boring? I wrote a Mail List Manager suite, (think majordomo 
and you're at least in the right province) but you told me email is boring.
> 
> Ulimate Goals:
> - To learn to think in terms of OO/procedural paradigms as need be.
> - Develop good *progamming* skill so as to pick up any resume building
> language like Java, C, C++ Visual Basic, Php, whatever.
> 
> Projects:
> I have been trying to learn programming in vain for a long time now. I
> never get beneath the surface of it because I never find anything to do.
> Can anyone recommend me to some project where I can apprentice? I should
> head for sourceforge? That has never works! Finding a project isn't
> easy, atleast it has been difficult for me. 
> 
> thanks for your time.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From jeff at ccvcorp.com  Mon Aug 11 18:41:00 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 11 20:40:14 2003
Subject: [Tutor] [Long]General Questions
References: <20030811205927.GA664@Joss>
Message-ID: <3F38379C.1060409@ccvcorp.com>

Sukrit K Mehra wrote:

>Background:
>I have a system adminstration background. I want to learn *programming*.
>I just read "How to think like a computer scientist: Python".
>

I'm a self-taught programmer, so of course I applaud your efforts.  So, 
here's some of what seems to have worked for me.

>Computer Science:
>How do I go about learning the following, keeping in mind I have no exams to
>pass, using python.
>a Algorithms
>b Data Structures
>

There's a few books about these, but not many.  Keep in mind that the 
principles of algorithms and data structures will be the same no matter 
*what* language is used.  Of course, following examples can be difficult 
if you don't understand the language, but as of yet there's very little 
written for Python.  If you can find any books on either, read them -- 
chances are that, even if the example language doesn't make sense to 
you, you'll glean enough to make it worth your time.

At some point, you *will* want to read the "Gang of Four" Design 
Patterns book -- http://www.net-language.com/Book.aspx?i=461 .  It uses 
C++ and Smalltalk for its examples, but there's enough discussion of the 
patterns that you should be able to get a fair idea even without being 
able to really follow the examples.  This is not intended as an 
introductory book, though, so be prepared to take it slowly and spend a 
lot of time thinking about it.  You may be better off starting with 
Bruce Eckel's book-in-progress Thinking In Patterns -- 
http://www.mindview.net/Books/TIPatterns/ .  Design patterns aren't 
quite the same thing as algorithms or data structures, but definitely a 
useful concept to have in mind.

Read the comp.lang.python newsgroup, and pay particular attention when 
some of the gurus (Tim Peters, Alex Martelli, etc) discuss the 
principles behind certain technicalities.  Even if you don't understand 
half of what they're saying, you'll slowly start to assemble the parts 
of what you *do* understand.  Just having the general idea of some of 
the options available, and the relative tradeoffs between them, can be a 
great benefit.

>Engineering:
>I want to be productive asap and I believe I need these python skills
>- Threads
>- Unix Sys Calls
>- Reg Ex
>- Network Programming
>- Wxpython/ gtk-python
>- CGI
>- Web Clients 
>- DataBase connectivity
>
>What would a smallish project in which I could use most of these skills
>(I thought of a mail client but it's boring and it's ... boring; I learn
>faster when I am *NOT* writing programs that compute factorials of
>numbers.)
>

You're not likely to find a single project that'll exercise all of those 
skills -- at least, not a smallish project that'll be easy to get 
started in.  You've already found one of the keys of "practice makes 
perfect" -- you need to be *interested* in your practice in order to 
bother.  ;)  So, rather than approaching from the direction of "What can 
I do that'll require such-and-such skill", start from the perspective of 
"What am I interested in?"  One of my first wxPython projects came about 
because of my (then) new digital camera.  I found that I had lots of 
directories full of files with names like "DSCN0023(5).JPG", where "up" 
would vary from picture to picture.  So, I wrote a small app that would 
look through one of these directories, showing a preview of the picture 
and allowing me to rotate it properly, and naming the pictures something 
like "birthday05.JPG" (automatically advancing the numeric sequence 
number, etc).  This taught me quite a bit about wxPython and image 
handling.  It was (relatively) simple to do, and most of all, it was a 
practical benefit to me, so I had motivation to really make it work. 
 So, find something that'll make your life a little simpler, or that 
you're curious about, and go for it.  

You might also find some useful examples/ideas/challenges on Useless 
Python ( http://www.uselesspython.com/ ) -- it's a site that's designed 
with beginning programmers in mind, and is anything but useless.

Jeff Shannon
Technician/Programmer
Credit International




From vibrations at cetlink.net  Mon Aug 11 22:14:29 2003
From: vibrations at cetlink.net (SGD)
Date: Mon Aug 11 21:15:03 2003
Subject: [Tutor] pyopengl for python 2.3?
Message-ID: <000001c3606f$26784b40$5036c6d1@whiterhino2>

Is anyone using pyopengl with python 2.3 release?
 
If so can you explain to me how to get around the installer message
"python 2.2 not found". I tried to install from pythons shell but got an
error saying "NameError: name 'std_include_dirs' is not defined" but the
directory strucure is consistant. I'm on windows, it that helps any, and
the error code lines in the setup.py point's tward my MSVS.net directory
and every thing seems to be straight.
 
Or will I have to wait for a python 2.3 release of pyopengl? If so
anyone got any info on when it might be release, the web site gives no
clues for me to go off of?
 
Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030811/95f4c131/attachment.htm
From amonroe at columbus.rr.com  Mon Aug 11 22:42:59 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Mon Aug 11 21:38:51 2003
Subject: [Tutor] pyopengl for python 2.3?
In-Reply-To: <000001c3606f$26784b40$5036c6d1@whiterhino2>
References: <000001c3606f$26784b40$5036c6d1@whiterhino2>
Message-ID: <75353326476.20030811214259@columbus.rr.com>

> Is anyone using pyopengl with python 2.3 release?
 
No, and I've been wondering the exact same things as you :^)

I figured if I was patient, someone would eventually upload a 2.3
version...

Alan


From shalehperry at comcast.net  Mon Aug 11 21:05:23 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Mon Aug 11 23:06:02 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F37C196.6010107@netzero.net>
References: <BB5D2231.BD08%clay@shirky.com> <3F37C196.6010107@netzero.net>
Message-ID: <200308112005.23974.shalehperry@comcast.net>

On Monday 11 August 2003 09:17, Kirk Bailey wrote:
> IN fact, I did indeed just place an order with amazon for 'Textprocessing
> in Python" as it is language specific, addresses re rather well according
> to opion and review, and also covers other non re aspects of mangling text
> in the language of choice.
>
> With any luck, it will even contain some silly skits and jokes in the
> examples, although that's hoping for a bit much. As for dead parrots, all
> mine are alive, and one is shitting on my sholder right now.
>

I would not call it dry reading, but there is not much humor in the book.

Personally, I bought it and returned it.  However for a programmer new to the 
subject it does cover absolutely all of the possible text processing 
approaches.

My one, major beef was the author's insistance on functional programming.  
Don't get me wrong I enjoy the style, but I dislike authors who push a 
programming style when the book is not about style.


From clickron at webtv.net  Tue Aug 12 00:21:54 2003
From: clickron at webtv.net (Ron A)
Date: Mon Aug 11 23:21:58 2003
Subject: [Tutor] Re: using debug
In-Reply-To: tutor-request@python.org's message of Mon, 11 Aug 2003
	18:59:22 -0400
Message-ID: <20488-3F385D52-140@storefull-2132.public.lawson.webtv.net>

>If its of any help my book(the paper
> version) contains a chapter on
> debugging which has a section on using
> the Python debugger pdb. Most of that
> applies to the IDLE debugger too. 

>Problem is you need a copy of my book -
> maybe your local library?

Not a problem. I already ordered it and it should be here any day now. 

Thanks


From klhjhm at hotmail.com  Tue Aug 12 14:32:28 2003
From: klhjhm at hotmail.com (kamariah lamim)
Date: Tue Aug 12 01:33:03 2003
Subject: [Tutor] help on string replacement in a file
Message-ID: <BAY1-F93y3GwJKMb38100033e91@hotmail.com>

Thank you for your code.
may i know what i does it means by inplace?

>From: klappnase <klappnase@freenet.de>
>To: tutor@python.org
>Subject: Re: [Tutor] help on  string replacement in a file
>Date: Wed, 6 Aug 2003 11:07:39 +0200
>
>On Wed, 06 Aug 2003 12:22:34 +0800
>"kamariah lamim" <klhjhm@hotmail.com> wrote:
>
> > Hi.
> >    I wrote a function to replace a string in a file.I used built-in 
>replace(
> > ) to do that . However it failed to overwrite the old content of file 
>with
> > the new one. . Could someone trace this problem.the function is 
>something
> > like this:
> >
> > lineseen=0
> > drot='0.678'
> > batchNo=1
> >
> > def modify5File(drot,batchNo):
> > 	global lineSeen
> > 	updateFile=open('disper.501','rw')
> > 	x=updateFile.readlines()
> > 	for everyLine in x:
> > 		lineSeen += 1
> > 		if lineSeen == 10:
> > 			string.replace(everyLine,'+0.2000000000d+00',drot,1)
> > 		else:
> > 			pass
> > 	updateFile.close()
> >
>Hi,
>
>I am not sure about that, but I think you should use the fileinput module 
>for that, like:
>
>def modify5File():
>     for line in fileinput.input(path-to-file, inplace=1):
>         line = line.replace('+0.2000000000d+00', '0.678')
>         sys.stdout.write(line)
>
>This should replace every '+0.2000000000d+00' in the file with '0.678' .
>
>Best regards
>
>Michael
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Download the latest MSN Messenger http://messenger.msn.com.my


From RASTM2 at aol.com  Tue Aug 12 02:56:56 2003
From: RASTM2 at aol.com (RASTM2@aol.com)
Date: Tue Aug 12 01:57:06 2003
Subject: [Tutor] Portuguese characters in window command line
Message-ID: <7f.3b2d4e92.2c69dba8@aol.com>

In a message dated 8/11/03 11:05:15 AM Central Daylight Time, 
tutor-request@python.org writes:

> From: as1116522 <as1116522@sapo.pt>
> Subject: [Tutor] Displaying characters
> To: tutor@python.org
> Message-ID: <1060614804.3f37b294cf856@webmail.sapo.pt>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> 
> Hi, is there any way to display portuguese characters 
> like: "?", "?", "?" in windows command line? 
> 

Hello, as1116522,
The way to make those characters is to uses the 
ALT\NUMBER_PAD methode.
Hold down the "alt" key while typing on the number pad
? = alt - 135
? = alt - 160
? = alt - 130

HTH
Ray St. Marie 
Rastm2@users.sourceforge.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030812/a182cad4/attachment-0001.htm
From alex at gabuzomeu.net  Tue Aug 12 12:26:47 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Tue Aug 12 05:26:46 2003
Subject: [Tutor] [Long]General Questions
In-Reply-To: <20030811205927.GA664@Joss>
References: <20030811205927.GA664@Joss>
Message-ID: <3F38B2D7.2090203@gabuzomeu.net>

Hello Sukrit,


Sukrit K Mehra wrote:

>I am new to programming and in need of some advice. 
>
>Background:
>I have a system adminstration background. I want to learn *programming*.
>I just read "How to think like a computer scientist: Python".
>
I suggest you read several tutorials. When I started learning Python, I 
found it useful to read several texts since they often focus on 
different concepts:
- Some teach you programming concepts through Python.
- Some are more focused on Python itself.
- Some assume you already know how to programm in other languages, etc. 
(Eg. "Dive Into Python").

>Computer Science:
>How do I go about learning the following, keeping in mind I have no exams to
>pass, using python.
>a Algorithms
>b Data Structures
>
Suggestions:
- Read this list (Python Tutor). I picked up a lot of background 
information just reading this list.
- Read Python newsgroups.
- Look for information on the Web. There's a lot of material, though 
often it's not focused on Python.

Example: I came accross this reference a few days ago: "A Compact Guide 
to Sorting and Searching", by Thomas Niemann

    http://www.oopweb.com/Algorithms/Documents/Sman/Volume2.html

>What would a smallish project in which I could use most of these skills
>(I thought of a mail client but it's boring and it's ... boring; I learn
>faster when I am *NOT* writing programs that compute factorials of
>numbers.)
>
As already mentioned, you should probably pick up a project that is 
interesting to you, so that you are motivated to finish it. How about 
trying to automate some boring task you have to do manually (in sysadmin 
for instance)?


Cheers.

Alexandre




From gnux at freesurf.fr  Tue Aug 12 15:24:48 2003
From: gnux at freesurf.fr (gnux@freesurf.fr)
Date: Tue Aug 12 08:05:24 2003
Subject: [Tutor] [Long]General Questions
In-Reply-To: <3F3827F7.3090306@netzero.net>
References: <3F3827F7.3090306@netzero.net>
Message-ID: <2653.81.248.40.239.1060691088.squirrel@arlette.freesurf.fr>

Hi
> 4. Take up reading eveything you can as a hobby.
I try to do so
>
> 5. Hang around this list a lot. :-)
idem ;-)
>
I've got a question concerning this prog: why have u written
"radius=input()"rather than "radius=raw_input()"
I thought we use the second when we ask something to the user
Thx if u can explain me the difference between the two and why u
use the second
> #!/usr/bin/python
> # The above line MUST point at the python interpeter in YOUR server!
> pi='3.1415926'			# we need this later to crunch the
numbers.
> print				# print program header
> print 'PIPEVOLUME v:1.0.0'
> print				# prints a blank line to space things out.
> print 'what is the length of the pipe in meters?', # comma supresses
> newline length=input()
> print 'what is the radiius of the pipe in meters?'
> radius=input()
> volume=((radius*radius)*pi)*length
> print				# prints a blank line to seperate the answer
> #				# to majke it easier to read the screen.
> print 'The volume of the specified pipe is ',volume,' meters^3.'
>
> this is in the flow of:
>
> setup>prompt>input>crunch>output>terminate (implicit in the language)
>
> which is a fairly good broad outline for many programs.
>
> This is procedural programming, not object programming. I know what
> must be done  to generate a valid answer, and build a process to set up
> the tools the program  needs, and then interact with the user, crunch,
> and deliver the result.
>
> I could have created a function, as:
> def sqr(r):
> 	sq=r*r
> 	return sq
> and then used it in another defined function:
>
> def volume(r,l):
> 	volume=(sqr(r)*3.1415925)*l
> 	return volume
> then the program would look like:
>
> #!/usr/bin/python
> # The above line MUST point at the python interpeter in YOUR server!
> pi='3.1415926'			# we need this later to crunch the
numbers.
> def sqr(r):
> 	sq=r*r
> 	return sq
> #
> def volume(r,l):
> 	volume=(sqr(r)*3.1415925)*l
> 	return volume
> #
> print				# print program header
> print 'PIPEVOLUME v:1.0.0'
> print				# prints a blank line to space things out.
> print 'what is the length of the pipe in meters?', # comma supresses
> newline length=input()
> print 'what is the radiius of the pipe in meters?'
> radius=input()
> #
> print				# prints a blank line to seperate the answer
> #				# to majke it easier to read the screen.
> print 'The volume of the specified pipe is ',volume(radius,length),'
> meters^3.' print
> In effect, I just invented two entirely new commands in python, the
> applied  them. In python, functions always end in (roundbrackets) even
> if the function  does not need any arguements pased to it.
>
> return simply means ou are telling the function to say something, and
> what it is  to say.
>
> Suppose you had this function:
> def hello():
> 	return 'Hello world!'
>
> >> >hello()
> 'Hello world!'
> >> >print hello()
> Heello world!
> >> >
>
> Dig? Of course, it can be A LOT more complex than this. your new
> function can be  a complete subprogram in itself, in effect a
> SUBROUTINE, and it can invoke other  such things in it's definition, as
> long as they exist already when your function  executes. YOU CANNOT
> INVOKE SOMETHING THAT DOES NOT EXIST YET.
>
>
>
>> Computer Science:
>> How do I go about learning the following, keeping in mind I have no
>> exams to pass, using python.
>> a Algorithms
>> b Data Structures
>>
>> After these what else could be nearly as practically rewarding?
>>
>> Engineering:
>> I want to be productive asap and I believe I need these python skills
>> - Threads
>> - Unix Sys Calls
> actually, try the os module for the details.
>> - Reg Ex
>> - Network Programming
> Hmmm, LAN stuff? WAN? TCP/IP stack stuff?
>> - Wxpython/ gtk-python
>> - CGI
> When you grok cgi, you will de delighted with how wonderful the cgi
> module is to  use. Try creating a simple form of some sort, and record
> the input in a text  file for later examination. I did this some time
> back when I wrote a weblog.
>> - Web Clients
> Um, what sort?
>> - DataBase connectivity
> bd hash tables, freeform databases, what?
>>
>> What would a smallish project in which I could use most of these
>> skills (I thought of a mail client but it's boring and it's ...
>> boring; I learn faster when I am *NOT* writing programs that compute
>> factorials of numbers.)
> Well, what is NOT boring? I wrote a Mail List Manager suite, (think
> majordomo  and you're at least in the right province) but you told me
> email is boring.
>>
>> Ulimate Goals:
>> - To learn to think in terms of OO/procedural paradigms as need be. -
>> Develop good *progamming* skill so as to pick up any resume building
>> language like Java, C, C++ Visual Basic, Php, whatever.
>>
>> Projects:
>> I have been trying to learn programming in vain for a long time now. I
>> never get beneath the surface of it because I never find anything to
>> do. Can anyone recommend me to some project where I can apprentice? I
>> should head for sourceforge? That has never works! Finding a project
>> isn't easy, atleast it has been difficult for me.
>>
>> thanks for your time.
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> --
>
> --
>
> end
>
> Cheers!
>         Kirk D Bailey
>
>  +                              think                                +
>   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
>   http://www.listville.net     | BOX |  http://www.sacredelectron.org
>   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
>  +                              think                                +
>
> Fnord.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



----------------------------------------------------------------
Ce service de mailing vous est offert par http://www.freesurf.fr.
FreeSurf, votre acces ADSL a partir de 29 euros/mois
http://www.freesurf.fr/adsl/



From max_ig at yahoo.com  Tue Aug 12 06:08:34 2003
From: max_ig at yahoo.com (MI)
Date: Tue Aug 12 08:08:39 2003
Subject: [Tutor] Tkinter, PMW and Linux
Message-ID: <20030812120834.49766.qmail@web11303.mail.yahoo.com>

I wrote a code in Python in a Windows98 machine and tried to run it on
a Linux machine but I had some few errors with Tkinter and PMW.
Specifically I had problems (i.e. many screens full of errors) with
".tk_focusNext()" and PMW.Group.

If anybody has any idea to help me will be wonderful.


Max

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From gnux at freesurf.fr  Tue Aug 12 15:09:18 2003
From: gnux at freesurf.fr (gnux@freesurf.fr)
Date: Tue Aug 12 08:14:27 2003
Subject: [Tutor] [Long]General Questions
In-Reply-To: <3F38379C.1060409@ccvcorp.com>
References: <3F38379C.1060409@ccvcorp.com>
Message-ID: <2585.81.248.40.239.1060690158.squirrel@arlette.freesurf.fr>

Hi
> So, find something that'll make your life a little simpler, or that
> you're curious about, and go for it.
That's one of my problem: I don't know what I can write to improve
my python. It's difficult to find THE good thing:the thing which is
neither uninteresting nor difficult
>
> You might also find some useful examples/ideas/challenges on Useless
> Python ( http://www.uselesspython.com/ ) -- it's a site that's designed
>  with beginning programmers in mind, and is anything but useless.
Thx for the links, will see it :)
Regards
>
> Jeff Shannon
> Technician/Programmer
> Credit International
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



----------------------------------------------------------------
Ce service de mailing vous est offert par http://www.freesurf.fr.
FreeSurf, votre acces ADSL a partir de 29 euros/mois
http://www.freesurf.fr/adsl/



From marc_barry at hotmail.com  Tue Aug 12 10:22:12 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Tue Aug 12 09:23:41 2003
Subject: [Tutor] Testing a variable for being a number,
	string or other object...
Message-ID: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>

Dear All:

My first question is how do I test if a variable is a number or a string?  I 
need to to do this for error checking on values passed into methods.

The second question I have is does Python have a way of testing for 
instances like Java does?  For example, the "instanceof" operator that lets 
you determine if an instance is of a certain type?

Regards,

Marc

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*   
http://join.msn.com/?page=features/junkmail


From clay at shirky.com  Tue Aug 12 11:01:57 2003
From: clay at shirky.com (Clay Shirky)
Date: Tue Aug 12 10:02:19 2003
Subject: [Tutor] help on string replacement in a file
In-Reply-To: <BAY1-F93y3GwJKMb38100033e91@hotmail.com>
Message-ID: <BB5E6B95.BDDD%clay@shirky.com>

> Thank you for your code.
> may i know what i does it means by inplace?

Lots of operations modify an existing piece of data to produce a new piece
of data. For example,

my_long = long(my_hex, 16)

takes a string, my_hex, expressed in hexadecimal and assigns it to my_long
as a long integer. You started with one piece of data, performed an
operation on it, and now you have two pieces of data, the original  my_hex
and the new my_long.

An in-place operation, by contrast, modifies data, well, in place. When you
say my_list.sort(), for example, you end up with a sorted version of
my_list, but no longer have the unsorted version. In this case, you started
with one piece of data, performed an in-place operation on it, and now you
still have one piece of data, the newly sorted my_list.

-clay


From clay at shirky.com  Tue Aug 12 11:05:19 2003
From: clay at shirky.com (Clay Shirky)
Date: Tue Aug 12 10:05:21 2003
Subject: [Tutor] Testing a variable for being a number, string or
	other object...
In-Reply-To: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>
Message-ID: <BB5E6C5F.BDFA%clay@shirky.com>

> My first question is how do I test if a variable is a number or a string?  I
> need to to do this for error checking on values passed into methods.

type(), as in 

  hex_num  = "DECAFBAD"
  long_num = long(hex_num, 16)

  print type(hex_num)
  print type(long_num)

returns 

<type 'str'>
<type 'long'>





From marc_barry at hotmail.com  Tue Aug 12 11:10:49 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Tue Aug 12 10:11:23 2003
Subject: [Tutor] Testing a variable for being a number,
	string or other object...
Message-ID: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>

I have done the following and it seems to solve all of my problems.  I use 
the isinstance function to check for an objects instance type.  If there are 
any downfalls to doing this, please let me know.  Here is the general 
concept of what I have done.

------------------------------------------------------------

from types import IntType
from types import StringType

class IntHolder:
	def __init__(self, an_int):
		if(isinstance(an_int, IntType)):
			self.__an_int = an_int
		else:
			raise TypeError("Not an int.")
	def __str__(self):
		return str(self.__an_int)

def check(must_be_an_int, must_be_a_string, must_be_an_IntHolder):
	if(not isinstance(must_be_an_int, IntType)):
		raise TypeError("Not an int.")
	elif(not isinstance(must_be_a_string, StringType)):
		raise TypeError("Not a string.")
	elif(not isinstance(must_be_an_IntHolder, IntHolder)):
		raise TypeError("Not an IntHolder.")
	else:
		print must_be_an_int
		print must_be_a_string
		print must_be_an_IntHolder

new_holder = IntHolder(10)

check(10, "Hello", new_holder)

-------------------------------------------------------

Regards,

Marc



From: "Marc Barry" <marc_barry@hotmail.com>
To: tutor@python.org
Subject: [Tutor] Testing a variable for being a number,string or other 
object...
Date: Tue, 12 Aug 2003 09:22:12 -0400

Dear All:

My first question is how do I test if a variable is a number or a string?  I 
need to to do this for error checking on values passed into methods.

The second question I have is does Python have a way of testing for 
instances like Java does?  For example, the "instanceof" operator that lets 
you determine if an instance is of a certain type?

Regards,

Marc

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*   
http://join.msn.com/?page=features/junkmail


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

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8.  
http://join.msn.com/?page=features/junkmail


From magnus at thinkware.se  Tue Aug 12 17:34:50 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Aug 12 10:27:33 2003
Subject: [Tutor] using python to start and stop a program
In-Reply-To: <20030811003532.33693.qmail@web80703.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030812163134.020ddf28@www.thinkware.se>

Hi Johanna, perhaps you can show us some code, and we
might spot the problems in it. In what way did writing
the info to a file and reading it back fail. Writing
or reading? Did it get to the file?

Why do you need to store the pid in a file? Are you
using separate python processes to start and stop? Has
the writing process exited before the other process
reads the file?

At 17:35 2003-08-10 -0700, Joanna Ingrahm wrote:
>I have a program that I have to start using the win32
>comand line. to stop it I use ctrl+c.
>Now I tried to do that using python but still have
>problems with it.
>I can start the program and receive the pid of it
>using:
>
>os.spawnl(os.P_NOWAIT,...
>
>but then how can I use that information to terminate
>the process again? I tried to write it in a file and
>read it again but couldn't get it to work.
>Appreciate any help!



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From justin at unixremedies.com  Tue Aug 12 10:25:10 2003
From: justin at unixremedies.com (Justin Heath)
Date: Tue Aug 12 10:29:03 2003
Subject: [Tutor] [Long]General Questions
In-Reply-To: <20030811205927.GA664@Joss>
References: <20030811205927.GA664@Joss>
Message-ID: <3F38F8C6.4050808@unixremedies.com>

Sukrit K Mehra wrote:

>Hi Pythoners,
>
>I am new to programming and in need of some advice. 
>
>Background:
>I have a system adminstration background. I want to learn *programming*.
>I just read "How to think like a computer scientist: Python".
>
>Computer Science:
>How do I go about learning the following, keeping in mind I have no exams to
>pass, using python.
>a Algorithms
>b Data Structures
>
>After these what else could be nearly as practically rewarding?
>
>Engineering:
>I want to be productive asap and I believe I need these python skills
>- Threads
>- Unix Sys Calls
>- Reg Ex
>- Network Programming
>- Wxpython/ gtk-python
>- CGI
>- Web Clients 
>- DataBase connectivity
>
>What would a smallish project in which I could use most of these skills
>(I thought of a mail client but it's boring and it's ... boring; I learn
>faster when I am *NOT* writing programs that compute factorials of
>numbers.)
>
>Ulimate Goals:
>- To learn to think in terms of OO/procedural paradigms as need be.
>- Develop good *progamming* skill so as to pick up any resume building
>language like Java, C, C++ Visual Basic, Php, whatever.
>
>Projects:
>I have been trying to learn programming in vain for a long time now. I
>never get beneath the surface of it because I never find anything to do.
>Can anyone recommend me to some project where I can apprentice? I should
>head for sourceforge? That has never works! Finding a project isn't
>easy, atleast it has been difficult for me. 
>
>thanks for your time.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
I also am a sysadmin starting in Python. I can tell you as a sysadmin
there are always parts of your systems/os/tools that you are not 100%
happy with. This is a good place to start. For example rather than
having your log files mailed and trolling through them every day write a
program to parse the log files extract the info you want to see and then
mail it to you. Write some sripts to keep track of user accounts when
thier passwords were last changed an thier activities. Write some
programs to send you info in disk usage, load, etc. When you have the
tools written expand upon them by making the reporting web based. When
you are done with that make them into a GUI. I think you see where I am
going here. You need to find a goal "YOU" want to accomplish. Start
small and build from there. It doesnt matter how small the programs are
as long as you start them and see them to completion. The only way to
learn anything is hands on, so just get in  and get your hands dirty.

Thanks,
Justin




From op73418 at mail.telepac.pt  Tue Aug 12 16:31:26 2003
From: op73418 at mail.telepac.pt (Rodrigues)
Date: Tue Aug 12 10:30:50 2003
Subject: [Tutor] Testing a variable for being a number,
	string or other object...
In-Reply-To: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKMEFHCBAA.op73418@mail.telepac.pt>



> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
> Behalf Of Marc Barry
>
> Dear All:
>
> My first question is how do I test if a variable is a
> number or a string?  I
> need to to do this for error checking on values passed into methods.
>
> The second question I have is does Python have a way of testing for
> instances like Java does?  For example, the "instanceof"
> operator that lets
> you determine if an instance is of a certain type?

Yes, isinstance.

>>> isinstance(1, int)
True
>>> isinstance('', int)
False
>>>

And this answers your first question.

Note though, that the usual Pythonic mode is to code for protocol not
for type, as embodied in Easier to Ask Forgiveness Than Permission
principle. I don't know your cosde, so your constraints may be
different, but in general it really doens't matter the *exact type (or
class)* of the object but only the protocol or interface to which it
responds.

Let me give you an example: What is a string? Well, one answer would
be isinstance(<whatever>, str) returns True, but this is too-stringent
for our needs.

>>> def isstringy(obj):
... 	try:
... 		obj + ''
... 	except TypeError:
... 		return False
... 	else:
... 		return True
...

This defines a function that checks if some object can be *added* to
the empty string. If it can we count it as stringy enough.

Another example: For a lot of code (more than I ever imagined
actually) it really does not matter if we get a list, a tuple,
whatever. It only matter if we can *traverse* the object. In Python >
2.2 this is embodied in the iterator protocol, that is:

>>> def isiterable(obj):
... 	"""Return True if object is iterable, False otherwise."""
... 	try:
... 		iter(obj)
... 	except TypeError:
... 		return False
... 	else:
... 		return True
...

With these ideas in hand, the EAFTP is easy to explain. One just goes
ahead and *tries* to do the operations one wants, taking care of the
exceptions on the way. For an iterable, something like

try:
    #Use object in the way intended.
    ...
except TypeError #Or other exceptions.
    ...

Some care must be exercised, though, to put as little code in the try
block as possible so as not to catch "unwanted" exceptions.

HTH, with my best regards,
G. Rodrigues


From magnus at thinkware.se  Tue Aug 12 17:39:47 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Aug 12 10:32:38 2003
Subject: [Tutor] Python versions on Linux
In-Reply-To: <Pine.LNX.4.44.0308102203420.32411-100000@mauve.rahul.net>
References: <5.2.1.1.0.20030810234617.0526e580@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030812163523.0526da68@www.thinkware.se>

At 22:04 2003-08-10 -0700, Terry Carroll wrote:
>Sure, if it's your Linux distribution.  In this case, it's my ISP's.

My ISP has been very helpful in upgrading Python when I asked them. :)

You can always ask... It's fully possible to have new Python versions
installed in parallel with Python 1.5.2 which older RedHats need. The
executable will be python2, not python, if they install from Red Hat
RPMs. They could also build it from source, and have /usr/local/bin/python
be the new python, and /usr/bin/python the old.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From justin at unixremedies.com  Tue Aug 12 10:38:20 2003
From: justin at unixremedies.com (Justin Heath)
Date: Tue Aug 12 10:39:58 2003
Subject: [Tutor] Testing a variable for being a number, string or
	other object...
In-Reply-To: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>
References: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>
Message-ID: <3F38FBDC.50106@unixremedies.com>

Marc Barry wrote:

> Dear All:
>
> My first question is how do I test if a variable is a number or a 
> string?  I need to to do this for error checking on values passed into 
> methods.
>
> The second question I have is does Python have a way of testing for 
> instances like Java does?  For example, the "instanceof" operator that 
> lets you determine if an instance is of a certain type?
>
> Regards,
>
> Marc
>
> _________________________________________________________________
> STOP MORE SPAM with the new MSN 8 and get 2 months FREE*   
> http://join.msn.com/?page=features/junkmail
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Also checkout ClassFoo.__class__.__name__



From pythontutor at venix.com  Tue Aug 12 12:01:17 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Aug 12 11:01:55 2003
Subject: [Tutor] Testing a variable for being a number,	string or other
	object...
In-Reply-To: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>
References: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>
Message-ID: <3F39013D.6010700@venix.com>

It is usually simpler to simply use:
from types import *
rather than manually keeping the import in synch with your checks.

In general, you do NOT need to impose the same kind of stringent checking
that C requires.  Catching errors as they occur is generally preferable.
A low level function or method simply uses its arguments to do what it does.
The caller, or some caller of the caller, has the try / except logic that
deals with potential errors.  However, garbage in implies garbage out.
Type checking can be needed when storing inputs for later use.

Note that StringTypes includes both unicode and "regular" strings, which
might be preferable for what you are doing here.

I find I mostly have type checking when distinguishing between a string
or list of strings, within a function that will accept either.

Marc Barry wrote:

> I have done the following and it seems to solve all of my problems.  I 
> use the isinstance function to check for an objects instance type.  If 
> there are any downfalls to doing this, please let me know.  Here is the 
> general concept of what I have done.
> 
> ------------------------------------------------------------
> 
> from types import IntType
> from types import StringType
> 
> class IntHolder:
>     def __init__(self, an_int):
>         if(isinstance(an_int, IntType)):
>             self.__an_int = an_int
>         else:
>             raise TypeError("Not an int.")
>     def __str__(self):
>         return str(self.__an_int)
> 
> def check(must_be_an_int, must_be_a_string, must_be_an_IntHolder):
>     if(not isinstance(must_be_an_int, IntType)):
>         raise TypeError("Not an int.")
>     elif(not isinstance(must_be_a_string, StringType)):
>         raise TypeError("Not a string.")
>     elif(not isinstance(must_be_an_IntHolder, IntHolder)):
>         raise TypeError("Not an IntHolder.")
>     else:
>         print must_be_an_int
>         print must_be_a_string
>         print must_be_an_IntHolder
> 
> new_holder = IntHolder(10)
> 
> check(10, "Hello", new_holder)
> 
> -------------------------------------------------------
> 
> Regards,
> 
> Marc
> 
> 
> 
> From: "Marc Barry" <marc_barry@hotmail.com>
> To: tutor@python.org
> Subject: [Tutor] Testing a variable for being a number,string or other 
> object...
> Date: Tue, 12 Aug 2003 09:22:12 -0400
> 
> Dear All:
> 
> My first question is how do I test if a variable is a number or a 
> string?  I need to to do this for error checking on values passed into 
> methods.
> 
> The second question I have is does Python have a way of testing for 
> instances like Java does?  For example, the "instanceof" operator that 
> lets you determine if an instance is of a certain type?
> 
> Regards,
> 
> Marc
> 
> _________________________________________________________________
> STOP MORE SPAM with the new MSN 8 and get 2 months FREE*   
> http://join.msn.com/?page=features/junkmail
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _________________________________________________________________
> Tired of spam? Get advanced junk mail protection with MSN 8.  
> http://join.msn.com/?page=features/junkmail
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From carroll at tjc.com  Tue Aug 12 10:11:13 2003
From: carroll at tjc.com (Terry Carroll)
Date: Tue Aug 12 12:11:18 2003
Subject: [Tutor] Python versions on Linux
In-Reply-To: <5.2.1.1.0.20030812163523.0526da68@www.thinkware.se>
Message-ID: <Pine.LNX.4.44.0308120907300.29812-100000@mauve.rahul.net>

On Tue, 12 Aug 2003, Magnus Lyck? wrote:

> At 22:04 2003-08-10 -0700, Terry Carroll wrote:
> >Sure, if it's your Linux distribution.  In this case, it's my ISP's.
> 
> My ISP has been very helpful in upgrading Python when I asked them. :)

Mine, too.  But our Python is sufficiently up-to-date for my purposes.  

I may have misunderstood, but I thought by "it's probably a good idea to
upgrade your Linux distribution," you were referring to the distribution
of Linux itself, rather than the Python distribution on Linux.

On the list of things that matter to me, invoking the more current version
of Python as "python2" vs. "python" is way down the list.  Most of my
Python work is done on my home system, anyway, which is Python 2.2.2 (for
now).

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982



From amk at asti-usa.com  Tue Aug 12 14:25:34 2003
From: amk at asti-usa.com (A.M. Kuchling)
Date: Tue Aug 12 13:26:09 2003
Subject: [Tutor] Testing a variable for being a number,
	string or other object...
In-Reply-To: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>
References: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>
Message-ID: <20030812172534.GA9427@vail.asti-usa.com>

On Tue, Aug 12, 2003 at 10:10:49AM -0400, Marc Barry wrote:
> from types import IntType
> from types import StringType

The 'types' module isn't being deprecated, but its use is being
discouraged.  Starting in Python 2.2, built-ins such as 'int' and
'float' are really type objects, so you can write 'isinstance(an_int, int)'.

In most cases the isinstance() function can be used instead of calling type()
and comparing type objects, meaning that instead of writing:

	if type(param) == type(''):
	    ...

you can write the clearer code:

	if isinstance(param, str):
            ...

'str' and 'unicode' are two different types; if you want to check for 
either of them, you can use the base_string built-in type.

--amk                                            (www.amk.ca)
My nose shall never be touched while heaven give me strength.
      -- Sterne, _Tristram Shandy_



From jeff at ccvcorp.com  Tue Aug 12 12:06:52 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Aug 12 14:06:07 2003
Subject: [Tutor] pyopengl for python 2.3?
References: <000001c3606f$26784b40$5036c6d1@whiterhino2>
Message-ID: <3F392CBC.4030808@ccvcorp.com>

SGD wrote:

> Is anyone using pyopengl with python 2.3 release?
>
> If so can you explain to me how to get around the installer message 
> python 2.2 not found. I tried to install from pythons shell but got 
> an error saying NameError: name 'std_include_dirs' is not defined 
> but the directory strucure is consistant. Im on windows, it that 
> helps any, and the error code lines in the setup.py points tward my 
> MSVS.net directory and every thing seems to be straight.
>
> Or will I have to wait for a python 2.3 release of pyopengl? If so 
> anyone got any info on when it might be release, the web site gives no 
> clues for me to go off of?
>

I don't use PyOpenGL, but it most likely uses compiled extensions 
(.pyd). Compiled extensions are not portable between different versions 
of Python. Even with no PyOpenGL code changes, the libraries would need 
to be recompiled with the Python 2.3 headers/libraries. So, yes, you'll 
have to wait for a Python 2.3 release of PyOpenGL, unless you want to 
try downloading the source and compiling it yourself...

Jeff Shannon
Technician/Programmer
Credit International



From jeff at ccvcorp.com  Tue Aug 12 12:18:18 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Aug 12 14:17:38 2003
Subject: [Tutor] [Long]General Questions
References: <3F3827F7.3090306@netzero.net>
	<2653.81.248.40.239.1060691088.squirrel@arlette.freesurf.fr>
Message-ID: <3F392F6A.8010709@ccvcorp.com>

gnux@freesurf.fr wrote:

>I've got a question concerning this prog: why have u written
>"radius=input()"rather than "radius=raw_input()"
>I thought we use the second when we ask something to the user
>Thx if u can explain me the difference between the two and why u
>use the second
>

Both input() and raw_input() prompt the user to type something, and 
return that to the program.  However, they handle what's typed a bit 
differently.

raw_input() will always return a string, exactly as the user typed it. 
 input(), on the other hand, evaluates that string as if it were a 
Python expression -- input() is equivalent to eval(raw_input()).  This 
makes input() more convenient for entering numbers, because you can just 
type the number and get an integer (or float, or whatever), just as if 
you'd typed a numeric literal in the interpreter.  By comparison, with 
raw_input(), you'd then have to use int() or float() to convert the 
string into a number.  On the other hand, input() is less convenient for 
entering strings, because (just like a string literal in the 
interpreter) you need to use quotes around it.  And if the quotes are 
forgotten, then whatever is typed is interpreted as a Python identifier, 
which might look up an existing variable or might throw a NameError. 
 And since input() effectively executes an arbitrary expression, it 
leaves you *wide* open to malicious (or accidental) attacks on your 
computer system.

In short, input() should only be used when you know exactly what's going 
to happen.  Which, really, should only be when you're working in the 
interactive interpreter.  It's too dangerous for routine production use.

Jeff Shannon
Technician/Programmer
Credit International



From glingl at aon.at  Tue Aug 12 22:20:10 2003
From: glingl at aon.at (Gregor Lingl)
Date: Tue Aug 12 15:18:06 2003
Subject: [Tutor] Testing a variable for being a number,	string or other
	object...
References: <Sea2-F8ZQBnW2KVNnOB00022741@hotmail.com>
	<20030812172534.GA9427@vail.asti-usa.com>
Message-ID: <3F393DEA.1070903@aon.at>

A.M. Kuchling schrieb:

>On Tue, Aug 12, 2003 at 10:10:49AM -0400, Marc Barry wrote:
>  
>
>>from types import IntType
>>from types import StringType
>>    
>>
>
>The 'types' module isn't being deprecated, but its use is being
>discouraged.  Starting in Python 2.2, built-ins such as 'int' and
>'float' are really type objects, so you can write 'isinstance(an_int, int)'.
>  
>
...

>'str' and 'unicode' are two different types; if you want to check for 
>either of them, you can use the base_string built-in type.
>  
>
Until now I couldn't find out if there are names for some of the 
built-in types.

In this case:
 >>> b=u""
 >>> type(b)==unicode
True
 >>> type(b)==base_string

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in -toplevel-
    type(b)==base_string
NameError: name 'base_string' is not defined

So the type object refering to the above mentioned
built-in type base_string has another identifier?

Equally I'd like to know if there are type-objects for
the built-in types "function" and "generator".

What's the "canonical way" to find out if an object is
a function or a generator?

Regards, Gregor




From abli at freemail.hu  Tue Aug 12 22:25:32 2003
From: abli at freemail.hu (Abel Daniel)
Date: Tue Aug 12 15:25:56 2003
Subject: [Tutor] Tkinter, PMW and Linux
In-Reply-To: <20030812120834.49766.qmail@web11303.mail.yahoo.com>
References: <20030812120834.49766.qmail@web11303.mail.yahoo.com>
Message-ID: <20030812192532.GA12275@hooloovoo>

MI wrote:
> I wrote a code in Python in a Windows98 machine and tried to run it on
> a Linux machine but I had some few errors with Tkinter and PMW.
> Specifically I had problems (i.e. many screens full of errors) with
> ".tk_focusNext()" and PMW.Group.
> 
> If anybody has any idea to help me will be wonderful.
Post the code, and the version numbers of python, tkinter and pmw.
(You might want to narrow down the problem to avoid needing to post too
much code. Make sure to post something that can be run after a simple
cut&pasting, without editing it.)
And post some of the traceback you get. (those
"many screen full of errors" will most likely be something repeating
many times. Try weeding out the duplicates.)

Abel Daniel

From dyoo at hkn.eecs.berkeley.edu  Tue Aug 12 13:30:21 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug 12 15:30:26 2003
Subject: [Tutor] [Long]General Questions   [How to practice programming]
In-Reply-To: <3F38F8C6.4050808@unixremedies.com>
Message-ID: <Pine.LNX.4.44.0308121158060.23466-100000@hkn.eecs.berkeley.edu>



>> How do I go about learning the following, keeping in mind I have no
>> exams to pass, using python.
>
>> a Algorithms
>> b Data Structures


We can bring up a problem that we're trying to solve --- the Python-Tutor
list can then try talking about appropriate algorithms or data structures
that we can apply to solve that problem.

Alternatively, we can go about it from the other direction: if you bring
up a particular data structure (linked list / dictionary / tree), we can
talk about practical reasons for using such structures in Python code.

In both, we can make the conversation relevant by practicing on concrete
examples, as well as talking about the theory that makes it work.



>> I have been trying to learn programming in vain for a long time now. I
>> never get beneath the surface of it because I never find anything to
>> do. Can anyone recommend me to some project where I can apprentice? I
>> should head for sourceforge? That has never works! Finding a project
>> isn't easy, atleast it has been difficult for me.
>
>
>> What would a smallish project in which I could use most of these skills
>> (I thought of a mail client but it's boring and it's ... boring; I
>> learn faster when I am *NOT* writing programs that compute factorials
>> of numbers.)


Good question!  It might be useful to do look at Sourceforge.net and see
what sort of projects are out there.  What kind of stuff are you
interested in?  Games, possibly?  Or text mining?



I remember Patrick O'Brien talked about the PythonCard project once:

    http://pythoncard.sourceforge.net/

and it looked very nice.  It's a system for developing GUI applications
with relative ease.  It might be interesting to look at it in detail on
Python-Tutor, as a model project that we can study.  And perhaps we can
contribute to it!

If I have time, I can play around with it and try to write a more detailed
post about it.



> The only way to learn anything is hands on, so just get in and get your
> hands dirty.

Agreed.  Experience is important.  And supervised experience is often even
better. *grin*

Please feel free to talk on Python-Tutor as you're practicing your skills.
All of us here will be happy to help you to program more effectively.



Good luck to you!


From as1116522 at sapo.pt  Tue Aug 12 21:04:52 2003
From: as1116522 at sapo.pt (Paulo Baptista)
Date: Tue Aug 12 16:03:37 2003
Subject: [Tutor] Displaying characters
References: <1060614804.3f37b294cf856@webmail.sapo.pt>
	<m3fzk7x66d.fsf@ieee.org>
Message-ID: <000601c36109$67b0dd30$c9e40dd5@zeus>

Thanks for your help but...
Well, yes they print, if you do it from the interactive shell, but if you do
it with a file like c:\python xpto.py this characters wont show up, instead
they'll print symbols. I'm trying this with windows, but as far as I can
remember this worked fine with linux.

----- Original Message -----
From: "Jorge Godoy" <godoy@metalab.unc.edu>
To: "as1116522" <as1116522@sapo.pt>
Cc: <tutor@python.org>
Sent: Monday, August 11, 2003 9:58 PM
Subject: Re: [Tutor] Displaying characters


as1116522 <as1116522@sapo.pt> writes:

> Hi, is there any way to display portuguese characters
> like: "?", "?", "?" in windows command line?

I just print them and it works.

In Windows, Linux and FreeBSD. It is also true for wxPython
applications.


Some silly phrases:

>>> print 'Ol?! Como est?o as coisas a? em Portugal?'
Ol?! Como est?o as coisas a? em Portugal?
>>> print 'Aqui no Brasil est?o muito frias. O inverno est? bem severo.'
Aqui no Brasil est?o muito frias. O inverno est? bem severo.
>>> print 'Espero que os exemplos tenham ajudado. Uma palavra com "?":
ma??.'
Espero que os exemplos tenham ajudado. Uma palavra com "?": ma??.
>>>


See you,
--
Godoy.     <godoy@metalab.unc.edu>

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


From alan.gauld at blueyonder.co.uk  Tue Aug 12 22:22:37 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Aug 12 16:22:14 2003
Subject: [Tutor] [Long]General Questions
References: <3F3827F7.3090306@netzero.net>
	<2653.81.248.40.239.1060691088.squirrel@arlette.freesurf.fr>
Message-ID: <004801c3610f$79300620$6401a8c0@xp>

> I've got a question concerning this prog: why have u written
> "radius=input()"rather than "radius=raw_input()"
> I thought we use the second when we ask something to the user

You are right, raw_input is preferred because it is less of a 
security risk. input effectively does the same as raw_input but 
then evaluates the string as a python expression and returns 
the result, thus:

v = raw_input('?')  # user enters 5 + 4
print v             # prints '5 + 4'
v = input('?')      # user enters 5 + 4
print v             # prints 9
######## DONT TRY THIS ONE FOLKS! ############
v = input('?')      # user enters import os; os.system("format C:")
...ooops!           

But if you trust your users input() saves a bit of conversion 
work for the programmer.

Also notice above that input() and raw_input() can both take a 
prompt string as a parameter thus avoiding the need for the 
initial print statements in Kirk's original post.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Tue Aug 12 22:35:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Aug 12 16:35:06 2003
Subject: [Tutor] Testing a variable for being a number,
	string or other object...
References: <Sea2-F50ugu3WOXs8Nx00008e2c@hotmail.com>
Message-ID: <001801c36111$469cdf10$6401a8c0@xp>

> My first question is how do I test if a variable is a number or a
string?  I
> need to to do this for error checking on values passed into methods.

First, you hardly ever need to do this in a dynamic language like
Python.
If the object supports the operations you want to perform it doesn't
matter what type it is most of the time. Indeed that's one of Python
(and Smalltalk, and Lisp etc) strongest points.

If you are concerned you may get incompatible types passed to a
function you can use try/except to catch a TypeError  and deal
with it.

def aFunction(aParameter):
    try:
       # some code
    except TypeError:
       # set a default or raise it further.

This is muich more flexible since your function can then
deal with types that haven't even been invented yet!
(like user defined classes etc)

In the few cases where you do really want to test explicit types
there is the type() function which can be used to compare an
unknown to a known:

if type(foo) == type(""): print 'a string'

To mae that slightly more readable there is the types module which
contains definitions for the standard types.

> The second question I have is does Python have a way of testing for
> instances like Java does?  For example, the "instanceof" operator

There is, but I've yet to find an use for it. Maybe somebody else
has played with it.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From klappnase at freenet.de  Tue Aug 12 12:25:48 2003
From: klappnase at freenet.de (klappnase)
Date: Tue Aug 12 18:22:34 2003
Subject: [Tutor] help on string replacement in a file
In-Reply-To: <BAY1-F93y3GwJKMb38100033e91@hotmail.com>
References: <BAY1-F93y3GwJKMb38100033e91@hotmail.com>
Message-ID: <20030812112548.4fe9d1cf.klappnase@freenet.de>

On Tue, 12 Aug 2003 13:32:28 +0800
"kamariah lamim" <klhjhm@hotmail.com> wrote:

> Thank you for your code.
> may i know what i does it means by inplace?
> 

> >
> >I am not sure about that, but I think you should use the fileinput module 
> >for that, like:
> >
> >def modify5File():
> >     for line in fileinput.input(path-to-file, inplace=1):
> >         line = line.replace('+0.2000000000d+00', '0.678')
> >         sys.stdout.write(line)
> >
> >This should replace every '+0.2000000000d+00' in the file with '0.678' .
> >
> >Best regards
> >
> >Michael
> >
>
Hi,

the library reference says on this:

Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup='.<some extension>' is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. 

I hope this helps

Best regards

Michael

From idiot1 at netzero.net  Tue Aug 12 19:22:59 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Tue Aug 12 18:23:15 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <200308112005.23974.shalehperry@comcast.net>
References: <BB5D2231.BD08%clay@shirky.com> <3F37C196.6010107@netzero.net>
	<200308112005.23974.shalehperry@comcast.net>
Message-ID: <3F3968C3.1060502@netzero.net>



Sean 'Shaleh' Perry wrote:

> On Monday 11 August 2003 09:17, Kirk Bailey wrote:
> 
>>IN fact, I did indeed just place an order with amazon for 'Textprocessing
>>in Python" as it is language specific, addresses re rather well according
>>to opion and review, and also covers other non re aspects of mangling text
>>in the language of choice.
>>
>>With any luck, it will even contain some silly skits and jokes in the
>>examples, although that's hoping for a bit much. As for dead parrots, all
>>mine are alive, and one is shitting on my sholder right now.
>>
> 
> 
> I would not call it dry reading, but there is not much humor in the book.
>
So I'll break out the Bushnell's...

> Personally, I bought it and returned it.  However for a programmer new to the 
> subject it does cover absolutely all of the possible text processing 
> approaches.
Good reference for my librarypile then- the shelves are overflowing already.
> 
> My one, major beef was the author's insistance on functional programming.  
> Don't get me wrong I enjoy the style, but I dislike authors who push a 
> programming style when the book is not about style.
I can see your point, and certainly not the place for it.

However, did anyone write 'The big dummy's guide to OOP' or 'OOP for the 
compleat idiote'?

Dear GAWHD, don't tell me it's MY karma to learn this stuff until I can write 
it... please. please. brains are steaming now.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From dyoo at hkn.eecs.berkeley.edu  Tue Aug 12 16:38:30 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug 12 18:38:35 2003
Subject: [Tutor] ANN: Baypiggies User Group Meeting, August 13th 7:30pm
Message-ID: <Pine.LNX.4.44.0308121537160.31621-100000@hkn.eecs.berkeley.edu>

Hi everyone,


(Sorry for the late announcement!)


============================================


BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group

When: August 13th, 2003 @ 7:30pm
Where: Carnegie Institute of Washington
       at Stanford University; Palo Alto, CA
Agenda: Python 2.3!
Speaker: Brett Cannon


Brett will be giving a talk on Python 2.3's new features, as well as
the Python development process and his involvement with the python-dev
summaries.

You can find more information (and driving instructions) at:

    http://www.baypiggies.net


Hope to see everyone there!


From magnus at thinkware.se  Wed Aug 13 02:23:22 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Aug 12 19:16:11 2003
Subject: [Tutor] Displaying characters
In-Reply-To: <000601c36109$67b0dd30$c9e40dd5@zeus>
References: <1060614804.3f37b294cf856@webmail.sapo.pt>
	<m3fzk7x66d.fsf@ieee.org>
Message-ID: <5.2.1.1.0.20030813011248.020e6d38@www.thinkware.se>

At 20:04 2003-08-12 +0100, Paulo Baptista wrote:
>Thanks for your help but...
>Well, yes they print, if you do it from the interactive shell, but if you do
>it with a file like c:\python xpto.py this characters wont show up, instead
>they'll print symbols. I'm trying this with windows, but as far as I can
>remember this worked fine with linux.

Python version? From 2.3 you should state what encoding you
use in the beginning of the file. See
http://www.python.org/doc/2.3/whatsnew/section-encodings.html



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From dyoo at hkn.eecs.berkeley.edu  Tue Aug 12 17:48:55 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug 12 19:49:02 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <3F3968C3.1060502@netzero.net>
Message-ID: <Pine.LNX.4.44.0308121538570.31621-100000@hkn.eecs.berkeley.edu>



On Tue, 12 Aug 2003, Kirk Bailey wrote:

> > My one, major beef was the author's insistance on functional
> > programming.  Don't get me wrong I enjoy the style, but I dislike
> > authors who push a programming style when the book is not about style.
>
> I can see your point, and certainly not the place for it.

Hi everyone,


But is there a particular example we can talk about where the author's
"functional" approach is not appropriate?

I thought that David Mertz's articles have been pretty good.  Functional
programming isn't just about style -- in some cases, the functional
approach can avoid silly problems that plague a traditional approach.



But let's take one of his examples from:

    http://gnosis.cx/TPiP/chap3.txt

though and talk about it.  The following code is part of the problem of
making a text block "flush left".  One part of the problem tries to find
the minimum indent level of all the lines in a piece of text.


###
from re import findall,sub
indent = lambda s: reduce(min,map(len,findall('(?m)^ *(?=\S)',s)))
flush_left = lambda s: sub('(?m)^ {%d}' % indent(s),'',s)

if __name__ == '__main__':
    import sys
    print flush_left(sys.stdin.read())
###



Hmmm.  Yikes.  Ok, I do agree with you here.  The statement:

    indent = lambda s: reduce(min,map(len,findall('(?m)^ *(?=\S)',s)))

is overloaded.  *grin*



For those who haven't seen it before: 'lambda' is an operator that creates
simple functions.  Let's rewrite the code above slightly so it's slightly
more familiar looking:

###
def indent(s):
    return reduce(min,map(len,findall('(?m)^ *(?=\S)',s)))
###

This should have the exact same meaning as the lambda statement.  But the
'lambda' here doesn't necessarily make a function more "functional":  we
really do need to look within the heart of the function, and that's where
all that 'reduce' and 'map' stuff comes into play.


Now those things are all functional, and people might not like them too
much unless they've been exposed to functional concepts.  For reference, a
traditional approach to the above might use an explicit for loop:

###
def indent(s):
    results = findall('(?m)^ *(?=\S)',s)
    minimum = len(results[0])
    for r in results:
        if len(r) < minimum:
            minimum = len(r)
    return minimum
###

This explicit looping approach works, but it mixes together applying a
function across a sequence with finding the minimum of the sequence.
There's more potential for programmer error with this approach.



A "functional" approach concentrates on applying functions on our
sequences.  With it, we can often avoid using explicit loops or any
assignments.

They're often easier to debug: if something is going wrong in:

    reduce(min, map(len, findall('(?m)^ *(?=\S)', s)))

then there are at least two ways we can debug this: we can look at the
results of:

    findall('(?m)^ *(?=\S)', s)
    map(len, findall('(?m)^ *(?=\S)', s))


That is, we can take a look at the subexpressions.  If we're getting
unexpected results, then we know exactly where the problem starts.  In
contrast, debugging the traditional approach might involve a more laborous
'tracing' process where we step, statement-by-statement, through the
program.



Furthermore, the functional approach doesn't necessarily have to look
evil; I think we can improve on it quite a bit!  The expression:

    reduce(min,
           map(len, findall('(?m)^ *(?=\S)', s)))


is really non-optimal, because min() knows how to deal with lists.  So we
can simplify the expression down to:

    min(map(len, findall('(?m)^ *(?=\S)', s)))

which actually reads a bit better: "Give us the minimum out of the lengths
of all the indents".  It's just as "functional" as the original code.


Now that we've simplified it a little more, let's test it:

###
>>> def indent(s):
...     return min(map(len,findall('(?m)^ *(?=\S)',s)))
...
>>> indent(' hello\n   this is a test')
1
>>> indent('    hello\n    this is a test\n        ')
4
>>> indent('    hello\n    this is a test\n  \n')
4
###

Hey, look there!  Is that last case a problem or a bug?  Shouldn't it
return 2, since the last line has an indent of two spaces?


Well, how can we debug this?  We can look back at the definition of
indent():

    min(map(len,findall('(?m)^ *(?=\S)',s)))

and assuming that the min() and map()ping steps are working ok, we can
take a look at the findall() subexpression:

###
>>> s = '    hello\n    this is a test\n  \n'
>>> findall('(?m)^ *(?=\S)',s)
['    ', '    ']
###

And we can verify that the problem isn't really a problem: the regular
expression only pays attention to lines that aren't empty, so the indent()
function is doing the right job.

We were able to check this casually, without too much pain, precisely
because the function was written in a functional style: it let us pinpoint
our search down to a particular subexpression.



Going back to the other, non-functional approach to indent():

###
def indent(s):
    results = findall('(?m)^ *(?=\S)',s)
    minimum = len(results[0])
    for r in results:
        if len(r) < minimum:
            minimum = len(r)
    return minimum
###

debugging something like this might involve more work.  Did we mess up our
loop, for example?  Or is the assignment not working the way we expect?
There are simply more factors to consider here, and pinpointing the
problem now involves stepping through each statement to find out at what
point things start turning sour.

Of course, it's not difficult in this example to pinpoint our confusion
down to the findall() regular expression statement (since it's the very
first statement... *grin*), but I hope the point about the advantage of
debugging a functional program is more clear.



Please feel free to ask more questions about this.  Good luck to you!


From amonroe at columbus.rr.com  Tue Aug 12 22:06:35 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue Aug 12 21:02:17 2003
Subject: [Tutor] wiki madness grows one you like a brain fungus [regex
	refinements, re.sub() can take in a subst. function]
In-Reply-To: <3F3968C3.1060502@netzero.net>
References: <BB5D2231.BD08%clay@shirky.com> <3F37C196.6010107@netzero.net>
	<200308112005.23974.shalehperry@comcast.net>
	<3F3968C3.1060502@netzero.net>
Message-ID: <9437542643.20030812210635@columbus.rr.com>


> However, did anyone write 'The big dummy's guide to OOP' or 'OOP for the
> compleat idiote'?

Not sure, but I hope the same guy writes "Design Patterns for the
Compelete Idiot" too, because the few books I've flipped through so
far were a little beyond my hobby level.

Somewhere on the net, I once saw someone spoofing these types of books
with the fictitious title "Idiot's Guide to Unleashing your Inner
Dummy in 21 Days!" :^)

Alan


From dyoo at hkn.eecs.berkeley.edu  Tue Aug 12 19:55:14 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug 12 21:55:20 2003
Subject: [Tutor] [Off-topic rant on the title of the "Dummies/Idiots/Morons"
 book series]
In-Reply-To: <9437542643.20030812210635@columbus.rr.com>
Message-ID: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>



On Tue, 12 Aug 2003, R. Alan Monroe wrote:

> > However, did anyone write 'The big dummy's guide to OOP' or 'OOP for
> > the compleat idiot'?
>
> Not sure, but I hope the same guy writes "Design Patterns for the
> Compelete Idiot" too, because the few books I've flipped through so far
> were a little beyond my hobby level.

[Off topic rant: sorry, have to get this off my chest!]


False modesty is one thing, but insulting the intelligence of your
readership is just crude.  The real beef I have about the "Idiot" books is
the implication that the people who read the books are incurable idiots.
I shiver whenever I read some title at the bookstore like "Internet
Security for Idiots".  Do I really want idiots anywhere near my firewalls
or handling any of my security?


My attitude might be better if the book series wore titles like:

    "*Foobar* for the Ignorant"

because ignorance is very curable.  Paradoxically though, I think
"ignorant" has an even uglier connotation in English than "idiot", perhaps
because being an idiot automatically qualifies one to reliquish some
responsibility: if one is an idiot, he or she has perfectly good reasons
for not understanding anything.  Someone can be a "lovable idiot", to be
pitied, but I've seldom heard of someone being a "lovable ignoramus".


If anything, I'd love to see something like:

    "The Apprentice's Guide to Learning Python"

because "apprentice" strikes the right balance of the kind of person who
doesn't quite have enough experience yet in a particular field, but who is
very willing to learn.  It makes no statement on the person's expertise in
anything else, and that's exactly right.  Expertise is not intrinstic, and
it can be learned with experience.


Dunno why I get fired up about these issues.  Naming is very important to
programmers, I guess.  *grin* Please forgive me for my rant.


From clay at shirky.com  Wed Aug 13 00:12:42 2003
From: clay at shirky.com (Clay Shirky)
Date: Tue Aug 12 23:12:55 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <Pine.LNX.4.44.0308121538570.31621-100000@hkn.eecs.berkeley.edu>
Message-ID: <BB5F24EA.BEAD%clay@shirky.com>

> Hmmm.  Yikes.  Ok, I do agree with you here.  The statement:
> 
>   indent = lambda s: reduce(min,map(len,findall('(?m)^ *(?=\S)',s)))
> 
> is overloaded.  *grin*

You know, I picked up that book expecting to love it (almost everything I do
involves processing text in some way or other), but after reading at Ch 1, I
mostly learned that functional programming is a way of making Python look
like Perl.

> For those who haven't seen it before: 'lambda' is an operator that creates
> simple functions.

My impression is that lambda and map/filter/reduce can often be replaced by
list comprehensions. Is this correct?
 
> ###
> def indent(s):
>   results = findall('(?m)^ *(?=\S)',s)
>   minimum = len(results[0])
>   for r in results:
>       if len(r) < minimum:
>           minimum = len(r)
>   return minimum
> ###

This is *so* much more readable than the above.
 
> This explicit looping approach works, but it mixes together applying a
> function across a sequence with finding the minimum of the sequence.
> There's more potential for programmer error with this approach.

I'm skeptical about this. This assumes that most programmer error comes from
writing rather than maintaining code. If you think the code will get written
once and read often, the risk of error from semantic density grows.
 
> Of course, it's not difficult in this example to pinpoint our confusion
> down to the findall() regular expression statement (since it's the very
> first statement... *grin*), but I hope the point about the advantage of
> debugging a functional program is more clear.

Well this is the ironic part. The problem in this example is in the regex,
and since the regex is an explicit assignment and first, you'll catch it
*faster* with a step-through approach than you would in the functional
approach, esp if you assume that the person doing the debugging is different
from the person doing the coding. Furthermore, since regexes are usually
more problematic than assignments or loops, being able to zero in on that is
easier with an explicit assignment from findall.

>From looking at TPiP, it looks to me like FP takes some basically sensible
ideas -- the easiest loop to debug is the loop you don't write, nested
transformations can make the operations on an object clear -- and makes them
cardinal virtues, at the risk of losing things like readability and obvious
flow.

-clay


From carroll at tjc.com  Tue Aug 12 22:11:42 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug 13 00:11:45 2003
Subject: [Tutor] Converting ascii string to hex?
Message-ID: <Pine.LNX.4.44.0308122108440.24074-100000@violet.rahul.net>

Is there a straightforward way to convert an ascii string to printable 
hexadecimal?

I've kludged up this, but there has to be a cleaner way:

>>> def asctohex(string_in):
...     a=""
...     for x in string_in:
...         a = a + (hex(ord(x)))[2:4]
...     return(a)
...
>>> print asctohex("a 1")
612031
>>>

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From carroll at tjc.com  Tue Aug 12 22:57:12 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug 13 00:57:16 2003
Subject: [Tutor] Converting ascii string to hex?
In-Reply-To: <Pine.LNX.4.44.0308122108440.24074-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0308122143410.24074-100000@violet.rahul.net>

On Tue, 12 Aug 2003, Terry Carroll wrote:

> >>> def asctohex(string_in):
> ...     a=""
> ...     for x in string_in:
> ...         a = a + (hex(ord(x)))[2:4]
> ...     return(a)

I've also noticed this gives erroneous results where the input string 
includes a character whose hex value is <16, because Python represents 
these as, e.g. decimal 10 ==> "0xa" rather than "0x0a".

Here's an even more kludy (but more working version:

>>> def asctohex(string_in):
...     a=""
...     for x in string_in:
...         a = a + ("0"+((hex(ord(x)))[2:]))[-2:]
...     return(a)
...
>>> print asctohex("a 1")
612031
>>> print asctohex(chr(10))
0a
>>>

There *is* a cleaner way, isn't there?  Is there nothing akin to what I 
imagine would be simply 

 hex(s)

where "s" is a string?

The above feels like I'm writing in Perl again.


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From shalehperry at comcast.net  Tue Aug 12 23:26:19 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 13 01:26:55 2003
Subject: [Tutor] [Off-topic rant on the title of the
	"Dummies/Idiots/Morons" book series]
In-Reply-To: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
Message-ID: <200308122226.19336.shalehperry@comcast.net>

On Tuesday 12 August 2003 18:55, Danny Yoo wrote:
>
> because ignorance is very curable.  Paradoxically though, I think
> "ignorant" has an even uglier connotation in English than "idiot", perhaps
> because being an idiot automatically qualifies one to reliquish some
> responsibility: if one is an idiot, he or she has perfectly good reasons
> for not understanding anything.  Someone can be a "lovable idiot", to be
> pitied, but I've seldom heard of someone being a "lovable ignoramus".
>
>

When I worked tech support one of the things I routinely told people was:

Ignorance is the lack of knowledge, stupidity is the inability to learn.

Most of my callers took heart in this and it helped move them forward.  I tell 
the same thing to newbies on the various lists I read.

Danny, many of us agree with you on the naming thing.


From shalehperry at comcast.net  Tue Aug 12 23:28:34 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 13 01:29:08 2003
Subject: [Tutor] ANN: Baypiggies User Group Meeting, August 13th 7:30pm
In-Reply-To: <Pine.LNX.4.44.0308121537160.31621-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308121537160.31621-100000@hkn.eecs.berkeley.edu>
Message-ID: <200308122228.34920.shalehperry@comcast.net>

On Tuesday 12 August 2003 15:38, Danny Yoo wrote:
>
>
> BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group
>
> When: August 13th, 2003 @ 7:30pm
> Where: Carnegie Institute of Washington
>        at Stanford University; Palo Alto, CA
> Agenda: Python 2.3!
> Speaker: Brett Cannon
>

Unfortunately these tend to coincide with the Bay Area Debian get togethers.  
Tomorrow's is at Triple Rock in Berkeley.  We have 10 years of Debian to 
celebrate!

(For those who do not know, Debian is one of the first Linux distributions and 
is 100% run and maintained by volunteers for fun.  No money is involved)


From shalehperry at comcast.net  Tue Aug 12 23:39:45 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 13 01:40:19 2003
Subject: [Tutor] Converting ascii string to hex?
In-Reply-To: <Pine.LNX.4.44.0308122143410.24074-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0308122143410.24074-100000@violet.rahul.net>
Message-ID: <200308122239.45357.shalehperry@comcast.net>

On Tuesday 12 August 2003 21:57, Terry Carroll wrote:
>
> There *is* a cleaner way, isn't there?  Is there nothing akin to what I
> imagine would be simply
>
>  hex(s)
>
> where "s" is a string?
>
> The above feels like I'm writing in Perl again.

def asctohex(s):
    empty = '' # I use this construct because I find ''.join() too dense
    return empty.join(['%02x' % ord(c) for c in s]) # the %02 pads when needed

or for those eschewing list comps:
    return empty.join(map(lambda c: '%02x' % ord(c), s))


From qsc at icon.co.za  Wed Aug 13 09:03:20 2003
From: qsc at icon.co.za (Quentin)
Date: Wed Aug 13 02:03:29 2003
Subject: [Tutor] [Off-topic rant on the title of the
	"Dummies/Idiots/Morons" book series]
In-Reply-To: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F39D4A8.5090504@icon.co.za>

Yup, and it seems like they are written by idiots as well.
Years ago I tried to learn C++. The first book I bought was an Idiots 
guide to C++ (Only one on it in the store). It was also the last.
I got peeved when this "idiot" found errors in the examples, and quite a 
few of them.
I don't normally throw books away I payed for, this one I did.
I felt like an idiot for buying the book in the first place.

And I never got into C++, but personally, I did not like it.

Quentin


From magnus at thinkware.se  Wed Aug 13 10:49:25 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Aug 13 03:42:15 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <BB5F24EA.BEAD%clay@shirky.com>
References: <Pine.LNX.4.44.0308121538570.31621-100000@hkn.eecs.berkeley.edu>
Message-ID: <5.2.1.1.0.20030813093116.0216fe90@www.thinkware.se>

At 23:12 2003-08-12 -0400, Clay Shirky wrote:
>My impression is that lambda and map/filter/reduce can often be replaced by
>list comprehensions. Is this correct?

List comprehension replaces map and filter (with lambdas) but
not reduce, so it doesn't do what reduce does, and in cases where
filter would return a string or a list, list comprehension will
still return a list.

E.g.

map(lambda x: x*x, l)    => [x*x for x in l]
filter(lambda x: x<5, l) => [x for x in l if x < 5]

The big syntactical gain comes when you would have combined map and filter:

map(lambda x: x*x, filter(lambda x: x<5, l)) => [x*x for x in l if x < 5]

Reduce is typically easiest to replace with a loop if
you want to avoid it, as in:

import operator
sum = reduce(operator.add, l)

sum = 0
for i in l: sum += i

For this particular case there is a builtin sum() function though.

aSum = sum(l)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From alan.gauld at blueyonder.co.uk  Wed Aug 13 09:48:00 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug 13 03:48:05 2003
Subject: [Tutor] Text processing and functional programming?
References: <BB5F24EA.BEAD%clay@shirky.com>
Message-ID: <004901c3616f$38714f80$6401a8c0@xp>

> You know, I picked up that book expecting to love it (almost
everything I do
> involves processing text in some way or other), but after reading at
Ch 1, I
> mostly learned that functional programming is a way of making Python
look
> like Perl.

I reviewed Mertz' book and one of my comments was that he needed
to expand the explanation of FP because even intermediate Python
programmers often avoid the FP stuff. In response the explanation
did almost double. But the point remains that FP is foreign
territory to many programmers.

> My impression is that lambda and map/filter/reduce can often be
replaced by
> list comprehensions. Is this correct?

Often, not always. And comprehensions are confusing in themselves
(although powerful) and 'filter' or 'map' is a much more descriptive
term for whats going on. Unfortunately FP is heavily geared toward
those with a formal math training, particularly those who have
studied predicate logic and the lambda calculus. If you haven't
(and that means most of us!) then FP can seem extremely arcane.

> > This explicit looping approach works, but it mixes together
applying a
> > function across a sequence with finding the minimum of the
sequence.
> > There's more potential for programmer error with this approach.
>
> I'm skeptical about this.

You shouldn't be, its based on many years of study and data
collection.
One of the definite advantages of FP is that it leads to more reliable
(note this is different from easy to debug!) code because it removes
complexity (in the CS sense not the human eye sense).

What that means is that given a programmer who is as fluent in FP as
in imperitive programming, his FP code will contain fewer errors.

> This assumes that most programmer error comes from
> writing rather than maintaining code.

No, actually it assumes most error comes in the translation
from design to source code. "Off by one" index errors etc.
Again thats based on empirical studies into the nature of
software faults.

> From looking at TPiP, it looks to me like FP takes some basically
sensible
> ideas -- the easiest loop to debug is the loop you don't write,
nested
> transformations can make the operations on an object clear -- and
makes them
> cardinal virtues, at the risk of losing things like readability and
obvious
> flow.

That's a pretty good summary. It is more demanding of the programmer
but
offers, in return, shorter code, more error free code and often more
performant code. But its harder for the non expert to read and
maintain
and often a nighmare to debug with conventional tools.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Wed Aug 13 09:51:57 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug 13 03:52:06 2003
Subject: [Tutor] [Off-topic rant on the title of
	the"Dummies/Idiots/Morons" book series]
References: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
	<200308122226.19336.shalehperry@comcast.net>
Message-ID: <004e01c3616f$c5316a40$6401a8c0@xp>

Sean wrote:
> Ignorance is the lack of knowledge, stupidity is the inability to
learn.
>
> Danny, many of us agree with you on the naming thing.

The name doesn't bother me, I proudly display two ...for Dummies'
books on my shelves :-)

However I am currently teaching myself to program my Apple iBook
using Cocoa and Objective C and the book I'm using contains this
fantastic bit of advice:

"Whenever things don't work out as you expected just repeat:
'Programming is hard and I am not stupid!'"

I thought that was great.

Alan G.


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 13 02:14:01 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 13 04:14:32 2003
Subject: [Tutor] [Off-topic rant on the title of the"Dummies/Idiots/Morons"
	book series]
In-Reply-To: <004e01c3616f$c5316a40$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0308130111470.18864-100000@hkn.eecs.berkeley.edu>


> "Whenever things don't work out as you expected just repeat:
> 'Programming is hard and I am not stupid!'"

Ah, I remember that phrase.  You're reading Aaron Hillegass's "Cocoa
Programming for Mac OS X", aren't you?  *grin*


Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 13 02:32:41 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 13 04:32:51 2003
Subject: [Tutor] Converting ascii string to hex?
In-Reply-To: <Pine.LNX.4.44.0308122143410.24074-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0308130125540.18864-100000@hkn.eecs.berkeley.edu>



> Here's an even more kludy (but more working version:
>
> >>> def asctohex(string_in):
> ...     a=""
> ...     for x in string_in:
> ...         a = a + ("0"+((hex(ord(x)))[2:]))[-2:]
> ...     return(a)
> ...
> >>> print asctohex("a 1")
> 612031
> >>> print asctohex(chr(10))
> 0a
> >>>
>
> There *is* a cleaner way, isn't there?  Is there nothing akin to what I
> imagine would be simply
>
>  hex(s)
>
> where "s" is a string?


Hi Terry,

Yes: check the 'binascii' module:

    http://www.python.org/doc/lib/module-binascii.html#l2h-3835

binascii.hexlify() should do the trick:

###
>>> binascii.hexlify('hello world')
'68656c6c6f20776f726c64'
###


binascii.unhexlify('486f706520746869732068656c707321')


From gnux at freesurf.fr  Wed Aug 13 15:16:07 2003
From: gnux at freesurf.fr (gnux@freesurf.fr)
Date: Wed Aug 13 08:47:53 2003
Subject: [Tutor] Coding a ftp client thx to python+C
Message-ID: <1391.80.13.246.200.1060776967.squirrel@jose.freesurf.fr>

Hi
Do u think it's possible to code such a thing?
It would be great:)
The matter is I don't know if it was ever done and where I can find some
docs about that point.
So will be very pleased if u got suggestion of reading or anything else
about coding such a thing.
Thx


----------------------------------------------------------------
Ce service de mailing vous est offert par http://www.freesurf.fr.
FreeSurf, votre acces ADSL a partir de 29 euros/mois
http://www.freesurf.fr/adsl/



From marc_barry at hotmail.com  Wed Aug 13 10:59:29 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Wed Aug 13 10:00:04 2003
Subject: [Tutor] Iterators and Generators...
Message-ID: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>

Dear All:

I have a class which is an iterator, but I can't figure out why it is not 
working.  I have included a pointless example to illutsrate what is 
happening.  I have created a class called list_iterator that implements the 
iterator protocol over a list.  I know that that this is already done for 
lists, but it shows the problem I am having.  Here is the Python code:

#-----

class list_iterator:

	def __init__(self, a_list):
		self.a_list = a_list

	def __iter__(self):
		return self

	def next(self):
		for i in self.a_list:
			yield i
		raise StopItertion

a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])

for i in a_list_iterator:
	print i

#-----

When I run the above, I expected the following output:

1
2
3
4
5
6
7
8
9
10

Instead, I get something similar to the following:

<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
<generator object at 0x007EA418>
<generator object at 0x007EA328>
...  Well you get the point, it just loops forever.  Also, my yeild 
statement seems to be retruning a generator object instead of the number.  
Also, it never reaches the 'raise' statement.  Obviously, there is a flaw in 
my understanding of how to use a generator and the iterator protocol.  Can 
anyone clear this up for me?

Regards,

Marc

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From glingl at aon.at  Wed Aug 13 18:45:27 2003
From: glingl at aon.at (Gregor Lingl)
Date: Wed Aug 13 11:43:18 2003
Subject: [Tutor] Iterators and Generators...
References: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
Message-ID: <3F3A5D17.3040600@aon.at>

Marc Barry schrieb:

> Dear All:
>
> I have a class which is an iterator, but I can't figure out why it is 
> not working.  I have included a pointless example to illutsrate what 
> is happening.  I have created a class called list_iterator that 
> implements the iterator protocol over a list.  I know that that this 
> is already done for lists, but it shows the problem I am having.  Here 
> is the Python code:
>
> #-----
>
> class list_iterator:
>
>     def __init__(self, a_list):
>         self.a_list = a_list
>
>     def __iter__(self):
>         return self
>
>     def next(self):
>         for i in self.a_list:
>             yield i
>         raise StopItertion

To define an iterator you must or need not use generators, i. e.
the keyword yield. (This makes next a generator, therefore your strange 
output)
I think, one should try to understand itrators and generators als
different concepts.

Instead this might work:

class list_iterator:

    def __init__(self, a_list):
        self.a_list = a_list
        self.i = 0

    def __iter__(self):
        return self

    def next(self):
        try:
            value = self.a_list[self.i]
        except:
            raise StopIteration
        self.i += 1
        return value
   
 >>> a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])
 >>> for v in a_list_iterator:
    print v,

   
1 2 3 4 5 6 7 8 9 10

Regards, Gregor

>
> a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])
>
> for i in a_list_iterator:
>     print i
>
> #-----
>
> When I run the above, I expected the following output:
>
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> 10
>
> Instead, I get something similar to the following:
>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> <generator object at 0x007EA418>
> <generator object at 0x007EA328>
> ...  Well you get the point, it just loops forever.  Also, my yeild 
> statement seems to be retruning a generator object instead of the 
> number.  Also, it never reaches the 'raise' statement.  Obviously, 
> there is a flaw in my understanding of how to use a generator and the 
> iterator protocol.  Can anyone clear this up for me?
>
> Regards,
>
> Marc
>
> _________________________________________________________________
> Protect your PC - get McAfee.com VirusScan Online  
> http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>





From nas-pytut at python.ca  Wed Aug 13 09:49:48 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Wed Aug 13 11:43:50 2003
Subject: [Tutor] Iterators and Generators...
In-Reply-To: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
References: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
Message-ID: <20030813154948.GA28040@glacier.arctrix.com>

Marc Barry wrote:
> I have a class which is an iterator, but I can't figure out why it is not 
> working.

This is probably what you want:

    class list_iterator:

            def __init__(self, a_list):
                    self.a_list = a_list

            def __iter__(self):
                    for i in self.a_list:
                            yield i

A function containing a 'yield' statement returns a generator when it is
called.  Calling '.next()' on that generator object starts executation
of the function body until a yield statement is reached (and so on).  If
the end of the function is reached then StopIteration is raised.

HTH,

  Neil

From op73418 at mail.telepac.pt  Wed Aug 13 17:48:31 2003
From: op73418 at mail.telepac.pt (Rodrigues)
Date: Wed Aug 13 11:47:57 2003
Subject: [Tutor] Iterators and Generators...
In-Reply-To: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKMEGACBAA.op73418@mail.telepac.pt>



> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
> Behalf Of Marc Barry
> Sent: quarta-feira, 13 de Agosto de 2003 14:59
> To: tutor@python.org
> Subject: [Tutor] Iterators and Generators...
>
>
> Dear All:
>
> I have a class which is an iterator, but I can't figure out
> why it is not
> working.  I have included a pointless example to illutsrate what is
> happening.  I have created a class called list_iterator
> that implements the
> iterator protocol over a list.  I know that that this is
> already done for
> lists, but it shows the problem I am having.  Here is the
> Python code:
>
> #-----
>
> class list_iterator:
>
> 	def __init__(self, a_list):
> 		self.a_list = a_list
>
> 	def __iter__(self):
> 		return self
>
> 	def next(self):
> 		for i in self.a_list:
> 			yield i
> 		raise StopItertion
>
>

I do not have time to explain much now, but I'll just give you the
correct code:

>>> class list_iter(object):
... 	def __init__(self, lst):
... 		self.list = lst
... 	def __iter__(self):
... 		for i in self.list:
... 			yield i
...
>>> a = list_iter(range(1, 11))
>>> for i in a:
... 	print i
...
1
2
3
4
5
6
7
8
9
10


You are aware though that iter(a_list) does exactly the same as above,
no?

With my best regards,
G. Rodrigues


From glingl at aon.at  Wed Aug 13 18:56:45 2003
From: glingl at aon.at (Gregor Lingl)
Date: Wed Aug 13 11:54:34 2003
Subject: [Tutor] Iterators and Generators...
References: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
	<20030813154948.GA28040@glacier.arctrix.com>
Message-ID: <3F3A5FBD.8090305@aon.at>

Neil Schemenauer schrieb:

>Marc Barry wrote:
>  
>
>>I have a class which is an iterator, but I can't figure out why it is not 
>>working.
>>    
>>
>
>This is probably what you want:
>
>    class list_iterator:
>
>            def __init__(self, a_list):
>                    self.a_list = a_list
>
>            def __iter__(self):
>                    for i in self.a_list:
>                            yield i
>  
>

Doesn't this one do exactly the same (without using classes):

 >>> def list_iterator(a_list):
    for item in a_list:
        yield item

       
 >>> li = list_iterator([1,2,3])
 >>> li.next()
1
 >>> while 1:
    try:
              print li.next()
        except:
              break

2
3

Reagards, Gregor

>A function containing a 'yield' statement returns a generator when it is
>called.  Calling '.next()' on that generator object starts executation
>of the function body until a yield statement is reached (and so on).  If
>the end of the function is reached then StopIteration is raised.
>
>HTH,
>
>  Neil
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>





From sigurd at 12move.de  Wed Aug 13 19:06:42 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Aug 13 12:09:19 2003
Subject: [Tutor] Iterators and Generators...
In-Reply-To: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com> (Marc Barry's message
	of "Wed, 13 Aug 2003 09:59:29 -0400")
References: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
Message-ID: <m3isp1pn1v.fsf@hamster.pflaesterer.de>

On 13 Aug 2003, Marc Barry <- marc_barry@hotmail.com wrote:

> class list_iterator:

> 	def __init__(self, a_list):
> 		self.a_list = a_list

> 	def __iter__(self):
> 		return self
                           ^^^^
here you should call your next method

> 	def next(self):
> 		for i in self.a_list:
> 			yield i
> 		raise StopItertion
                             ^^
StopIteration

> a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])

> for i in a_list_iterator:
> 	print i

[...]
> Instead, I get something similar to the following:

> <generator object at 0x007EA328>
[...]

> ...  Well you get the point, it just loops forever.  Also, my yeild
> statement seems to be retruning a generator object instead of the
> number.  Also, it never reaches the 'raise' statement.  Obviously,
> there is a flaw in my understanding of how to use a generator and the
> iterator protocol.  Can anyone clear this up for me?

You never called your next() method (and you have a typo); I underlined
both in your example.

So the correct code would be:

class list_iterator:
        def __init__(self, a_list):
                self.a_list = a_list

        def __iter__(self):
                return self.next()

        def next(self):
                for i in self.a_list:
                        yield i
                raise StopIteration

# Example in IPython
In [32]: a_list_iterator = list_iterator([1,2,3,4,5,6,7,8,9,10])

In [33]: for i in a_list_iterator:
   ....:     print i
   ....: 
1
2
3
4
5
6
7
8
9
10


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From nas-pytut at python.ca  Wed Aug 13 10:24:26 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Wed Aug 13 12:18:26 2003
Subject: [Tutor] Iterators and Generators...
In-Reply-To: <m3isp1pn1v.fsf@hamster.pflaesterer.de>
References: <Sea2-F25T83Hlqsv3W10000eb3c@hotmail.com>
	<m3isp1pn1v.fsf@hamster.pflaesterer.de>
Message-ID: <20030813162426.GA28241@glacier.arctrix.com>

Karl Pfl?sterer wrote:
> You never called your next() method (and you have a typo); I underlined
> both in your example.
> 
> So the correct code would be:
> 
> class list_iterator:
>         def __init__(self, a_list):
>                 self.a_list = a_list
> 
>         def __iter__(self):
>                 return self.next()
> 
>         def next(self):
>                 for i in self.a_list:
>                         yield i
>                 raise StopIteration

Yikes.  There's no need to explicitly raise StopIteration.  Also, the
'next' method could be called anything.  Don't get confused that the
name is somehow special.  For example, the following code does exactly
the same thing:

class list_iterator:
        def __init__(self, a_list):
                self.a_list = a_list

        def __iter__(self):
                return self.pumpkin()

        def pumpkin(self):
                for i in self.a_list:
                        yield i

Furthermore, you don't need the extra method if you put the yield loop
in the __iter__ method.

  Neil

From magnus at thinkware.se  Wed Aug 13 22:24:40 2003
From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Aug 13 15:17:26 2003
Subject: [Tutor] Best approach to sort data based on several
  criteria
In-Reply-To: <m3adb8x7kz.fsf@ieee.org>
Message-ID: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se>

At 11:44 2003-07-21 -0300, Jorge Godoy wrote:
>I have a huge amount of data that's stored in a file where each record
>is in a line made of 22 columns, and each column is separated from the
>other by a ';'.
>
>I need to show this data (some columns each time) sorted out
>accordingly to some columns (e.g. columns zero, one, five and six,
>each on a different view and in one of these views, I need to sort
>based on multiple keys).

The fastest approach in Python is typically to transform your
data into a list which can be sorted directly with the list.sort()
method.

You can supply a function to the sort method call, but that makes
sorting much slower. For big lists with high performance requirements,
it's typically faster to create a new list that can be sorted as is.

This is sometimes called a Schwartzian transform, after Perl guru
Randal Schwartz. What you do in Python is to change a list of rows
to a list of tuples: (sort_criteria, row), then sort it, and finally
transform it back to the list of rows without the preceding sort
criteria. This will also work with dates if they are given as
objects of some date type/class such as mx.DateTime or the new
datetime class in 2.3, or in a sane string format, such as ISO 8601.

It could look something like this:

 >>> l = [('a', 2),
          ('c', 1),
          ('b', 3)]
 >>> col = 0
 >>> for i, row in enumerate(l):
         l[i] = (row[col], row)

 >>> l.sort()
 >>> for i, row in enumerate(l):
         l[i] = row[1]

 >>> l
[('a', 2), ('b', 3), ('c', 1)]
 >>> col = 1
 >>> for i, row in enumerate(l):
         l[i] = (row[col], row)

 >>> l.sort()
 >>> for i, row in enumerate(l):
         l[i] = row[1]

 >>> l
[('c', 1), ('a', 2), ('b', 3)]


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 


From justin at unixremedies.com  Wed Aug 13 15:26:11 2003
From: justin at unixremedies.com (Justin Heath)
Date: Wed Aug 13 15:38:52 2003
Subject: [Tutor] Command lines args (getopt)
Message-ID: <3F3A90D3.8040308@unixremedies.com>

All,

I am getting upwards of single character arguments that make sense for a 
program I am writing. I am using getopt to parse the arguments. My 
question is I would like to use two character short options such as -lu 
(for local user) and -ru (for remote user). I know I can acomplish this 
(well almost) with long opts such as --ru, but I am trying to stay away 
from that. Any suggestions?

Thanks,
Justin



From david at graniteweb.com  Wed Aug 13 15:55:13 2003
From: david at graniteweb.com (David Rock)
Date: Wed Aug 13 15:55:49 2003
Subject: [Tutor] Command lines args (getopt)
In-Reply-To: <3F3A90D3.8040308@unixremedies.com>
References: <3F3A90D3.8040308@unixremedies.com>
Message-ID: <20030813195513.GA26699@wdfs.graniteweb.com>

* Justin Heath <justin@unixremedies.com> [2003-08-13 14:26]:
> All,
> 
> I am getting upwards of single character arguments that make sense for a 
> program I am writing. I am using getopt to parse the arguments. My 
> question is I would like to use two character short options such as -lu 
> (for local user) and -ru (for remote user). I know I can acomplish this 
> (well almost) with long opts such as --ru, but I am trying to stay away 
> from that. Any suggestions?

I would recommend just living with how the options are designed, an
extra hyphen won't kill you ;-)

If you MUST do it this way, try defining the short option so that it
expects a value (e.g. local user -> l:) and just treat the "u" as the
argument to the option. I have not tried this, but I see no reason why
this wouldn't work except if you have a -u option, maybe.

There is a new option parser in Python 2.3 that may have something
different for "long-short" options, but I have not looked in great
depth, yet.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030813/d1c5c84c/attachment.bin
From clay at shirky.com  Wed Aug 13 18:27:20 2003
From: clay at shirky.com (Clay Shirky)
Date: Wed Aug 13 17:27:34 2003
Subject: [Tutor] Command lines args (getopt)
In-Reply-To: <3F3A90D3.8040308@unixremedies.com>
Message-ID: <BB602578.BF37%clay@shirky.com>

> I am getting upwards of single character arguments that make sense for a
> program I am writing. I am using getopt to parse the arguments. My
> question is I would like to use two character short options such as -lu
> (for local user) and -ru (for remote user). I know I can acomplish this
> (well almost) with long opts such as --ru, but I am trying to stay away
> from that. Any suggestions?

My suggestion is don't stay away from long opts.

The heuristic for long opts is when you get upwards of single character
arguments that make sense, so don't just add long opts, add them in a way
that makes them readable, as in --remote and --local, or --ruser and
--luser, or whatever makes them comprehensible to your users.

-clay


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 13 15:36:07 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 13 17:36:20 2003
Subject: [Tutor] Coding a ftp client thx to python+C
In-Reply-To: <1391.80.13.246.200.1060776967.squirrel@jose.freesurf.fr>
Message-ID: <Pine.LNX.4.44.0308131434070.12147-100000@hkn.eecs.berkeley.edu>



On Wed, 13 Aug 2003 gnux@freesurf.fr wrote:

> Do u think it's possible to code such a thing?
> It would be great:)


Yes, it would be very possible.  There's a module called 'ftplib' that you
can take advantage of:

    http://www.python.org/doc/lib/module-ftplib.html

It's very bare-bones though: you will probably need to do some work to
make it more useable.  But it's enough to do certain automated tasks with
FTP.


Good luck to you!


From carroll at tjc.com  Wed Aug 13 15:38:57 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug 13 17:39:01 2003
Subject: [Tutor] Converting ascii string to hex?
In-Reply-To: <Pine.LNX.4.44.0308130125540.18864-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0308131438220.5487-100000@violet.rahul.net>

On Wed, 13 Aug 2003, Danny Yoo wrote:

> binascii.hexlify() should do the trick:

Ah, this looks like it's exactly what I was looking for.  Thanks!


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 13 16:02:48 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 13 18:02:55 2003
Subject: [Tutor] Best approach to sort data based on several  criteria
In-Reply-To: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se>
Message-ID: <Pine.LNX.4.44.0308131436490.12147-100000@hkn.eecs.berkeley.edu>



> >I have a huge amount of data that's stored in a file where each record
            ^^^^^^^^^^^^^^^^^^^
> >is in a line made of 22 columns, and each column is separated from the
> >other by a ';'.


Hi Jorge,

Hmmm... When you say "huge amount of data", can you be more specific? If
you're taking about several megabytes, then we don't have much to worry
about.  But if we're talking about hundreds of megabytes (or even
gigabytes), then we have to be a bit more careful.


If your set of data is really humongous, you may want to consider using a
database management system --- such as PostgreSQL or MySQL --- to do the
brunt of the sorting and storage grunt work.  Can you give us an estimate
of how large your dataset's going to be?


Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 13 16:13:59 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 13 18:14:03 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <BB5F24EA.BEAD%clay@shirky.com>
Message-ID: <Pine.LNX.4.44.0308131504120.12147-100000@hkn.eecs.berkeley.edu>



On Tue, 12 Aug 2003, Clay Shirky wrote:

> My impression is that lambda and map/filter/reduce can often be replaced by
> list comprehensions. Is this correct?
>
> > ###
> > def indent(s):
> >   results = findall('(?m)^ *(?=\S)',s)
> >   minimum = len(results[0])
> >   for r in results:
> >       if len(r) < minimum:
> >           minimum = len(r)
> >   return minimum
> > ###
>
> This is *so* much more readable than the above.


Hi Clay,


Hmmm... Ok, fair enough.  How about this?

###
def indent(s):
    results = findall('(?m)^ *(?=\S)',s)
    lengths = map(len, results)
    return min(lengths)
###


I guess I'm trying to argue that we can be pragmatic about this and use
both imperative and functional techniques where they're appropriate.
Functional-style programming doesn't have to be ugly.


That being said, I agree that TPiP is a bit dense, perhaps needlessly so.
Perhaps we can send some feedback to David Mertz so that he can try
revising his code examples for readability's sake, without sacrificing too
much of its functional "purity".


From bgailer at alum.rpi.edu  Wed Aug 13 17:48:17 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed Aug 13 18:49:59 2003
Subject: [Tutor] Best approach to sort data based on several 
  criteria
In-Reply-To: <Pine.LNX.4.44.0308131436490.12147-100000@hkn.eecs.berkeley .edu>
References: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030813164740.02b9fd50@66.28.54.253>

At 03:02 PM 8/13/2003 -0700, Danny Yoo wrote:



> > >I have a huge amount of data that's stored in a file where each record
>             ^^^^^^^^^^^^^^^^^^^
> > >is in a line made of 22 columns, and each column is separated from the
> > >other by a ';'.
>
>
>Hi Jorge,
>
>Hmmm... When you say "huge amount of data", can you be more specific? If
>you're taking about several megabytes, then we don't have much to worry
>about.  But if we're talking about hundreds of megabytes (or even
>gigabytes), then we have to be a bit more careful.
>
>
>If your set of data is really humongous, you may want to consider using a
>database management system --- such as PostgreSQL or MySQL

Please add SQLIte to that list.

>  --- to do the
>brunt of the sorting and storage grunt work.  Can you give us an estimate
>of how large your dataset's going to be?

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From idiot1 at netzero.net  Wed Aug 13 21:58:57 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Aug 13 20:59:49 2003
Subject: [Tutor] [Off-topic rant on the title of the
	"Dummies/Idiots/Morons" book series]
In-Reply-To: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F3ADED1.4000402@netzero.net>

Well then, we could do something on the subject. 'The apprentices guide to oop'. 
WE could make it a community effort for the Python croud.

IN fact, I offer my wiki as the place where one and all may do exactly this.
http://www.tinylist.org/piki.py/OopGuide

Danny Yoo wrote:

> 
> On Tue, 12 Aug 2003, R. Alan Monroe wrote:
> 
> 
>>>However, did anyone write 'The big dummy's guide to OOP' or 'OOP for
>>>the compleat idiot'?
>>
>>Not sure, but I hope the same guy writes "Design Patterns for the
>>Compelete Idiot" too, because the few books I've flipped through so far
>>were a little beyond my hobby level.
> 
> 
> [Off topic rant: sorry, have to get this off my chest!]
> 
> 
> False modesty is one thing, but insulting the intelligence of your
> readership is just crude.  The real beef I have about the "Idiot" books is
> the implication that the people who read the books are incurable idiots.
> I shiver whenever I read some title at the bookstore like "Internet
> Security for Idiots".  Do I really want idiots anywhere near my firewalls
> or handling any of my security?
> 
> 
> My attitude might be better if the book series wore titles like:
> 
>     "*Foobar* for the Ignorant"
> 
> because ignorance is very curable.  Paradoxically though, I think
> "ignorant" has an even uglier connotation in English than "idiot", perhaps
> because being an idiot automatically qualifies one to reliquish some
> responsibility: if one is an idiot, he or she has perfectly good reasons
> for not understanding anything.  Someone can be a "lovable idiot", to be
> pitied, but I've seldom heard of someone being a "lovable ignoramus".
> 
> 
> If anything, I'd love to see something like:
> 
>     "The Apprentice's Guide to Learning Python"
> 
> because "apprentice" strikes the right balance of the kind of person who
> doesn't quite have enough experience yet in a particular field, but who is
> very willing to learn.  It makes no statement on the person's expertise in
> anything else, and that's exactly right.  Expertise is not intrinstic, and
> it can be learned with experience.
> 
> 
> Dunno why I get fired up about these issues.  Naming is very important to
> programmers, I guess.  *grin* Please forgive me for my rant.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Wed Aug 13 22:11:27 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Aug 13 21:12:20 2003
Subject: [Tutor] [Off-topic rant on the title of the
	"Dummies/Idiots/Morons" book series]
In-Reply-To: <39524358107.20030813211331@columbus.rr.com>
References: <Pine.LNX.4.44.0308121820170.6436-100000@hkn.eecs.berkeley.edu>
	<3F3ADED1.4000402@netzero.net>
	<39524358107.20030813211331@columbus.rr.com>
Message-ID: <3F3AE1BF.5010909@netzero.net>

my bad. getting tired. try this instead:
http://www.tinylist.org/cgi-bin/piki.py/OopGuide

R. Alan Monroe wrote:

>>IN fact, I offer my wiki as the place where one and all may do exactly this.
>>http://www.tinylist.org/piki.py/OopGuide
> 
> 
> Pity the url doesn't work :^)
> 
> Alan
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From clay at shirky.com  Wed Aug 13 18:57:19 2003
From: clay at shirky.com (Clay Shirky)
Date: Wed Aug 13 22:00:53 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <004901c3616f$38714f80$6401a8c0@xp>
Message-ID: <BB602C7F.BF3F%clay@shirky.com>

> Often, not always. And comprehensions are confusing in themselves
> (although powerful) and 'filter' or 'map' is a much more descriptive
> term for whats going on.

Then this is probably personal -- coming from perl, I find the naturalness
of pythons list expressions intoxicating, and while I agree that map and
filter are somewhat mnemonic, lambda feels kludgy to me, like "We sure shot
ourselves in the foot there with that 'one argument' limit -- better make a
wrapper for inline functions."

Reading Mark Pilgrim's code, for example, I find the list comprehensions
much clearer than the same constructs rendered with classic functions.

So because list comprehensions are a single construct that does the job of
several functions, and because I got here just as 2.3 was launching and so
don't have a history of using map, filter and lambda, I wonder if there is a
guide to FP that explains them in terms of list comprehensions?

-clay



From marc_barry at hotmail.com  Thu Aug 14 03:33:03 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Thu Aug 14 02:33:41 2003
Subject: [Tutor] Iterators and Generators...
Message-ID: <Sea2-F68menuJrqkqpN0004e651@hotmail.com>

Everyone, thanks for the help.  I was confused with what the yield statement 
in a function actually did.  I was trying to implement the iterator protocol 
and therefore I thought that I had to define two methods; __iter__ and 
next() (which is true).  But, I thought that the 'yield' statement just 
returned its value and upon calling the method/function another time would 
resume after the 'yield' statement.  So my confusion was that I did't know 
that a function or method with a yield statement returns a generator (which 
already implements the iterator protocol).  Just calling the next() method 
executes the method or function up to the yield statement and then returns 
the value (whilst preserving the state of the method/function).

So, alles klar -> As pointed out below, there is no need to call the next() 
method in my class as I could just put all the code from the next method 
into the __iter__ method.

I have a question, why didn't Python just cause a method with a 'yield' 
statement to return its value and preserve its state.  Then, upon subsequent 
calls to the method it could begin execution from the point it left off.  
Basically, I am asking why they didn't choose the above option and chose to 
return a generator (i.e. build the object for you) instead?  With the above 
option, a person could easily implement the iterator protocol and there is 
no need for a generator.

Regards,

Marc


From: Neil Schemenauer <nas-pytut@python.ca>
To: tutor@python.org
Subject: Re: [Tutor] Iterators and Generators...
Date: Wed, 13 Aug 2003 09:24:26 -0700

Karl Pfl?sterer wrote:
 > You never called your next() method (and you have a typo); I underlined
 > both in your example.
 >
 > So the correct code would be:
 >
 > class list_iterator:
 >         def __init__(self, a_list):
 >                 self.a_list = a_list
 >
 >         def __iter__(self):
 >                 return self.next()
 >
 >         def next(self):
 >                 for i in self.a_list:
 >                         yield i
 >                 raise StopIteration

Yikes.  There's no need to explicitly raise StopIteration.  Also, the
'next' method could be called anything.  Don't get confused that the
name is somehow special.  For example, the following code does exactly
the same thing:

class list_iterator:
         def __init__(self, a_list):
                 self.a_list = a_list

         def __iter__(self):
                 return self.pumpkin()

         def pumpkin(self):
                 for i in self.a_list:
                         yield i

Furthermore, you don't need the extra method if you put the yield loop
in the __iter__ method.

   Neil

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

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8.  
http://join.msn.com/?page=features/junkmail


From marc_barry at hotmail.com  Thu Aug 14 03:33:04 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Thu Aug 14 02:33:49 2003
Subject: [Tutor] Iterators and Generators...
Message-ID: <Sea2-F39ypKsEgJXOxJ00046266@hotmail.com>

Everyone, thanks for the help.  I was confused with what the yield statement 
in a function actually did.  I was trying to implement the iterator protocol 
and therefore I thought that I had to define two methods; __iter__ and 
next() (which is true).  But, I thought that the 'yield' statement just 
returned its value and upon calling the method/function another time would 
resume after the 'yield' statement.  So my confusion was that I did't know 
that a function or method with a yield statement returns a generator (which 
already implements the iterator protocol).  Just calling the next() method 
executes the method or function up to the yield statement and then returns 
the value (whilst preserving the state of the method/function).

So, alles klar -> As pointed out below, there is no need to call the next() 
method in my class as I could just put all the code from the next method 
into the __iter__ method.

I have a question, why didn't Python just cause a method with a 'yield' 
statement to return its value and preserve its state.  Then, upon subsequent 
calls to the method it could begin execution from the point it left off.  
Basically, I am asking why they didn't choose the above option and chose to 
return a generator (i.e. build the object for you) instead?  With the above 
option, a person could easily implement the iterator protocol and there is 
no need for a generator.

Regards,

Marc


From: Neil Schemenauer <nas-pytut@python.ca>
To: tutor@python.org
Subject: Re: [Tutor] Iterators and Generators...
Date: Wed, 13 Aug 2003 09:24:26 -0700

Karl Pfl?sterer wrote:
 > You never called your next() method (and you have a typo); I underlined
 > both in your example.
 >
 > So the correct code would be:
 >
 > class list_iterator:
 >         def __init__(self, a_list):
 >                 self.a_list = a_list
 >
 >         def __iter__(self):
 >                 return self.next()
 >
 >         def next(self):
 >                 for i in self.a_list:
 >                         yield i
 >                 raise StopIteration

Yikes.  There's no need to explicitly raise StopIteration.  Also, the
'next' method could be called anything.  Don't get confused that the
name is somehow special.  For example, the following code does exactly
the same thing:

class list_iterator:
         def __init__(self, a_list):
                 self.a_list = a_list

         def __iter__(self):
                 return self.pumpkin()

         def pumpkin(self):
                 for i in self.a_list:
                         yield i

Furthermore, you don't need the extra method if you put the yield loop
in the __iter__ method.

   Neil

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

_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From alan.gauld at blueyonder.co.uk  Thu Aug 14 09:14:16 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Aug 14 03:14:12 2003
Subject: [Tutor] Text processing and functional programming?
References: <BB602C7F.BF3F%clay@shirky.com>
Message-ID: <003b01c36233$ac27ced0$6401a8c0@xp>

Hi Clay,

> of pythons list expressions intoxicating, and while I agree that map
and
> filter are somewhat mnemonic, lambda feels kludgy to me,

The point about all of these functions is that they are a
staight translation of the math. If you get a book on discrete math
and read about predicate and lambda calculus you will find that
the fundamental operations include maps, filters, reductions
comprehensions and lambdas.

Software engineering folks often say the difference between
S/w engineering and traditional engineering is the lack of
a mathematical basis, however thats only half true, using
prdicate calculus etc you can go straight from a meth
expression of the problem to a software solution, just as you
can go from a meth model to an electronic circuit diagram etc.

The problem is very few people, even computing students,
study discrete math. But FP is simply a way of expressing
of discrete math more directly in code.

> ourselves in the foot there with that 'one argument' limit -- better
make a
> wrapper for inline functions."

BTW I do agree that Pythons lambda implementation is a little
flaky compared to, say Lisp, but it is mathematically sound and
theoretically complete.

> So because list comprehensions are a single construct that does
> the job of several functions,

comprehensions do a single job, that of building lists.
Its coincidental that you can use a comprehension to apply
a filter etc. To be pedantic :-)

> guide to FP that explains them in terms of list comprehensions?

I doubt it but you may be better looking through a math book instead.
Truth to tell it was only when I saw the math behind it that FP
started to make sense to me. I can recommend the old, but still
valuable:

Logic, Algebra and Databases by
Peter Gray

if you can get hold of it.
You only ned to read the first 3 chapters to understand FP, but
if you also want the mathematical basis behind languages like
Prolog and SQL then go ahead and read the rest too.

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  Thu Aug 14 03:49:57 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Aug 14 05:50:08 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <BB602C7F.BF3F%clay@shirky.com>
Message-ID: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>



On Wed, 13 Aug 2003, Clay Shirky wrote:

> So because list comprehensions are a single construct that does the job
> of several functions, and because I got here just as 2.3 was launching
> and so don't have a history of using map, filter and lambda, I wonder if
> there is a guide to FP that explains them in terms of list
> comprehensions?

Hi Clay,


Conceptually, map() transforms a sequence of objects by applying a
function on each element.  If map() weren't built in, we could conceivably
implement it like this:

###
def map(function, sequence):
    """Transforms a sequence with a particular function."""
    mapped_elements = []
    for element in sequence:
        mapped_elements.append(function(element))
    return mapped_elements
###


(If we're sadistic, we can even reimplement map() by using list
comprehensions!

###
def map(function, sequence):
    return [function(x) for x in sequence]
###
)



With map() now defined, here's an example of it in action:

###
>>> def square(x): return x * x
...
>> map(square, range(20))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
 289, 324, 361]
###

If you've seen other FP languages, the above won't look too weird.  But if
your experience is with something like Pascal, then the above will look
very weird.


Most people aren't yet comfortable passing functions as arguments to other
functions.  It's not a feature that is quite mainstream, though GUI
programmers know about this: it's the core of how "callbacks" work.  As a
result, not many people used map(), even if using it might improve the
clarity of the code.


In Python 2.0, a language enhancement was proposed --- list comprehensions
--- to make this sort of mapping behavior a little easier to work with.

    http://www.python.org/peps/pep-0202.html

The equivalent list comprehension might look something like this:

###
>>> [square(x) for x in range(20)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
 289, 324, 361]
###

List comprehensions can take in an arbitrary expression, so we can also do
it this way:

###
>>> [x*x for x in range(20)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
 289, 324, 361]
###

In contrast, map() only deals with function objects, and not arbitrary
expressions.  Trying to do something like:

    map(x * x, range(20))               ## <--  this doesn't work

just doesn't work.  However, all is not lost: we're able to dynamically
generate a function object with 'lambda':

    map(lambda x: x*x, range(20))

That's what lambda's used for, to allow us to wrap an arbitrary expression
as a function.  Nothing fancier than that.  It might have been nice to
avoid the intimidating keyword "lambda", but oh well.  *grin*


Since Python has list comprehensions as part of the language core now,
it's often preferable to use them instead of the traditional map()
builtin: most programmers will feel comfortable with list comprehensions
because the syntax isn't that daunting.


I still think, though, that it's worthwhile to know how to use functional
programming techniques, sooner or later, because there are some very cool
things that are possible with them.  Functional programmers often focus on
writing small, well-defined functions, and more importantly, know how to
make functions that can create other functions.  Here's a small example:

###
>>> def make_mapper(function):
...     def new_function(L):
...         return [function(x) for x in L]
...     return new_function
...
>>> square_list = make_mapper(square)
>>> square_list(range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
###


With something like make_mapper(), it suddenly becomes a lot more
convenient to make functions that know how to deal with sequences, given
that we have a function that can deal with a single object.

###
>>> take_all_lengths = map_maker(len)
>>> take_all_lengths(['This', 'is', 'a', 'test'])
[4, 2, 1, 4]
>>> mass_url_reader = map_maker(urllib.urlopen)
>>> docs = mass_url_reader(['http://python.org/topic/learn',
...                         'http://slashdot.org'])
###

The potential for abuse is enormous.  *grin* But it's also very liberating
to be able to do this processes on lists with the same ease that we can
apply functions on single objects.


If all we knew were list comprehensions, we wouldn't be able to create
functions like take_all_lengths() or mass_url_reader() with the same kind
of ease.  Defining them without knowing FP techniques is perfectly doable:

###
def take_all_lengths(L):
    return [len(x) for x in L]

def mass_url_reader(L):
    return [urllib.urlopen(x) for x in L]
###

So it's not hard, but it's just a bit more work.


Anyway, I hope this gives a taste of functional programming techniques!
I was sorta half asleep while writing this, so if any of it looks weird,
it's probably me.  *grin*


Please feel free to ask more questions; we'll be happy to talk about this
more.  Good luck!


From Janssen at rz.uni-frankfurt.de  Thu Aug 14 13:05:27 2003
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Aug 14 06:05:53 2003
Subject: [Tutor] split by wiki format - was: wiki madness- it's contagious,
	want to get infected?
In-Reply-To: <3F2C47EC.6040600@netzero.net>
References: <3F2C47EC.6040600@netzero.net>
Message-ID: <Pine.A41.4.56.0308141142520.514408@hermes-22.rz.uni-frankfurt.de>

On Sat, 2 Aug 2003, Kirk Bailey wrote:

> ok, this means it's time for me to learn some re lore, I expect.

> What is holding me  back is parsing the wikicode into html. SOME of this
> code uses unique flags, so can be swapped with a strong.replace
> statement for that-   in effect, a rule.
>
> But some of this demands that a tag be replaced 2 different ways,
> turning on or off a function. For instance, "'''" (3 'singlequotes') not
> only turns ON bold print, it turns it off again- it is a state toggle.
>
> Therefore, the guts of a page must be read through sequentially,
> previous state alters response to a detected tag.

Hi Kirk,

I havn't followed every bit of the "wiki" threads so I can't say for
shure nobody else has already postet a similar solution or if you got
something better by now. Anyway:

*split* the text by your format string and decorate every odd element
with the appropriate html tags:


s = "A '''wiki''' text"
split_list = s.split("'''")

for n in range(1, len(split_list), 2):
    split_list[n] = '<b>' + split_list[n] +'</b>'

html = ' '.join(split_list)

[this is not extensivly tested]

Just put it into a function and call it with three arguments
wiki_format, html_start_tag, html_end_tag. This way, you can iterate
through different formats (format with longest wiki string first). You
will need to do it also for combined bold+italic (7 singlequotes in
wiki?), otherwise you will end with <i><b>ugly</i></b> html with
incorrect nesting.

Note that this is not efficient in terms of memory consumption. In case
you're already in the state-machine an text processing technology, keep
going (as long as you are not interested in writing a wiki with mimimal
code complexity, which would be a nice goal).


reagards
Michael

From godoy at metalab.unc.edu  Thu Aug 14 12:08:14 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Thu Aug 14 10:12:11 2003
Subject: [Tutor] Best approach to sort data based on several criteria
In-Reply-To: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se> (Magnus
	=?iso-8859-1?q?Lyck=E5's?= message of "Wed, 13 Aug 2003 21:24:40 +0200")
References: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se>
Message-ID: <m34r0k5o35.fsf@ieee.org>


NOTE: I already solved that problem by using an RDBMS system, as
      suggested and acknowledged by me in prior posts, but I really
      think this discussion is useful for other programs/future
      use. :-) 

      I am very thankful for your answers.

Magnus Lyck? <magnus@thinkware.se> writes:

> The fastest approach in Python is typically to transform your data
> into a list which can be sorted directly with the list.sort()
> method.

Hmmmm... This is what I had in mind initially. The problem was with
the composite index scheme. 

> You can supply a function to the sort method call, but that makes
> sorting much slower. For big lists with high performance
> requirements, it's typically faster to create a new list that can be
> sorted as is.

Here it was my problem: performance. I needed it relatively fast. 

I hadn't, on the other hand, thought about creating 'sublists'.

Something like sorting a list accordingly to the first key, then
splitting each different 'first item' (the first key) on a new list
and sorting such a new list accordingly to the second key and
repeating the process 'til all data was sorted out would require too
much memory, wouldn't it? 

How could I do that and go easy on memory at the same time? 

> This is sometimes called a Schwartzian transform, after Perl guru
> Randal Schwartz. What you do in Python is to change a list of rows
> to a list of tuples: (sort_criteria, row), then sort it, and finally
> transform it back to the list of rows without the preceding sort
> criteria. This will also work with dates if they are given as
> objects of some date type/class such as mx.DateTime or the new
> datetime class in 2.3, or in a sane string format, such as ISO 8601.
>
> It could look something like this:
>
>  >>> l = [('a', 2),
>           ('c', 1),
>           ('b', 3)]
>  >>> col = 0
>  >>> for i, row in enumerate(l):
>          l[i] = (row[col], row)
>
>  >>> l.sort()
>  >>> for i, row in enumerate(l):
>          l[i] = row[1]
>
>  >>> l
> [('a', 2), ('b', 3), ('c', 1)]
>  >>> col = 1
>  >>> for i, row in enumerate(l):
>          l[i] = (row[col], row)
>
>  >>> l.sort()
>  >>> for i, row in enumerate(l):
>          l[i] = row[1]
>
>  >>> l
> [('c', 1), ('a', 2), ('b', 3)]

This is "easy" (you have to think this first, but after the idea the
code flows easily) for a two collumn list or for a little number of
columns. How would you handle that easily with, e.g., 5 sorting keys
working with 22 columns and several megabytes of data (the actual size
of the base is bigger than one hundred megabytes and this is another
reaso to use an RDBMS --- but make it something like 50K records just
to have an idea)? 


Just to let you know, the old 'system' used to use several
spreadsheets with weekly data on it and they had to open some of them
to make a useful analisys. With the database system, everything is
there and can be recovered in a much easier and effective way. 


See you,
-- 
Godoy.     <godoy@metalab.unc.edu>

From godoy at metalab.unc.edu  Thu Aug 14 12:13:55 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Thu Aug 14 10:17:40 2003
Subject: [Tutor] Best approach to sort data based on several  criteria
In-Reply-To: <Pine.LNX.4.44.0308131436490.12147-100000@hkn.eecs.berkeley.edu>
	(Danny Yoo's message of "Wed, 13 Aug 2003 15:02:48 -0700 (PDT)")
References: <Pine.LNX.4.44.0308131436490.12147-100000@hkn.eecs.berkeley.edu>
Message-ID: <m3znic4998.fsf@ieee.org>

Danny Yoo <dyoo@hkn.eecs.berkeley.edu> writes:

> Hi Jorge,

Hi Danny.

I am also as thankful to you as to Magnus and the other for your
answer.

> Hmmm... When you say "huge amount of data", can you be more
> specific? If you're taking about several megabytes, then we don't
> have much to worry about.  But if we're talking about hundreds of
> megabytes (or even gigabytes), then we have to be a bit more
> careful.

I was talking about 1 or 2 hundreds of mebibytes. 

It means something like 1 or 2 million records (~ 100 bytes / record).

> If your set of data is really humongous, you may want to consider using a
> database management system --- such as PostgreSQL or MySQL --- to do the
> brunt of the sorting and storage grunt work.  Can you give us an estimate
> of how large your dataset's going to be?

It will be bigger than it already is and I ended up using PostgreSQL
and several functions (or stored procedures) to provide a lot of the
analisys I was going to code up if I hadn't used it (statistical
analisys, mainly). 


See you,
-- 
Godoy.     <godoy@metalab.unc.edu>

From godoy at metalab.unc.edu  Thu Aug 14 12:30:47 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Thu Aug 14 10:34:32 2003
Subject: [Tutor] Best approach to sort data based on several  criteria
In-Reply-To: <5.2.1.1.0.20030813164740.02b9fd50@66.28.54.253> (Bob Gailer's
	message of "Wed, 13 Aug 2003 16:48:17 -0600")
References: <5.2.1.1.0.20030813181840.052dbe80@www.thinkware.se>
	<5.2.1.1.0.20030813164740.02b9fd50@66.28.54.253>
Message-ID: <m3n0ec48h4.fsf@ieee.org>

Bob Gailer <bgailer@alum.rpi.edu> writes:

> Please add SQLIte to that list.

And put an exclamation mark on it. 

SQLite solves a lot of problems and is very interesting for deploying
solutions in a fast way. Migrating it for the definitive RDBMS is very
easy (this is only needed when SQLite lacks something or can't handle
the load since it is a VERY GOOD solution). 


See you,
-- 
Godoy.     <godoy@metalab.unc.edu>

From sigurd at 12move.de  Thu Aug 14 17:49:45 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Thu Aug 14 10:50:43 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
	(Danny Yoo's message of "Thu, 14 Aug 2003 02:49:57 -0700 (PDT)")
References: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
Message-ID: <m3znicuwyf.fsf@hamster.pflaesterer.de>

On 14 Aug 2003, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote:

[great stuff]

> I still think, though, that it's worthwhile to know how to use functional
> programming techniques, sooner or later, because there are some very cool
> things that are possible with them.  Functional programmers often focus on
> writing small, well-defined functions, and more importantly, know how to
> make functions that can create other functions.  Here's a small example:

> ###
>>>> def make_mapper(function):
> ...     def new_function(L):
> ...         return [function(x) for x in L]
> ...     return new_function
> ...

And further on think about closures.  They allow nice constructs (people
who know Common Lisp or Scheme use them all the time).

In [2]: def make_counter(start=0, step=1):
   ....:     def cfun(step=step, counter=[start]):
   ....:         counter[0] += step
   ....:         return counter[0]
   ....:     return cfun
   ...: 

In [3]: c = make_counter()

In [4]: c()
Out[4]: 1

In [5]: c()
Out[5]: 2

In [6]: d = make_counter(10,2)

In [7]: d()
Out[7]: 12

In [8]: d()
Out[8]: 14



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From clay at shirky.com  Thu Aug 14 12:01:57 2003
From: clay at shirky.com (Clay Shirky)
Date: Thu Aug 14 11:02:15 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
Message-ID: <BB611CA5.BFB3%clay@shirky.com>

> (If we're sadistic, we can even reimplement map() by using list
> comprehensions!
> 
> ###
> def map(function, sequence):
>   return [function(x) for x in sequence]
> ###
> )

But why not just do this in-line, as [ function(x) for x in sequence ] ?
What does the def and return buy you?
 
> If you've seen other FP languages, the above won't look too weird.  But if
> your experience is with something like Pascal, then the above will look
> very weird.

Its perl, actually, that I'm reacting to, where map is a key component of
much unreadable code.
 
> List comprehensions can take in an arbitrary expression, so we can also do
> it this way:
[...]
> In contrast, map() only deals with function objects, and not arbitrary
> expressions.  

So this gets at a question I put badly before: If list comprehensions can
take arbitrary expressions, and can pass any collection of values through
those functions, is the list comprehension construct a superset of what map,
filter, and lambda can do?

Put another way, other than preference for different flavors of syntactic
sugar, would you ever prefer map/filter/lambda to list comprehensions, or
v-v? 

And, relatedly, are list comprehensions FP constructs, or does hiding the
details of the (possibly nested) loops not create the same value as applying
functional equivalents of those loops?

> That's what lambda's used for, to allow us to wrap an arbitrary expression
> as a function.  Nothing fancier than that.  It might have been nice to
> avoid the intimidating keyword "lambda", but oh well.  *grin*

Someone on the python-dev list suggested it should have been called 'anon'.

> Since Python has list comprehensions as part of the language core now,
> it's often preferable to use them instead of the traditional map()
> builtin: most programmers will feel comfortable with list comprehensions
> because the syntax isn't that daunting.

Ah. Thanks. This answers my question above.
 
> def take_all_lengths(L):
>   return [len(x) for x in L]
> 
> def mass_url_reader(L):
>   return [urllib.urlopen(x) for x in L]
> ###
> 
> So it's not hard, but it's just a bit more work.

But, but, but now I'm confused again.

>>>> def take_all_lengths(L):
....    return [ len(x) for x in L ]
>>>> print take_all_lengths( [ 'This', 'is', 'a', 'test' ] )

is the same as
    
>>>> print [ len(x) for x in [ 'This', 'is', 'a', 'test' ] ]

so why do the bit more work in the first place? Right now, it just looks
like another layer of indirection to me.

Is it just that these are examples, and at some point you want to write a
def that performs so many functions that you don't want to write it in-line?
And if so, doesn't this push against the FP idea of narrowly defined
functions?

I believe Alan when he says the studies find that FP leads to more
performant code, but I still don't really understand why you would chose a
map/filter/lambda construction over a list comprehension, or v-v.

Are there times when you can do something with one of those constructs but
not the other?

-clay


From clay at shirky.com  Thu Aug 14 12:32:57 2003
From: clay at shirky.com (Clay Shirky)
Date: Thu Aug 14 11:33:05 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <m3znicuwyf.fsf@hamster.pflaesterer.de>
Message-ID: <BB6123E9.BFBD%clay@shirky.com>

> And further on think about closures.  They allow nice constructs (people
> who know Common Lisp or Scheme use them all the time).
> 
> In [2]: def make_counter(start=0, step=1):
>  ....:     def cfun(step=step, counter=[start]):
>  ....:         counter[0] += step
>  ....:         return counter[0]
>  ....:     return cfun

Isn't this what yield does? Are there kinds of closures that can't be
implemented with iterators? Or are iterators another way of creating
closures?

-clay


From clay at shirky.com  Thu Aug 14 12:38:21 2003
From: clay at shirky.com (Clay Shirky)
Date: Thu Aug 14 11:38:27 2003
Subject: [Tutor] Jython and J2ME?
In-Reply-To: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
Message-ID: <BB61252D.BFC0%clay@shirky.com>

If you wanted to write software for phones running J2ME, could you do it in
Jython, or is Jython only good for writing to the J2SE JVM?

-clay


From amk at asti-usa.com  Thu Aug 14 14:07:02 2003
From: amk at asti-usa.com (A.M. Kuchling)
Date: Thu Aug 14 13:07:36 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <BB611CA5.BFB3%clay@shirky.com>
References: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
	<BB611CA5.BFB3%clay@shirky.com>
Message-ID: <20030814170702.GB16162@vail.asti-usa.com>

> I believe Alan when he says the studies find that FP leads to more
> performant code, but I still don't really understand why you would chose a
> map/filter/lambda construction over a list comprehension, or v-v.

The only case when I use map/filter these days is when there's already
some built-in function that does the job.  Compare:

	L = map(int, L)
	L = [int(s) for s in L]

I find the first formulation preferable.  There aren't many built-in
functions that return Booleans -- I can't think of *any* offhand -- so
I never use filter(), only map().

> Are there times when you can do something with one of those constructs but
> not the other?

No; map/filter let you do exactly what list comps do.

A big reason for interest in functional programming stems is academic,
stemming from interest in proving things about programs.  Assignment
is very hard to handle in mathematical analyses of programs, and the
job of rigorously proving that a function f() implements the right
computation is made much easier if assignment is forbidden.  It's also
easier to perform transformations on a functionally-written program,
if you want to parallelize it or something.

--amk                                            (www.amk.ca)
I can hear the sound of empires toppling.
      -- The Doctor, in "The Happiness Patrol"


From jonathan.hayward at pobox.com  Thu Aug 14 19:28:24 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Thu Aug 14 13:28:29 2003
Subject: [Tutor] Splitting by word boundaries
Message-ID: <3F3BC6B8.7000603@pobox.com>

I'm trying to split along word boundaries, but when I pass e.g. "a b c 
d" to:

        text_tokens = re.split("\b", text)

But the re.split seems to return a list with only one string, the uncut 
text. Comments?

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From nas-pytut at python.ca  Thu Aug 14 11:42:39 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Thu Aug 14 13:36:39 2003
Subject: [Tutor] Iterators and Generators...
In-Reply-To: <Sea2-F39ypKsEgJXOxJ00046266@hotmail.com>
References: <Sea2-F39ypKsEgJXOxJ00046266@hotmail.com>
Message-ID: <20030814174238.GB920@glacier.arctrix.com>

Marc Barry wrote:
> I have a question, why didn't Python just cause a method with a 'yield' 
> statement to return its value and preserve its state.  Then, upon 
> subsequent calls to the method it could begin execution from the point it 
> left off.  Basically, I am asking why they didn't choose the above option 
> and chose to return a generator (i.e. build the object for you) instead?  
> With the above option, a person could easily implement the iterator 
> protocol and there is no need for a generator.

An iterator is essentially an object that remembers the state of the
iteration.  Where should this state be stored?  For a list, the thing to
remember is the current index and the length of the list.  Each time you
want to iterate over a list you get a new iterator.  Witness:

    >>> seq = ["a", "b", "c"]
    >>> it1 = iter(seq)
    >>> it2 = iter(seq)
    >>> it1
    <listiterator object at 0x4025666c>
    >>> it2
    <listiterator object at 0x4025676c>
    >>> it1.next()
    'a'
    >>> it2.next()
    'a'
    >>> it1.next()
    'b'
    >>> it2.next()
    'b'
    >>> it1.next()
    'c'
    >>> it1.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

The list cannot be it's own iterator (hopefully that's obvious).  You
would not be able to iterate over the same list concurrently.  For
example:

    seq = ["a", "b", "c"]
    for x in seq:
        for y in seq:
            print x, y

While the inner 'for' loop is executing there are two iterators alive.
I hope this is a good clue as to why generator-functions return a
generator-iterator when called.  For all the details on iterators you
can read the PEP:

    http://www.python.org/peps/pep-0234.html

You can skip the C API part.  There is also a PEP for generators, if you
are interested.

  Neil

From amk at asti-usa.com  Thu Aug 14 14:45:48 2003
From: amk at asti-usa.com (A.M. Kuchling)
Date: Thu Aug 14 13:46:21 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <3F3BC6B8.7000603@pobox.com>
References: <3F3BC6B8.7000603@pobox.com>
Message-ID: <20030814174548.GE16162@vail.asti-usa.com>

On Thu, Aug 14, 2003 at 06:28:24PM +0100, Jonathan Hayward http://JonathansCorner.com wrote:
>        text_tokens = re.split("\b", text)

Inside a string literal, the \b is interpreted as a backspace
character; if there were any backspaces in the string, it would be
split along them.  Either use a raw string (r"\b") to avoid this
interpretation, or quote the backslash (r"\\b") so it gets passed to
the re module.

http://www.amk.ca/python/howto/regex/regex.html#SECTION000420000000000000000
has a slightly longer explanation of all this.

--amk

From nas-pytut at python.ca  Thu Aug 14 11:56:25 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Thu Aug 14 13:50:23 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <20030814170702.GB16162@vail.asti-usa.com>
References: <Pine.LNX.4.44.0308140145470.3232-100000@hkn.eecs.berkeley.edu>
	<BB611CA5.BFB3%clay@shirky.com>
	<20030814170702.GB16162@vail.asti-usa.com>
Message-ID: <20030814175625.GC920@glacier.arctrix.com>

A.M. Kuchling wrote:
> There aren't many built-in functions that return Booleans -- I can't
> think of *any* offhand -- so I never use filter(), only map().

callable() commes to mind.  And bool(). :-)  Hey, I just realized that

    filter(bool, ...)

is the same as the tricky

    filter(None, ...)

Neat.

  Neil

From lobow at brturbo.com  Thu Aug 14 16:19:16 2003
From: lobow at brturbo.com (Diego Galho Prestes)
Date: Thu Aug 14 14:17:18 2003
Subject: [Tutor] installing pyopengl
Message-ID: <3F3BD2A4.3020100@brturbo.com>

Hi someone know where I can find a tutorial to install pyopengl in 
linux? I tried to install but needs a module named glut. I tried to 
install this but I have many problems to install this. Where I can find 
a tutorial for this too, the one of Nvidia OpenGL Configuration 
mini-HOWTO page dont work here.

Diego


From Janssen at rz.uni-frankfurt.de  Thu Aug 14 21:57:41 2003
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Aug 14 14:57:47 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <20030814174548.GE16162@vail.asti-usa.com>
References: <3F3BC6B8.7000603@pobox.com>
	<20030814174548.GE16162@vail.asti-usa.com>
Message-ID: <Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>

On Thu, 14 Aug 2003, A.M. Kuchling wrote:

> On Thu, Aug 14, 2003 at 06:28:24PM +0100, Jonathan Hayward http://JonathansCorner.com wrote:
> >        text_tokens = re.split("\b", text)
>
> Inside a string literal, the \b is interpreted as a backspace
> character; if there were any backspaces in the string, it would be
> split along them.  Either use a raw string (r"\b") to avoid this
> interpretation, or quote the backslash (r"\\b") so it gets passed to
> the re module.

this is important but not enough. re.split(r'\b', 'word boundary') is
yet infunctional. I've looked through the sources to find out why.

My conclusion is: re.split tries to *match* (not search) on a given
string: a match is only found, when the strings *starts* with a possibly
match. In case the match is empty, it steps one character further
and matches again. Empty match indicates, that nothing is to be
done than proceding within the string and don't split on current
position. Since r'\b' matches the empty string, this leads to confusion.

Note that re.match doesn't return None if nothing is found but ''
(unlike re.search)


Unless you rewrite split (I'm not the one to tell if this is possible),
you can't use it with a pattern, that matches the empty string (But
you're free to do it in another way ;-).


Where did I found this information (beside some guessing ;-) ? Well, how
to tell it? split is implemented as the method pattern_split of a
SRE_Pattern in modul _sre. _sre is a builtin module (python -vEc "import
_sre"  gives this piece of information). This means, reading c code.
Suppose you've installed from tar you find the _src.c file in
INSTALL_DIR/Modules/. In case you are unfamilar with c you might look
into the old pre Modul (under PYTHON_LIB/), wich got a RegexObject class
with a split method very similar to _sre.SRE_Pattern.pattern_split (did
those c-coders made it the python way?).

The interesting lines are on 2155 (v2.3):

        if (state.start == state.ptr) {  # indicates empty match; mj
            if (last == state.end)
                break;  # break while loop if end of string; mj
            /* skip one character */
            state.start = (void*) ((char*) state.ptr + state.charsize);
            continue;


"continue" stops from processing the rest of the while loop. Here it
stops _sre.pattern_split from actually spliting the string.


Michael

From nas-pytut at python.ca  Thu Aug 14 13:33:41 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Thu Aug 14 15:27:40 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
References: <3F3BC6B8.7000603@pobox.com>
	<20030814174548.GE16162@vail.asti-usa.com>
	<Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
Message-ID: <20030814193341.GB1943@glacier.arctrix.com>

Michael Janssen wrote:
> this is important but not enough. re.split(r'\b', 'word boundary') is
> yet infunctional. I've looked through the sources to find out why.

re.findall(r'\w+', ...) should do what is intended.

  Neil

From jonathan.hayward at pobox.com  Thu Aug 14 22:34:16 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Thu Aug 14 16:34:21 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <20030814193341.GB1943@glacier.arctrix.com>
References: <3F3BC6B8.7000603@pobox.com>	<20030814174548.GE16162@vail.asti-usa.com>	<Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
	<20030814193341.GB1943@glacier.arctrix.com>
Message-ID: <3F3BF248.8090803@pobox.com>

Neil Schemenauer wrote:

>Michael Janssen wrote:
>  
>
>>this is important but not enough. re.split(r'\b', 'word boundary') is
>>yet infunctional. I've looked through the sources to find out why.
>>    
>>
>
>re.findall(r'\w+', ...) should do what is intended.
>  
>
[other discussion snipped]

I couldn't figure out how to get this to accept re.DOTALL or equivalent 
and wrote a little bit of HTML handling that the original regexp 
wouldn't have done:

    def split_at_word_boundaries(self, text):
        debug_log("split_at_word_boundaries")
        return text
        result = []
        current_segment = []
        text_characters = []
        is_on_first_newline_segment = 1
        newline_segments = string.split(text, "\n")
        for segment in newline_segments:
            if is_on_first_newline_segment:
                is_on_first_newline_segment = 0
            else:
                text_characters.append("\n")
            text_characters.extend(re.findall(".", segment))
        is_in_escape = 0
        if re.match(r"[\w&]", text_characters[0]):
            is_in_word = 1
        else:
            is_in_word = 0
            for current_character in text_characters:
                current_is_in_word = 0
                if is_in_word:
                    if current_character == "&":
                        is_in_escape = 1
                        current_is_in_word = 1
                    if is_in_escape and current_character == "#":
                        current_is_in_word = 1
                    if is_in_escape and current_character == ";":
                        is_in_escape = 0
                        current_is_in_word = 1
                    if self.word_character_matcher.match(current_character):
                        current_is_in_word = 1
                else:
                    if current_character == "&":
                        is_in_escape = 1
                        current_is_in_word = 1
                    if is_in_escape and current_character == "#":
                        current_is_in_word = 1
                    if is_in_escape and current_character == ";":
                        is_in_escape = 0
                        current_is_in_word = 1
                    if self.word_character_matcher.match(current_character):
                        current_is_in_word = 1
                if current_is_in_word == is_in_word:
                    current_segment.append(current_character)
                else:
                    result.append("".join(current_segment))
                    current_segment = []
                is_in_word = current_is_in_word
        return result


Usually when I do this I think I'm doing something Python tries to 
prevent programmers from needing. It's not duct tape, but it does read 
more like a C++ programmer trying to use Python as C++.

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From Janssen at rz.uni-frankfurt.de  Fri Aug 15 00:03:28 2003
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Aug 14 17:03:36 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <3F3BF248.8090803@pobox.com>
References: <3F3BC6B8.7000603@pobox.com>
	<20030814174548.GE16162@vail.asti-usa.com>
	<Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
	<20030814193341.GB1943@glacier.arctrix.com>
	<3F3BF248.8090803@pobox.com>
Message-ID: <Pine.A41.4.56.0308142249430.1724922@hermes-22.rz.uni-frankfurt.de>

On Thu, 14 Aug 2003, Jonathan Hayward http://JonathansCorner.com wrote:

> Neil Schemenauer wrote:

> >re.findall(r'\w+', ...) should do what is intended.

> I couldn't figure out how to get this to accept re.DOTALL or equivalent
> and wrote a little bit of HTML handling that the original regexp
> wouldn't have done:

[you needn't set re.DOTALL, when your pattern hasn't got a dot]

Running your code (after putting it into a state to run it ;-) doesn't
split input :-( For my eyes it is missing a while loop. In my approach I
relay on r'\b' to look ahead until next boundary and slice the string:

def boundary_split(s):
    back = []
    while 1:
        try:
            # r'.\b' and +1 prevents endless loop
            pos = re.search(r'.\b', s, re.DOTALL).start()+1
        except AttributeError:
            if s: back.append(s)
            break
        back.append(s[:pos])
        s = s[pos:]
    return back


>>> boundary_split("  ad=\n2  ")
['  ', 'ad', '=\n', '2', '  ']
>>> boundary_split("<title>word boundary</title>")
['<', 'title', '>', 'word', ' ', 'boundary', '</', 'title', '>']

is it this what you want to get?


Michael

From dyoo at hkn.eecs.berkeley.edu  Thu Aug 14 15:06:12 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Aug 14 17:06:18 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <20030814193341.GB1943@glacier.arctrix.com>
Message-ID: <Pine.LNX.4.44.0308141324280.26921-100000@hkn.eecs.berkeley.edu>



On Thu, 14 Aug 2003, Neil Schemenauer wrote:

> Michael Janssen wrote:
> > this is important but not enough. re.split(r'\b', 'word boundary') is
> > yet infunctional. I've looked through the sources to find out why.
>
> re.findall(r'\w+', ...) should do what is intended.

Hi Neil,


Similarly, we can split against nonwords:

###
>>> re.split(r'\W+', 'word boundary')
['word', 'boundary']
###


But for the reason why '\b' alone isn't splitting: '\b' is a bit special!
According to the docs:

    http://www.python.org/doc/lib/re-syntax.html

it matches the empty string, but only at the beginning or end of a word.


That '\b' matches the empty string is the important key to the mystery,
because trying to split against the empty string doesn't do anything:

###
>>> re.split(r'', 'word boundary')
['word boundary']
###


So by the same reasoning, doing '\b' to split won't work, since it's
trying to split with the empty string.


Hope this helps!


From Janssen at rz.uni-frankfurt.de  Fri Aug 15 00:12:00 2003
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Aug 14 17:12:07 2003
Subject: [Tutor] correction - was: Splitting by word boundaries
In-Reply-To: <Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
References: <3F3BC6B8.7000603@pobox.com>
	<20030814174548.GE16162@vail.asti-usa.com>
	<Pine.A41.4.56.0308141956080.1724922@hermes-22.rz.uni-frankfurt.de>
Message-ID: <Pine.A41.4.56.0308142303520.1724922@hermes-22.rz.uni-frankfurt.de>

On Thu, 14 Aug 2003, Michael Janssen wrote:

[correcting myself]

> Note that re.match doesn't return None if nothing is found but ''
> (unlike re.search)

This is wrong: re.match returns indeed None if the string does not
match the pattern. I have tricked myself using a single & silly
testcase (and not reading the docs).

Michael

From alan.gauld at blueyonder.co.uk  Thu Aug 14 23:23:17 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Aug 14 17:23:13 2003
Subject: [Tutor] Text processing and functional programming?
References: <BB611CA5.BFB3%clay@shirky.com>
Message-ID: <000601c362aa$4764b310$6401a8c0@xp>

> Put another way, other than preference for different flavors of
syntactic
> sugar, would you ever prefer map/filter/lambda to list
comprehensions, or
> v-v?

Its a matter of readability. If you undertand the FP principles
map/filter etc are much more readable - they express the intent
better.

For example, we can write:

if x > 5:
    y = x
else:
    y = 2*x

or we can write

y = ((x > 5) and x) or 2*x

They mean the same, but the first is easier to understand unless
you happen to be fluent in boolean algebra.

Similarly a comprehension, precisely because it can do so many
things has to be read and studied much more carefully that an
expression using map/filter etc. The comprehension just tells
you a list is being returned, you have to read the content to
see what kind of transformation is being done.

However if you aren't already familiar with FP concepts then
comprehensions probably tell you as much as the named functions
do - and are usually faster!

> And, relatedly, are list comprehensions FP constructs,

Yes, they come from Haskell most directly but the concept of
comprehensions exists in the math too.

> > avoid the intimidating keyword "lambda", but oh well.  *grin*

But lambda is the intuitive name for anyone who has loked at the
math. If you have studied the lamda calculus any other name would
seem totally bizarre! A lambda is a lambda, thats its name. Its
like deciding to call a tuple a 'bunch' just because you hadn't
heard the term tuple used before... They are both the correct
mathematical term for the concept they embody.

> Is it just that these are examples, and at some point you want to
write a
> def that performs so many functions that you don't want to write it
in-line?

Exactly so, Danny was just keeping it short.

> Are there times when you can do something with one of those
constructs but
> not the other?

Well a lambda is completely unrelated to the others. You don't need
lambda to use map or filter and you can use lambda in writing a
comprehension. In fact, ironically, before comprehensions came along
lambda was never needed because you could allways use def instead, but
comprehensions provide (I think) the only place in Python where
lambda is the only way to do it.(You can of course build such a list
without lambdas using a loop)

What I refer to is the ability to generate a list of functions
using a comprehension:

>>> numbers = [2,5,9]
>>> multipliers = [lambda x,y=z: y*x for z in numbers]
>>> for n in range(3):
...    print multipliers[n](7)
...
14
35
63
>>>

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From abli at freemail.hu  Fri Aug 15 00:27:44 2003
From: abli at freemail.hu (Abel Daniel)
Date: Thu Aug 14 17:27:22 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <BB6123E9.BFBD%clay@shirky.com>
References: <m3znicuwyf.fsf@hamster.pflaesterer.de>
	<BB6123E9.BFBD%clay@shirky.com>
Message-ID: <20030814212744.GA24731@hooloovoo>

> > And further on think about closures.  They allow nice constructs (people
> > who know Common Lisp or Scheme use them all the time).
> > 
> > In [2]: def make_counter(start=0, step=1):
> >  ....:     def cfun(step=step, counter=[start]):
> >  ....:         counter[0] += step
> >  ....:         return counter[0]
> >  ....:     return cfun
> 
> Isn't this what yield does? Are there kinds of closures that can't be
> implemented with iterators? Or are iterators another way of creating
> closures?

In the above, cfun can get extra parameters, so you can do:
>>> c=make_counter()
>>> c()
1
>>> c()
2
>>> c(2)
4

I don't think this is possible with iterators.

Abel Daniel

From alan.gauld at blueyonder.co.uk  Thu Aug 14 23:28:08 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Aug 14 17:28:01 2003
Subject: [Tutor] Jython and J2ME?
References: <BB61252D.BFC0%clay@shirky.com>
Message-ID: <002d01c362aa$f5025900$6401a8c0@xp>


> If you wanted to write software for phones running J2ME, could you
do it in
> Jython, or is Jython only good for writing to the J2SE JVM?

This is pure guesswork, but J2ME relies on a cut down set of
Java classes etc, wheras I suspect that Jython is likely to
use several of the missed out capabilities. So if I'm right
it would not run on J2ME.

But I could be totally wrong! :-)

Alan G.


From idiot1 at netzero.net  Thu Aug 14 19:13:29 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug 14 18:12:59 2003
Subject: [Tutor] NE dark, and I'm not feeling to well either...
Message-ID: <3F3C0989.8010204@netzero.net>

I was just wondering if the NE power grid is managed by windows baised systems...

Ought to go over to un*x and python of course.

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From dyoo at hkn.eecs.berkeley.edu  Thu Aug 14 16:24:02 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Aug 14 18:24:10 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <000601c362aa$4764b310$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0308141425500.29911-100000@hkn.eecs.berkeley.edu>



> Yes, they come from Haskell most directly but the concept of
> comprehensions exists in the math too.
>
> > > avoid the intimidating keyword "lambda", but oh well.  *grin*
>
> But lambda is the intuitive name for anyone who has loked at the math.
> If you have studied the lamda calculus any other name would seem totally
> bizarre! A lambda is a lambda, thats its name. Its like deciding to call
> a tuple a 'bunch' just because you hadn't heard the term tuple used
> before...


Hi Alan,


There is historical precedent to giving the 'lambda' operator a different
name, though.  The OCaml folks, for example, use the keyword 'function' to
create anonymous functions:

(*** OCaml ***)
# let square = function x -> x * x;;
val square : int -> int = <fun>
# square 42;;
- : int = 1764
(*************)

I just personally feel that when the lambda concept was introduced into
Python, that 'function' would have been a better keyword than 'lambda'.
Just an opinion, though, and not that big of a deal.




> What I refer to is the ability to generate a list of functions using a
> comprehension:
>
> >>> numbers = [2,5,9]
> >>> multipliers = [lambda x,y=z: y*x for z in numbers]
> >>> for n in range(3):
> ...    print multipliers[n](7)
> ...
> 14
> 35
> 63



The heart of functional programming, I think, isn't really map() or
filter(), but the ability to create and handle dynamic functions like
these --- to be able to play with functions just like strings or numbers.

It might be worthwhile to give another slightly more realistic example of
closures.  Here's another example, writing a set of functions to generate
HTML code:

###
>>> def make_tagger(tag_name):
...     def tag_function(content):
...         return "<%s>%s</%s>" % (tag_name, content, tag_name)
...     return tag_function
...
>>>
>>>
>>> p, h1, h2, i, b = map(make_tagger, ['p', 'h1', 'h2', 'i', 'b'])
>>>
>>>
>>> p("Hello, this is a test, "
...   + i("italicized") + " and " + b("bolded!"))
'<p>Hello, this is a test, <i>italicized</i> and <b>bolded!</b></p>'
###


Again, this code is a oversimplified, but it hints at the kind of power we
have with closures.  Of course, we can do all of this without having to
using any mapping or closure or FP technique:


###
def p(content):
    return "<p>%s</p>" % content

def h1(content):
    return "<h1>%s</h1>" % content

# etc...
###

but that's just dull code: why not let Python do most of this work?
*grin*



One other advantage about this approach is that it allows us to localize
our changes: we may later want to make sure that all of the content within
our tags are entity-escaped.  With the closure approach, we just need to
modify our make_tagger()  function:

###
>>> import xml.sax.saxutils
>>> def make_tagger(tag_name):
...     def tag_function(content):
...         return "<%s>%s</%s>" % (tag_name,
...                                 xml.sax.saxutils.escape(content),
...                                 tag_name)
...     return tag_function
...
>>>
>>> p = make_tagger('p')
>>>
>>> p("Hello, this is a test.  1 < 2")
'<p>Hello, this is a test.  1 &lt; 2</p>'
###


All our tag-generating functions then gain the benefit of proper HTML
escaping, because all of them are the offspring of make_tagger().  This is
a case where the extra indirection is a big win.



Hope this helps!


From david at graniteweb.com  Thu Aug 14 21:44:08 2003
From: david at graniteweb.com (David Rock)
Date: Thu Aug 14 21:44:41 2003
Subject: [Tutor] Splitting by word boundaries
In-Reply-To: <3F3BC6B8.7000603@pobox.com>
References: <3F3BC6B8.7000603@pobox.com>
Message-ID: <20030815014408.GB31608@wdfs.graniteweb.com>

* Jonathan Hayward http://JonathansCorner.com <jonathan.hayward@pobox.com> [2003-08-14 18:28]:
> I'm trying to split along word boundaries, but when I pass e.g. "a b c 
> d" to:
> 
>        text_tokens = re.split("\b", text)
> 
> But the re.split seems to return a list with only one string, the uncut 
> text. Comments?

If you are splitting by word boundaries, why not just use string.split?
The default split is whitespace:
	import string
	test = 'a b c d'
	split_test = string.split( test )

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030814/c1dcdd51/attachment.bin
From idiot1 at netzero.net  Thu Aug 14 20:55:08 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Aug 14 22:33:56 2003
Subject: [Tutor] split by wiki format - was: wiki madness- it's contagious,
	want to get infected?
In-Reply-To: <Pine.A41.4.56.0308141142520.514408@hermes-22.rz.uni-frankfurt.de>
References: <3F2C47EC.6040600@netzero.net>
	<Pine.A41.4.56.0308141142520.514408@hermes-22.rz.uni-frankfurt.de>
Message-ID: <3F3C215C.60808@netzero.net>

Michael, thank you for your reply.
I have most of it working now, but it still manages to mangle SOME words which 
are followed by punctuation or some form of a hypertag.
To see what I mean, you can view the semiworking wiki's output here:
http://www.tinylist.org/cgi-bin/wikinehesa.py/
It will come up with FrontPage.
To see it working right, look at the output of the working piki engine:
http://www.tinylist.org/cgi-bin/piki.py
And to examine the sourefile for the page, in it's original wikicode, just click 
the edit link in the footer. DO NOT save the page that comes up, unless you want 
to modify the page.


Michael Janssen wrote:

> On Sat, 2 Aug 2003, Kirk Bailey wrote:
> 
> 
>>ok, this means it's time for me to learn some re lore, I expect.
> 
> 
>>What is holding me  back is parsing the wikicode into html. SOME of this
>>code uses unique flags, so can be swapped with a strong.replace
>>statement for that-   in effect, a rule.
>>
>>But some of this demands that a tag be replaced 2 different ways,
>>turning on or off a function. For instance, "'''" (3 'singlequotes') not
>>only turns ON bold print, it turns it off again- it is a state toggle.
>>
>>Therefore, the guts of a page must be read through sequentially,
>>previous state alters response to a detected tag.
> 
> 
> Hi Kirk,
> 
> I havn't followed every bit of the "wiki" threads so I can't say for
> shure nobody else has already postet a similar solution or if you got
> something better by now. Anyway:
> 
> *split* the text by your format string and decorate every odd element
> with the appropriate html tags:
> 
> 
> s = "A '''wiki''' text"
> split_list = s.split("'''")
> 
> for n in range(1, len(split_list), 2):
>     split_list[n] = '<b>' + split_list[n] +'</b>'
> 
> html = ' '.join(split_list)
> 
> [this is not extensivly tested]
> 
> Just put it into a function and call it with three arguments
> wiki_format, html_start_tag, html_end_tag. This way, you can iterate
> through different formats (format with longest wiki string first). You
> will need to do it also for combined bold+italic (7 singlequotes in
> wiki?), otherwise you will end with <i><b>ugly</i></b> html with
> incorrect nesting.
> 
> Note that this is not efficient in terms of memory consumption. In case
> you're already in the state-machine an text processing technology, keep
> going (as long as you are not interested in writing a wiki with mimimal
> code complexity, which would be a nice goal).
> 
> 
> reagards
> Michael
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From clay at ernie.webservepro.com  Fri Aug 15 14:06:18 2003
From: clay at ernie.webservepro.com (Clay Shirky)
Date: Fri Aug 15 13:06:31 2003
Subject: [Tutor] Text processing and functional programming?
In-Reply-To: <000601c362aa$4764b310$6401a8c0@xp> from "Alan Gauld" at Aug 14,
	2003 10:23:17 PM
Message-ID: <200308151706.h7FH6IQt005518@ernie.webservepro.com>

> However if you aren't already familiar with FP concepts then
> comprehensions probably tell you as much as the named functions
> do - and are usually faster!

This is the position I'm in -- its all list operations to me, and
having a separate name for "checks the elements against a condition"
and "transforms the elements" doesn't make much difference.

Of course, the other thing pushing me in this direction is that I just
got here, so to me, things like yeild and list comprehensions have
always been part of python, the same way def and return have. There's
no familiarity barrier.

> > Is it just that these are examples, and at some point you want to
> > write a def that performs so many functions that you don't want to
> > write it in-line?
> 
> Exactly so, Danny was just keeping it short.

got it, thx

-clay

From arkamir at softhome.net  Fri Aug 15 12:45:43 2003
From: arkamir at softhome.net (arkamir@softhome.net)
Date: Fri Aug 15 13:45:47 2003
Subject: [Tutor] what is foo
Message-ID: <courier.3F3D1C47.00006211@softhome.net>

hey ive been reading several books about python lately and the \y all 
included foo. Can someone please tell me what it is. Thanks 

From amk at asti-usa.com  Fri Aug 15 14:54:27 2003
From: amk at asti-usa.com (A.M. Kuchling)
Date: Fri Aug 15 13:55:00 2003
Subject: [Tutor] what is foo
In-Reply-To: <courier.3F3D1C47.00006211@softhome.net>
References: <courier.3F3D1C47.00006211@softhome.net>
Message-ID: <20030815175427.GA14233@vail.asti-usa.com>

On Fri, Aug 15, 2003 at 11:45:43AM -0600, arkamir@softhome.net wrote:
> hey ive been reading several books about python lately and the \y all 
> included foo. Can someone please tell me what it is. Thanks 

See http://www.catb.org/~esr/jargon/html/F/foo.html .

--amk

From clay at ernie.webservepro.com  Fri Aug 15 14:55:33 2003
From: clay at ernie.webservepro.com (Clay Shirky)
Date: Fri Aug 15 13:55:42 2003
Subject: [Tutor] what is foo
In-Reply-To: <courier.3F3D1C47.00006211@softhome.net> from
	"arkamir@softhome.net" at Aug 15, 2003 11:45:43 AM
Message-ID: <200308151755.h7FHtXIY007208@ernie.webservepro.com>

> hey ive been reading several books about python lately and the \y all 
> included foo. Can someone please tell me what it is. Thanks 

foo is jokingly called the "metasyntactic varaible" in some hacker
circles, which is a way of saying "its our version of thingie", as in
"hon, have you seen that thingie that keeps water from going down the
drain?"

A common problem in explaining programming is how to tell the user
when part of an example is supposed to be replaced by them. 

One way to do it is to make the name self-secriptive, as in 

  for your_variable_name_here in your_list_name_here:
	  your_function_name_here()

but that can get tedious, so by convention, a variety of placeholder
names have sprung up, such as foo, bar, blatz, quux, and
spam. Whenever one of these appears in an example, it means "replace
it with a real variable, so "for line in foo.txt" means "replace
foo.txt with the real name of your file."

foo and bar are the commonest metasyntactic variables, and seem to
be phonetic representations of FUBAR, military-speak for "Fucked Up
Beyond All Recognition."

-clay

ps. The marvellous hackers dictionary (no url, but you can google it), has
lots of this sort of lore, btw.


From jonathan.hayward at pobox.com  Fri Aug 15 21:06:25 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 15 15:06:29 2003
Subject: [Tutor] Using jon.fcgi to speed up subsequent invocations
Message-ID: <3F3D2F31.10900@pobox.com>

I have a search script that spends 90+% of its time in initialization. 
One initialisation gets everything ready for multiple searches, so it 
should speed up with fast cgi. I converted, or tried to convert it, to 
jon.fcgi to use Fast CGI.

As is, I can't tell a performance difference. If I load the larger 
dataset, a search takes ~20 seconds with or without fcgi. Do I need to 
tell Apache something different to use it as a fast CGI script (what's 
the URL to the relevant HOWTO)? Here are relevant snippets of my script:

import jon.cgi as cgi
import jon.fcgi as fcgi

class Handler(cgi.Handler):
   def process(self, request):
       multitasking.get_thread_specific_storage()["handler"] = 
request.params
       request.set_header("Content-Type", "text/html")
       request.write(get_output())

if __name__ == "__main__":
   init() # This is the really slow invocation that should only be 
needed once.
   fcgi.Server({fcgi.FCGI_RESPONDER: Handler}, 0, None, fcgi.Request, 
0).run()

Thanks,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From dyoo at hkn.eecs.berkeley.edu  Fri Aug 15 13:46:48 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug 15 15:46:54 2003
Subject: [Tutor] Using jon.fcgi to speed up subsequent invocations
In-Reply-To: <3F3D2F31.10900@pobox.com>
Message-ID: <Pine.LNX.4.44.0308151226060.18066-100000@hkn.eecs.berkeley.edu>



On Fri, 15 Aug 2003, Jonathan Hayward http://JonathansCorner.com wrote:

> I have a search script that spends 90+% of its time in initialization.
> One initialisation gets everything ready for multiple searches, so it
> should speed up with fast cgi. I converted, or tried to convert it, to
> jon.fcgi to use Fast CGI.

Hi Jonathan,


You may want to try mod_python instead:

    http://www.modpython.org/


> As is, I can't tell a performance difference. If I load the larger
> dataset, a search takes ~20 seconds with or without fcgi. Do I need to
> tell Apache something different to use it as a FastCGI script (what's
> the URL to the relevant HOWTO)?


Yes, there's some extra setup that needs to be done to make Python treat
it as a FastCGI.  It looks like you may need to add a handler block in
Apache's httpd.conf.  Here's a LinuxWorld article that shows how to set it
up:

    http://www.linuxworld.com/story/32798.htm


It might be a good idea to check with the folks on comp.lang.python to see
how FastCGI and mod_python compare.  I had the impression that mod_python
was very well supported and actively developed.  But I'm a lot more
ignorant about FastCGI.  I tried connected to:

    http://www.fastcgi.com/

but the site appears to be down at the moment.  Stupid power outages...
*grin*



Good luck to you!


From pythontutor at venix.com  Fri Aug 15 16:48:40 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Aug 15 15:49:15 2003
Subject: [Tutor] Using jon.fcgi to speed up subsequent invocations
In-Reply-To: <3F3D2F31.10900@pobox.com>
References: <3F3D2F31.10900@pobox.com>
Message-ID: <3F3D3918.8070309@venix.com>

You need the apache fast-cgi module (You are using apache??)
### Section 2: 'Main' server configuration
#
<IfModule mod_fastcgi.c>

         # URIs that begin with /fcgi-bin/, are found in /var/www/fcgi-bin/
         Alias /fcgi-bin/ /var/www/fcgi-bin/

         # Anything in here is handled as a "dynamic" server if not defined as "static" or "external"
         <Directory /var/www/fcgi-bin/>
             SetHandler fastcgi-script
             Options +ExecCGI
         </Directory>

</IfModule>
I think this is fairly self explanatory.

I found Jon helpful in getting the regular cgi module to work.  My code (based
on his advice) looks like:

# somecgi.py
import cgi as stdcgi
import jon.cgi as joncgi

class Handler(joncgi.Handler):
	def process(self, req):
		fields = stdcgi.FieldStorage(fp=req.stdin, environ=req.environ)
###################

There is a jonpy mailing list, but it gets a lot of spam.  The pyweb list
focuses on the more elaborate python web frameworks.

Hope this helps.  (Let me know if I left out critical info.)

Jonathan Hayward http://JonathansCorner.com wrote:

> I have a search script that spends 90+% of its time in initialization. 
> One initialisation gets everything ready for multiple searches, so it 
> should speed up with fast cgi. I converted, or tried to convert it, to 
> jon.fcgi to use Fast CGI.
> 
> As is, I can't tell a performance difference. If I load the larger 
> dataset, a search takes ~20 seconds with or without fcgi. Do I need to 
> tell Apache something different to use it as a fast CGI script (what's 
> the URL to the relevant HOWTO)? Here are relevant snippets of my script:
> 
> import jon.cgi as cgi
> import jon.fcgi as fcgi
> 
> class Handler(cgi.Handler):
>   def process(self, request):
>       multitasking.get_thread_specific_storage()["handler"] = 
> request.params
>       request.set_header("Content-Type", "text/html")
>       request.write(get_output())
> 
> if __name__ == "__main__":
>   init() # This is the really slow invocation that should only be needed 
> once.
>   fcgi.Server({fcgi.FCGI_RESPONDER: Handler}, 0, None, fcgi.Request, 
> 0).run()
> 
> Thanks,
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From glingl at aon.at  Sat Aug 16 00:26:58 2003
From: glingl at aon.at (Gregor Lingl)
Date: Fri Aug 15 17:29:07 2003
Subject: [Tutor] type objects - 2nd try
Message-ID: <3F3D5022.3050709@aon.at>

Hi!
I'll try to ask a question which I asked already some days ago,
but nobody took notice of it. I'd be very interested  in the answer
and I hope to get one, this time.

1. EXPOSITION
There are "type objects" in python:
 >>> str
<type 'str'>
 >>> int
<type 'int'>
I'm confronted with them e. g. in this way:
 >>> type(1)
<type 'int'>
 >>> type("a")
<type 'str'>
I can use them to check types for example in this way:
 >>> type(1)==int
True
 >>> type(1.0)==int
False
This works even for type-objects themselves:
 >>> type(type)
<type 'type'>
 >>> type
<type 'type'>
 >>> type(type) == type
True
2. OBSERVATION
The  type (i.e . the type type) , which is used like a function
outputs several other types:
 >>> def f():
...     pass
...
 >>> type(f)
<type 'function'>
 >>> def g():
...     yield 1
...    
 >>> type(g())
<type 'generator'>
 >>> type(len)
<type 'builtin_function_or_method'>
BUT there seem to be no type-objects, at least with these names, belonging
to this "types":
 >>> function
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'function' is not defined
 >>> generator
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'generator' is not defined
So I have to resort to the "old-fashioned" way to determine
types of objects, namely to compare to the types of  known
objects:
 
 >>> type(len) == type(abs)
True
 >>> type(f)==type(g)
True
 >>> def h():
...     yield 2
...    
 >>> x = h()
 >>> y = g()
 >>> x
<generator object at 0x00E244E0>
 >>> y
<generator object at 0x00E24440>
 >>> type(x)==type(y)
True
3. QUESTION
(1) Are there named type-objects for functions, generators, classes
and the like, in order to determine the type of functions, generators etc.
more easily, i. e. not to need to define a "prototype"-object first.
If so, what are their names?
(2) Where can I find an in-depth - albei easily to read - discussion
of "type-objects", especially if there are different types of types
("All types are equal, but some are more equal ?)

Thanks in advance,
Gregor




From jonathan.hayward at pobox.com  Fri Aug 15 23:54:03 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 15 17:54:06 2003
Subject: [Tutor] FastCGI install help
Message-ID: <3F3D567B.9090803@pobox.com>

I installed mod_fastcgi-2.2.12-1.i386.rpm, and it put mod_fastcgi.so in 
a different directory from Apache's other modules. I copied it to the 
default directory, and added:

LoadModule fastcgi_module modules/mod_fastcgi.so

at the end of the modules. When I tried to restart apache, I got:

Cannot load /etc/httpd/modules/mod_fastcgi.so into server: 
/etc/httpd/modules/mod_fastcgi.so: undefined symbol: ap_user_id

How can I get fastcgi to load with apache? Or if it won't work, what is 
something similar that will work?

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From sigurd at 12move.de  Sat Aug 16 00:59:00 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Fri Aug 15 18:03:08 2003
Subject: [Tutor] type objects - 2nd try
In-Reply-To: <3F3D5022.3050709@aon.at> (Gregor Lingl's message of "Fri, 15
	Aug 2003 23:26:58 +0200")
References: <3F3D5022.3050709@aon.at>
Message-ID: <m3y8xur3l6.fsf@hamster.pflaesterer.de>

On 15 Aug 2003, Gregor Lingl <- glingl@aon.at wrote:

[...]

> 3. QUESTION
> (1) Are there named type-objects for functions, generators, classes
> and the like, in order to determine the type of functions, generators etc.
> more easily, i. e. not to need to define a "prototype"-object first.
> If so, what are their names?

$ python
Python 2.3 (#1, Aug  1 2003, 15:01:23) 
[GCC 3.2 20020927 (prerelease)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import types
>>> def f():
...     pass
... 
>>> type(f) == types.FunctionType
True
>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__']
>>> 


> (2) Where can I find an in-depth - albei easily to read - discussion
> of "type-objects", especially if there are different types of types
> ("All types are equal, but some are more equal ?)

Did you look in the Python language reference?  The node is numbered 3.2
`The standard type hierarchy'.  The file is
/path_to_your_python_docs/html/ref/types.html 



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From idiot1 at netzero.net  Fri Aug 15 20:34:15 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 15 19:34:14 2003
Subject: [Tutor] wiki mandess grows on the brain like athletes foot on a
 dirty wrestling mat!
Message-ID: <3F3D6DF7.5020402@netzero.net>

Well, it gets worswe, or better, or at least BIGGER.

I wrote the backsearch script. If one now clicks on the title of the page being 
misviewed, it finds pages with links in them to that page and lists them for 
you. Does not count, but does reliably detect. Makes  nice list, pretty links.

Here is a link to the sourcecode:
http://www.tinylist.org/backsearch.txt
That is to a ln soft link  to the actual script, backsearch.py.

To use it, when viewing a page, click the title of it in the page header.
example:
http;//www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage
-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Fri Aug 15 22:15:22 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 15 21:15:23 2003
Subject: [Tutor] chain gangs of the mind...
Message-ID: <3F3D85AA.9030706@netzero.net>

I want a script, at the end of execution, to launch another script. I don't care 
if this wipes the old one out of memory, namespace, whatever, it will no longer 
be needed. When the editor finishes provessing a page, I want it as a last act 
to launch the browser wiki script with the page name fed to it. Any ideas on how 
to effect this?
-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From jonathan.hayward at pobox.com  Sat Aug 16 04:20:12 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 15 22:20:16 2003
Subject: [Tutor] mod_fastcgi.so
Message-ID: <3F3D94DC.3090706@pobox.com>

The one RPM I found with mod_fastcgi.so didn't work. Could you e-mail me 
your /usr/lib/httpd/modules/mod_fastcgi.so? I think another one might work.

TIA,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From RASTM2 at aol.com  Sat Aug 16 06:38:13 2003
From: RASTM2 at aol.com (RASTM2@aol.com)
Date: Sat Aug 16 05:38:19 2003
Subject: [Tutor] Re:what is foo From Online Observations
Message-ID: <48.20eb405d.2c6f5585@aol.com>



> From: arkamir@softhome.net
> Subject: [Tutor] what is foo
> To: tutor@python.org
> Message-ID: <courier.3F3D1C47.00006211@softhome.net>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1"
> 
> hey ive been reading several books about python lately and the \y all 
> included foo. Can someone please tell me what it is. Thanks 

Hello ARKAMIR, 

And that is the ultimate question.
What "is" foo?

Foo is sort of like a variable in a sentence or in an example.
A word to take the place of any word.
You just replace "foo" or "bar" or any of many such words with
the "real" words your going to use.

i.e.

>>> def foo(bar):

...          if bar:

...        print "foo means", bar

... 

>>> foo()

Traceback (most recent call last):
  
File "<interactive input>", line 1, in ?

TypeError: foo() takes exactly 1 argument (0 given)


As you can see from the trace back, foo takes exactly one argument,
so if you don't give it a meaning, it will be meaningless.    ; )  


>>> foo('this')
          # give it a meaning and then
foo means this
        # it has a meaning
>>> 

Here's a couple good places to find out what "foo" is. 

>From Denis Howe's  Free On Line Dictionary Of Computing
<A HREF="http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?foo">http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?foo</A>

see especially also 
Eric S. Raymond's 
Jargon File<A HREF="http://www.catb.org/~esr/jargon/html/F/foo.html">
http://www.catb.org/~esr/jargon/html/F/foo.html</A>


Hope this helps and you enjoy the reading.

Ray St. Marie
Rastm2@users.sourceforge.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030816/1f539dc5/attachment.htm
From pythontutor at venix.com  Sat Aug 16 12:30:06 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Aug 16 11:30:42 2003
Subject: [Tutor] mod_fastcgi.so
In-Reply-To: <3F3D94DC.3090706@pobox.com>
References: <3F3D94DC.3090706@pobox.com>
Message-ID: <3F3E4DFE.4040007@venix.com>

You are using Apache 2.  I just tried moving my stuff to my Apache 2
system.  It does not work!   I took a look at the fastcgi.com web site
and downloaded mod_fastcgi-2.4.0.   The Docs talk about Apache 1.3+.

I have not yet had a chance to try to compile with Apache 2.  I am not
optomistic.  I'll be in trouble with my code since it will need to run
with an apache 2 webserver later this year.

Jonathan Hayward http://JonathansCorner.com wrote:
> The one RPM I found with mod_fastcgi.so didn't work. Could you e-mail me 
> your /usr/lib/httpd/modules/mod_fastcgi.so? I think another one might work.
> 
> TIA,
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From goki75 at vsnl.net  Fri Aug 15 21:34:23 2003
From: goki75 at vsnl.net (G Kiran)
Date: Sat Aug 16 11:39:13 2003
Subject: [Tutor] look for a particular string in a stream
Message-ID: <000201c3640c$733871d0$0100a8c0@VULCAN>

I am reading from a socket and need to wait till a particular string arrives

s=socket(AF_INET,SOCK_STREAM)
s.listen(5)
conn,recv=s.connect()
  while (1):
        waitonsocket(conn,"START")
        blah
        blah
        blah


presently i implemented a string queue of length of string i am waiting for
and i repeatedly read one byte/char at time from the socket and add it to
the queue
and check whether queue contains the string i am looking for...is there a
faster way of doing this

reading one char at a time and adding and checking the queue slows down the
program

--kiran


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.509 / Virus Database: 306 - Release Date: 8/12/2003


From jonathan.hayward at pobox.com  Sat Aug 16 19:23:36 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug 16 13:23:42 2003
Subject: [Tutor] mod_fastcgi.so
In-Reply-To: <3F3E4DFE.4040007@venix.com>
References: <3F3D94DC.3090706@pobox.com> <3F3E4DFE.4040007@venix.com>
Message-ID: <3F3E6898.3060001@pobox.com>

Lloyd Kvam wrote:

> You are using Apache 2.  I just tried moving my stuff to my Apache 2
> system.  It does not work!   I took a look at the fastcgi.com web site
> and downloaded mod_fastcgi-2.4.0.   The Docs talk about Apache 1.3+.
>
> I have not yet had a chance to try to compile with Apache 2.  I am not
> optomistic.  I'll be in trouble with my code since it will need to run
> with an apache 2 webserver later this year.

Oof.

I can't test this now because my webserver is toast, but I'd definitely 
like to have my program forking an oracle process and consulting the 
oracle. Last I checked, it hung; I tried to simplify things by using 
cPickle. What I want to happen is for the client to pickle its 
environment and CGI query, send them, and then read from the oracle a 
pickled page. Here are the pages that should be doing that but might be 
responsible for the hanging:

    def get_page_from_oracle(self):
        self.check_and_start_oracle()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect((configuration.get_search_server_ip(), \
              configuration.get_search_server_port()))
            sockIn = sock.makefile("rb")
            sockOut = sock.makefile("wb")
            cPickle.dump(os.environ, sockOut)
            cPickle.dump(cgi.FieldStorage(), sockOut)
            result = cPickle.load(sockIn)
            sock.close()
            sockIn.close()
            sockOut.close()
            return result
        except socket.error, e:
            return "Content-type: text/html\n\n<h1>There was an error 
loading this page.</h1>" + str(e)

    def handle_oracle_query(self, sock, address):
        """Reads a CGI or other header variable alone on a line, format like
            cgi_value <HTML form element name>
            environment_variable REMOTE_ADDR
        and then a pickled value. There is exactly one space between the two
        elements, and neither element may contain a space"""
        sockIn = sock.makefile("rb")
        sockOut = sock.makefile("wb")
        self.get_thread_specific_storage()["environment_variables"] = \
          cPickle.load(sockIn)
        self.get_thread_specific_storage()["cgi"] = cPickle.load(sockIn)
        generate_output()
        print_output(sockOut)
        sock.close()
        sockIn.close()
        sockOut.close()

The complete version of the program is at 
http://haywardfamily.org/jonathan/datamine.txt ; the methods above are 
from the class multitasking_manager.

Thank you; I'd really like to have this working.

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From idiot1 at netzero.net  Sat Aug 16 14:27:51 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 13:28:10 2003
Subject: [Tutor] where you is?
Message-ID: <3F3E6997.60900@netzero.net>

Where did everyone go? Is this a list for people who are at work to participate 
in? Do almost all members go home for the weekend and not look at it until 
monday? wow, the list's throughput is down to less than a quater of normal.

We now return you to your regularly scheduled foo...


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From pythontutor at venix.com  Sat Aug 16 14:52:24 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Aug 16 13:52:59 2003
Subject: [Tutor] where you is?
In-Reply-To: <3F3E6997.60900@netzero.net>
References: <3F3E6997.60900@netzero.net>
Message-ID: <3F3E6F58.8080208@venix.com>

I suspect that real life does intrude sometimes.
(power woes, blaster cleanup - if only for friends and family, etc.)

Kirk Bailey wrote:

> Where did everyone go? Is this a list for people who are at work to 
> participate in? Do almost all members go home for the weekend and not 
> look at it until monday? wow, the list's throughput is down to less than 
> a quater of normal.
> 
> We now return you to your regularly scheduled foo...
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From andi at buxach.de  Sat Aug 16 20:30:08 2003
From: andi at buxach.de (Andreas Zwinkau)
Date: Sat Aug 16 15:24:33 2003
Subject: [Tutor] gtk.glade missing
Message-ID: <20030816193008.03cc6992.andi@buxach.de>

Hi

i installed pygtk and glade and wanted to test my first little gui. The
problem is gtk.glade is somehow missing. I do only need the pygtk
wrapper with gtk2, don't i?
This is the test, which always leads to an exception:

import pygtk
pygtk.require("2.0")

try:
        import gtk
        import gtk.glade # here it brakes
except:
        print "You need to install pyGTK or GTKv2 or set your PYTHONPATH
correctly."
        print "try: export
PYTHONPATH=/usr/local/lib/python2.2/site-packages/"
        sys.exit(1)

The example is copied from the Linux Journal, thats why there are these
error messages
http://www.linuxjournal.com/article.php?sid=6586

pygtk, gtk2 is installed, do i need something else? 

mfg
Andreas Zwinkau
 | web: andi.dasstellenwirinsinternet.de
 | mail: andi@buxach.de
 | jabber: beza1e1@amessage.de

From idiot1 at netzero.net  Sat Aug 16 19:37:10 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 18:36:36 2003
Subject: [Tutor] wiki mandess grows on the brain like athletes foot on
	adirty wrestling mat!
In-Reply-To: <184670-22003861622833293@M2W030.mail2web.com>
References: <184670-22003861622833293@M2W030.mail2web.com>
Message-ID: <3F3EB216.8070202@netzero.net>

Works now, sorry. try again
http://www.tinylist.org/backsearch.txt
this is a ln soft link to the actual script in the cgi-bin. If the script 
changes, so will it.

mgulver@britishlibrary.net wrote:

>>Here is a link to the sourcecode:
>>http://www.tinylist.org/backsearch.txt
> 
> 
> The link 404 me. Please check/upload whatever.
> 
> Marcus
> 
> --------------------------------------------------------------------
> mail2web - Check your email from the web at
> http://mail2web.com/ .
> 
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From jim_938 at hotmail.com  Sun Aug 17 05:20:55 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Sat Aug 16 18:51:29 2003
Subject: [Tutor] forking process with python
Message-ID: <Sea1-F6vKQUUEczzjk700025447@hotmail.com>

Hello,

I am having a problem in understanding this example from the o'rellys book 
for python programming.

#!/usr/bin/python

def counter(count):
	for i in range(count):
		time.sleep(10)
		print '[%s]--> %s ' %(os.getpid(), i)


for i in range(10):
	pid = os.fork()
	if pid != 0:
		print 'Process %d spawned' %pid
	else:
		counter(10)
		os._exit(0)

print 'Main process exiting.'



I am not getting how this os.fork is working as when the child process will 
be created, when the pid will be zero.

As far i can understand is that fork returns the pid of the parent and 0 as 
the return value for the child process( am i right ?).

Kindly suggest sthing regarding the working of this example.
If we have some links on the internet from where i can get information 
related to forking process with python, pls point me towards that also.

Thanks to all.


Regards,

Jim

_________________________________________________________________
MSN Hotmail now on your Mobile phone. 
http://server1.msn.co.in/sp03/mobilesms/ Click here.


From tpc at csua.berkeley.edu  Sat Aug 16 17:42:45 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Sat Aug 16 19:42:51 2003
Subject: [Tutor] where you is?
In-Reply-To: <3F3E6997.60900@netzero.net>
Message-ID: <20030816164205.B75049-100000@localhost.name>


for the mentally challenged such as myself, I consider it a refreshing
change of pace to have weekends to focus on other important things like
video games and riding my bicycle.  I did, however, have my first Python
dream just a few minutes ago...

On Sat, 16 Aug 2003, Kirk Bailey wrote:

> Where did everyone go? Is this a list for people who are at work to participate
> in? Do almost all members go home for the weekend and not look at it until
> monday? wow, the list's throughput is down to less than a quater of normal.
>
> We now return you to your regularly scheduled foo...
>
>
> --
>
> end
>
> Cheers!
>          Kirk D Bailey
>
>   +                              think                                +
>    http://www.howlermonkey.net  +-----+        http://www.tinylist.org
>    http://www.listville.net     | BOX |  http://www.sacredelectron.org
>    Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
>   +                              think                                +
>
> Fnord.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From jonathan.hayward at pobox.com  Sun Aug 17 02:52:08 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug 16 20:52:12 2003
Subject: [Tutor] Test case
Message-ID: <3F3ED1B8.8050102@pobox.com>

I'm trying to have a client open a socket, send two pickled hashes,
and receive a pickled object (I'm also writing the server, to listen,
read two pickled hashes, and send a pickled object). I've been able to
boil down what doesn't work to a small demo case:
____________________________________________________________

SERVER:
#!/usr/bin/python

import cPickle, socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", 1234))
sock.listen(5)

try:
    newsocket, address = sock.accept()
    sockOut = newsocket.makefile("wb")
    sockIn = newsocket.makefile("rb")
    cPickle.load(sockIn)
    cPickle.load(sockIn)
    cPickle.dump("Hello, world!", sockOut)
    newsocket.close()
    sockOut.close()
    sockIn.close()
finally:
    sock.close()
____________________________________________________________

CLIENT:
#!/usr/bin/python

import cPickle, socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 1234))
sockOut = sock.makefile("wb")
sockIn = sock.makefile("r")
cPickle.dump({}, sockOut)
cPickle.dump({}, sockOut)
response_data = cPickle.load(sockIn)
print response_data
sockOut.close()
sockIn.close()
sock.close()
____________________________________________________________

When I start the server and then start the client, they both hang, as
has happened with the real script. Can you tell me what I am misusing
and preferably how to correct it?

TIA,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From jonathan.hayward at pobox.com  Sun Aug 17 03:10:17 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug 16 21:10:23 2003
Subject: [Tutor] Test case
In-Reply-To: <3F3ED1B8.8050102@pobox.com>
References: <3F3ED1B8.8050102@pobox.com>
Message-ID: <3F3ED5F9.2010508@pobox.com>

Just after posting the below, I realised that my test case worked after 
I added flushes. The next problem I have is that, in the real program, 
the server gets an EOFError when it first tries to read from the socket. 
Relevant portions follow the error message below:

Traceback (most recent call last):
  File "/var/www/cgi-bin/datamine", line 1633, in ?
    find_and_output_appropriate_page()
  File "/var/www/cgi-bin/datamine", line 1461, in 
find_and_output_appropriate_page
    sys.stdout.write(get_output())
  File "/var/www/cgi-bin/datamine", line 1497, in get_output
    return multitasking.get_page_from_oracle()
  File "/var/www/cgi-bin/datamine", line 976, in get_page_from_oracle
    self.check_and_start_oracle()
  File "/var/www/cgi-bin/datamine", line 972, in check_and_start_oracle
    self.start_oracle()
  File "/var/www/cgi-bin/datamine", line 1083, in start_oracle
    self.run_oracle()
  File "/var/www/cgi-bin/datamine", line 1056, in run_oracle
    self.handle_oracle_query(newsocket, address)
  File "/var/www/cgi-bin/datamine", line 1015, in handle_oracle_query
    self.get_thread_specific_storage()["environment_variables"] = \
EOFError
Traceback (most recent call last):
  File "/var/www/cgi-bin/datamine", line 1633, in ?
    find_and_output_appropriate_page()
  File "/var/www/cgi-bin/datamine", line 1461, in 
find_and_output_appropriate_page
    sys.stdout.write(get_output())
  File "/var/www/cgi-bin/datamine", line 1497, in get_output
    return multitasking.get_page_from_oracle()
  File "/var/www/cgi-bin/datamine", line 988, in get_page_from_oracle
    result = cPickle.load(sockIn)
IOError: [Errno 104] Connection reset by peer

 From the server side, here are run_oracle() and handle_oracle_query():

    def run_oracle(self):
        #thread.start_new_thread(\
          #self.initialize, ())
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", configuration.get_search_server_port()))
        sock.listen(5)
        while 1:
            try:
                newsocket, address = sock.accept()
                self.handle_oracle_query(newsocket, address)
                #thread.start_new_thread(self.handle_oracle_query, 
(newsocket, \                  #address))
            except socket.error:
                sock.close()
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sock.bind(("", configuration.get_search_server_port()))
                sock.listen(5)

    def handle_oracle_query(self, sock, address):
        sockIn = sock.makefile("rb")
        sockOut = sock.makefile("wb")
        sockIn.flush()
### Line 1015, immediately below, is where the EOF error is reported.
        self.get_thread_specific_storage()["environment_variables"] = \
          cPickle.load(sockIn)
        sockIn.flush()
        self.get_thread_specific_storage()["cgi"] = cPickle.load(sockIn)
        generate_output()
        print_output(sockOut)
        sockOut.flush()
        sock.close()
        sockIn.close()
        sockOut.close()

 From the client side, here is get_page_from_oracle():

    def get_page_from_oracle(self):
        self.check_and_start_oracle()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect((configuration.get_search_server_ip(), \
              configuration.get_search_server_port()))
            sockIn = sock.makefile("rb")
            sockOut = sock.makefile("wb")
            cPickle.dump(os.environ, sockOut)
            sockOut.flush()
            cPickle.dump(cgi.FieldStorage(), sockOut)
            sockOut.flush()
            sockIn.flush()
### Line 988, immediately below, also gets an error, but I believe this 
is secondary damage.
            result = cPickle.load(sockIn)
            sock.close()
            sockIn.close()
            sockOut.close()
            #return "Content-type: text/html\n\nget_page_from_oracle"
            return result



Jonathan Hayward http://JonathansCorner.com wrote:

> I'm trying to have a client open a socket, send two pickled hashes,
> and receive a pickled object (I'm also writing the server, to listen,
> read two pickled hashes, and send a pickled object). I've been able to
> boil down what doesn't work to a small demo case:
> ____________________________________________________________
>
> SERVER:
> #!/usr/bin/python
>
> import cPickle, socket
>
> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> sock.bind(("", 1234))
> sock.listen(5)
>
> try:
>    newsocket, address = sock.accept()
>    sockOut = newsocket.makefile("wb")
>    sockIn = newsocket.makefile("rb")
>    cPickle.load(sockIn)
>    cPickle.load(sockIn)
>    cPickle.dump("Hello, world!", sockOut)
>    newsocket.close()
>    sockOut.close()
>    sockIn.close()
> finally:
>    sock.close()
> ____________________________________________________________
>
> CLIENT:
> #!/usr/bin/python
>
> import cPickle, socket
>
> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> sock.connect(("127.0.0.1", 1234))
> sockOut = sock.makefile("wb")
> sockIn = sock.makefile("r")
> cPickle.dump({}, sockOut)
> cPickle.dump({}, sockOut)
> response_data = cPickle.load(sockIn)
> print response_data
> sockOut.close()
> sockIn.close()
> sock.close()
> ____________________________________________________________
>
> When I start the server and then start the client, they both hang, as
> has happened with the real script. Can you tell me what I am misusing
> and preferably how to correct it?
>
> TIA,
>


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From jonathan.hayward at pobox.com  Sun Aug 17 03:16:13 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug 16 21:16:17 2003
Subject: [Tutor] forking process with python
In-Reply-To: <Sea1-F6vKQUUEczzjk700025447@hotmail.com>
References: <Sea1-F6vKQUUEczzjk700025447@hotmail.com>
Message-ID: <3F3ED75D.7080101@pobox.com>

Jimmy verma wrote:

> Hello,
>
> I am having a problem in understanding this example from the o'rellys 
> book for python programming.
>
> #!/usr/bin/python
>
> def counter(count):
>     for i in range(count):
>         time.sleep(10)
>         print '[%s]--> %s ' %(os.getpid(), i)
>
>
> for i in range(10):
>     pid = os.fork()
>     if pid != 0:
>         print 'Process %d spawned' %pid
>     else:
>         counter(10)
>         os._exit(0)
>
> print 'Main process exiting.'
>
>
>
> I am not getting how this os.fork is working as when the child process 
> will be created, when the pid will be zero.
>
> As far i can understand is that fork returns the pid of the parent and 
> 0 as the return value for the child process( am i right ?).
>
> Kindly suggest sthing regarding the working of this example.
> If we have some links on the internet from where i can get information 
> related to forking process with python, pls point me towards that also. 

You've almost got it. When a process forks, the parent remains and a 
child is created. The return value for the *parent* is the *child's* 
PID, and the return value for the *child* is 0.

In terms of reference material, Alex Martelli and David Ascher's _Python 
Cookbook_ is useful. Pp. 229-231 discuss this, although it seems to me 
that you've got the basic concept; you just had one detail wrong.

>
> Thanks to all.
>
>
> Regards,
>
> Jim
>
> _________________________________________________________________
> MSN Hotmail now on your Mobile phone. 
> http://server1.msn.co.in/sp03/mobilesms/ Click here.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From idiot1 at netzero.net  Sat Aug 16 23:47:14 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 22:46:51 2003
Subject: [Tutor] where you is?
In-Reply-To: <20030816164205.B75049-100000@localhost.name>
References: <20030816164205.B75049-100000@localhost.name>
Message-ID: <3F3EECB2.5080204@netzero.net>



tpc@csua.berkeley.edu wrote:

> for the mentally challenged such as myself, I consider it a refreshing
> change of pace to have weekends to focus on other important things like
> video games and riding my bicycle.  I did, however, have my first Python
> dream just a few minutes ago...
> 
wow. serious hard case. My kind of hacker. Been there myself when hammering it 
in hard early on in the learning curve. tell me, was it a happy dream, just a 
strange mix of dreamstuff and codestuff, frightening nightmare, or- well, shall 
we say, was it of an adult nature?

And I'm glad to see some people still manage to have a life AND a passion for 
programming.

> On Sat, 16 Aug 2003, Kirk Bailey wrote:
> 
> 
>>Where did everyone go? Is this a list for people who are at work to participate
>>in? Do almost all members go home for the weekend and not look at it until
>>monday? wow, the list's throughput is down to less than a quater of normal.
>>
>>We now return you to your regularly scheduled foo...
>>
>>
>>--
>>
>>end
>>
>>Cheers!
>>         Kirk D Bailey
>>
>>  +                              think                                +
>>   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
>>   http://www.listville.net     | BOX |  http://www.sacredelectron.org
>>   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
>>  +                              think                                +
>>
>>Fnord.
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Sun Aug 17 00:22:15 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 23:22:14 2003
Subject: [Tutor] upload tag and uploading files through a script to the
	server
Message-ID: <3F3EF4E7.1040304@netzero.net>

ok. I want to have a upload form in the footer. I know the html tag exists, but 
never used it. I want the form to talk to a script in the server to upload a 
file, inention is to permit uploading image files, so they can be included in a 
wiki page with image tags. Anyone got some clues on the art?



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Sun Aug 17 00:40:33 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 23:40:10 2003
Subject: [Tutor] uploading
Message-ID: <3F3EF931.9080601@netzero.net>

here is a link from netscape itself on the matter:
http://wp.netscape.com/assist/net_sites/html_extensions_3.html
And in it is this sample form:

<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD=POST>

Send this file: <INPUT NAME="userfile" TYPE="file">

<INPUT TYPE="submit" VALUE="Send File">

</FORM>

Natch, it demands a recipient script to receive the data and turn it into a nice 
image file someplace safe, such as in the images directory.

Anyone ever done this?

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From idiot1 at netzero.net  Sun Aug 17 00:42:28 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Aug 16 23:42:26 2003
Subject: [Tutor] uploading
Message-ID: <3F3EF9A4.3020307@netzero.net>

here is a link from netscape itself on the matter:
http://wp.netscape.com/assist/net_sites/html_extensions_3.html
And in it is this sample form:

<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD=POST>

Send this file: <INPUT NAME="userfile" TYPE="file">

<INPUT TYPE="submit" VALUE="Send File">

</FORM>

Now, I have it on a page on the tinylist site:
http://www.tinylist.org/testform.html

Note the script it wants to invoke (upload.py) DOES NOT EXIST YET. Trying to use 
it is a waste of time-tonight.

Natch, it demands a recipient script to receive the data and turn it into a nice 
image file someplace safe, such as in the images directory.

Anyone ever done this?


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From david at graniteweb.com  Sat Aug 16 23:47:02 2003
From: david at graniteweb.com (David Rock)
Date: Sat Aug 16 23:47:37 2003
Subject: [Tutor] where you is?
In-Reply-To: <3F3EECB2.5080204@netzero.net>
References: <20030816164205.B75049-100000@localhost.name>
	<3F3EECB2.5080204@netzero.net>
Message-ID: <20030817034702.GA6051@wdfs.graniteweb.com>

* Kirk Bailey <idiot1@netzero.net> [2003-08-16 22:47]:
> 
> tpc@csua.berkeley.edu wrote:
> 
> >for the mentally challenged such as myself, I consider it a refreshing
> >change of pace to have weekends to focus on other important things like
> >video games and riding my bicycle.  I did, however, have my first Python
> >dream just a few minutes ago...
> >
> wow. serious hard case. My kind of hacker. Been there myself when hammering 
> it in hard early on in the learning curve. tell me, was it a happy dream, 
> just a strange mix of dreamstuff and codestuff, frightening nightmare, or- 
> well, shall we say, was it of an adult nature?
> 
> And I'm glad to see some people still manage to have a life AND a passion 
> for programming.

The only reason I have a life is because my wife says so ;-) 
I would be a hopeless case if she didn't make me socialize with normal
people.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030816/c2640d74/attachment.bin
From idiot1 at netzero.net  Sun Aug 17 01:15:33 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 17 00:15:12 2003
Subject: [Tutor] upload version 0.0000001X
Message-ID: <3F3F0165.6060803@netzero.net>

ok, I whacked out a first approximation at a uploader.
Here is a link to the script:
http://www.tinylist.org/upload.txt
another soft link, that leads to the guts of the ACTUAL script in the server.

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From goki75 at vsnl.net  Sun Aug 17 13:52:12 2003
From: goki75 at vsnl.net (G Kiran)
Date: Sun Aug 17 03:24:19 2003
Subject: [Tutor] waiting for a particualr string from a socket
Message-ID: <003e01c36490$47b57b50$aa4c41db@VULCAN>

I am reading from a socket and need to wait till a particular string arrives

s=socket(AF_INET,SOCK_STREAM)
s.listen(5)
conn,recv=s.connect()
  while (1):
        waitonsocket(conn,"START")
        blah
        blah
        blah


presently i implemented a string queue of length of string i am waiting for
and i repeatedly read one byte/char at time from the socket and add it to
the queue
and check whether queue contains the string i am looking for...is there a
faster way of doing this

reading one char at a time and adding and checking the queue slows down the
program

--kiran




From op73418 at mail.telepac.pt  Sun Aug 17 13:46:50 2003
From: op73418 at mail.telepac.pt (Rodrigues)
Date: Sun Aug 17 07:45:49 2003
Subject: [Tutor] waiting for a particualr string from a socket
In-Reply-To: <003e01c36490$47b57b50$aa4c41db@VULCAN>
Message-ID: <DCEDLKJJJGHMCOCFGMGKEEHACBAA.op73418@mail.telepac.pt>



> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
> Behalf Of G Kiran
> Sent: domingo, 17 de Agosto de 2003 8:22
> To: python tutor
> Subject: [Tutor] waiting for a particualr string from a socket
>
>
> I am reading from a socket and need to wait till a
> particular string arrives
>
> s=socket(AF_INET,SOCK_STREAM)
> s.listen(5)
> conn,recv=s.connect()
>   while (1):
>         waitonsocket(conn,"START")
>         blah
>         blah
>         blah
>
>
> presently i implemented a string queue of length of string
> i am waiting for
> and i repeatedly read one byte/char at time from the socket
> and add it to
> the queue
> and check whether queue contains the string i am looking
> for...is there a
> faster way of doing this
>
> reading one char at a time and adding and checking the
> queue slows down the
> program
>

Hmmm, why don't you just buffer the recv calls and use s.find?
Something like

#A hint to the recv call.
HINT = 1024
string_to_find = "START"

#A list to buffer what we have scanned already.
lst = []
s = conn.recv(HINT)
#Enter loop.
while s.find(string_to_find) == -1:
    #Start may come in the middle of 2 packets so we break s
    #in a safe way, e.g. we leave the last len(string_to_find)
    #characters.
    lst.append(s[:-len(string_to_find)])
    #recv call.
    s = s[-len(string_to_find):] + conn.recv(HINT)


This gives you the general idea of how to go, but notice that there
are improvements that need to be made. For example, the calls from
recv may return '' indicating that the connection was closed on the
other end, etc.

HTH, with my best regards,
G. Rodrigues


From gerard.henry at free.fr  Sun Aug 17 15:44:38 2003
From: gerard.henry at free.fr (gerard henry)
Date: Sun Aug 17 08:44:52 2003
Subject: [Tutor] questions about debugging program
Message-ID: <3F3F78B6.5000408@free.fr>

hello,
i have to modify a big program writen in python (python 2.3, 
pygtk-0.6.11, MySQL module..., there is 60 modules!) and i begin to 
learn python with "Learning Python" book.
I've some experience in other langages as C, C++, so i want to replace 
in actual code:
print statement
by something like:
print "%s %d" __FILE__ __LINE__ statement
as we used to do in C/C++, so i can go to the right line in the right 
file easier.
I see that i can use __name__ or __file__ for file name, but how can i 
have the line number?
I think the best thing i can do is to replace print statement by 
something like print2(statement), but it s not easy to replace lines 
because sometimes print is more comlex, perhaps i can rewrite a print() 
function? i'm sure that somathing already exists, but where?

Thanks for your help,

gerard


From mwagman at charter.net  Sun Aug 17 13:55:07 2003
From: mwagman at charter.net (Mike Wagman)
Date: Sun Aug 17 08:55:09 2003
Subject: [Tutor] Killing the Dos window
Message-ID: <1061125072.2876.4.camel@24-159-242-118.jvl.wi.charter.com>

While I love getting error and debug messages when I am coding. I am
getting something ready to send to an end user (amatuer programmer with
first project with commercial potential). Is there a way - to not get
that dos window opening. I am using py2exe to create the executable, and
would just like to clean things up a bit. I am piping std error to a
file but the window still opens. 




From idiot1 at netzero.net  Sun Aug 17 12:05:23 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 17 11:05:05 2003
Subject: [Tutor] where you is?
In-Reply-To: <20030817034702.GA6051@wdfs.graniteweb.com>
References: <20030816164205.B75049-100000@localhost.name>	<3F3EECB2.5080204@netzero.net>
	<20030817034702.GA6051@wdfs.graniteweb.com>
Message-ID: <3F3F99B3.3050603@netzero.net>

She forces you to associate with NORMAL people? What a devoted husband,
to endure such suffering for her sake. Dear 'Bob', my sympathies sir...
how do you stand it?

RUN, do not walk, to http://www.subgenius.com/ for some quick acting
antidote, then scratch out a check for $30- salvation guranteed or
TRIPLE your money back!

And remember, SMILE, it drives normals crazy(ier) wondering what you're up to...

David Rock wrote:

> * Kirk Bailey <idiot1@netzero.net> [2003-08-16 22:47]:
> 
>>tpc@csua.berkeley.edu wrote:
>>
>>
>>>for the mentally challenged such as myself, I consider it a refreshing
>>>change of pace to have weekends to focus on other important things like
>>>video games and riding my bicycle.  I did, however, have my first Python
>>>dream just a few minutes ago...
>>>
>>
>>wow. serious hard case. My kind of hacker. Been there myself when hammering 
>>it in hard early on in the learning curve. tell me, was it a happy dream, 
>>just a strange mix of dreamstuff and codestuff, frightening nightmare, or- 
>>well, shall we say, was it of an adult nature?
>>
>>And I'm glad to see some people still manage to have a life AND a passion 
>>for programming.
> 
> 
> The only reason I have a life is because my wife says so ;-) 
> I would be a hopeless case if she didn't make me socialize with normal
> people.
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Sun Aug 17 14:54:25 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 17 13:54:28 2003
Subject: [Tutor] strange magic
Message-ID: <3F3FC151.50702@netzero.net>

ok, I got the thing feeding the file. Feeds the name, the fieldname, and the 
content of the file. The thing spews THIS at the receiving end:
('ware wordwrap...)
form= FieldStorage(None, 
None,[FieldStorage('userfile','AN_flaming_TinyList.gif', 
'GIF89a\211\0003\000\245\000\000\002\002\002\326\2726\225\020\006\202\010\003\273\2159\203&\015l\004\003\270@\027W\002\002\267\255\224C\002\002\263Y\032\2048\016\371\350#:\002\00266.bbR\344\332\257\352~)\211r\015\334\305\201\357\2310\212p\022\350\325@\244\'\015\332n&\372\366\307\212\210m4\002\002\365\272-\321Z\037\371\355k\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377!\377\013NETSCAPE2.0\003\001\000\000\000!\371\004\011\005\000 
\000,\000\000\000\000\211\0003\000\000\006\376@\220pH,\032\217H\004r\311l\032\225\316\250tJ\035\032\014\302\201\363p\250z\217\320\257x<\035h\267g\262z\315&\013\004\030L\372z\224H\332Q:~\257\216\023\257XC\002v\022\002|KZ\\]\207\214FZi\212]\213\200\202\203\025\025\206\215Eo\007~\232\237\177\221\006\010\007J\010\006f\211\002\227\025\240D\030\235\030\036\236\256{\251 
W\007\031\007\224(and much, much more; it's the data structure of an image file 
after all...)
ok, check this out.
	FieldStorage(...
ok, it says ther return is iteself an instance of FieldStorage.
	('userfile',
right, that's the name of the field in the form used to upload the thing.
	'AN_flaming_TinyList.gif'
right, that's the name of the file. How to ACCESS this stuff is puzzling. I am 
going to read the cgi module doc AGAIN, but any and all relevant comments would 
be well received.
	'GIF89a'....
  That's the start of the actual filedata.

To witness this chaos for yourself, visit
http://www.tinylist.org/testform.html
and click the browse button. Don't sweat, the program has a sys.exit in it long 
before the thing would save the file. Right now I am puzzling out the unpacking 
of the post method data into elements-and filename.

please advise.


-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From clay at shirky.com  Sun Aug 17 15:04:03 2003
From: clay at shirky.com (Clay Shirky)
Date: Sun Aug 17 14:14:12 2003
Subject: [Tutor] The Zen of List Comprehension
In-Reply-To: <BB6123E9.BFBD%clay@shirky.com>
Message-ID: <BB653BD3.C000%clay@shirky.com>

The most interesting thing to me about the functional programming thread is
that I had to explain to myself what it is I find compelling about list
comprehensions, and today it hit me: filter and map are inappropriately high
level for functions as basic as they are, and list comprehensions are a way
of making operations on lists fundamental.

If you think of simple transformations of lists, in either number or value
of elements, as a basic tool, then having special functions for these
operations makes no more sense than having a function like
assignVariable(x=1). Since assignment is an essential operation,
assignVariable() is needless verbiage. Instead, you can just assign
directly: x=1.

Saying you are going to filter a list before actually filtering it is
likewise needless verbiage. Instead of saying filter(), just filter
directly: [ x for x in nums if x > 3 ].

The same goes for map. Instead of declaring in advance that you are going to
map each element of a list to some transforming function, just write the
transformation directly into the list operation: [ len(n) for n in words ].

Add the limitation of operations on single anonymous variables (so perlish),
and the resultant profusion of lambdas (again, don't say "Now I'm going to
put a function in-line", just put the function in-line: [x*x for x in
nums]), and list comprehensions look to me like a huge improvement.

The one thing I still don't understand is whether list comps are valid
functional programming constructs. Does

return [ (x, x*y) \
         for x in nums if x > 0 \
             for y in values if y < 10 ]

count as functional programming? (which is, I think, a slightly different
question than "Did it come from haskell?")

-clay




From shalehperry at comcast.net  Sun Aug 17 20:13:44 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug 17 22:14:23 2003
Subject: [Tutor] chain gangs of the mind...
In-Reply-To: <3F3D85AA.9030706@netzero.net>
References: <3F3D85AA.9030706@netzero.net>
Message-ID: <200308171913.44600.shalehperry@comcast.net>

On Friday 15 August 2003 18:15, Kirk Bailey wrote:
> I want a script, at the end of execution, to launch another script. I don't
> care if this wipes the old one out of memory, namespace, whatever, it will
> no longer be needed. When the editor finishes provessing a page, I want it
> as a last act to launch the browser wiki script with the page name fed to
> it. Any ideas on how to effect this?
> --

just like you do in C, use one of the exec() family.  In Python these are 
found in the 'os' module.

You usually hear of people doing fork() before exec() because they want to run 
a program AND keep the existing program running.


From idiot1 at netzero.net  Sun Aug 17 23:30:44 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 17 22:30:42 2003
Subject: [Tutor] chain gangs of the mind...
In-Reply-To: <200308171913.44600.shalehperry@comcast.net>
References: <3F3D85AA.9030706@netzero.net>
	<200308171913.44600.shalehperry@comcast.net>
Message-ID: <3F403A54.20802@netzero.net>

In this case, the new program runs at the very end of the old one- specifically, 
when the editor finishes, I want it to hand off to the browser, handing it the 
name of the page just edited. so it will do the displaying of the result, 
avoiding having to write the display engine another time, import parts of the 
script, yadayadayada... I figured that if I do it right, I can avoid having more 
in  memory than is needed for the CURRENT program. Forking in this application 
is not needed.

On another note (AHHHHHH... ) I finished up the titlelisting, and included 
references to it and the backsearch in the browser footers. Browser is still 
bulching pagecode, but a bit better.
Here is alink to the wiki:
http://www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage
the sourcecode:
http://www.tinylist.org/wikinehesa.txt
backsearch sourcecode:
http://www.tinylist.org/backsearch.txt
titlelist sourcecode:
http;//www.tinylist.org/titlelist.txt

I still need to do 2 things:
	* beat the processing of wikiwords into proper submission
	* create the uploader script for images to the ../images directory.

All inout is saught and appreciated.

Will read replies to any and all issues tomorrow after work. Goodnight.



Sean 'Shaleh' Perry wrote:

> On Friday 15 August 2003 18:15, Kirk Bailey wrote:
> 
>>I want a script, at the end of execution, to launch another script. I don't
>>care if this wipes the old one out of memory, namespace, whatever, it will
>>no longer be needed. When the editor finishes provessing a page, I want it
>>as a last act to launch the browser wiki script with the page name fed to
>>it. Any ideas on how to effect this?
>>--
> 
> 
> just like you do in C, use one of the exec() family.  In Python these are 
> found in the 'os' module.
> 
> You usually hear of people doing fork() before exec() because they want to run 
> a program AND keep the existing program running.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From shalehperry at comcast.net  Sun Aug 17 21:01:09 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug 17 23:01:44 2003
Subject: [Tutor] chain gangs of the mind...
In-Reply-To: <3F403A54.20802@netzero.net>
References: <3F3D85AA.9030706@netzero.net>
	<200308171913.44600.shalehperry@comcast.net>
	<3F403A54.20802@netzero.net>
Message-ID: <200308172001.09108.shalehperry@comcast.net>

On Sunday 17 August 2003 19:30, Kirk Bailey wrote:
> In this case, the new program runs at the very end of the old one-
> specifically, when the editor finishes, I want it to hand off to the
> browser, handing it the name of the page just edited. so it will do the
> displaying of the result, avoiding having to write the display engine
> another time, import parts of the script, yadayadayada... I figured that if
> I do it right, I can avoid having more in  memory than is needed for the
> CURRENT program. Forking in this application is not needed.
>

silly.

That's the point.  If you *JUST* exec() the new process takes over the old 
one.  Kind of like in the Matrix where an Agent takes over one of the humans 
still trapped.

And Kirk, please, no need to CC people who respond to you.  Just reply to the 
list.  Thanks.


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 17 21:08:27 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 17 23:08:33 2003
Subject: [Tutor] questions about debugging program
In-Reply-To: <3F3F78B6.5000408@free.fr>
Message-ID: <Pine.LNX.4.44.0308171956440.26899-100000@hkn.eecs.berkeley.edu>



On Sun, 17 Aug 2003, gerard henry wrote:

> I've some experience in other langages as C, C++, so i want to replace
> in actual code:
> print statement
> by something like:
> print "%s %d" __FILE__ __LINE__ statement
> as we used to do in C/C++, so i can go to the right line in the right
> file easier.

Hi Gerard,

Welcome aboard!  Yes, there is a way of emulating __LINE__:

    http://www.faqts.com/knowledge_base/view.phtml/aid/4456/fid/538

But that being said, you may want to take a close look into Python's
'logging' package:

    http://www.python.org/doc/lib/module-logging.html

This logging package was recently introduced into Python 2.3.  It is very
good because it supports several options for each log message, including a
'lineno' option.  We can do this by creating a Formatter object:

    formatter = logging.Formatter('%(module)s %(lineno)d: %(message)s')

and use the setFormatter() method of our logging handler object.  This
approach is more robust than doing the line-number hack from the FAQTS
link above.


'logging' was just recently added into the standard library, so you may
not have it in your installation.  If you need to stick with an older
version of Python, you can look into Vinay Sajip's 'logging' module:

    http://www.red-dove.com/python_logging.html

which I think has a similar API to the Standard Library's logger.  But if
you can, upgrade to Python 2.3: it has a lot of nice features.


If you have more questions, please feel free to ask on Tutor; we'll be
happy to help!


From luc.saffre at gmx.net  Mon Aug 18 07:08:38 2003
From: luc.saffre at gmx.net (Luc Saffre)
Date: Sun Aug 17 23:08:55 2003
Subject: [Tutor] Killing the Dos window
In-Reply-To: <1061125072.2876.4.camel@24-159-242-118.jvl.wi.charter.com>
References: <1061125072.2876.4.camel@24-159-242-118.jvl.wi.charter.com>
Message-ID: <3F404336.6060608@gmx.net>

Mike,

This page speaks about your problem:
http://www.onlamp.com/pub/a/python/excerpts/chpt20/index.html?page=2

Luc

On 17/08/2003 15:57, Mike Wagman wrote:

>While I love getting error and debug messages when I am coding. I am
>getting something ready to send to an end user (amatuer programmer with
>first project with commercial potential). Is there a way - to not get
>that dos window opening. I am using py2exe to create the executable, and
>would just like to clean things up a bit. I am piping std error to a
>file but the window still opens. 
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 17 21:10:30 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 17 23:10:33 2003
Subject: [Tutor] Killing the Dos window
In-Reply-To: <1061125072.2876.4.camel@24-159-242-118.jvl.wi.charter.com>
Message-ID: <Pine.LNX.4.44.0308172008430.26899-100000@hkn.eecs.berkeley.edu>



On 17 Aug 2003, Mike Wagman wrote:

> While I love getting error and debug messages when I am coding. I am
> getting something ready to send to an end user (amatuer programmer with
> first project with commercial potential). Is there a way - to not get
> that dos window opening. I am using py2exe to create the executable, and
> would just like to clean things up a bit. I am piping std error to a
> file but the window still opens.

Hi Mike,

Yes, we can keep the console window from opening up by naming your
Python program file with a '.pyw' extension.

Alternatively, we can use the '--windows' option from py2exe,

   http://py2exe.sourceforge.net/

and it'll will also suppress the console window.


Good luck to you!


From RASTM2 at aol.com  Mon Aug 18 02:24:31 2003
From: RASTM2 at aol.com (RASTM2@aol.com)
Date: Mon Aug 18 01:24:41 2003
Subject: [Tutor] RE: Killing the Dos window
Message-ID: <97.3cea800b.2c71bd0f@aol.com>

In a message dated 8/17/03 10:09:40 PM Central Daylight Time, 
tutor-request@python.org writes:

> Mike Wagman <mwagman@charter.net>
> Subject: [Tutor] Killing the Dos window
> 
Mike writes:

> While I love getting error and debug messages when I am coding. I am
> getting something ready to send to an end user (amatuer programmer with
> first project with commercial potential). Is there a way - to not get
> that dos window opening. I am using py2exe to create the executable, and
> would just like to clean things up a bit. I am piping std error to a
> file but the window still opens. 
> 

Hi, Mike

The advice I was given for that situation, is to call the 
setup.py and py2exe with pythonw 
instead of plain ol' python. 

Like:

---8<------------

c:\myscripts\pythonw setup.py py2exe

---8<----------

Worked pretty good too. 
I got my little windowed progy and no 
DumbOl'System box in the background. 

HTH, Pleased to serve.

Ray St. Marie
Rastm2@aol.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030818/6fd04669/attachment.htm
From alan.gauld at blueyonder.co.uk  Mon Aug 18 09:48:10 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 18 03:47:08 2003
Subject: [Tutor] questions about debugging program
References: <3F3F78B6.5000408@free.fr>
Message-ID: <011101c3655d$12686020$6401a8c0@xp>

> print "%s %d" __FILE__ __LINE__ statement
> as we used to do in C/C++, so i can go to the right line in the
right
> file easier.

AFAIK There is no easy way to do this in Python.
I think the only option is to raise an exception and catch
it immediately. The traceback object can then be queried
to find the line number where it occured - I think.

Something like:

try:   raise TypeError   # any old exception.
except TypeError: printError(e)

Where printError looks like:

def printError(anException):
    tb = sys.exc_info()
    print "line = ",tb.tb_lineno

Check the manual for the traceback module, I think there are
some functions there to help get exactly what you want displayed...

Caveat: I have never tried this just read about it! Usually I
just live without the __Line__ info. And if dealing with big
programs I usually prefer to use the dbg module to watch whats
happening rather than insert lots of print statements.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at blueyonder.co.uk  Mon Aug 18 09:51:21 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 18 03:50:15 2003
Subject: [Tutor] Killing the Dos window
References: <1061125072.2876.4.camel@24-159-242-118.jvl.wi.charter.com>
Message-ID: <011801c3655d$841505c0$6401a8c0@xp>


> first project with commercial potential). Is there a way - to not
get
> that dos window opening.

In regular Python you would just rename the .py file to .pyw

> I am using py2exe to create the executable,

I never use py2exe but does it have any options to select pyw
files instead of py? THat might be enough?

Or it might be the python interpreter (pythonw.exe) that you need
to change?

Just some ideas,
HTH,

Alan G.


From alan.gauld at blueyonder.co.uk  Mon Aug 18 10:07:39 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 18 04:06:37 2003
Subject: [Tutor] The Zen of List Comprehension
References: <BB653BD3.C000%clay@shirky.com>
Message-ID: <012101c3655f$caee01c0$6401a8c0@xp>

> of elements, as a basic tool, then having special functions for
these
> operations makes no more sense than having a function like
> assignVariable(x=1). Since assignment is an essential operation,

And here you raise another thorny issue since one of the features
of pure FP is that assignment is NOT an essential operation but
in fact is something to avoid. Indeed the grandaddy of FP languages
Lisp has no assignment operation as we know it but uses a function
to do assignment:

(set x 7)

:-)

> likewise needless verbiage. Instead of saying filter(), just filter

OK, But the name 'filter' is there as a reminder of the purpose of
the function. Its a readability issue as much as anything. If I'm
scanning the code I don;t need to know whatexactly is being
filtered I just know that something has been filtered out of
the list into a new list. Whereas with a LC I have to read the
internal detail even to know that a filter has happened!

> Add the limitation of operations on single anonymous variables,
> and the resultant profusion of lambdas

Yes but the intent is not that you put lambdas in map and filter
but that you put real named functions:

def square(x): return x*x
map(square,aList)

As I've said many times lambdas are just a coincidental feature
of how many folks use map/filter etc, they are not a necessary
element. Now of course for simple one-liner funtions like above
it is more work to create the function than to use a lambda,
and much more so than to use an inline expression, the improvement
in readability is significant.

> The one thing I still don't understand is whether list comps are
valid
> functional programming constructs. Does

Yes they are. Any book on discrete math will include how to describe
list comprehensions. Its a fundamental part of the subject the ability
to describe a list and its contents.

The FP approach however is to use LC as the list initialiser then
apply list operations(like filter, map etc) to modify the list.
In FP LCs are kind of like constructors for lists.

Alan G.


From alan.gauld at blueyonder.co.uk  Mon Aug 18 10:10:30 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 18 04:09:30 2003
Subject: [Tutor] questions about debugging program
References: <Pine.LNX.4.44.0308171956440.26899-100000@hkn.eecs.berkeley.edu>
Message-ID: <012c01c36560$3113e8c0$6401a8c0@xp>

> But that being said, you may want to take a close look into Python's
> 'logging' package:
> 
>     http://www.python.org/doc/lib/module-logging.html

Wow! I missed that one. Thanks for pointing it out Danny.

Alan G.


From vicki at thepenguin.org  Mon Aug 18 10:47:02 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Mon Aug 18 10:47:08 2003
Subject: [Tutor] how to check if serial port is open
Message-ID: <8103.206.53.226.4.1061218022.squirrel@www.thepenguin.org>

I have a program which reads from and writes to a device via an infrared
dongle attached to my computer's serial port. I can read and write fine
when the device is in communication mode, but I don't know how to test
whether or not the device is available. The device itself is proprietary,
but I was hoping that there is something similar out there to use as an
example. Basically, I send a command in hex format to the device and the
device responds with a hex response. If the device has timed out and is no
longer in com mode, I get nothing back. Is there a standard way to test
for this condition so that I can send an appropriate error code to the
user?

--vicki

From joanna9765 at yahoo.com  Mon Aug 18 11:11:51 2003
From: joanna9765 at yahoo.com (Joanna Ingrahm)
Date: Mon Aug 18 13:11:56 2003
Subject: [Tutor] using python to start and stop a program
In-Reply-To: <5.2.1.1.0.20030812163134.020ddf28@www.thinkware.se>
Message-ID: <20030818171151.99640.qmail@web80705.mail.yahoo.com>

Hi Magnus,
sorry I didn't reply sooner!
> Hi Johanna, perhaps you can show us some code, and
> we
> might spot the problems in it. 

I tried s.th. like this:
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock 
os.spawnl(os.P_NOWAIT, "D:\\Apps", "prog.exe", "-l")
sys.stdout = saveout                                  
 
fsock.close()  



>In what way did writing
> the info to a file and reading it back fail. Writing
> or reading? Did it get to the file?

No

> Why do you need to store the pid in a file? 
It doesn't have to be like that, I just don't know how
else I could do it

Are you
> using separate python processes to start and stop?

so far I only tried to start  it

> Has
> the writing process exited before the other process
> reads the file?

I only have one process running so far...

thanks,
Joanna

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From dyoo at hkn.eecs.berkeley.edu  Mon Aug 18 11:38:04 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 18 13:38:08 2003
Subject: [Tutor] Follow up the question: Does Python support a centralized
 network install?
Message-ID: <Pine.LNX.4.44.0308181036010.21452-100000@hkn.eecs.berkeley.edu>

Hi Alan,

I know this is sorta late, but I'm following up on your original question:


"""Can all Windows users on a LAN/WAN cleanly run a central installation
of Python from a central server? Or is this not really practical? I think
speed would be an issue but is it supported at all?"""


This just came up on the comp.lang.python newsgroup this week:

http://groups.google.com/groups?threadm=mailman.1060677681.10554.python-list@python.org


In short: yes.  *grin*




Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Mon Aug 18 11:57:33 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 18 13:57:47 2003
Subject: [Tutor] The Zen of List Comprehension
In-Reply-To: <BB653BD3.C000%clay@shirky.com>
Message-ID: <Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>



On Sun, 17 Aug 2003, Clay Shirky wrote:

> Saying you are going to filter a list before actually filtering it is
> likewise needless verbiage. Instead of saying filter(), just filter
> directly: [ x for x in nums if x > 3 ].


Hi Clay,

Yes, that's very true.  filter() pays off if the test is either already
built-in, or is some boolean function that we've already written.  But for
arbitrary expressions that we might use just once, it is a little more
work to use filter(), and in those cases, we'd prefer using the list
comprehension.


> Add the limitation of operations on single anonymous variables (so
> perlish), and the resultant profusion of lambdas (again, don't say "Now
> I'm going to put a function in-line", just put the function in-line:
> [x*x for x in nums]), and list comprehensions look to me like a huge
> improvement.

Just to clarify: list comprehensions are syntactic improvements: they
don't give us any new capabilities, but they do make those existing
capabilities easier to use.  In academic terms, they are a kind of
"syntactic sugar", since almost everything we can do with list
comprehensions is possible with a direct combination of map() and
filter().

List comprehensions are pretty sweet, though... *grin* I'm glad to hear
that you got them.



It sounds like you're getting more interested about functional
programming.  For a more comprehensive taste of it, you may find David
Mertz's other articles useful.  For example:

http://www-106.ibm.com/developerworks/linux/library/l-cpyiter.html?ca=dgr-lnxw06Itertools

shows off a set of functions from the new 'itertools' library package. His
article shows things that are possible with these functional tools that
don't really have equivalents with list comprehensions.



I personally got exposed to functional programming in one of my college
courses.  If you're interested, the textbook for that course is here:

    http://mitpress.mit.edu/sicp/full-text/book/book.html

It doesn't use Python --- it uses a language called Scheme --- but, in my
opinion, it's one of the nicest CS textbooks I've ever read.  A bit mind
warping, through.  *grin*



Good luck to you!



From karld at ugcs.caltech.edu  Mon Aug 18 12:41:18 2003
From: karld at ugcs.caltech.edu (karl d'adamo)
Date: Mon Aug 18 14:41:22 2003
Subject: [Tutor] Graphical object browser?
In-Reply-To: <Pine.LNX.4.44.0308051840520.28264-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0308051840520.28264-100000@violet.rahul.net>
Message-ID: <20030818184117.GA16401@ugcs.caltech.edu>

On Tue, Aug 05, 2003 at 06:45:05PM -0700, Terry Carroll wrote:
 : I'm trying to get started with the XML DOM interface, and am finding that 
 : I tend to get lost in the document object.
 : 
 : I've had this happen before on smaller scale, and worked through using 
 : dir(object) and dir(object.thing) and dir(object.thing[0].dohickie), etc. 
 : and it's kind of awkward.

it sounds like you aren't that fond of walking through the
xml tree, but you might want to check out xmltramp [0].

you can do things like:

  d = xmltramp.parse(urllib2.urlopen(XMLDOC).read())
  >>> d[0]                # First child.
  <author>...</author>
  >>> d.author            # First author.
  <author>...</author>
  >>> str(d.author)
  'John Polk and John Palfrey'
  >>> d[dc.creator]        # First dc:creator.
  <dc:creator>...</dc:creator>
  >>> d[dc.creator:]       # All creators.
  [<dc:creator>...</dc:creator>,
  <dc:creator>...</dc:creator>]

its nice if you want to browse a document from the python
interpreter without knowing much about its structure, or
change one small thing.

peace

[0] http://www.aaronsw.com/2002/xmltramp/

From karld at ugcs.caltech.edu  Mon Aug 18 12:51:10 2003
From: karld at ugcs.caltech.edu (karl d'adamo)
Date: Mon Aug 18 14:51:20 2003
Subject: [Tutor] Windows software reporting
In-Reply-To: <3F33FCD0.10402@unixremedies.com>
References: <3F33FCD0.10402@unixremedies.com>
Message-ID: <20030818185110.GB16401@ugcs.caltech.edu>

On Fri, Aug 08, 2003 at 02:41:04PM -0500, Justin Heath wrote:
 : 
 : I am currently writing a program that queries Linux, Solaris boxes for 
 : installed software and software versions and comparing this information 
 : against a database. It appears this could be useful to our Windows guys 
 : as well. My question is how to get this information on a Windows box. 
 : Currently for Linux I am using os.popen("rpm -qa", "r"), for example. 
 : Any suggestions?

this is not a python solution, but i have used and like
Balarc advisor (free for noncommerical use) [0].
unfortunately, its just an executable, so you won't be
able to learn much about how this is done.

[0] http://www.belarc.com/free_download.html

From justin at unixremedies.com  Mon Aug 18 12:12:02 2003
From: justin at unixremedies.com (Justin Heath)
Date: Mon Aug 18 15:02:18 2003
Subject: [Tutor] gdbm / python howto or tutorial
Message-ID: <3F40FAD2.60909@unixremedies.com>

All,

I am looking for information on using gdbm with python. I have not used 
gdbm in the past but am interested in using it in cases where I cannot 
use mysql. Therefore, I do need something pretty introductory. I have 
looked for documentation but mostly what I have found is C code, and 
don't want to "learn" C just to get started. Any pointers would be 
appreciated.

Thanks,
Justin



From dyoo at hkn.eecs.berkeley.edu  Mon Aug 18 15:01:09 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 18 17:01:35 2003
Subject: [Tutor] gdbm / python howto or tutorial
In-Reply-To: <3F40FAD2.60909@unixremedies.com>
Message-ID: <Pine.LNX.4.44.0308181314480.27171-100000@hkn.eecs.berkeley.edu>



On Mon, 18 Aug 2003, Justin Heath wrote:

> I am looking for information on using gdbm with python. I have not used
> gdbm in the past but am interested in using it in cases where I cannot
> use mysql. Therefore, I do need something pretty introductory. I have
> looked for documentation but mostly what I have found is C code, and
> don't want to "learn" C just to get started. Any pointers would be
> appreciated.

Hi Justin,


The documenation to gdbm:

    http://www.python.org/doc/lib/module-gdbm.html

doesn't itself have an example, but it say that 'gdbm' objects behave a
lot like dictionaries (except that keys and values are forced to be
strings).


Here's a quicky example: Let's say that we'd like to create a new DBM
file:

###
>>> import gdbm
>>> definitions = gdbm.open('test_gdbm.dbm', 'c')
>>> definitions['pair programming'] = '''
... An XP practice requiring that each piece of source code
... to be integrated into the software product should be created
... by two programmers jointly at one computer.'''.strip()
>>> definitions['code smell'] = '''
... The unpleasant feeling you get when you see bad code'''.strip()
>>> definitions.close()
###


This saves a 'dbm' file onto disk.  Another program can then open this dbm
file up:

###
>>> import gdbm
>>> definitions = gdbm.open('test_gdbm.dbm')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
gdbm.error: Flag ' ' is not supported.
###


Oh.  Unlike regular file opening, this one doesn't default to 'read' mode,
so we'll have to directly specify it:

###
>>> definitions = gdbm.open('test_gdbm.dbm', 'r')
>>> definitions.keys()
['code smell', 'pair programming']
>>> definitions['code smell']
'The unpleasant feeling you get when you see bad code'
###


Ok, better.  *grin*




By the way, Bob Gailer recently mentioned Sqlite,

    http://www.hwaci.com/sw/sqlite/


which does appear to be an alternative way of getting very lightweight SQL
behavior.  The equivalent code, using Sqlite, looks like:

###
>>> import sqlite
>>> conn = sqlite.connect(db='definitions')
>>> cursor = conn.cursor()
>>> cursor.execute("""create table definitions
...  (word varchar not null, defn varchar not null)""")
>>> cursor.execute("insert into definitions values ('hello', 'world')")
>>> cursor.execute("select * from definitions")
>>> cursor.fetchall()
[('hello', 'world')]
>>> conn.commit()
###

One warning: when using any SQL database, don't forget to commit.  I made
this mistake a couple of times since MySQL has autocommit behavior, and I
still bungle it sometimes... *grin* But the changes to a Sqlite database
won't persist and will be rolled back when we quit the program, unless we
explicitely do the commit().


Hope this helps!


From amk at amk.ca  Mon Aug 18 17:05:17 2003
From: amk at amk.ca (A.M. Kuchling)
Date: Mon Aug 18 17:24:39 2003
Subject: [Tutor] type objects - 2nd try
In-Reply-To: <3F3D5022.3050709@aon.at>
Message-ID: <49D76C7C-D1B7-11D7-B7ED-0003931BF218@amk.ca>

On Friday, August 15, 2003, at 05:26  PM, Gregor Lingl wrote:
> >>> type(len) == type(abs)
> True

Better: isinstance(len, type(abs)) .

> (1) Are there named type-objects for functions, generators, classes
> and the like, in order to determine the type of functions, generators 
> etc.
> more easily, i. e. not to need to define a "prototype"-object first.
> If so, what are their names?

The 'types' module has FunctionType, GeneratorType, ClassType.  Note 
that built-ins such as callable() are more useful than checking if 
isinstance(thing, FunctionType); callable() will report methods as 
being callable, while the isinstance() check will only report true for 
functions.

--amk


From justin at unixremedies.com  Mon Aug 18 18:12:33 2003
From: justin at unixremedies.com (Justin Heath)
Date: Mon Aug 18 18:15:35 2003
Subject: [Tutor] gdbm / python howto or tutorial
In-Reply-To: <Pine.LNX.4.44.0308181314480.27171-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308181314480.27171-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F414F51.5070709@unixremedies.com>

Danny Yoo wrote:

>On Mon, 18 Aug 2003, Justin Heath wrote:
>
>  
>
>>I am looking for information on using gdbm with python. I have not used
>>gdbm in the past but am interested in using it in cases where I cannot
>>use mysql. Therefore, I do need something pretty introductory. I have
>>looked for documentation but mostly what I have found is C code, and
>>don't want to "learn" C just to get started. Any pointers would be
>>appreciated.
>>    
>>
>
>Hi Justin,
>
>
>The documenation to gdbm:
>
>    http://www.python.org/doc/lib/module-gdbm.html
>
>doesn't itself have an example, but it say that 'gdbm' objects behave a
>lot like dictionaries (except that keys and values are forced to be
>strings).
>
>
>Here's a quicky example: Let's say that we'd like to create a new DBM
>file:
>
>###
>  
>
>>>>import gdbm
>>>>definitions = gdbm.open('test_gdbm.dbm', 'c')
>>>>definitions['pair programming'] = '''
>>>>        
>>>>
>... An XP practice requiring that each piece of source code
>... to be integrated into the software product should be created
>... by two programmers jointly at one computer.'''.strip()
>  
>
>>>>definitions['code smell'] = '''
>>>>        
>>>>
>... The unpleasant feeling you get when you see bad code'''.strip()
>  
>
>>>>definitions.close()
>>>>        
>>>>
>###
>
>
>This saves a 'dbm' file onto disk.  Another program can then open this dbm
>file up:
>
>###
>  
>
>>>>import gdbm
>>>>definitions = gdbm.open('test_gdbm.dbm')
>>>>        
>>>>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>gdbm.error: Flag ' ' is not supported.
>###
>
>
>Oh.  Unlike regular file opening, this one doesn't default to 'read' mode,
>so we'll have to directly specify it:
>
>###
>  
>
>>>>definitions = gdbm.open('test_gdbm.dbm', 'r')
>>>>definitions.keys()
>>>>        
>>>>
>['code smell', 'pair programming']
>  
>
>>>>definitions['code smell']
>>>>        
>>>>
>'The unpleasant feeling you get when you see bad code'
>###
>
>
>Ok, better.  *grin*
>
>
>
>
>By the way, Bob Gailer recently mentioned Sqlite,
>
>    http://www.hwaci.com/sw/sqlite/
>
>
>which does appear to be an alternative way of getting very lightweight SQL
>behavior.  The equivalent code, using Sqlite, looks like:
>
>###
>  
>
>>>>import sqlite
>>>>conn = sqlite.connect(db='definitions')
>>>>cursor = conn.cursor()
>>>>cursor.execute("""create table definitions
>>>>        
>>>>
>...  (word varchar not null, defn varchar not null)""")
>  
>
>>>>cursor.execute("insert into definitions values ('hello', 'world')")
>>>>cursor.execute("select * from definitions")
>>>>cursor.fetchall()
>>>>        
>>>>
>[('hello', 'world')]
>  
>
>>>>conn.commit()
>>>>        
>>>>
>###
>
>One warning: when using any SQL database, don't forget to commit.  I made
>this mistake a couple of times since MySQL has autocommit behavior, and I
>still bungle it sometimes... *grin* But the changes to a Sqlite database
>won't persist and will be rolled back when we quit the program, unless we
>explicitely do the commit().
>
>
>Hope this helps!
>
>  
>
I have since found the refered document. I can now create and re-open db 
files I have created. However, I cannot seem to open redhat rpm database 
files or freebsd pkgdb files. I keep getting an invalid argument error 
when using the syntax:

 >>> import anydbm
 >>> dbf = anydbm.open('pkgdb', 'r')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.2/anydbm.py", line 86, in open
    return mod.open(file, flag, mode)
  File "/usr/lib/python2.2/dbhash.py", line 16, in open
    return bsddb.hashopen(file, flag, mode)
bsddb.error: (22, 'Invalid argument')

**Note I have also tried the above using bsdb abd dbhash with the same 
result.

This appears that it may be a versioning issue between versions of 
berkley db but I am unsure since I have tried using the db_upgrade on 
(copies of) the files with the same results. If anyone has gotten this 
to work or has any additional info please let me know.

Thanks,
Justin



From idiot1 at netzero.net  Mon Aug 18 21:12:09 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 18 20:12:30 2003
Subject: [Tutor] chain gangs revolt, film at 11
Message-ID: <3F416B59.9010404@netzero.net>

Dear anyone;
ok, trying to have one program on ending to fire off another. It's not 
happening. I never tried this before, and expertise has not been this low for 
quite a while.

Links:
program itself:
http://www.tinylist.org/wikinehesaed2.txt

Error log:
http://www.tinylist.org/STATS/www-error.log

problem,, quoting from the error log:

Traceback (innermost last):
   File "/www/www.tinylist.org/cgi-bin/wikinehesaed2.py", line 24, in ?
     os.execl(path+'/wikinehesa.py/'+pagename)
   File "/usr/local/lib/python1.5/os.py", line 169, in execl
     execv(file, args)
OSError: [Errno 20] Not a directory

Path is functioning flawlessly- see script listing to see how it is generated.
in breif, it reads the sys.argv[0] and chomps it apart to extract the path 
arguement that fired off the program. The script this one TRIES to trigger also 
lives in the web cgi-bin.

anyone want to provide some clue?



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From dyoo at hkn.eecs.berkeley.edu  Mon Aug 18 19:00:22 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 18 21:00:27 2003
Subject: [Tutor] chain gangs revolt, film at 11
In-Reply-To: <3F416B59.9010404@netzero.net>
Message-ID: <Pine.LNX.4.44.0308181730150.4043-100000@hkn.eecs.berkeley.edu>



On Mon, 18 Aug 2003, Kirk Bailey wrote:

> problem,, quoting from the error log:
>
> Traceback (innermost last):
>    File "/www/www.tinylist.org/cgi-bin/wikinehesaed2.py", line 24, in ?
>      os.execl(path+'/wikinehesa.py/'+pagename)
>    File "/usr/local/lib/python1.5/os.py", line 169, in execl
>      execv(file, args)
> OSError: [Errno 20] Not a directory
>
> Path is functioning flawlessly- see script listing to see how it is generated.


Hi Kirk,


A certain Tao verse comes to mind:


"""The wise programmer is told about Tao
and follows it.  The average programmer
is told about Tao and searches for it.
The foolish programmer is told about Tao
and laughs at it.

If it were not for laughter, ther would be no Tao.

The highest sounds are hardest to hear.
Going forward is a way to retreat.
Great talent shows itself late in life.
Even a perfect program still has bugs.

The Tao is hidden beyond all understanding.
"""


The penultimate sentence is one I take to heart.  *grin*


It's human nature to err, and it's not shameful to acknowledge that our
understanding about our programs is less than perfect.  Going in with eyes
closed to certain possibilities might help us find a bug more quickly...
or it may lead us totally astray.  Let's see what we can do to diagnose
the problem without making too many assumptions.


First, it seems that execl() is having a hard time getting at the
executable it's trying to execute.  we should try checking to see if the
path that we're feeding into execl refers to a real file.  We can check
this by adding an assertion:

    complete_path = path + '/wikinehesa.py/' + pagename)
    assert os.path.exists(complete_path), ("file %s does not exist" %
                                           complete_path)
    os.execl(complete_path)


... ok, wait a minute.  If we take a closer look at the error message:

> Traceback (innermost last):
>    File "/www/www.tinylist.org/cgi-bin/wikinehesaed2.py", line 24, in ?
>      os.execl(path+'/wikinehesa.py/'+pagename)
>    File "/usr/local/lib/python1.5/os.py", line 169, in execl
>      execv(file, args)
> OSError: [Errno 20] Not a directory


we can guess that Python is trying to say: "I don't know about a directory
called path+'/wikinehesa.py/'+pagename."  It's very likely that Python is
treating 'wikinhesa.py' as part of a path name.


Are you sure the path to your executable should include 'wikinehea.py/' +
pagename?  I think you mean to ask the system to evaluate 'wikinehesa.py',
using pagename as an an additional argument to the 'wikinehesa.py'
program.  If so, then

    path + "/wikinehesa.py"

alone needs to be our executable argument.


If so, then we need to specity 'pagename' as part of the additional
parameters to execl().  Here is an example that execl()'ing a call to the
'ls' file listing utility:

###
[dyoo@tesuque dyoo]$ python
Python 2.2.1 (#1, Sep  3 2002, 14:52:01)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.execl('/bin/ls', '/bin/ls', '/home/dyoo/pubsearch')
build		       HACKING		  log
build.xml	       HISTORY		  maint
build.xml.~1.56.~      images		  program.properties
ChangeLog	       index.jsp	  program.properties~
ChangeLog.bak	       index.jsp.~1.16.~  program.properties.backup
css		       INSTALL		  program.properties.sample
CVS		       js
program.properties.sample.~1.12.~
data		       jsp		  README
DCB_1035496690787.log  jspc_build	  README.~1.10.~
DCB_1054343490761.log  jspc_src		  TODO
DCB_1060903313342.log  jspc_srchome	  WEB-INF
doc		       jython
experimental	       lib
[dyoo@tesuque dyoo]$
###



Hope this helps!


From marc_barry at hotmail.com  Tue Aug 19 05:48:49 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Tue Aug 19 04:49:25 2003
Subject: [Tutor] String Tokenizer - As in Java
Message-ID: <Sea2-F59Kgc44RFYfsI00028775@hotmail.com>

All:

I was wondering if there is a module similar to Java's StringTokenizer in 
Python?  It is not that difficult to write such a module in pure Python, but 
I thought I would check here first to see if it has already been done and 
more importantly tested.

Regards,

Marc

_________________________________________________________________
Add photos to your messages with MSN 8. Get 2 months FREE*.  
http://join.msn.com/?page=features/featuredemail


From abli at freemail.hu  Tue Aug 19 15:16:30 2003
From: abli at freemail.hu (Abel Daniel)
Date: Tue Aug 19 08:16:33 2003
Subject: [Tutor] String Tokenizer - As in Java
In-Reply-To: <Sea2-F59Kgc44RFYfsI00028775@hotmail.com>
References: <Sea2-F59Kgc44RFYfsI00028775@hotmail.com>
Message-ID: <20030819121630.GA521@hooloovoo>

> I was wondering if there is a module similar to Java's StringTokenizer in 
> Python?  It is not that difficult to write such a module in pure Python, 
> but I thought I would check here first to see if it has already been done 
> and more importantly tested.

I don't know anything about Java, but  quick googling turned up the following
two links:

http://lists.free.net.ph/pipermail/python/2002-February/000115.html
(follow the "Next message" links at the bottom for the full thread)

http://groups.google.com/groups?th=aa5c620fe2b75a8e
(this one is a thread from comp.lang.python, from 2003-07-24, so I doubt
you will find anything better)

Abel Daniel

From just4info at serrati.net  Tue Aug 19 15:58:05 2003
From: just4info at serrati.net (just4info)
Date: Tue Aug 19 08:55:46 2003
Subject: [Tutor] GUI Builder
Message-ID: <3F421EDD.2060607@serrati.net>

Hi there.

Are there any GUI (Tk) Builder for python(I only found some one for 
Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?

Thanks in advance

Matthias




From pythontutor at venix.com  Tue Aug 19 10:32:09 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Aug 19 09:32:45 2003
Subject: [Tutor] [Fwd: cPickle and hashes]
Message-ID: <3F4226D9.4050401@venix.com>

Forwarding to the list.

Python in a Nutshell (Martelli) and Python Standard Library (Lundh)
contain brief discussions of pickle.  I would be more suspicious of the
the socket code myself.  Presumably you can display (or log) the pickle
and hash data before it goes over the wire to pin down where the problem occurs.
-------------- next part --------------
An embedded message was scrubbed...
From: "Jonathan Hayward http://JonathansCorner.com"
	<jonathan.hayward@pobox.com>
Subject: cPickle and hashes
Date: Mon, 18 Aug 2003 23:01:06 +0100
Size: 1572
Url: http://mail.python.org/pipermail/tutor/attachments/20030819/5631a114/cPickleandhashes.eml
From marc_barry at hotmail.com  Tue Aug 19 10:56:19 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Tue Aug 19 09:56:59 2003
Subject: [Tutor] String Tokenizer - As in Java
Message-ID: <Sea2-F18QtXvXOCcUB50004f073@hotmail.com>

Thanks for the help.

I tried to google for it also and I didn't find those two links.  The second 
one gave me the answer I was looking for as it seems that 'split' does 
exactly what I want.

Although, my interpretation is that 'split' only only allows the defintion 
of one separator.  This is okay for most things, but I have strings that I 
would like to split with two separators such as '.' and '@'.  I don't think 
that I can use split to handle this and therefore will have to resort to 
something more powerful (i.e. regular expressions).

Thanks for your quick and easy answer.

Marc




From: Abel Daniel <abli@freemail.hu>
To: Marc Barry <marc_barry@hotmail.com>
CC: tutor@python.org
Subject: Re: [Tutor] String Tokenizer - As in Java
Date: Tue, 19 Aug 2003 14:16:30 +0200

 > I was wondering if there is a module similar to Java's StringTokenizer in
 > Python?  It is not that difficult to write such a module in pure Python,
 > but I thought I would check here first to see if it has already been done
 > and more importantly tested.

I don't know anything about Java, but  quick googling turned up the 
following
two links:

http://lists.free.net.ph/pipermail/python/2002-February/000115.html
(follow the "Next message" links at the bottom for the full thread)

http://groups.google.com/groups?th=aa5c620fe2b75a8e
(this one is a thread from comp.lang.python, from 2003-07-24, so I doubt
you will find anything better)

Abel Daniel

_________________________________________________________________
Add photos to your messages with MSN 8. Get 2 months FREE*.  
http://join.msn.com/?page=features/featuredemail


From rick at niof.net  Tue Aug 19 11:41:26 2003
From: rick at niof.net (Rick Pasotto)
Date: Tue Aug 19 10:34:17 2003
Subject: [Tutor] String Tokenizer - As in Java
In-Reply-To: <Sea2-F18QtXvXOCcUB50004f073@hotmail.com>
References: <Sea2-F18QtXvXOCcUB50004f073@hotmail.com>
Message-ID: <20030819144125.GF22922@niof.net>

On Tue, Aug 19, 2003 at 09:56:19AM -0400, Marc Barry wrote:
> Thanks for the help.
> 
> I tried to google for it also and I didn't find those two links.  The 
> second one gave me the answer I was looking for as it seems that 'split' 
> does exactly what I want.
> 
> Although, my interpretation is that 'split' only only allows the defintion 
> of one separator.  This is okay for most things, but I have strings that I 
> would like to split with two separators such as '.' and '@'.  I don't think 
> that I can use split to handle this and therefore will have to resort to 
> something more powerful (i.e. regular expressions).

Two separators means using split twice.

s = s'tring.with.two.seps@in.it'
l = [x.split('.') for x in s.split('@')]

gives:

[['string', 'with', 'two', 'seps'], ['in', 'it']]

Now you've got a list of lists which can be combined:

z = []
for x in l: z += x

which gives:

['string', 'with', 'two', 'seps', 'in', 'it']

Does that do what you want? BTW, there's probably a better way to do the
last step (or to combine them) but I can't come up with it at the moment.

-- 
"Nothing is so aggravating as calmness." -- Oscar Wilde
    Rick Pasotto    rick@niof.net    http://www.niof.net

From ATrautman at perryjudds.com  Tue Aug 19 10:55:54 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Tue Aug 19 10:56:31 2003
Subject: [Tutor] GUI Builder
Message-ID: <06738462136C054B8F8872D69DA140DB0108B5@corp-exch-1.pjinet.com>

http://www.thekompany.com/products/blackadder/

is an IDE I have been keeping an eye on and seems interesting. 

Alan

-----Original Message-----
From: just4info [mailto:just4info@serrati.net]
Sent: Tuesday, August 19, 2003 7:58 AM
To: Tutor MailingList
Subject: [Tutor] GUI Builder


Hi there.

Are there any GUI (Tk) Builder for python(I only found some one for 
Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?

Thanks in advance

Matthias




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

From ATrautman at perryjudds.com  Tue Aug 19 11:01:47 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Tue Aug 19 11:02:31 2003
Subject: [Tutor] GUI Builder
Message-ID: <06738462136C054B8F8872D69DA140DB0108B6@corp-exch-1.pjinet.com>

Woops brain dead the address it Qt based.

Sorry,
Alan

-----Original Message-----
From: just4info [mailto:just4info@serrati.net]
Sent: Tuesday, August 19, 2003 7:58 AM
To: Tutor MailingList
Subject: [Tutor] GUI Builder


Hi there.

Are there any GUI (Tk) Builder for python(I only found some one for 
Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?

Thanks in advance

Matthias




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

From kalle at lysator.liu.se  Tue Aug 19 18:35:19 2003
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Tue Aug 19 11:35:24 2003
Subject: [Tutor] String Tokenizer - As in Java
In-Reply-To: <Sea2-F18QtXvXOCcUB50004f073@hotmail.com>
References: <Sea2-F18QtXvXOCcUB50004f073@hotmail.com>
Message-ID: <20030819153519.GJ11588@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Marc Barry]
> Although, my interpretation is that 'split' only only allows the
> defintion of one separator.  This is okay for most things, but I
> have strings that I would like to split with two separators such as
> '.' and '@'.  I don't think that I can use split to handle this and
> therefore will have to resort to something more powerful
> (i.e. regular expressions).

I once needed a split function for more than one separator, so I wrote
one.  Then, for reasons I can't remember, I wrote another one and some
code to test which was the fastest.

  def multisplit1(s, seps):
      res = s.split(seps[0])
      for sep in seps[1:]:
          tmp = []
          for r in res:
              tmp += r.split(sep)
          res = tmp
      return res
  
  def multisplit2(s, seps):
      res = [s]
      for i in seps:
          res2 = res
          res = []
          for j in res2:
              res += j.split(i)
      return res
  
  import time
  apan = []
  for m in multisplit1, multisplit2:
      s = "a;b:c;defg:xxxxx:" * 100000
      seps = [":", ";", "l"]
      x = time.time()
      apan.append(m(s, seps))
      print time.time() - x
  assert apan[0] == apan[1]

On my system, the first function runs this test a little bit faster.
I assume that could change with the test case or whatever.  I think a
regexp might be faster since that's C code (an exercise for the
interested reader: write multisplit3 that uses the re module), but
this might be clearer.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE/QkOwdNeA1787sd0RAgY7AKDOzJzBqT5M75flkutrYviAYSkgcgCgqyIl
uEIdMHXr0jyvT3vugNUuVfc=
=M+CY
-----END PGP SIGNATURE-----

From bgailer at alum.rpi.edu  Tue Aug 19 10:59:26 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue Aug 19 13:04:22 2003
Subject: [Tutor] String Tokenizer - As in Java
In-Reply-To: <Sea2-F59Kgc44RFYfsI00028775@hotmail.com>
Message-ID: <5.2.1.1.0.20030819095526.02c33790@66.28.54.253>

At 04:48 AM 8/19/2003 -0400, Marc Barry wrote:

>I was wondering if there is a module similar to Java's StringTokenizer in 
>Python?  It is not that difficult to write such a module in pure Python, 
>but I thought I would check here first to see if it has already been done 
>and more importantly tested.

In regard to your desire to split at multiple delimiters:

import re
re.split(r'[123]', 'string using 1 as a delimiter and also 2 and by the way 
3 is a delimiter')

will give you

['string using ', ' as a delimiter and also ', ' and by the way ', ' is a 
delimiter']

if you also want the delimiters:

re.split(r'([123])', 'string using 1 as a delimiter and also 2 and by the 
way 3 is a delimiter')
gives:
['string using ', '1', ' as a delimiter and also ', '2', ' and by the way 
', '3', ' is a delimiter']

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From jeff at ccvcorp.com  Mon Aug 18 11:10:04 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Aug 19 14:24:01 2003
Subject: [Tutor] strange magic
References: <3F3FC151.50702@netzero.net>
Message-ID: <3F41086C.90909@ccvcorp.com>

Kirk Bailey wrote:

> FieldStorage('userfile','AN_flaming_TinyList.gif', 
> 'GIF89a\211\0003\000\245\000\000\002\002\002\326\2726\225\020\006\202\010\003\273\2159\203&\015l\004\003\270@\027W\002\002\267\255\224C\002\002\263Y\032\2048\016\371\350#:\002\00266.bbR\344\332\257\352~)\211r\015\334\305\201\357\2310\212p\022\350\325@\244\'\015\332n&\372\366\307\212\210m4\002\002\365\272-\321Z\037\371\355k\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377!\377\013NETSCAPE2.0\003\001\000\000\000!\371\004\011\005\000 
> \000,\000\000\000\000\211\0003\000\000\006\376@\220pH,\032\217H\004r\311l\032\225\316\250tJ\035\032\014\302\201\363p\250z\217\320\257x<\035h\267g\262z\315&\013\004\030L\372z\224H\332Q:~\257\216\023\257XC\002v\022\002|KZ\\]\207\214FZi\212]\213\200\202\203\025\025\206\215Eo\007~\232\237\177\221\006\010\007J\010\006f\211\002\227\025\240D\030\235\030\036\236\256{\251 
> W\007\031\007\224(and much, much more; it's the data structure of an 
> image file after all...)

I'm guessing, here, but it looks like all you need to do is save that 
data into a file, with (presumably) the given filename.  Something 
like (untested pseudocode):

filefield = FieldStorage( [...] )

# First, open a file named 'AN_flaming_TinyList.gif' ...
outfile = file(filefield[1], 'wb')
# ... and simply dump the data into it
outfile.write(filefield[2])
outfile.close()

You now have a file on your server, and you know the path and filename 
(because you've just created it).  You should be able to use that 
filename in the generated html for the page.

Jeff Shannon
Technician/Programmer
Credit International


From gerard.henry at free.fr  Tue Aug 19 21:04:05 2003
From: gerard.henry at free.fr (gerard henry)
Date: Tue Aug 19 14:35:27 2003
Subject: [Tutor] questions about debugging program
In-Reply-To: <3F3F78B6.5000408@free.fr>
References: <3F3F78B6.5000408@free.fr>
Message-ID: <3F426695.7040400@free.fr>

hello,
with your help, i wrote a little module to trace all i want in my program.
My config is:
python 2.2.3
logging module 0.4.7 from Vinay Sajip

i write a little module: debug.py
##################### debug.py #########################################
import logging, logging.handlers	# pour logger les messages

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
handler_log = logging.FileHandler("LGD.log", 'a')
format = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d
%(levelname)-5s - %(message)s")
handler_log.setFormatter(format)
logger.addHandler(handler_log)
##################### end of debug.py ##################################

and in others modules, i have to add:

import debug

and     debug.logger.info(any_data)

it's great, yes, but if i want to suppress this last line, how can i do
to not forget to suppress "import debug" also? in C/C++, i know if
something is not used, and i can lite source code, but how can i do the
same in python? in my 60 files, there is a lot of import, and i m sure
there are not all necessary

thanks for your help

gerard



From dyoo at hkn.eecs.berkeley.edu  Tue Aug 19 14:48:41 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Aug 19 17:09:19 2003
Subject: [Tutor] questions about debugging program
In-Reply-To: <3F426695.7040400@free.fr>
Message-ID: <Pine.LNX.4.44.0308191328380.13717-100000@hkn.eecs.berkeley.edu>



On Tue, 19 Aug 2003, gerard henry wrote:

> i write a little module: debug.py
> ##################### debug.py #########################################
> import logging, logging.handlers	# pour logger les messages
>
> logger = logging.getLogger('')
> logger.setLevel(logging.DEBUG)
> handler_log = logging.FileHandler("LGD.log", 'a')
> format = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d
> %(levelname)-5s - %(message)s")
> handler_log.setFormatter(format)
> logger.addHandler(handler_log)
> ##################### end of debug.py ##################################
>
> and in others modules, i have to add:
>
> import debug
>
> and     debug.logger.info(any_data)
>
> it's great, yes, but if i want to suppress this last line, how can i do
> to not forget to suppress "import debug" also?

[warning: evil kludgy technique exposed in this post: if you're just
learning Python, do not try this as home.  *grin*]



Hi Gerard,

If you're trying to use your 'debug' module without importing it first,
it's possible, but may not be a good idea.  You can probably try smuggling
the contents of 'debug' into some other module that you import from the
rest of your other program.


In particular, it's possible to smuggle something by subverting Python's
__builtins__ global dictionary:

###
[dyoo@tesuque dyoo]$ cat test_smuggling.py
answer = 42
__builtins__['answer'] = answer
[dyoo@tesuque dyoo]$
[dyoo@tesuque dyoo]$
[dyoo@tesuque dyoo]$ cat test1.py
import test_smuggling

print answer
[dyoo@tesuque dyoo]$
[dyoo@tesuque dyoo]$
[dyoo@tesuque dyoo]$ python test1.py
42
###


__builtins__ is automatically a part of every module, so pushing that
logger into __builtins__ there should do the trick.  But, in general, this
technique is a very bad, disgusting, and evil idea, because it suffers the
same problems that globals variables present.  Subverting __builtins__
also a maintenence nightmare, since now it becomes much harder to track
down how in the world something got into it.


With all the dangers of modifying __builtins__, it's often best to be
explicit, bite down, and just do the 'import debug' instead.  *grin*




> in C/C++, i know if something is not used, and i can lite source code,
> but how can i do the same in python? in my 60 files, there is a lot of
> import, and i m sure there are not all necessary

If you're worried about the cost of import, you don't have to worry so
much: imports are cached in Python: once you import a module, it stays in
memory just once.  If that's your concern, you don't have to worry about
it: it's not an issue.


If you're worried about having to visit every file out of your project to
add that 'import debug' statement, then you may want to try automating the
process with another program!  It's a valid programming technique to use
programs to write and maintain source files.  Such a program might look
something like:

###
for filename in all_my_python_project_files:
    if is_missing_debug_import(filename):
        add_debug_import_in(filename)
###

where is_missing_debug_import() can be as simple as a string search for
the words 'import debug'.


If you have more questions, or if I've completely misinterpreted part of
your question, please feel free to reply to the list; we'll be happy to
clarify.  Good luck to you!



From clay at shirky.com  Thu Aug 21 17:57:16 2003
From: clay at shirky.com (Clay Shirky)
Date: Fri Aug 22 09:03:00 2003
Subject: [Tutor] One for Kirk...
In-Reply-To: <3F331955.7050805@netzero.net>
Message-ID: <BB6AAA6C.C41E%clay@shirky.com>

A wiki written in 23 lines of Python:
http://sbp.f2o.org/2003/wypy

Unreadable, of course (lotsa inline lambdas :), but kind of awe-inspiring,
nevertheless.

-clay


From andi at buxach.de  Tue Aug 19 20:57:33 2003
From: andi at buxach.de (Andreas Zwinkau)
Date: Fri Aug 22 09:04:19 2003
Subject: [Tutor] another problem
In-Reply-To: <20030816193008.03cc6992.andi@buxach.de>
References: <20030816193008.03cc6992.andi@buxach.de>
Message-ID: <20030819195733.62cbbf13.andi@buxach.de>

Ok, I managed the missing glade problem, now there is another problem.
The following errorline occurs (1 line! sylpheed wraps it)

(gui.py:270): libglade-CRITICAL **: file glade-xml.c: line 1172
(glade_xml_build_interface): assertion `wid != NULL' failed

The "270" changes, what is this number?
Any ideas about the error? I confess, i didn't do much about it yet, but
I have no idea where to start either ... :(

mfg
Andreas Zwinkau
 | web: andi.dasstellenwirinsinternet.de
 | mail: andi@buxach.de
 | jabber: beza1e1@amessage.de

From alan.gauld at blueyonder.co.uk  Fri Aug 22 01:47:21 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Aug 22 09:37:26 2003
Subject: [Tutor] GUI Builder
References: <3F421EDD.2060607@serrati.net>
Message-ID: <002601c3683e$90b18540$6401a8c0@xp>

> Are there any GUI (Tk) Builder for python(I only found some one for 
> Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?

Do a search on google groups, there has been a long thread on 
comp..lang.python about this in the last week or two. Just about 
every conceivable GUI builder for Python got a mention at some 
stage!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From jonathan.hayward at pobox.com  Thu Aug 21 17:35:00 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 22 09:44:06 2003
Subject: [Tutor] Pickling -- never mind
Message-ID: <3F44E6A4.5050700@pobox.com>

I had typed

        monolith = factory.get_monolith_class

instead of

        monolith = factory.get_monolith_class()

and that's why I couldn't pickle. Please disregard my message.

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From idiot1 at netzero.net  Thu Aug 21 21:44:17 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 22 09:50:55 2003
Subject: [Tutor] test
Message-ID: <3F456761.1070900@netzero.net>

test


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Tue Aug 19 22:38:37 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 22 10:07:27 2003
Subject: [Tutor] chain gangs revolting still
Message-ID: <3F42D11D.5090909@netzero.net>

OK, I want a python program to start another one on completion, replaceing the 
first in the existing space, NOT running another one cocurrently. This involves 
the os.exec*() series of commands.

NOTMALLY, the program is invoked as a url, as
http://www.tinylist.owg/cgi-bin/wikinehesa.py/FrontPage
where FrontPage is the name of the page being read.

I want the editor to invoke the reader to display the just saved edited page. 
The program should invoke the other program, which lives in the same directory 
as it does. The command should tell the wiki program what the name of the page 
to be viewed is in such  manner that the normal mechenism for receiving this 
data will operate and accept the pagename.

How do I do that? My first attempt is a barkingatthemoon dog of a failure. I 
have never worked with such functionality before in python, and have no idea 
what I am doing here.


-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From justin at unixremedies.com  Thu Aug 21 16:11:45 2003
From: justin at unixremedies.com (Justin Heath)
Date: Fri Aug 22 11:27:21 2003
Subject: [Tutor] Test
Message-ID: <3F452781.1020607@unixremedies.com>

I havent been able to reach the tutor list for the past couple of days. 
I just wanted to see if it was working now.

Thanks,
Justin



From vibrations at cetlink.net  Thu Aug 21 10:59:27 2003
From: vibrations at cetlink.net (SGD)
Date: Fri Aug 22 11:39:01 2003
Subject: [Tutor] More py please?
Message-ID: <000001c367ec$822017f0$bf37c6d1@whiterhino2>

I would like to install multipe instances of python, specificly 2.2.3
and 2.3. 

Is this possible? And if so, what are the laws that govern the process?
I tried the manuals, but I must have missed it...

Thanks


From vicki at thepenguin.org  Thu Aug 21 15:25:26 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Aug 22 12:04:57 2003
Subject: [Tutor] Issues with tokenizing a string
Message-ID: <7373.206.53.226.4.1061493926.squirrel@www.thepenguin.org>

I am trying to tokenize a string and then test on the values of the
tokens, some of which might be empty. The situation is such that I have to
retrieve data from a combobox dropdown and from a wxTextCtrl window if
populated with data. The wxTextCtrl will contain zero to several
space-delimited "tokens".

self.arguments = self.parameters.GetValue()
is what I use to read the string to tokenize. I get a string like:
"1 F 4"

I then try to tokenize the string with:
       if arguments:
            parameters=self.arguments.split(" ")
            x=0
            while parameters != "":
                outfile.write(parameters[x])
                print parameters[x]
                x=x+1
        else: parameters = ""

It doesn't seem to like parameters[x] very much, telling me that the list
index is out of range. If I substitute a '0', it works fine.

Also, I am not sure what to use to determine the end of the arguments. If
it is read in from a wxTextCtrl, is it terminated in a "\n" or what?

--vicki

From dyoo at hkn.eecs.berkeley.edu  Wed Aug 20 13:06:24 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug 22 12:11:43 2003
Subject: [Tutor] Trying to open RPM database with bsddb
In-Reply-To: <3F414F51.5070709@unixremedies.com>
Message-ID: <Pine.LNX.4.44.0308201148340.26665-100000@hkn.eecs.berkeley.edu>



> I have since found the refered document. I can now create and re-open db
> files I have created. However, I cannot seem to open redhat rpm database
> files or freebsd pkgdb files. I keep getting an invalid argument error
> when using the syntax:
>
>  >>> import anydbm
>  >>> dbf = anydbm.open('pkgdb', 'r')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.2/anydbm.py", line 86, in open
>     return mod.open(file, flag, mode)
>   File "/usr/lib/python2.2/dbhash.py", line 16, in open
>     return bsddb.hashopen(file, flag, mode)
> bsddb.error: (22, 'Invalid argument')
>
> **Note I have also tried the above using bsdb abd dbhash with the same
> result.
>
> This appears that it may be a versioning issue between versions of
> berkley db but I am unsure since I have tried using the db_upgrade on
> (copies of) the files with the same results. If anyone has gotten this
> to work or has any additional info please let me know.

Hi Justin,


I was able to get something useful by using bsddb:

###
[dyoo@tesuque rpm]$ ls -l /var/lib/rpm/Packages
-rw-r--r--    1 rpm      rpm      22253568 Aug 11 14:24
/var/lib/rpm/Packages
[dyoo@tesuque rpm]$ file /var/lib/rpm/Packages
/var/lib/rpm/Packages: Berkeley DB (Hash, version 7, native byte-order)
###


The 'file' utility agrees with anydbm: the file format of the RPM database
is Berkeley DB.

It's possible that your Python distribution has an older version of bsddb
that isn't quite working.  I know that bsddb was recently "overhauled" in
Python 2.3.  (That is, completely deprecated and replaced by an
alternative implementation.  *grin*)


You might want to see if you can open it using Python 2.3.
Alternatively, you may want to see if PyBSDDB can open it:

    http://sourceforge.net/projects/pybsddb/



Here's what it looks like on my end:

###
[dyoo@tesuque rpm]$ /usr/local/bin/python
Python 2.3 (#1, Aug  1 2003, 17:14:57)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bsddb
>>> packages = bsddb.hashopen('Packages')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/local/lib/python2.3/bsddb/__init__.py", line 162, in hashopen
    d.open(file, db.DB_HASH, flags, mode)
bsddb._db.DBAccessError: (13, 'Permission denied')
>>> packages = bsddb.hashopen('Packages', 'r')
>>>
>>> names = bsddb.hashopen('Name', 'r')
>>> names.next()
('cdparanoia', 'P\x04\x00\x00\x00\x00\x00\x00')
>>> names.next()
('libtool-libs', '\xbc\x02\x00\x00\x00\x00\x00\x00')
>>> names.next()
('crontabs', '\x0b\x00\x00\x00\x00\x00\x00\x00')
>>> names.next()
('man', 'J\x05\x00\x00\x00\x00\x00\x00')
>>> names.next()
('sysklogd', '\xef\x02\x00\x00\x00\x00\x00\x00')
>>> names.next()
('qt1x', '\x16\x00\x00\x00\x00\x00\x00\x00')
###


The bsddb package appears to be able to open the database file ok.
Anyway, I hope this helps get you started.  Good luck!


From idiot1 at netzero.net  Wed Aug 20 21:51:32 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 22 13:02:03 2003
Subject: [Tutor] test
Message-ID: <3F441794.8080008@netzero.net>

test


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From jonathan.hayward at pobox.com  Thu Aug 21 17:22:02 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 22 14:59:11 2003
Subject: [Tutor] Pickling debugging question
Message-ID: <3F44E39A.9080803@pobox.com>

I am trying to save a monolith consisting of classes I wrote, all 
boiling down to primitive objects. I get this error:

Traceback (most recent call last):
  File "/home/jonathan/dm/datamined", line 1889, in keep_saving_monolith
    save_object(monolith, "monolith")
  File "/home/jonathan/dm/datamined", line 1935, in save_object
    cPickle.dump(object, filehandle)
  File "/usr/lib/python2.2/copy_reg.py", line 57, in _reduce
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle function objects

Could this mean that I typed:

    self.field = function

instead of

    self.field = function()

What are the probable culprits for this type of error?

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From dhanvik at gmx.net  Fri Aug 22 14:41:21 2003
From: dhanvik at gmx.net (K Dhanvi)
Date: Fri Aug 22 16:27:22 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class ? 
Message-ID: <00d101c36884$fae66200$0d001eac@ud.cybage.com>

Dear friends,

 I have a query about giving names to variables inside classes and thus to
the objects of the classes..

 I have a class called configReader which reads a configuration file and
then puts the configuration data into a dictionary at prsent. Before reading
the configuration file, the config object is told what keys to expect and
their datatpyes for simple santiy checks on the corresonding values.. At
present the key and values are stored in a dictionary.. I would like to make
each key a property of the respective configReader object.
  for example => 
 If one of my keys in the configuration file is MAX_THREADS..
I would like my code to be as follows
------------------------------------------------------------------------------------- 
        import ConfigReader
        config = ConfigReader( "./config.file")
        config.AddKey( "MAX_THREADS", INT )
        config.ReadConfigFile()

        noOfThreads = config.MAX_THREADS
-------------------------------------------------------------------------------------

The first 3 lines of the sample code have been completed.. I would like to
add the functionality similar to the final line of the sample code. Each
object willl have different properties in itself depending upon the keys it
was initialized with. i.e there could be another config object which will
access another property "REGISTRATION_CURVE"..
 config1.REGISTRATION_CURVE.

please lemme  know if theres any way this can be achieved in Python ?

Thank you for your time and help :)

Dhanvi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030822/0e559124/attachment-0001.htm
From idiot1 at netzero.net  Wed Aug 20 20:09:34 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 22 17:36:30 2003
Subject: [Tutor] test
Message-ID: <3F43FFAE.5050308@netzero.net>

test

the list seems to have flat STOPPED. This is simply to insure it is still 
serving traffic.



-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From vicki at thepenguin.org  Fri Aug 22 11:46:57 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Aug 22 18:28:22 2003
Subject: [Tutor] parsing woes
Message-ID: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>

Okay, I didn't get an answer to this last time, so let me restate it and
try again. I am attempting to parse a string which is in the form:

1 F 5

I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
The difficulty is that there might be no parameters or any number up to 3.
They won't always be a single digit or letter but they will always be
space-delimited. My problem is that when I try to display them, I get an
error if there are not 3 parameters.

    if parameters[2]:
IndexError: list index out of range

when I try to run this code to see what the values are:
    if parameters[0]:
         print parameters[0]
    if parameters[1]:
         print parameters[1]
    if parameters[2]:
         print parameters[2]

I am parsing them this way:

if arguments:
    parameters=arguments.split(" ")
else: parameters = ""


Can someone tell me what I am doing wrong? I just want the if
parameters[2] to be bypassed if there isn't a third parameter.

--vicki


From zak at harlekin-maus.com  Fri Aug 22 16:10:44 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Fri Aug 22 23:40:40 2003
Subject: [Tutor] Intializing Lists - Did it again!!
Message-ID: <3662.192.206.201.218.1061590244.squirrel@mail.harlekin-maus.com>

Can you believe it? I've been fiddling with pygame lately, and had to
initialize a list of lists (to represent a 2d set of map tiles).

So I then go and stupidly do the following:
tilemap = [[0] * 10] * 10

Now, repeat after me: This creates ONE [0] * 10 list and filles the outer
list with pointers to that list. I.e.:

###

>>> a = [['a'] * 3] * 3
>>> a
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> a[0][1] = 2
>>> a
[['a', 2, 'a'], ['a', 2, 'a'], ['a', 2, 'a']]

###

Man, didn't I JUST ask the Tutor list about this very same thing? Anyhow,
thought I'd reiterate such an important thing.

PS - I was able to throw together an scrolling map with isometric,
overlapping (big rocks and such) tiles ... all in two lunches ... oh, and
the mouse scrolls the map a la Starcraft. Is Python awesome, or what?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From vicki at thepenguin.org  Fri Aug 22 14:18:57 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Aug 22 23:40:50 2003
Subject: [Tutor] Re: parsing woes
In-Reply-To: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <10757.206.53.226.4.1061576337.squirrel@www.thepenguin.org>

> Okay, I didn't get an answer to this last time, so let me restate it and
> try again. I am attempting to parse a string which is in the form:
>
> 1 F 5
>
> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.
>
>     if parameters[2]:
> IndexError: list index out of range
>
> when I try to run this code to see what the values are:
>     if parameters[0]:
>          print parameters[0]
>     if parameters[1]:
>          print parameters[1]
>     if parameters[2]:
>          print parameters[2]
>
> I am parsing them this way:
>
> if arguments:
>     parameters=arguments.split(" ")
> else: parameters = ""
>
>
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.
>
> --vicki
>
>
Okay I finally got it figured out. I had to change the if statements to
try statements and deal with the index error. The code looks like this
now:

            if arguments:
                parameters=arguments.split(" ")
                i=0
                for a in parameters:
                    print "parameter[" + str(i) + "] = " + a + "\n"
                    i+=1

and then:

            try:
                parameters[0]
            except IndexError:
                print "parameters[0] undefined"
            else:
                print parameters[0]
            try:
                parameters[1]
            except IndexError:
                print "parameters[1] undefined"
            else:
                print parameters[1]
            try:
                parameters[2]
            except IndexError:
                print "parameters[2] undefined"
            else:
                print parameters[2]

--vicki

From D.J.Kniep at chello.nl  Sat Aug 23 00:53:26 2003
From: D.J.Kniep at chello.nl (Dick Kniep)
Date: Fri Aug 22 23:41:00 2003
Subject: [Tutor] GUI Builder
In-Reply-To: <3F421EDD.2060607@serrati.net>
References: <3F421EDD.2060607@serrati.net>
Message-ID: <1061589210.27635.2.camel@server.kniep>

On Tue, 2003-08-19 at 14:58, just4info wrote:
Hi Matthias
> 
> Are there any GUI (Tk) Builder for python(I only found some one for 
> Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?

Take a look at wxPython with Boa Constructor as IDE I have used it in a
fairly large system and it is perfect!

Regards,
Dick Kniep
 



From idiot1 at netzero.net  Wed Aug 20 00:09:24 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Aug 22 23:41:12 2003
Subject: [Tutor] chain gang revolt put down! (longish)
Message-ID: <3F42E664.4070909@netzero.net>

YET AGAIN, is proven the power of DETERMINED AND UNRELENTING PERSISTANCE.
(Not to mention my need for a formal education in programming...)

ok. I whipped their assets. Experimenting, and reading between the lines, then 
reading between the whitespaces, and then I clicked onto an intresting factoid.

Intresting little detail; with os.excecl() and all the others not ending in 'e', 
the new program inherits the old program's environment. (~e() versions let you 
define the environment the program will receive.) Hmmm...

EDITOR BACKGROUND
Here's how the editor works. It is 2 programs. The first receives the pagename 
in the url, and sends out a perfectly normal form with a textarea, preloaded 
with the raw page, and the pagename in a hidden input field. The server does not 
save any sort of state in itself. You edit the page guts normally in your 
browser's window- nothing fancy at all in any of this. You click SAVE (a submit 
button) and using the post method, the form sends it to editor script #2, which 
saves the data, overwriting the old file file with the new data in the named 
file. This also sends the pagename as a hidden input field so it know's what 
pagename it is talking about.

That last fact did sidetrack me for a spell, until I realized that such an 
action did NOT preclude another simple action- tagging the pagename onto the end 
of the url.

I wanted to use the existing reader to display the results of editing the page, 
avoiding the need to have not one, but TWO wikicode interpeters. Therefore, the 
second editor program must work with the demands of the existing 
wikibrowser/interpeter OR I must change it to receive it's pagename 2 different 
ways, which I was loathe to do 'cause it's DUMB.

WIKI BROWSER BACKGROUND
Wikinehesa.py get's it's page name in the url, which is passed to the program in 
the environment by the web server, in a variable called PATH_INFO. When you 
submit a url with data after a program name, seperated with a "/", the data is 
saved to the $PATH_INFO environment variable. The variation on this theme is to 
use the '?' followed by data; this is the classic GET method of cgi forms.

For instance, to read SandBox page:
http://www.tinylist.org/cgi-bin/wikinehesa.py/SandBox

That last part ('SandBox') is saved as PATH_INFO by the webserver. (The '/' 
seperating the page name and the data is discarded.) That's how wikinehesa 
works. In fact, this is how ALL wiki's work with either '/' or '?' preceeding 
the pagename. Had I used '?pagename' it would have been saved as QUERY_STRING 
but all else would be the same.

My task was to tailor editor script #2 so as to feed data to the reader script 
using the existing mechenism so it would read the updated page and display it, 
in effect serving both as browser and as edit result displayer. Therefore, the 
second editor program had to feed the data to the browser in the environment. HOW?

Playing about with the environment is not my long suit, and not something I want 
to bung up in a working server with 2 no kidding commercial sites in it. 
Therefore, I added this to the form action which is generated by the FIRST 
editor script  (wikinehesaed1.py):
"(webpath)/wikinehesaed2.py/(pagename)"
That (pagename) gets saved in the environment as $PATH_INFO.

*** This is significant. ***

The second editor script as it's last act hands off to the reader with 
os.execl(program), GIVING IT'S ENVIRONMENT TO THAT PROGRAM. The just loaded wiki 
interpeter upon starting up looks in the environment it is handed, reads the 
PATH_ INFO data, and opens that page normally. No change to the environment was 
required, and only a small one in the FIRST editor script was demanded.
In it, I modified the ACTION so that after the name of the page is '/'+pagename+'">'
The program then sends a form with the action defined as
<FORM ACTION="http://www.tinylist.org/cgi-bin/wikinehesaed2.py/SandBox" 
METHOD="Post">

The script still runs. The data is saved in the environment by the webserver. 
The newly loaded wikireader gets the data and reads the page normally, then 
terminates normally.

BIG WIN. I don't have to maintain 2 display engines, or import one, or play 
games with the environment or anything else, I just hand the task FROM one 
program TO the one browser engine and let it do the work, taking advantage of 
how the operating system works and how python works. :-) That it is technically 
GET and POST in the same form bothers me not a bit, how about you?

Now if I can only figure out how to get it to process the wikicode into html 
perfectly, avoiding the strange chunks and errors it tosses out, I will have a 
functional and rather nice looking wiki to give away to one and all. The reverse 
search and titlelisting are already working just fine.

Now to see what is going on, take a look at this link:
http://www.tinylist.org/cgi-bin/piki.py/WikiNehesa
A page, rendered by a working wiki engine, named piki.

Here is the EXACT SAME PAGE rendered by wikinehesa:
http://www.tinylist.org/cgi-bin/wikinehesa.py/WikiNehesa
odd stuff, occasional strange bits and peices, handles punctuation following the 
wikiwords poorly.

If you want to mess around with editing things, try it in the SandBox, that's 
what it's there for.
http;//www.tinylist.org/cgi-bin/wikinehesa.py/SandBox
Click the EDIT PAGE button in the footer to bring up editor script #1 and it's 
output of a edit webpage. Submitting that fires off at editor #2, which will 
load the browser to display the results.

Now here is a link to examine the guts of the wikinehesa.py script:
http://www.tinylist.org/wikinehesa.txt
And editor #1:
http://www.tinylist.org/wikinehesaed1.txt
and editor #2:
http://www.tinylist.org/wikinehesaed2.txt
ALL are ln soft links leading directly to the scripts and are instantly updated 
if the scripts are updated.

PLEASE feel free to laugh at my amateurish code and point out how much better it 
could be if I just did (foo).

I will sleep well tonight,. Goodnight all.


--

end

ZZZZzzzz....
             Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From pauljhickey at eircom.net  Sat Aug 23 00:02:52 2003
From: pauljhickey at eircom.net (Paul Hickey)
Date: Fri Aug 22 23:42:22 2003
Subject: [Tutor] re Test!
Message-ID: <000c01c368f9$22410de0$fdc4fea9@pjhickey>

I hear you !!!
Holidays i guess!!!
Or else nobody got no problems!
Good luck
Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030822/e832f323/attachment.htm
From justin at unixremedies.com  Fri Aug 22 11:22:33 2003
From: justin at unixremedies.com (Justin Heath)
Date: Sat Aug 23 11:58:30 2003
Subject: [Tutor] Help with a cgi example
Message-ID: <3F463539.6070400@unixremedies.com>

All,

I am currently working thru some of the cgi examples in "Programming
Python". I am stuck on how one of the examples works. Here is the example:

#!/usr/bin/python

import cgi, sys, string
form = cgi.FieldStorage(  )
print "Content-type: text/html"

html = """
<TITLE>test5.cgi</TITLE>
<H1>Greetings</H1>
<HR>
<H4>Your name is %(name)s</H4>
<H4>You wear rather %(shoesize)s shoes</H4>
<H4>Your current job: %(job)s</H4>
<H4>You program in %(language)s</H4>
<H4>You also said:</H4>
<P>%(comment)s</P>
<HR>"""

data = {}
for field in ['name', 'shoesize', 'job', 'language', 'comment']:
    if not form.has_key(field):
        data[field] = '(unknown)'
    else:
        if type(form[field]) != type([]):
            data[field] = form[field].value
        else:
            values = map(lambda x: x.value, form[field])
            data[field] = string.join(values, ' and ')
print html % data

I am confused on the 'values = map(lambda x: x.value, form[field])'
line. I do not understand exactly what is happeing here. I believe I
understand that he is applying the lambda to every item in form[field]
by using map. However, I dont seem to understand what the lambda is
doing. I thought it was doing the same thing as 'form[field].value', but
I appear to be wrong since when I try this manually I get an error
stating that form[field] does not have a 'value' attribute.

I am not sure if anyone will need this for context but I have also
pasted the html form example here:

<HTML><BODY>
<TITLE>CGI 101</TITLE>
<H1>Common input devices</H1>
<HR>
<FORM method=POST action="test5.cgi">
  <H3>Please complete the following form and click Send</H3>
  <P><TABLE>
    <TR>
      <TH align=right>Name:
      <TD><input type=text name=name>
    <TR>
      <TH align=right>Shoe size:
      <TD><table>
      <td><input type=radio name=shoesize value=small>Small
      <td><input type=radio name=shoesize value=medium>Medium
      <td><input type=radio name=shoesize value=large>Large
      </table>
    <TR>
      <TH align=right>Occupation:
      <TD><select name=job>
        <option>Developer
        <option>Manager
        <option>Student
        <option>Evangelist
        <option>Other
      </select>
    <TR>
      <TH align=right>Political affiliations:
      <TD><table>
      <td><input type=checkbox name=language value=Python>Pythonista
      <td><input type=checkbox name=language value=Perl>Perlmonger
      <td><input type=checkbox name=language value=Tcl>Tcler
      </table>
    <TR>
      <TH align=right>Comments:
      <TD><textarea name=comment cols=30 rows=2>Enter text here</textarea>
    <TR>
      <TD colspan=2 align=center>
      <input type=submit value="Send">
  </TABLE>
</FORM>
<HR>
</BODY></HTML>

Thanks,
Justin





From missive at hotmail.com  Sat Aug 23 16:22:17 2003
From: missive at hotmail.com (Lee Harr)
Date: Sun Aug 24 00:01:51 2003
Subject: [Tutor] Re: Dynamic variables names to objects of the same class ?
Message-ID: <BAY2-F152BAyxJMXehY00013bbf@hotmail.com>

        import ConfigReader
        config = ConfigReader( "./config.file")
        config.AddKey( "MAX_THREADS", INT )
        config.ReadConfigFile()

        noOfThreads = config.MAX_THREADS


Hi;

I am not exactly sure what you need to do, but maybe something
along the lines of...

if hasattr(config, 'MAX_THREADS'):
    noOfThreads = config.MAX_THREADS
else:
    noOfThreads = DEFAULT_MAX_THREADS


or


try:
    noOfThreads = config.MAX_THREADS
except KeyError:
    noOfThreads = DEFAULT_MAX_THREADS


will help.

ps. please send only plain text to the list  :o)

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From alan.gauld at blueyonder.co.uk  Sat Aug 23 09:31:48 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Aug 24 00:35:08 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class ? 
References: <00d101c36884$fae66200$0d001eac@ud.cybage.com>
Message-ID: <009401c36948$9cec27b0$6401a8c0@xp>

> object willl have different properties in itself depending
> upon the keys it was initialized with.
> please lemme  know if theres any way this can be achieved in Python
?

There are ways of achieving this in Python using the getattr()
and setattr() methods for example. But I'd ask why you don't
want to use a dictionary? This looks like a classic dictionary
solution and using a class just for the sake of it doesn't make
sense. Is there something more that you want to do with the
class that requires that approach?

If you do need a class approach then why not just use a
dictionary inside the class? That will be more reliable and
faster than writing your own dictionary type object...

And if you are using Python 2.2 or above you could even try
making your class a subclass of the dictionary type.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From idiot1 at netzero.net  Sun Aug 24 02:08:31 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 24 02:14:51 2003
Subject: [Tutor] chain gangs will not work together, warden losing his mind
Message-ID: <3F48484F.50107@netzero.net>

WEll, it's fustrating. I get some things to work, and it mulches others. OK, I 
disable something and get another to work.

At the moment, it will display an image. and do wikiwords. But not external 
links. If I handle links, it mulches the image tag.

And it NEVER wants to do a table in the body of the page- header and footer 
areas are canned strings, not processed through the wikicode procesing area. All 
the program does is add correct domain info for links.

Here is the chaos of the moment:
http://www.tinylist.org/cgi-bin/wikinehesa.py/FrontPage
notice the nice image displayed in the page itself, which is the wiki responding 
to image markup in the page body.

Here is the sourcecode for the program.
http://www.tinylist.org/wikinehesa.txt

Somewhat simpler, removed a few things and rewrote others. Getting there slowly.

ANYONE taking any intrest in this project, or text processing, please give it a 
look.


-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From garnaez at yahoo.com  Sat Aug 23 16:36:18 2003
From: garnaez at yahoo.com (Gerardo Arnaez)
Date: Sun Aug 24 05:12:56 2003
Subject: [Tutor] Network stuff
Message-ID: <20030823223618.18349.qmail@web20202.mail.yahoo.com>

Hello all, enjoying the heck out of python. using to
help set up user accounts at a public internet cafe
where they will sell these accoutnts in 30 min
sessions.

Right now I can get a list of any user and total time
logged in to one computer.  I break this up into a
dictionary.

The problem is that I am not sure how to transmit this
information.  Ie I have some data I want to sent to
another application on another computer.

At first twisted was mentioned to me,
and I see socket and socketServer modules,
but I need some hints in what would be the pythonic
way to go about this.

All I really want to do is send a dictionary from a
client app and have it examined in the server app.

Anyway, I would should could but its so simplistic
that is amounts to parseing the output of 'ac' an gnu
account procces and logins
and storing them into a dictionary.

Anyway, Thanks for all your help

G




__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From missive at hotmail.com  Sat Aug 23 16:06:17 2003
From: missive at hotmail.com (Lee Harr)
Date: Sun Aug 24 05:24:07 2003
Subject: [Tutor] Re: another problem
Message-ID: <BAY2-F93mibfvTqPKGC00010145@hotmail.com>

>Ok, I managed the missing glade problem, now there is another problem.
>The following errorline occurs (1 line! sylpheed wraps it)
>
>(gui.py:270): libglade-CRITICAL **: file glade-xml.c: line 1172
>(glade_xml_build_interface): assertion `wid != NULL' failed
>
>The "270" changes, what is this number?
>Any ideas about the error? I confess, i didn't do much about it yet, but
>I have no idea where to start either ... :(
>

Hi;  I am not using that program, so these are just educated guesses:

gui.py is the name of the python module that is having a problem.
270 is the line number in that file where it is having a problem.

Looks to me like it is importing an extension module (a python module
written in C) which is raising an assertion and causing the whole problem.

wid != NULL is saying that it does not have a handle on a window.

So, maybe you found a bug, or maybe you just have some kind of version
skew (ie, requires libglade-0.53 but you have libglade-0.47)

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE* 
http://join.msn.com/?page=features/virus


From shalehperry at comcast.net  Fri Aug 22 23:58:13 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Sun Aug 24 05:55:22 2003
Subject: [Tutor] Issues with tokenizing a string
In-Reply-To: <7373.206.53.226.4.1061493926.squirrel@www.thepenguin.org>
References: <7373.206.53.226.4.1061493926.squirrel@www.thepenguin.org>
Message-ID: <200308222258.13323.shalehperry@comcast.net>

On Thursday 21 August 2003 12:25, Vicki Stanfield wrote:
> I am trying to tokenize a string and then test on the values of the
> tokens, some of which might be empty. The situation is such that I have to
> retrieve data from a combobox dropdown and from a wxTextCtrl window if
> populated with data. The wxTextCtrl will contain zero to several
> space-delimited "tokens".
>
> self.arguments = self.parameters.GetValue()
> is what I use to read the string to tokenize. I get a string like:
> "1 F 4"
>
> I then try to tokenize the string with:
>        if arguments:
>             parameters=self.arguments.split(" ")
>             x=0
>             while parameters != "":
>                 outfile.write(parameters[x])
>                 print parameters[x]
>                 x=x+1
>         else: parameters = ""
>

for param in parameters:
  print param

will catch each parameter.  What you likely want to do is count the number of 
items that split() returns and go from there:

parameters = self.arguments.split() # no need for an argument, it will split 
on whitespace

count = len(parameters)
if count == 3:
  # handle 3 case
elif count == 2:
  # handle 2 case
else:
  # error, we always want 2 or 3 items (for instance)


From dyoo at hkn.eecs.berkeley.edu  Sat Aug 23 00:31:11 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 24 06:55:12 2003
Subject: [Tutor] Issues with tokenizing a string
In-Reply-To: <7373.206.53.226.4.1061493926.squirrel@www.thepenguin.org>
Message-ID: <Pine.LNX.4.44.0308222318280.26480-100000@hkn.eecs.berkeley.edu>



> self.arguments = self.parameters.GetValue()
> is what I use to read the string to tokenize. I get a string like:
> "1 F 4"
>
> I then try to tokenize the string with:
>        if arguments:
>             parameters=self.arguments.split(" ")

Hi Vicki,

You can simplify it slightly more by not defining the delimiter:

        parameters = self.arguments.split()

The default version of split() is slightly nicer, because it can also
handle cases where there are multiple spaces between the tokens:

###
>>> 'hello      this   is   a test'.split()
['hello', 'this', 'is', 'a', 'test']
###


>             x=0
>             while parameters != "":
>                 outfile.write(parameters[x])
>                 print parameters[x]
>                 x=x+1
>         else: parameters = ""
>
> It doesn't seem to like parameters[x] very much, telling me that the
> list index is out of range. If I substitute a '0', it works fine.

I see; you're using an index to iterate across your parameters.  The bug
is that 'parameters' is a list of elements, so your test:

    while parameters != "": ...

is broken: a list can never equal the empty string.  What you probably
mean to do is check to make sure the index 'x' is within bounds of the
size of our 'parameter' list.

    while x < len(parameters): ...

This terminates as long as 'x' gets larger and larger... and as long as
'parameters' stays the same size.  *grin* Let's check that:

    x = 0
    while x < len(parameters)
        outfile.write(parameters[x])
        print parameters[x]
        x=x+1

Yup, that's simple enough: x will continue to get larger, and there's
nothing in the body of the loop to change the length of our parameter
list.


But there's an alternative way to run across a list of elements besides
explicit indexing.  Python's 'for' loop is designed to go across things,
and it's perfect for going across ("iterating") across a list.  The code
block above can be rewritten as:

    for param in parameters:
        outfile.write(param)
        print param

The for loop usually eliminates the need for a separate 'index' variable,
and, as a bonus, we end up with simpler code.



> Also, I am not sure what to use to determine the end of the arguments. If
> it is read in from a wxTextCtrl, is it terminated in a "\n" or what?

I'm not sure.  You can experimentally try this out by doing a 'repr()' on
the text from wxTextCtrl and see what comes out.  repr() is a function
that will explicitely show all the control characters in a string, and is
very useful for debugging.  For example:

###
>>> s = 'this is a \b\b\b\b\b\b\b\b\b\bhello!'
>>> print s
hello!s a
>>> repr(s)
"'this is a \\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08hello!'"
###

Notice that when we print out the string, we don't see the first few
letters because there's some embedded 'backspace' characters that cover it
up.  The repr() function makes this all too apparent by showing us an
escaped representation of the string.


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


From alex at gabuzomeu.net  Sun Aug 24 13:52:14 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Sun Aug 24 10:43:29 2003
Subject: [Tutor] Network stuff
In-Reply-To: <20030823223618.18349.qmail@web20202.mail.yahoo.com>
References: <20030823223618.18349.qmail@web20202.mail.yahoo.com>
Message-ID: <3F4898DE.4040103@gabuzomeu.net>

Hi Gerardo,


Gerardo Arnaez wrote:
> Hello all, enjoying the heck out of python. using to
> help set up user accounts at a public internet cafe
> where they will sell these accoutnts in 30 min
> sessions.
> 
> Right now I can get a list of any user and total time
> logged in to one computer.  I break this up into a
> dictionary.
> 
> The problem is that I am not sure how to transmit this
> information.  Ie I have some data I want to sent to
> another application on another computer.

You could setup a minimal server to offer data to the other computer. 
XML-RPC comes to mind; I tested this technology a couple of weeks ago 
and it looked very simple to use.

In Python 2.2+, look into the "SimpleXMLRPCServer" and "xmlrpclib" 
modules in the standard library. There's some doc around too:

The Python Web services developer: XML-RPC for Python, 2002
<http://www-106.ibm.com/developerworks/webservices/library/ws-pyth10.html?dwzone=webservices>

XML-RPC Howto
<http://xmlrpc-c.sourceforge.net/xmlrpc-howto/xmlrpc-howto.html>

XML-RPC in Python, 2000
<http://www.onlamp.com/lpt/a/468>

I can post a code example if you are interested.

For a fancier solution, you could also look at Pyro (Python Remote 
Objects). I toyed with this module yesterday and it's quite easy for a 
client to access an object on a remote server.

http://pyro.sourceforge.net



Cheers.

Alexandre




From scot at possum.in-berlin.de  Sat Aug 23 14:13:33 2003
From: scot at possum.in-berlin.de (Scot W. Stevenson)
Date: Sun Aug 24 11:04:38 2003
Subject: [Tutor] Tutor-level docs: Some gushing on optparse
Message-ID: <200308231313.33957.scot@possum.in-berlin.de>

Hi there, 

I would like to take a moment to gush  about some Python documentation that 
is so good that it is actually a sort of mini-tutorial in itself. If you are 
not in a mood to be gushed at on Saturday morning, you might want to skip 
this =8). 

Python 2.3 has a new module named "optparse" that handles command line 
options, and handles them so well that it is almost obscene: You find 
yourself inserting options all over the place because it is so easy. Well 
yes, you say -- easy to use, elegant setup, powerful, all very nice, but 
this is Python, after all, so /everything/ is friendly and cheerful and 
filled with chirping birds and pretty flowers and warm sunshine [except of 
course for lambda, which is evil incarnate], so what is so special about 
optparse?

The documentation (http://www.python.org/doc/2.3/lib/module-optparse.html). 
It is actually almost more like a thesis. It starts out with a "Philosophy" 
section that explains command line options, good design (including some 
points on "required options" that I hadn't thought about before), and then 
goes on thru basic to advanced usage to extending the module. At the end, I 
not only felt I knew how to use optparse (and had lots of good examples to 
steal), but that I had learned more about options in Linux/Unix in general.

Beautiful work. If you have a program that uses a lot of options, upgrading 
to 2.3 might be worth your while just for optparse alone.

Y, Scot

-- 
          How to quiet a crying baby with the X Window System: 
                  nice xlock -inwindow -mode kumppa

               Scot W. Stevenson - Zepernick, Germany


From clay at shirky.com  Sat Aug 23 13:21:38 2003
From: clay at shirky.com (Clay Shirky)
Date: Sun Aug 24 11:39:41 2003
Subject: [Tutor] parsing woes
In-Reply-To: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <BB6D0CD2.C5A3%clay@shirky.com>

> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.

The function len() will tell you the length of the list you are making, so
rather than testing each value, you can just test the total length to see
how many parameters there are.

You can see this in action here:

argument_list = ["1 F 5",
"2 G H 6", 
"3 IJ KL MN 7", 
"4"]

for arguments in argument_list:
    parameters=arguments.split() # split splits on space by default
    print len(parameters),

This prints "3 4 5 1", the number of parameters in each of those four test
samples.

Now you can loop...

for i in range( len(parameters) ):
    print parameters[i]

Or test...

if len(parameters) > 2:
    print parameters[2]

-clay


From gus.tabares at verizon.net  Sun Aug 24 17:10:55 2003
From: gus.tabares at verizon.net (Gus Tabares)
Date: Sun Aug 24 12:20:04 2003
Subject: [Tutor] More py please?
In-Reply-To: <000001c367ec$822017f0$bf37c6d1@whiterhino2>
References: <000001c367ec$822017f0$bf37c6d1@whiterhino2>
Message-ID: <1061614807.9835.5.camel@blackbetty>

On Thu, 2003-08-21 at 09:59, SGD wrote:
> I would like to install multipe instances of python, specificly 2.2.3
> and 2.3. 
> 
> Is this possible? And if so, what are the laws that govern the process?
> I tried the manuals, but I must have missed it...

Hello,

   You'd probably have to tell us which operating system you plan on
doing this on. I've successfully run two different versions of Python on
a Windows machine, but I have not tried this under Linux. 

   The only thing you should be careful of is your PATH system variable.
You'd have to set it accordingly depending on which version of Python
you want to access at that certain time.

-- 
/Gus


From jason at museunlimited.com  Sat Aug 23 12:38:28 2003
From: jason at museunlimited.com (Jason Thompson)
Date: Sun Aug 24 12:53:27 2003
Subject: [Tutor] parsing woes
In-Reply-To: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <200308231139.29600.jason@museunlimited.com>

If I'm understanding your question properly, you simply need to determine the 
length of your parameters list. The following example works for any number of 
parameters. 

#!/usr/bin/python

parameters = ['1', 'F', '5']

if len(parameters) == 0			#if there aren't any parameters
	print "No parameters given"
else:
	length = len(parameters)
	top = length-1			#the 'top' index for parameters
	for p in parameters:
		print parameters[top] 	#print the highest index in list
		top = top-1			#reduce by one to print next lowest

Obviously I've simplified your example a great deal, but if I'm understanding 
your problem correctly, this should get you started. This way your program 
will never try to address any parameter that doesn't exist.
Best,
Jason

On August 22, 2003 11:46 am, Vicki Stanfield wrote:
> Okay, I didn't get an answer to this last time, so let me restate it and
> try again. I am attempting to parse a string which is in the form:
>
> 1 F 5
>
> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.
>
>     if parameters[2]:
> IndexError: list index out of range
>
> when I try to run this code to see what the values are:
>     if parameters[0]:
>          print parameters[0]
>     if parameters[1]:
>          print parameters[1]
>     if parameters[2]:
>          print parameters[2]
>
> I am parsing them this way:
>
> if arguments:
>     parameters=arguments.split(" ")
> else: parameters = ""
>
>
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.
>
> --vicki
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From dyoo at hkn.eecs.berkeley.edu  Sat Aug 23 00:18:05 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 24 13:01:36 2003
Subject: [Tutor] More py please?
In-Reply-To: <000001c367ec$822017f0$bf37c6d1@whiterhino2>
Message-ID: <Pine.LNX.4.44.0308222314090.26480-100000@hkn.eecs.berkeley.edu>



On Thu, 21 Aug 2003, SGD wrote:

> I would like to install multipe instances of python, specificly 2.2.3
> and 2.3.
>
> Is this possible? And if so, what are the laws that govern the process?
> I tried the manuals, but I must have missed it...

Hi SGD,

Yes, it's very possible.  I'm not too familiar with how things work on the
Windows side, so you may need to get a response from someone else about
it.

On Unix systems, at least, Python 2.2 installs itself with two names by
default:

    /usr/local/bin/python

and

    /usr/local/bin/python2.2

Python 2.3 will co-opt '/usr/local/bin/python' when it's installed, but
will leave '/usr/local/bin/python2.2' alone.  (Python 2.3 will also make
itself '/usr/local/bin/python2.3').

The libraries directories are totally separate too, so if you've installed
any third-party modules for Python 2.2, you'll need to do the same for
Python 2.3.  Slightly inconvenient, but it guarantees that 2.3 doesn't do
any munging of 2.2-based libraries.


Hope this helps!


From missive at hotmail.com  Sat Aug 23 16:13:55 2003
From: missive at hotmail.com (Lee Harr)
Date: Sun Aug 24 13:03:09 2003
Subject: [Tutor] Re: More py please?
Message-ID: <BAY2-F170puP2GbwZLA00004c59@hotmail.com>

>I would like to install multipe instances of python, specificly 2.2.3 and 
>2.3.
>
>Is this possible? And if so, what are the laws that govern the process?
>

I have 3 versions installed:

$pkg_info | grep python
python-2.1.3_3      An interpreted object-oriented programming language
python-2.2.3        An interpreted object-oriented programming language
python-2.3          An interpreted object-oriented programming language
python-doc-html-2.2.2 Documentation for the Python programming language
python-doc-html-2.3 Documentation for the Python programming language


Generally, python is quite good at not stepping on its own toes.

One thing you need to be careful of is the actual python executable.
Probably this depends a lot on which os you are using, but on my
system, I have:

$ls -l /usr/local/bin/python*
-r-xr-xr-x  2 root  wheel    2964 Aug  1 15:20 /usr/local/bin/python
-r-xr-xr-x  1 root  wheel  520908 Apr 19 05:07 /usr/local/bin/python2.1
-r-xr-xr-x  1 root  wheel  657672 Jun  9 18:22 /usr/local/bin/python2.2
-r-xr-xr-x  2 root  wheel    2964 Aug  1 15:20 /usr/local/bin/python2.3

what you can see here is that python and python2.3 both have 2 references,
and they are both the same size. They are actually just 2 "hard links" to 
the
same file. (the reason they are much smaller than the others is that it is 
built
with the shared libraries instead of statically. I think the FreeBSD port 
changed
the way this was done recently)

So, if you have some application which depends on python being python2.2
you should make sure after all the installation is done which version of
python is the main one.

_________________________________________________________________
Get MSN 8 and help protect your children with advanced parental controls.  
http://join.msn.com/?page=features/parental


From david at graniteweb.com  Fri Aug 22 23:17:17 2003
From: david at graniteweb.com (David Rock)
Date: Sun Aug 24 14:38:24 2003
Subject: [Tutor] parsing woes
In-Reply-To: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <20030823031717.GA1955@wdfs.graniteweb.com>

* Vicki Stanfield <vicki@thepenguin.org> [2003-08-22 10:46]:
> Okay, I didn't get an answer to this last time, so let me restate it and
> try again. I am attempting to parse a string which is in the form:
> 
> 1 F 5
> 
> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.
> 
>     if parameters[2]:
> IndexError: list index out of range
> 
> when I try to run this code to see what the values are:
>     if parameters[0]:
>          print parameters[0]
>     if parameters[1]:
>          print parameters[1]
>     if parameters[2]:
>          print parameters[2]
> 
> I am parsing them this way:
> 
> if arguments:
>     parameters=arguments.split(" ")
> else: parameters = ""
> 
> 
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.

put it into a try block. The problem is you are accessing an index that
doesn't exist. This raises the IndexError exception:

try:
	if parameters[0]:
	   print parameters[0]
	if parameters[1]:
	   print parameters[1]
	if parameters[2]:
	   print parameters[2]
except:
	pass

This example just throws it away if there is an error during this block
of code. This is by no means a clean example, but it demonstrates how to
use the try/except code.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030822/39bd48d3/attachment.bin
From scot at possum.in-berlin.de  Sun Aug 24 19:29:05 2003
From: scot at possum.in-berlin.de (Scot W. Stevenson)
Date: Sun Aug 24 15:08:04 2003
Subject: [Tutor] More py please?
In-Reply-To: <1061614807.9835.5.camel@blackbetty>
References: <000001c367ec$822017f0$bf37c6d1@whiterhino2>
	<1061614807.9835.5.camel@blackbetty>
Message-ID: <200308241829.05481.scot@possum.in-berlin.de>

Hi there, 

>    You'd probably have to tell us which operating system you plan on
> doing this on. I've successfully run two different versions of Python on
> a Windows machine, but I have not tried this under Linux.

I have SuSE 8.2 default Python installed (2.2, I think) and later upgraded to 
2.3 without a problem: It seems that Python likes to put itself in 
/usr/local instead of mainlining it. Also, /usr/bin/python is just a 
symbolik link to /usr/bin/python2.2 on my machine. 

Y, Scot


-- 
          How to quiet a crying baby with the X Window System: 
                  nice xlock -inwindow -mode kumppa

               Scot W. Stevenson - Zepernick, Germany


From pythontutor at venix.com  Sat Aug 23 13:46:44 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sun Aug 24 15:21:55 2003
Subject: [Tutor] Re: parsing woes
In-Reply-To: <10757.206.53.226.4.1061576337.squirrel@www.thepenguin.org>
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
	<10757.206.53.226.4.1061576337.squirrel@www.thepenguin.org>
Message-ID: <3F479A74.8070607@venix.com>

I think you really want to know how many parameters are present.
parm_count = len(parameters)
will give you that information.

I do not understand enough of what you are doing to suggest much
more detail.  Presumably you could wind up with code like:
if parm_count == 0:
	# handle no parms
elif parm_count == 1:
	# adjust for two missing parms
elif parm_count == 2:
	# adjust for one missing parm
elif parm_count == 3:
	# do what needs to be done
else:
	# error handling for too many

if you write functions for these cases you could possibly do this:
{ 0: no_parms_func,
   1: one_parm_func,
   2: two_parm_func,
   3: three_parm_func}.get(len(parameters), too_many_func)(parameters)

Use len(parameters) to choose the correct function from a dictionary.
Specify a function for the "else" case.
Call (invoke) the funtion passing it the parameter list.


One other suggestion.  Your earlier email showed:
 >if arguments:
 >     parameters=arguments.split(" ")
 > else: parameters = ""
else: parameters = []
would probably be better.  In that case, note that "".split() returns [].
You probably do NOT need the if arguments test.

Hope this helps.

Vicki Stanfield wrote:

>>Okay, I didn't get an answer to this last time, so let me restate it and
>>try again. I am attempting to parse a string which is in the form:
>>
>>1 F 5
>>
>>I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
>>The difficulty is that there might be no parameters or any number up to 3.
>>They won't always be a single digit or letter but they will always be
>>space-delimited. My problem is that when I try to display them, I get an
>>error if there are not 3 parameters.
>>...
> 
> Okay I finally got it figured out. I had to change the if statements to
> try statements and deal with the index error. The code looks like this
> now:
 > ...
> --vicki

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From pythontutor at venix.com  Sat Aug 23 14:33:54 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sun Aug 24 15:24:21 2003
Subject: [Tutor] Help with a cgi example
In-Reply-To: <3F463539.6070400@unixremedies.com>
References: <3F463539.6070400@unixremedies.com>
Message-ID: <3F47A582.9080500@venix.com>

Justin Heath wrote:
> All,
> 
> I am currently working thru some of the cgi examples in "Programming
> Python". I am stuck on how one of the examples works. Here is the example:
>        if type(form[field]) != type([]):
>            data[field] = form[field].value
>        else:
>            values = map(lambda x: x.value, form[field])
>            data[field] = string.join(values, ' and ')
> print html % data
> 
It is possible for multiple values to be supplied for a field.  In that
case form.field will return a list of FieldStorage (or MiniFieldStorage)
instances.  The funny looking code takes the list of FieldStoage instances
and extracts the values which are strings.  The lambda expression simply
calls the FieldStorage instance's value method to get the string that
was entered through the HTML form.  Map applies that value call to each
of the FieldStorage instances in the form[field] list.  We are
transforming a list of FieldStorage instances into a list of strings.
The join expression that conbines these strings could have been written:
	' and '.join(values)
The resulting string is then assigned into the dictionary named data using
field as the key.


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From pythontutor at venix.com  Sat Aug 23 14:00:28 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sun Aug 24 15:25:32 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class
 ?
In-Reply-To: <00d101c36884$fae66200$0d001eac@ud.cybage.com>
References: <00d101c36884$fae66200$0d001eac@ud.cybage.com>
Message-ID: <3F479DAC.4040703@venix.com>

The python function setattr should do what you want.  I expect you
would write something like:

class ConfigReader:
	# stuff
	def ReadConfigFile(self):
		# stuff to get key_names and key_value pairs so that
		# key_name = "MAX_THREADS and key_value = some_integer
		setattr( self, key_name, key_value)

Then your line:
 >         noOfThreads = config.MAX_THREADS
should work.

This example code does not make any use of whatever might have been
done in the AddKey method.

HTH


K Dhanvi wrote:

> Dear friends,
> 
>  I have a query about giving names to variables inside classes and thus to
> the objects of the classes..
> 
>  I have a class called configReader which reads a configuration file and
> then puts the configuration data into a dictionary at prsent. Before reading
> the configuration file, the config object is told what keys to expect and
> their datatpyes for simple santiy checks on the corresonding values.. At
> present the key and values are stored in a dictionary.. I would like to make
> each key a property of the respective configReader object.
>   for example => 
>  If one of my keys in the configuration file is MAX_THREADS..
> I would like my code to be as follows
> ------------------------------------------------------------------------------------- 
> 
>         import ConfigReader
>         config = ConfigReader( "./config.file")
>         config.AddKey( "MAX_THREADS", INT )
>         config.ReadConfigFile()
> 
>         noOfThreads = config.MAX_THREADS
> -------------------------------------------------------------------------------------
> 
> The first 3 lines of the sample code have been completed.. I would like to
> add the functionality similar to the final line of the sample code. Each
> object willl have different properties in itself depending upon the keys it
> was initialized with. i.e there could be another config object which will
> access another property "REGISTRATION_CURVE"..
>  config1.REGISTRATION_CURVE.
> 
> please lemme  know if theres any way this can be achieved in Python ?
> 
> Thank you for your time and help :)
> 
> Dhanvi
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From darnold02 at sprynet.com  Fri Aug 22 23:16:50 2003
From: darnold02 at sprynet.com (Don Arnold)
Date: Sun Aug 24 15:42:28 2003
Subject: [Tutor] parsing woes
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <039701c36925$056be790$8f10ba3f@defaultcomp>


----- Original Message -----
From: "Vicki Stanfield" <vicki@thepenguin.org>
To: <tutor@python.org>
Sent: Friday, August 22, 2003 10:46 AM
Subject: [Tutor] parsing woes


> Okay, I didn't get an answer to this last time, so let me restate it and
> try again. I am attempting to parse a string which is in the form:
>
> 1 F 5
>
> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.
>
>     if parameters[2]:
> IndexError: list index out of range
>
> when I try to run this code to see what the values are:
>     if parameters[0]:
>          print parameters[0]
>     if parameters[1]:
>          print parameters[1]
>     if parameters[2]:
>          print parameters[2]
>
> I am parsing them this way:
>
> if arguments:
>     parameters=arguments.split(" ")
> else: parameters = ""
>
>
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.
>
> --vicki
>

How about using len( ) to test for the number of parameters you're dealing
with? Not too pretty, but:

def parse(arguments=''):
    parameters = arguments.split()

    numParams = len(parameters)

    if numParams > 0:
        print parameters[0]
    if numParams > 1:
        print parameters[1]
    if numParams > 2:
        print parameters[2]

so:

>>> parse('1 2 3')
1
2
3

>>> parse('1 2')
1
2

>>> parse('1')
1

>>> parse('')


Note that the last one prints nothing since an empty string was passed.

HTH,
Don


From idiot1 at netzero.net  Sat Aug 23 15:56:16 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 24 15:57:45 2003
Subject: [Tutor] One for Kirk...
In-Reply-To: <BB6AAA6C.C41E%clay@shirky.com>
References: <BB6AAA6C.C41E%clay@shirky.com>
Message-ID: <3F47B8D0.9000804@netzero.net>

I saved the sourcecode, and placed it on my server.
	http://www.tinylist.prg/cgi-bin/wypy.py

It generates a error:
-----------------------------------------------------------------------
   File "/www/www.tinylist.org/cgi-bin/wypy.py", line 23
     main(dict([(i.name, i.value) for i in cgi.FieldStorage().list]))
                                    ^
SyntaxError: invalid syntax
[Sat Aug 23 14:45:21 2003] [error] [client 67.31.207.132] Premature end of 
script headers: /www/www.tinylist.org/cgi-bin/wypy.py
-----------------------------------------------------------------------
intresting. wonder why it does this?

Ccould use the '' and ''' for itilac and bold, respectively, but it's good. Wish 
I could read the dad blaimed thing... I could steal something for wikinehesa...


http://www.tinylist.org/cgi-bin/wikinehesa.py




Clay Shirky wrote:
> A wiki written in 23 lines of Python:
> http://sbp.f2o.org/2003/wypy
> 
> Unreadable, of course (lotsa inline lambdas :), but kind of awe-inspiring,
> nevertheless.
> 
> -clay
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From garnaez at yahoo.com  Sat Aug 23 16:33:28 2003
From: garnaez at yahoo.com (Gerardo Arnaez)
Date: Sun Aug 24 16:20:58 2003
Subject: [Tutor] Network stuff
Message-ID: <20030823223328.73715.qmail@web20207.mail.yahoo.com>

Hello all, enjoying the heck out of python. using to
help set up user accounts at a public internet cafe
where they will sell these accoutnts in 30 min
sessions.

Right now I can get a list of any user and total time
logged in to one computer.  I break this up into a
dictionary.

The problem is that I am not sure how to transmit this
information.  Ie I have some data I want to sent to
another application on another computer.

At first twisted was mentioned to me,
and I see socket and socketServer modules,
but I need some hints in what would be the pythonic
way to go about this.

All I really want to do is send a dictionary from a
client app and have it examined in the server app.

Anyway, I would should could but its so simplistic
that is amounts to parseing the output of 'ac' an gnu
account procces and logins
and storing them into a dictionary.

Anyway, Thanks for all your help

G




__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From alan.gauld at blueyonder.co.uk  Sun Aug 24 17:55:23 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Aug 24 16:44:55 2003
Subject: [Tutor] parsing woes
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
	<00ce01c36a0f$461bda30$6401a8c0@xp>
	<41631.127.0.0.1.1061731712.squirrel@www.thepenguin.org>
Message-ID: <00de01c36a58$21297fe0$6401a8c0@xp>

> > try:
> >    if ....
> > except IndexError:
> >    pass
> >
> > That will simply ignore the index error.
> This is what I am currently doing. It seems to be working fine.

You were checking each line with try/except. I am suggesting
using just 1 try/exeptr pair to encapsulate all the indexing
operations - saves some code and im[roves readability, at
the cost of losing the precision of the error response.

> > if num > 2: print parameters[2]
> > if num > 3: print "Too many parameters!"
> >
> I'll have to look into the len function. I was under the assumption
that
> not knowing what the length of the parameter would prohibit its use.

Its purpose is to tell you how many things are in the sequence.

> parameters could be a single letter or number of multiple
letter/number
> combination. I only know that they will be space-delimited.

OK but by this time you have already "split" them into a list.
len() will tell you how many items are in the list. It won't
tell you anything about what "the things" are, just how many...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From vibrations at cetlink.net  Sun Aug 24 15:32:04 2003
From: vibrations at cetlink.net (SGD)
Date: Sun Aug 24 18:38:06 2003
Subject: [Tutor] more py revisited
Message-ID: <001001c36a6e$16969520$2a34c6d1@whiterhino2>

I didn't give enough info in my last question so I'll restate it.

I would like to install multiple instances of python on windows XP,
specifically 2.2.3 and 2.3.    
Is this possible? And if so, what are the laws that govern the process?
I tried the manuals, but I must have missed it...

I'm not confident in knowing I could use 2.3 as my main environment and
still allowing me to work in 2.2.3 until the packages I would like to
use are updated. Say I'm using an IDE connected to 2.3, how would I run
a 2.2.3 script from that same IDE (any IDE really, I use so many, so
hard to decide which I like best)? Or better yet, specifying which run
time version I would like to run a script from explorer? Is it legal to
rename one of the exe's to say, python.exe->py22.exe and
pythonw.exe->pyw22.exe, to use windows "right click" "open with", or
something similar?

I had both installed before but was experiencing problem, I think I
missed something.
I'm looking specifically for windows, but anyone who has info on this
for other platforms (Linux, UNIX, etc.) would be useful all the same.

Thanks


From wsalloum at intertrust.com  Wed Aug 20 18:25:36 2003
From: wsalloum at intertrust.com (Wael Salloum)
Date: Sun Aug 24 18:42:48 2003
Subject: [Tutor] Help in geting external program output
Message-ID: <D5987FFC5C2504499274E608BA47C51B8A0F19@exch-1.corp.intertrust.com>

Hello!

 

            So I am just learning python- and I have a program in java
and it writes into a file, and I want it to return the filename to me
(in python.)

 

            So I have a script and I use fileName = os.popen('java
theApplication').read()

 

            However, its always returning blank! 

 

            Now when I do os.popen('dir').read() it works just fine...

 

            So my question is, what does Python deem is the output of a
file, and how can I get my java code to 'output' a filename..

 

            Its obviously not println's (I tried that).. so I am
stumped.. Do you have any ideas?

 

            I just started in python, so I am sorry if this is a stupid
question- I am not subscribed to the list so let me know how it goes.

 

            Thanks... Wael

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030820/261b1a72/attachment.htm
From dhanvik at cybage.com  Fri Aug 22 14:40:24 2003
From: dhanvik at cybage.com (K Dhanvi)
Date: Sun Aug 24 18:43:12 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class ? 
Message-ID: <00c001c36884$d7f4eaf0$0d001eac@ud.cybage.com>

Dear friends,

 I have a query about giving names to variables inside classes and thus to
the objects of the classes..

 I have a class called configReader which reads a configuration file and
then puts the configuration data into a dictionary at prsent. Before reading
the configuration file, the config object is told what keys to expect and
their datatpyes for simple santiy checks on the corresonding values.. At
present the key and values are stored in a dictionary.. I would like to make
each key a property of the respective configReader object.
  for example. If one of my keys in the configuration file is MAX_THREADS..
I would like my code to be as follows
----------------------------------------------------------------------------
--------- 
        import ConfigReader
        config = ConfigReader( "./config.file")
        config.AddKey( "MAX_THREADS", INT )
        config.ReadConfigFile()

        noOfThreads = config.MAX_THREADS
----------------------------------------------------------------------------
---------

The first 3 lines of the sample code have been completed.. I would like to
add the functionality similar to the final line of the sample code. Each
object willl have different properties in itself depending upon the keys it
was initialized with. i.e there could be another config object which will
access another property "REGISTRATION_CURVE"..
 config1.REGISTRATION_CURVE.

please lemme  know if theres any way this can be achieved in Python ?

Thank you for your time and help :)

Dhanvi


From derek at leder.com.au  Sat Aug 23 14:25:28 2003
From: derek at leder.com.au (Derek at leder)
Date: Sun Aug 24 18:43:37 2003
Subject: [Tutor] Unicode (utf-16-le)
Message-ID: <5.2.0.9.0.20030823132404.00ae8bf0@127.0.0.1>

Does anyone know of a module for converting utf-16-le to ascii?

before I write one.


Derek

// Derek Morton & Lenise Whyte from Eltham in Victoria, Australia //
//        derek at leder com au    lenise at leder com au         //
Outgoing mail is certified Virus Free.
From peterabrown at froggy.com.au  Sun Aug 24 08:08:45 2003
From: peterabrown at froggy.com.au (Peter Brown)
Date: Sun Aug 24 18:44:02 2003
Subject: [Tutor] Server stuff
Message-ID: <3.0.6.32.20030824070845.00b17df0@mail.froggy.com.au>

Hi,

I'm very new to Python, so please be kind.

1. I'm trying to write a server program. How do I do this without looping
forever and calling time.sleep()?

2. Is there an easy way to extract a sequence of at least 6 digits from a
string. Can't rely on the digits to be in a word by themselves.

 It's mainly for text processing from a file that has to be checked if it
exists and if it does I process the file and insert into postrgesQl
database and write back to a backup file. I've been reading and googling
for days without success.

Thanks in advance.

Peter




From vicki at thepenguin.org  Sun Aug 24 09:28:32 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Sun Aug 24 18:51:18 2003
Subject: [Tutor] parsing woes
In-Reply-To: <00ce01c36a0f$461bda30$6401a8c0@xp>
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org> 
	<00ce01c36a0f$461bda30$6401a8c0@xp>
Message-ID: <41631.127.0.0.1.1061731712.squirrel@www.thepenguin.org>

>> when I try to run this code to see what the values are:
>>     if parameters[0]:
>>          print parameters[0]
>>     if parameters[1]:
>>          print parameters[1]
>>     if parameters[2]:
>>          print parameters[2]
>
> There are at least two approaches you could use:
>
> try:
>    if ....
> except IndexError:
>    pass
>
> That will simply ignore the index error.
This is what I am currently doing. It seems to be working fine.

>
> Or more explicitly (prevention is better than cure philosophy)
>
> num = len(parameters)
> if num == 0: print "No parameters"
> if num > 0: print parameters[0]
> if num > 1: print parameters[1]
> if num > 2: print parameters[2]
> if num > 3: print "Too many parameters!"
>
I'll have to look into the len function. I was under the assumption that
not knowing what the length of the parameter would prohibit its use. The
parameters could be a single letter or number of multiple letter/number
combination. I only know that they will be space-delimited.

--vicki

From alan.gauld at blueyonder.co.uk  Sun Aug 24 09:13:52 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Aug 24 19:00:21 2003
Subject: [Tutor] parsing woes
References: <7086.206.53.226.4.1061567217.squirrel@www.thepenguin.org>
Message-ID: <00ce01c36a0f$461bda30$6401a8c0@xp>

> when I try to run this code to see what the values are:
>     if parameters[0]:
>          print parameters[0]
>     if parameters[1]:
>          print parameters[1]
>     if parameters[2]:
>          print parameters[2]

There are at least two approaches you could use:

try:
   if ....
except IndexError:
   pass

That will simply ignore the index error.

Or more explicitly (prevention is better than cure philosophy)

num = len(parameters)
if num == 0: print "No parameters"
if num > 0: print parameters[0]
if num > 1: print parameters[1]
if num > 2: print parameters[2]
if num > 3: print "Too many parameters!"

HTH,

Alan G.

From peterabrown at froggy.com.au  Mon Aug 25 09:45:22 2003
From: peterabrown at froggy.com.au (Peter Brown)
Date: Sun Aug 24 19:12:11 2003
Subject: [Tutor] Server stuff
Message-ID: <3.0.6.32.20030825084522.00b1b770@mail.froggy.com.au>

Hi,

I'm very new to Python, so please be kind.

1. I'm trying to write a server program. How do I do this without looping
forever and calling time.sleep()?
2. Is there an easy way to extract a sequence of at least 6 digits from a
string. Can't rely on the digits to be in a word by themselves.

 It's mainly for text processing from a file that has to be checked if it
exists and if it does I process the file and insert into postrgesQl
database and write back to a backup file. I've been reading and googling
for days without success.

Thanks in advance.

Peter




From dyoo at hkn.eecs.berkeley.edu  Sun Aug 24 17:05:17 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 24 19:32:18 2003
Subject: [Tutor] Unicode (utf-16-le)
In-Reply-To: <5.2.0.9.0.20030823132404.00ae8bf0@127.0.0.1>
Message-ID: <Pine.LNX.4.44.0308241601400.25450-100000@hkn.eecs.berkeley.edu>



On Sat, 23 Aug 2003, Derek at leder wrote:

> Does anyone know of a module for converting utf-16-le to ascii?
> before I write one.

Hi Derek,

Strings support other character sets through the 'encode()' and 'decode()'
methods.  For example:

###
>>> s = 'hello world'
>>> utf_txt = s.encode('utf-16')
>>> utf_txt
'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>>> utf_txt.decode('utf-16')
u'hello world'
###

Here's a partial list of the character encodings that Python supports:

    http://www.python.org/doc/lib/node126.html

According to that list, 'utf-16-le' is a codec that it can handle, so you
should be in good shape.  *grin*


Good luck to you!


From idiot1 at netzero.net  Fri Aug 22 19:00:17 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 24 19:52:11 2003
Subject: [Tutor] COOL! Surf's up! So's the wiki!
Message-ID: <3F469271.6060303@netzero.net>

OK, mail.python.org is back up. Great news, sorry the virus hit the thing to 
begin with- is it a windows server, perish the thought?

Wikinehesa is coming along. Got backsearch, titlelist, phrasesearch all working. 
It hands off the the browser program on concluding saving the edited page. Still 
got a few issues with how it processes a few wikitags, but as of now it is a 
working and mostly debugged betastage wiki. Only remaining task is to get the 
dagnab code conversion debugged so it does not mulch some items during later 
processing, and render it immune to things PRECEEDING wikiwords. Maybe this is 
late alpha testing?

Anyone intrested, here's some urls:

wikinehesa- see how it renders pages:
	http://www.tinylist.org/cgi-bin/wikinehesa.py

the sourcecode:
	http://www.tinylist.org/wikinehesa.txt

Feel free to write. IN fact, feel free to dive into the wiki. The editor works fine.


-- 

end

Cheers!
         Kirk D Bailey

  +                              thimk                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | XOB |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              thimk                                +

Fnord.



From dyoo at hkn.eecs.berkeley.edu  Sun Aug 24 17:22:08 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 24 20:07:53 2003
Subject: [Tutor] Re: email problems with tutor list
In-Reply-To: <3F47AA24.4000200@venix.com>
Message-ID: <Pine.LNX.4.44.0308241539410.24223-100000@hkn.eecs.berkeley.edu>



On Sat, 23 Aug 2003, Lloyd Kvam wrote:

> I assume that the mail list server is getting hammered by the bogus
> email from the sobig virus.  Do you need any help in dealing with that?
> I can possibly help with writing code for filtering messages or possibly
> help with some testing.

[CCing to the rest of the list so that people are aware of the issue, even
though it's sorta off-topic]

Hi Lloyd,

Yes, we know about it; it's not just Tutor, but all of the mailing lists
hosted on mail.python.org.

For people who haven't been blasted by spam yet, here's what's going on.
There's a ugly virus going around called SoBig:

    http://reviews.cnet.com/4520-6600_7-5065445.html?tag=cnetfd.glnav

This bug is evil because it's hammering a lot of mail systems across the
network, and this includes the one for Python.org.  The folks at
Python.org have told me that they're working on the problem, so things
should gradually get back to normal.  It might take a while though, so
please be patient.


I don't personally administrate the machines; if you're interested in
helping, you may want to check with webmaster@python.org and volunteer
your efforts there.  If that email address doesn't respond too quickly,
ask on the comp.lang.python newsgroup.


By the way, if you know anyone with a Windows machine, please tell them to
make sure they're running updated antivirus software and the latest
Windows patches.  We need to kill this silly virus so we can go back to
talking about real issues, like learning Python programming.


Thanks again!


From tim.one at comcast.net  Sun Aug 24 21:06:09 2003
From: tim.one at comcast.net (Tim Peters)
Date: Sun Aug 24 20:19:41 2003
Subject: [Tutor] COOL! Surf's up! So's the wiki!
In-Reply-To: <3F469271.6060303@netzero.net>
Message-ID: <LNBBLJKPBEHFEDALKOLCGENIFGAB.tim.one@comcast.net>

[Kirk Bailey]
> OK, mail.python.org is back up.

It's still struggling to return to normalcy, but the worst may be over.

> Great news, sorry the virus hit the thing to begin with- is it a
> windows server, perish the thought?

No, no.  There was no virus *on* mail.python.org.  The virus had no direct
effect on the box (which is a Linux box regardless).  What happens is that
worms sending email forge the sender address, and because python.org hosts
many well-known email addresses, countless virus messages went out claiming
to come from python.org; this was on top of that the virus found a
python.org email address on many machines that were infected, so tried to
send itself to one or more python.org addresses from infected machines.

The result was hundreds of thousands of connections trying to send email to
a python.org address, either the virus trying to propagate itself, or idiot
email servers replying to a forged python.org sender address to complain
about a virus they received.  Add to that the occasional clueless virus
recipient sending outraged email back to a forged python.org address, and in
some cases thousands of outraged emails.

The moral of the story is that you don't have to contract a virus to suffer
from it:  the huge email traffic it generates can kill you regardless, if
you're unlucky enough to be picked as a recipient or as a forged sender
address.  The operating system you run is irrelevant then.


From clay at shirky.com  Sun Aug 24 21:24:20 2003
From: clay at shirky.com (Clay Shirky)
Date: Sun Aug 24 20:29:11 2003
Subject: [Tutor] parsing woes
In-Reply-To: <41631.127.0.0.1.1061731712.squirrel@www.thepenguin.org>
Message-ID: <BB6ECF74.C6EB%clay@shirky.com>

> I'll have to look into the len function. I was under the assumption that
> not knowing what the length of the parameter would prohibit its use. The
> parameters could be a single letter or number of multiple letter/number
> combination. I only know that they will be space-delimited.

Note that the param_count = len(params) format that many of us suggested
does not tell you the length in chars of *each* parameter, it tells you the
length of the parameter *list*, which is to say how many elements are in
that list.

-clay



From shad at mail.kubtelecom.ru  Mon Aug 25 05:44:16 2003
From: shad at mail.kubtelecom.ru (Denis Dzyubenko)
Date: Sun Aug 24 20:54:52 2003
Subject: [Tutor] buffering IO
Message-ID: <20030825004416.GK27693@station>

Hello,

I need to disable buffering for some file descriptors. For regular files
I can use third argument of open(fname, mode, bufsize), but what to do
with stdin and stdout? In C I can use setvbuf function to disable
buffering, but I can't find python-version of this function.

I am writing a front-end to python console application and buffering
isn't a good idea in this situation.

-- 
Denis

From clay at shirky.com  Sun Aug 24 21:55:25 2003
From: clay at shirky.com (Clay Shirky)
Date: Sun Aug 24 20:55:55 2003
Subject: [Tutor] Server stuff
In-Reply-To: <3.0.6.32.20030824070845.00b17df0@mail.froggy.com.au>
Message-ID: <BB6ED6BD.C6F0%clay@shirky.com>

> 2. Is there an easy way to extract a sequence of at least 6 digits from a
> string. Can't rely on the digits to be in a word by themselves.

You want to search the string for the regex \d{6,}  (that is, 6 or more
digits), and then print the matchobject, like so:

strings = [ '1234spam', '123456eggs', 'spam1234567toast', '12345678' ]

for string in strings:
    match = re.search( "(\d{6,})", string )
    if match: print match.group(1)

This prints

123456
1234567
12345678


From kuros at sbcglobal.net  Sun Aug 24 21:52:18 2003
From: kuros at sbcglobal.net (Kuros)
Date: Sun Aug 24 21:53:00 2003
Subject: [Tutor] XML DOM
Message-ID: <001901c36aab$84e26fd0$9865fea9@Malkil>

Hello,

I'm running into a problem using DOM with XML.

What I want to do is this:

I have an XML document, it looks like this:

<world>
 <room>
  <id>1</id>
  <name>A Room</name>
  <desc>A Large Room</desc>
  a few other values like these..
 </room>
 <room>
 a new room with the same values here
 </room>
</world>

Now, what I want to do is use DOM to go over ever room entry, and create a new class containing the values.

I have my class looking like this:

class Room:
     id = 0
     name = ''
     desc = ''
and more values for every attribute in the XML document

Now, I want to take all the attributes in the room node of the XML document, and assign them to thier appropiate value in the object. At the end of the room node, I want to create a new class for the room, and add it to a list of room classes. Repeat for every room node.

That I think I know how to do, but what I am having trouble with is traversing the DOM tree to get the values.

I have managed to create a treewalker, and get the DOM loaded into memory. I can make it display a list of node names and thier values, with something like this...

while 1:
print walker.currentNode.nodeName
print walker.currentNode.nodeValue
next = walker.nextNode()
if next is None: break

I have tried to do something like this:

while 1:
next = walker.nextNode()
if walker.currentNode.nodeName == 'room':
curnode = next.currentNode.firstChild
roomid = curnode.nodeValue
curnode = curnode.nextSibling
etc

Unfortuantly, it doesn't work. The interperter window just continually scrolls...

If anyone has a link to something that could help me, or any ideas on how to accomplish this, I would be most thankful.

Thanks,
Kuros
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030824/e605a0a7/attachment.htm
From speno at isc.upenn.edu  Sun Aug 24 23:54:51 2003
From: speno at isc.upenn.edu (John P Speno)
Date: Sun Aug 24 22:54:54 2003
Subject: [Tutor] buffering IO
In-Reply-To: <20030825004416.GK27693@station>
References: <20030825004416.GK27693@station>
Message-ID: <20030825025451.GA9465@isc.upenn.edu>

On Mon, Aug 25, 2003 at 04:44:16AM +0400, Denis Dzyubenko wrote:
> Hello,
> 
> I need to disable buffering for some file descriptors. For regular files
> I can use third argument of open(fname, mode, bufsize), but what to do
> with stdin and stdout? In C I can use setvbuf function to disable
> buffering, but I can't find python-version of this function.

See the -u option for python, which says:

       -u     Force  stdin,  stdout  and  stderr  to  be  totally
              unbuffered.

From idiot1 at netzero.net  Sun Aug 24 23:56:06 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Aug 24 22:56:37 2003
Subject: [Tutor] chain gangs pressed into obediant service at last
Message-ID: <3F497AC6.40803@netzero.net>

and boy am I glad. This thing has more kinks to it than a madam's commercial 
imagination! It is displaying images, doing nice titleheaders, links are right, 
email and offsite http links are rightious, and it kills any html code you want 
to imbed into a page. SCREWY way to do it, and hacked to hell and back, and 
desperately in need of some state aware processing subroutines, which I do not 
yet grok, but it seems to work.

therefore, one and all, take a look and play in my wiki.

http://www.tinylist.org/cgi-bin/wikinehesa.py

There's the wiki area, an area about wikinehesa, the randy poet's society, and 
more. I invite anyone intrested to look, even dive in.

To examine the sourcecode, click THIS:
http://www.tinylist.org/wikinehesa.txt


-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From project5 at redrival.net  Mon Aug 25 03:11:06 2003
From: project5 at redrival.net (Andrei)
Date: Sun Aug 24 23:24:47 2003
Subject: [Tutor] Re: Server stuff
In-Reply-To: <3.0.6.32.20030825084522.00b1b770@mail.froggy.com.au>
References: <3.0.6.32.20030825084522.00b1b770@mail.froggy.com.au>
Message-ID: <bibka2$hs2$1@sea.gmane.org>

Peter Brown wrote:
> 2. Is there an easy way to extract a sequence of at least 6 digits from a
> string. Can't rely on the digits to be in a word by themselves.

Use a regular expression:

   >>> import re
   >>> mystring = "asdf11111a2a33333333ef444444d"
   >>> myexpr = re.compile(r"(?:\d+){6}")
                   # at least six digits, no upper bounder
   >>> myexpr.findall(mystring)
   ['33333333', '444444']

>  It's mainly for text processing from a file that has to be checked if it
> exists and if it does I process the file and insert into postrgesQl

What's wrong with sleeping for this purpose?

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From project5 at redrival.net  Sun Aug 24 21:34:29 2003
From: project5 at redrival.net (Andrei)
Date: Sun Aug 24 23:25:01 2003
Subject: [Tutor] Regex
Message-ID: <bib0iu$mqp$1@sea.gmane.org>

I'm quite sure I've seen a question of this type before, but I seem 
unable to find it. How can I match a re pattern ONLY if it is not 
preceded by another re pattern? I know how to construct both individual 
regexes, but I don't know how to glue them together in order to achieve 
this.

Think for example of finding all URLs in a piece of text, but *not* if 
they are inside link tags and therefore preceded by 'href="'.
<a href="http://python.org">Python</a> shouldn't give a match, but 
http://python.org on its own should.

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From shad at mail.kubtelecom.ru  Mon Aug 25 08:34:50 2003
From: shad at mail.kubtelecom.ru (Denis Dzyubenko)
Date: Sun Aug 24 23:38:13 2003
Subject: [Tutor] buffering IO
In-Reply-To: <20030825025451.GA9465@isc.upenn.edu>
References: <20030825004416.GK27693@station>
	<20030825025451.GA9465@isc.upenn.edu>
Message-ID: <20030825033450.GL27693@station>

On Sun Aug 24, 2003 at 22:54:51 -0400, John P Speno wrote:
JPS> See the -u option for python, which says:
JPS> 
JPS>        -u     Force  stdin,  stdout  and  stderr  to  be  totally
JPS>               unbuffered.

thank you, this helps me.

How should I launch python-program in this case - should I use
'popen("/usr/bin/python2.2 -u /tmp/pychat.py")' or there is another way
to launch it?

-- 
Denis

From dyoo at hkn.eecs.berkeley.edu  Sun Aug 24 22:00:56 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 25 00:01:02 2003
Subject: [Tutor] Regex  [negative lookbehind / use HTMLParser to parse
	HTML]
In-Reply-To: <bib0iu$mqp$1@sea.gmane.org>
Message-ID: <Pine.LNX.4.44.0308242046290.23261-100000@hkn.eecs.berkeley.edu>



On Sun, 24 Aug 2003, Andrei wrote:

> I'm quite sure I've seen a question of this type before, but I seem
> unable to find it. How can I match a re pattern ONLY if it is not
> preceded by another re pattern?

Hi Andrei,

We can use the negative lookbehind "(?<! )" syntax:

    http://www.python.org/doc/lib/re-syntax.html

For example:

###
>>> regex = re.compile(r'(?<!foo)bar')
>>> regex.search('the chocolate bar melts')
<_sre.SRE_Match object at 0x1e8900>
>>> regex.search('foobar')
>>>
###



> Think for example of finding all URLs in a piece of text, but *not* if
> they are inside link tags and therefore preceded by 'href="'. <a
> href="http://python.org">Python</a> shouldn't give a match, but
> http://python.org on its own should.

The prerequisite "don't parse HTML with regular expressions alone" retort
is instinctively at the tip of my tongue.  *grin*


For this particular example, it's a better idea to use regular expressions
in concert with something like HTMLParser:

    http://www.python.org/doc/lib/module-HTMLParser.html

For example:

###
>>> regex = re.compile("(http://python.org)")
>>> text = """
... The python.org web site,
... <a href="http://python.org">http://python.org</a>
... is a great resource"""
>>>
>>> regex.findall(text)
['http://python.org', 'http://python.org']
###

Here we see the problem of grabbing http://python.org twice --- we'd like
to avoid looking at tag attributes.  To solve this, we can use a parser
that only pays attention to the non-tag data, and run our url-matching
regex on that:

###
>>> import HTMLParser
>>> class Parser(HTMLParser.HTMLParser):
...     def __init__(self):
...         HTMLParser.HTMLParser.__init__(self)
...         self.urls = []
...     def handle_data(self, data):
...         self.urls.extend(regex.findall(data))
...     def getUrls(self):
...         return self.urls
...
>>> p = Parser()
>>> p.feed(text)
>>> p.close()
>>> p.getUrls()
['http://python.org']
###

Hope this helps!


From dhanvik at gmx.net  Mon Aug 25 13:12:13 2003
From: dhanvik at gmx.net (K Dhanvi)
Date: Mon Aug 25 02:44:27 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class ?
References: <00d101c36884$fae66200$0d001eac@ud.cybage.com>
	<3F479DAC.4040703@venix.com>
Message-ID: <03ff01c36ad5$7ad7b0c0$0d001eac@ud.cybage.com>

Hi Thanks for the reply...
It was exactly what I was looking for :)..

The AddKey function is basically for doing some input value validation once
the values are read. This would atleast remove some of the overhead of
validating the inputs.

Thanks for ur help
Dhanvi
----- Original Message ----- 
From: "Lloyd Kvam" <pythontutor@venix.com>
To: "K Dhanvi" <dhanvik@gmx.net>
Cc: <tutor@python.org>
Sent: Saturday, August 23, 2003 10:30 PM
Subject: Re: [Tutor] Dynamic variables names to objects of the same class ?


> The python function setattr should do what you want.  I expect you
> would write something like:
>
> class ConfigReader:
> # stuff
> def ReadConfigFile(self):
> # stuff to get key_names and key_value pairs so that
> # key_name = "MAX_THREADS and key_value = some_integer
> setattr( self, key_name, key_value)
>
> Then your line:
>  >         noOfThreads = config.MAX_THREADS
> should work.
>
> This example code does not make any use of whatever might have been
> done in the AddKey method.
>
> HTH
>
>
> K Dhanvi wrote:
>
> > Dear friends,
> >
> >  I have a query about giving names to variables inside classes and thus
to
> > the objects of the classes..
> >
> >  I have a class called configReader which reads a configuration file and
> > then puts the configuration data into a dictionary at prsent. Before
reading
> > the configuration file, the config object is told what keys to expect
and
> > their datatpyes for simple santiy checks on the corresonding values.. At
> > present the key and values are stored in a dictionary.. I would like to
make
> > each key a property of the respective configReader object.
> >   for example =>
> >  If one of my keys in the configuration file is MAX_THREADS..
> > I would like my code to be as follows
>
> --------------------------------------------------------------------------
----------- 
> >
> >         import ConfigReader
> >         config = ConfigReader( "./config.file")
> >         config.AddKey( "MAX_THREADS", INT )
> >         config.ReadConfigFile()
> >
> >         noOfThreads = config.MAX_THREADS
>
> --------------------------------------------------------------------------
-----------
> >
> > The first 3 lines of the sample code have been completed.. I would like
to
> > add the functionality similar to the final line of the sample code. Each
> > object willl have different properties in itself depending upon the keys
it
> > was initialized with. i.e there could be another config object which
will
> > access another property "REGISTRATION_CURVE"..
> >  config1.REGISTRATION_CURVE.
> >
> > please lemme  know if theres any way this can be achieved in Python ?
> >
> > Thank you for your time and help :)
> >
> > Dhanvi
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> -- 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice: 603-443-6155
> fax: 801-459-9582
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From dhanvik at gmx.net  Mon Aug 25 14:33:01 2003
From: dhanvik at gmx.net (K Dhanvi)
Date: Mon Aug 25 03:54:21 2003
Subject: [Tutor] Dynamic variables names to  objects of the same class ? 
References: <00d101c36884$fae66200$0d001eac@ud.cybage.com>
	<009401c36948$9cec27b0$6401a8c0@xp>
Message-ID: <047b01c36adf$53bf19b0$0d001eac@ud.cybage.com>

Hi
I didn't want to use Dictionary since, then, the user would need to remember
the name of the dictionary each time he needs to access the keys inside it..

The configuration file has multiple key=value pairs that would be read and
validated when the configuration file is read.. For the final user of the
module it would be easier, if he can access the keys of the config file as
attributes of the configReader object rather than through a dictionary.this
would according to me simply accessing the keys for the user...this way he
need not know about the dictionary in which I would have to otherwise store
values.

The AddKey function would maintain a dictionary of the keys and their
datatypes for simple sanity validation of the input. This would help me to
remove some overhead from the end user on doing sanity checks on the values
for the config keys.

I would like to know whether there is any documentation on the web regarding
objects in Python and more functions like setattr and hasattr.. I dont think
these are so well documented functions on objects. So I am looking for help
from more experienced programmers on the group to show me a way :-).. Thanks
a lot for your help.

Dhanvi

PS : Sorry for the previous HTML posting.. I shld have checked my mail
format before sending.. :-)

----- Original Message ----- 
From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
To: "K Dhanvi" <dhanvik@gmx.net>; <tutor@python.org>
Sent: Saturday, August 23, 2003 1:01 PM
Subject: Re: [Tutor] Dynamic variables names to objects of the same class ?


> > object willl have different properties in itself depending
> > upon the keys it was initialized with.
> > please lemme  know if theres any way this can be achieved in Python
> ?
>
> There are ways of achieving this in Python using the getattr()
> and setattr() methods for example. But I'd ask why you don't
> want to use a dictionary? This looks like a classic dictionary
> solution and using a class just for the sake of it doesn't make
> sense. Is there something more that you want to do with the
> class that requires that approach?
>
> If you do need a class approach then why not just use a
> dictionary inside the class? That will be more reliable and
> faster than writing your own dictionary type object...
>
> And if you are using Python 2.2 or above you could even try
> making your class a subclass of the dictionary type.
>
> HTH,
>
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From just4info at serrati.net  Mon Aug 25 12:47:59 2003
From: just4info at serrati.net (just4info)
Date: Mon Aug 25 05:45:33 2003
Subject: [Tutor] GUI Builder
In-Reply-To: <1061589210.27635.2.camel@server.kniep>
References: <3F421EDD.2060607@serrati.net>
	<1061589210.27635.2.camel@server.kniep>
Message-ID: <3F49DB4F.8060505@serrati.net>

Dick Kniep wrote:

>On Tue, 2003-08-19 at 14:58, just4info wrote:
>Hi Matthias
>  
>
>>Are there any GUI (Tk) Builder for python(I only found some one for 
>>Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?
>>    
>>
>
>Take a look at wxPython with Boa Constructor as IDE I have used it in a
>fairly large system and it is perfect!
>
>Regards,
>Dick Kniep
> 
>
>
>
>  
>
hi dick,

the problem with wx, qt, gtk ... is that our customers are not very glad 
to install new libraries on their workstations. Tk would be the best 
solution. It seems that there is no reasonable solution :-(

Regards

matthias


From midnightcoder at comcast.net  Mon Aug 25 07:00:51 2003
From: midnightcoder at comcast.net (Bruce Williams)
Date: Mon Aug 25 06:02:30 2003
Subject: [Tutor] How do you execute a stored function?
Message-ID: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>

I new to Python and am looking for something like the Lisp "eval" function.
I have had no trouble storing functions in a dictionary, but haven't
stumbled upon a way to use them. 

Regards,
Bruce Williams
 
"So, we caught one of our interns out back with our mission critical C++
code, a couple of scripting languages, and SWIG. 
He had the project half done.
We killed him--had no other choice." -- Anonymous 



From darnold02 at sprynet.com  Mon Aug 25 06:44:35 2003
From: darnold02 at sprynet.com (Don Arnold)
Date: Mon Aug 25 06:45:03 2003
Subject: [Tutor] How do you execute a stored function?
References: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
Message-ID: <091101c36af5$e9d57c80$8f10ba3f@defaultcomp>


----- Original Message -----
From: "Bruce Williams" <midnightcoder@comcast.net>
To: <tutor@python.org>
Sent: Monday, August 25, 2003 8:00 AM
Subject: [Tutor] How do you execute a stored function?


> I new to Python and am looking for something like the Lisp "eval"
function.
> I have had no trouble storing functions in a dictionary, but haven't
> stumbled upon a way to use them.


I don't know Lisp's "eval", but once you have the functions in a dictionary,
just access them with the appropriate key and call them like any other
function:


def func1(args=None):
    print 'func1 called with:', args

def func2(args=None):
    print 'func2 called with:', args

def func3(args=None):
    print 'func1 called with:', args

funcDict = {1: func1, 2: func2, 3: func3}

funcDict[1](20)
>>> func1 called with: 20

funcDict[2]('test')
>>> func2 called with: test

funcDict[3]()
>>> func1 called with: None


> Regards,
> Bruce Williams

HTH,
Don


From midnightcoder at comcast.net  Mon Aug 25 08:01:00 2003
From: midnightcoder at comcast.net (Bruce Williams)
Date: Mon Aug 25 07:06:32 2003
Subject: [Tutor] How do you execute a stored function?
In-Reply-To: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
Message-ID: <000001c36b11$51bbe3f0$0a6d2f44@tallboy>

Never mind :-) It is absurdly simple. 
I think I am going to really like Python.

Bruce Williams
If you ignore the facts, you'll never worry about being wrong

> -----Original Message-----
> From: tutor-bounces@python.org 
> [mailto:tutor-bounces@python.org] On Behalf Of Bruce Williams
> Sent: Monday, August 25, 2003 6:01 AM
> To: tutor@python.org
> Subject: [Tutor] How do you execute a stored function?
> 
> 
> I new to Python and am looking for something like the Lisp 
> "eval" function. I have had no trouble storing functions in a 
> dictionary, but haven't stumbled upon a way to use them. 
> 
> Regards,
> Bruce Williams
>  
> "So, we caught one of our interns out back with our mission 
> critical C++ code, a couple of scripting languages, and SWIG. 
> He had the project half done.
> We killed him--had no other choice." -- Anonymous 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tut> or
> 


From kalle at lysator.liu.se  Mon Aug 25 14:21:01 2003
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Mon Aug 25 07:21:47 2003
Subject: [Tutor] How do you execute a stored function?
In-Reply-To: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
References: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
Message-ID: <20030825112101.GE28726@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Bruce Williams]
> I new to Python and am looking for something like the Lisp "eval" function.
> I have had no trouble storing functions in a dictionary, but haven't
> stumbled upon a way to use them. 

Just use the "()" operator or apply():

def f():
    print "f"

def g(arg):
    print "g", arg

funs = {"f": f,
	"g": g}

funs["f"]()
funs["g"]("Hello, function world!")
apply(funs["g"], ["Another way."])

Or have I misunderstood what you were asking for?  There is an "eval"
function and an "exec" statement in Python, but they are used with
strings, not functions.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE/SfEWdNeA1787sd0RAnJOAKCWSUFqvbMEiIyAzfczCpYQR46CEgCeI/CX
mXs3vGTBrdVZ9EfiNOk3deE=
=d8vc
-----END PGP SIGNATURE-----

From vicki at thepenguin.org  Mon Aug 25 09:41:22 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Mon Aug 25 09:41:40 2003
Subject: [Tutor] parsing woes
In-Reply-To: <BB6ECF74.C6EB%clay@shirky.com>
References: <41631.127.0.0.1.1061731712.squirrel@www.thepenguin.org> 
	<BB6ECF74.C6EB%clay@shirky.com>
Message-ID: <23900.206.53.226.4.1061818882.squirrel@www.thepenguin.org>

>> I'll have to look into the len function. I was under the assumption that
>> not knowing what the length of the parameter would prohibit its use. The
>> parameters could be a single letter or number of multiple letter/number
>> combination. I only know that they will be space-delimited.
>
> Note that the param_count = len(params) format that many of us suggested
> does not tell you the length in chars of *each* parameter, it tells you
> the
> length of the parameter *list*, which is to say how many elements are in
> that list.
>
> -clay
>
>

Okay, I will look at this when I get time since it does sound like a
better way. Currently it works as is and I am onto the next hurdle.

Thanks,
--vicki

From abli at freemail.hu  Mon Aug 25 16:55:30 2003
From: abli at freemail.hu (Abel Daniel)
Date: Mon Aug 25 09:56:44 2003
Subject: [Tutor] Re: Help in geting external program output
In-Reply-To: <D5987FFC5C2504499274E608BA47C51B8A0F19@exch-1.corp.intertrust.com>
	(Wael Salloum's message of "Wed, 20 Aug 2003 17:25:36 -0700")
References: <D5987FFC5C2504499274E608BA47C51B8A0F19@exch-1.corp.intertrust.com>
Message-ID: <877k51j0z1.fsf@hooloovoo.i-did-not-set--mail-host-address--so-tickle-me>

"Wael Salloum" wrote:

> So I am just learning python- and I have a program in java
> and it writes into a file, and I want it to return the filename to me
> (in python.)
> So I have a script and I use fileName = os.popen(`java
> theApplication').read()
> However, its always returning blank!
> Now when I do os.popen(`dir').read() it works just fine...
>
> So my question is, what does Python deem is the output of
> a file, and how can I get my java code to `output' a filename..
With os.popen you get a pipe connected to the program you launched.
This means that you can write to it's stdin and read from it's stdout.
(and maybe stderr, I'm not that familiar with os.popen.)

Essentially, you can do the same thing a user could when launching the
program from console, i.e. a dos shell. If you execute
'java theApplication' from a dos shell, and the filename isn't written
back, then you won't be able to read it with os.popen, either.

The most likely problem is that your java program isn't writing to
stdout.

I don't know much about java, but a quick googling showed this as an
example for writing to stdout:
-----
// http://www.bagley.org/~doug/shootout/

public class hello {
    public static void main(String args[]) {
    System.out.print("hello world\n");
    }
}
-----

-- 
Abel Daniel

ps. sending html mail to a mailing list is a really bad idea.

From vicki at thepenguin.org  Mon Aug 25 11:00:12 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Mon Aug 25 11:00:19 2003
Subject: [Tutor] sprintf-like functionality in Python
Message-ID: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>

I am looking for something like sprintf functionality in Python. I have
seen several things on google groups that seem to indicate that sprintf
itself exists in Python but I haven't really found an explanation of it.
What I am trying to do is take data with comes into my program as hex and
convert it to ASCII. For instance, I get:

0x30
0x35

This represents the length of 5 (05), and I need to convert it to the
integer 5. The problem is that the first digit might be significant as in
(0x32 0x35) which translates to 25. I am not sure how to put the two
together in Python. In C, I'd use sprintf. In short, I start with 0x32
0x35 and need to translate it to the integer 25. Thanks.

--vicki

From alex at gabuzomeu.net  Mon Aug 25 19:48:25 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Mon Aug 25 12:43:56 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
Message-ID: <3F4A3DD9.7070104@gabuzomeu.net>

Hi Vicki


Vicki Stanfield wrote:
> I am looking for something like sprintf functionality in Python. I have
> seen several things on google groups that seem to indicate that sprintf
> itself exists in Python but I haven't really found an explanation of it.
> What I am trying to do is take data with comes into my program as hex and
> convert it to ASCII. For instance, I get:
> 
> 0x30
> 0x35
> 
> This represents the length of 5 (05), and I need to convert it to the
> integer 5. The problem is that the first digit might be significant as in
> (0x32 0x35) which translates to 25. I am not sure how to put the two
> together in Python. In C, I'd use sprintf. In short, I start with 0x32
> 0x35 and need to translate it to the integer 25. 

If only the last digit is significant, you might try this:

 >>> ("%x" % 0x35)[-1]
'5'
 >>> ("%x" % 0x32)[-1]
'2'
 >>> l = [0x32, 0x35]
 >>> int("".join([("%x" % x)[-1] for x in l]))
25

It's probably not the most elegant solution, but it seems to work.


Cheers.

Alexandre




From tpc at csua.berkeley.edu  Mon Aug 25 10:50:48 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Aug 25 12:50:56 2003
Subject: [Tutor] Regex
In-Reply-To: <bib0iu$mqp$1@sea.gmane.org>
Message-ID: <20030825094753.D32342-100000@localhost.name>


hi Andrei, my first thought is to use the negative lookahead, which
consists of a pattern you are searching for, followed by a (?!) group
which, if matched, will result in the regexp not matching.  Example:

<paste>
>>> testsearch = re.compile('tetsuro(?!hello)', re.IGNORECASE)
>>> testsearch.search('tetsurohello')
>>> testsearch.search('TETSUROhello')
>>> testsearch.search('hitetsuroone')
<_sre.SRE_Match object at 0x860e4a0>
</paste>

So you are searching for the string 'tetsuro' and you want a match unless
your string is followed by another string 'hello.'  Simple enough, and
from reading amk's site on re it will only get simpler.  If the negative
lookahead condition is matched, then the re will not match.

What's confusing about negative lookaheads is that in practice, what I've
seen does not seem to hold true.  For example, from Danny Yoo's 'A
Quick Introduction to Python', a regular expression that can recognize
most http urls the regex matches but removes the extraneous material:

<paste>
>>> myre = re.compile(r'http://[\w\.-]+\.?(?![\w.-/])', re.IGNORECASE)
>>> myre.search('http://python.org')
<_sre.SRE_Match object at 0x83db1e0>
>>> myre.search('<a href="http://python.org">Python</a>')
<_sre.SRE_Match object at 0x83deb70>
>>> myre.search('<a href="http://python.org">Python</a>').group(0)
'http://python.org'
</paste>

The 'r' in front of the quotes is called a "raw string" and turns off the
special meaning of the backslash.  Now I hope you are as interested and as
confused as I am.


On Sun, 24 Aug 2003, Andrei wrote:

> I'm quite sure I've seen a question of this type before, but I seem
> unable to find it. How can I match a re pattern ONLY if it is not
> preceded by another re pattern? I know how to construct both individual
> regexes, but I don't know how to glue them together in order to achieve
> this.
>
> Think for example of finding all URLs in a piece of text, but *not* if
> they are inside link tags and therefore preceded by 'href="'.
> <a href="http://python.org">Python</a> shouldn't give a match, but
> http://python.org on its own should.
>
> Andrei
>
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
> ernq gur yvfg, fb gurer'f ab arrq gb PP.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From jmillr at umich.edu  Mon Aug 25 13:52:27 2003
From: jmillr at umich.edu (John Miller)
Date: Mon Aug 25 12:52:31 2003
Subject: [Tutor] Re: GUI Builder
In-Reply-To: <E19rJ4j-0006Gg-00@mail.python.org>
Message-ID: <8236941B-D71C-11D7-A4C2-00039303967A@umich.edu>

I just saw this announcement which may prove helpful (but I've not used 
it at all):

Pmw 1.2, Python megawidgets for Tkinter.
         <http://pmw.sourceforge.net/>

"""
Pmw is a toolkit for building high-level compound widgets in Python 
using the Tkinter module.

It consists of a set of base classes and a library of flexible and 
extensible megawidgets built on this foundation.  These megawidgets 
include notebooks, comboboxes, selection widgets, paned widgets, 
scrolled widgets and dialog windows.
"""

John Miller

>>> Are there any GUI (Tk) Builder for python(I only found some one for
>>> Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?
>>>

> the problem with wx, qt, gtk ... is that our customers are not very 
> glad
> to install new libraries on their workstations. Tk would be the best
> solution. It seems that there is no reasonable solution :-(
>
> Regards
>
> matthias


From idiot1 at netzero.net  Mon Aug 25 13:57:35 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 12:58:14 2003
Subject: [Tutor] wikinehesa
Message-ID: <3F4A3FFF.3020101@netzero.net>

Wikinehesa is now apparently working correctly. All I must do is finish the 
upload script, and I can add that to the suite, bundle it into a tarball, and 
squirt it out across the world wide wait and see what happens.

Equipped with the usual baseline wikiways, it also will do images, 
colorheaderbars, color coordinated page headers and footers, and something I 
never saw a wiki do- centering. It offers the usual backsearch, titlelist, and 
phrase search functions through buttons or links in the footer, as well as a 
permenant link back to the FrontPage (think index.html for example). Although a 
little polishing is reasonable, I beleive it is now firmly ensconced into beta 
testing stage.

Anyone intrested, here it is:
	http://www.tinylist.org/cfi-bin/wikinehesa.py




-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From dyoo at hkn.eecs.berkeley.edu  Mon Aug 25 11:05:50 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 25 13:06:26 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
Message-ID: <Pine.LNX.4.44.0308251001490.26436-100000@hkn.eecs.berkeley.edu>



On Mon, 25 Aug 2003, Vicki Stanfield wrote:

> I am looking for something like sprintf functionality in Python. I have
> seen several things on google groups that seem to indicate that sprintf
> itself exists in Python

Hi Vicki,

Yes, we can find sprintf-like behavior with the "String Formatting"
operation:

###
>>> template = "hello %s, this is a %s"
>>> template % ('world', 'test')
'hello world, this is a test'
###

We can find out more about String Formatting here:

    http://www.python.org/doc/lib/typesseq-strings.html
    http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000


> What I am trying to do is take data with comes into my program as hex
> and convert it to ASCII. For instance, I get:
>
> 0x30
> 0x35
>
> This represents the length of 5 (05), and I need to convert it to the
> integer 5. The problem is that the first digit might be significant as
> in (0x32 0x35) which translates to 25.


Is this what you're looking for?


###
>>> chr(int('0x32', 16))
'2'
>>> chr(int('0x35', 16))
'5'
###

Good luck to you!


From alan.gauld at blueyonder.co.uk  Mon Aug 25 19:39:21 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 25 13:39:05 2003
Subject: [Tutor] GUI Builder
References: <3F421EDD.2060607@serrati.net><1061589210.27635.2.camel@server.kniep>
	<3F49DB4F.8060505@serrati.net>
Message-ID: <003801c36b2f$d1408f90$6401a8c0@xp>

> >>Are there any GUI (Tk) Builder for python(I only found some one
for
> >>Tcl/Tk)? Or is someone using generic Tcl-Tools (e.g. SpecTcl)?
> >
> >Take a look at wxPython with Boa Constructor as IDE I have used it
in a
> >fairly large system and it is perfect!
>
> the problem with wx, qt, gtk ... is that our customers are not very
glad
> to install new libraries on their workstations. Tk would be the best
> solution. It seems that there is no reasonable solution :-(

How about Jython and the Java GUI libraries? I assume they have
already
installed those along with the Microsoft MFC and VB libraries? Or if
they are using MacOS X then they'll have Cocoa, Carbon and Java
installed
already.

Or on *nix they'll have the X libraries, maybe Motif, probably GTk and
Tk and Qt already...

Since most platforms already have JVM installed then any bizarre
desire to minimise libraries (which after all are intended to minimise
code bloat and increase reuse, amongst other things!) will be
mitigated.

Alan g.


From dyoo at hkn.eecs.berkeley.edu  Mon Aug 25 11:40:08 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 25 13:40:12 2003
Subject: [Tutor] Unicode (utf-16-le) (fwd)
Message-ID: <Pine.LNX.4.44.0308251017430.26436-100000@hkn.eecs.berkeley.edu>

Hi Derek,


Let me redirect your question to Python-Tutor.  This will help keep
everyone in the loop, and it also lets someone else answer your question
if I'm too lazy to answer.  *grin*


If our file is in 'utf-16-le' format, we may want to use the StreamReaders
in:

    http://www.python.org/doc/lib/module-codecs.html

This 'codecs' module implements its own version of open() that knows about
the standard encodings, so hopefully:

###
import codecs
f = codecs.open('my-utf-16-le-encoded-file.utf16le',
                'r',
                'utf16-le')
###

should be enough to decode utf16-le files on the fly.




---------- Forwarded message ----------
Date: Mon, 25 Aug 2003 16:26:44 +1000
From: Derek at leder <derek@leder.com.au>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Unicode (utf-16-le)

Thanks Danny,

At 25/08/2003 09:05 AM, you wrote:
>On Sat, 23 Aug 2003, Derek at leder wrote:
>
>> Does anyone know of a module for converting utf-16-le to ascii?
>> before I write one.
>
>Hi Derek,
>
>Strings support other character sets through the 'encode()' and 'decode()'
>methods.  For example:
>
>###
>>>> s = 'hello world'
>>>> utf_txt = s.encode('utf-16')
>>>> utf_txt
>'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'

This is almost there, if you notice there are hex characters mixed up with ascii
ie \xff and \xfe are hex characters but the 'h' in \xfeh is ascii.

>>>> utf_txt.decode('utf-16')
>u'hello world'

While this works in immediate mode, it does not work when run from a file.??

any other clues :-)

>###
>
>Here's a partial list of the character encodings that Python supports:
>
>    http://www.python.org/doc/lib/node126.html
>
>According to that list, 'utf-16-le' is a codec that it can handle, so you
>should be in good shape.  *grin*
>
>
>Good luck to you!


From alan.gauld at blueyonder.co.uk  Mon Aug 25 19:46:02 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 25 13:45:47 2003
Subject: [Tutor] How do you execute a stored function?
References: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
Message-ID: <003d01c36b30$c0392a80$6401a8c0@xp>


> I new to Python and am looking for something like the Lisp "eval"
function.
> I have had no trouble storing functions in a dictionary, but haven't
> stumbled upon a way to use them.

There are a couple of ways to store a function in a dictionary:

1) Store the source code as a string

2) Store a reference to the function object.

To execute the first one you need to use Python's eval() function
just like you would in Lisp. Like so:

func = "x*x"

myDict = {'f':func}

for x in [1,2,3]:
   eval(myDict['f'])


To execute the second you just call it, like so:

def f(x):
   return x*x

myDict = {'f':f}

for n in [1,2,3]:
   myDict['f'](n)  # call the stored function here


Most folks prefer the second option as it's more powerful and
easier as well as being more secure and performant.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Mon Aug 25 19:56:25 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Aug 25 13:56:07 2003
Subject: [Tutor] sprintf-like functionality in Python
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
Message-ID: <004c01c36b32$33d99460$6401a8c0@xp>

> What I am trying to do is take data with comes into my program as
hex and
> convert it to ASCII. For instance, I get:
>
> 0x30
> 0x35
>
> together in Python. In C, I'd use sprintf. In short, I start with
0x32
> 0x35 and need to translate it to the integer 25. Thanks.

Can you show how you'd use sprintf in C?
Because I'm afraid the explanation confused me!

FWIW
the equivalent of sprintf in Python is the string format operator %:

mystring = "%s %d\t%3.2f %-8s" % ("Values:",42,56.89732,"tot")

or to make it clearer(?) whats happening:

fmtString = "%s %d\t%3.2f %-8s"      # %N markers the same as in C
vals = ("Values:",42,56.89732,"tot") # tuple, one value per marker
myString = fmtString % vals          # combine them with % operator

Python also provides some extra goodies in that you can use
keywords to identify the substitution values and pluck them
from a dictionary etc.

If that doesn't help send the equivalent C sprintf code and
we'll try to translate.


Alan G.


From project5 at redrival.net  Mon Aug 25 21:01:58 2003
From: project5 at redrival.net (Andrei)
Date: Mon Aug 25 14:03:51 2003
Subject: [Tutor] Re: Regex
In-Reply-To: <Pine.LNX.4.44.0308242046290.23261-100000@hkn.eecs.berkeley.edu>
References: <bib0iu$mqp$1@sea.gmane.org>
	<Pine.LNX.4.44.0308242046290.23261-100000@hkn.eecs.berkeley.edu>
Message-ID: <bidj1v$d98$1@sea.gmane.org>

Thanks, it *almost* helps, but I'm not trying to harvest the links. The 
issue is that I do *not* want to get URLs if they're in between <a> 
tags, nor if they're an attribute to some tag (img, a, link, whatever).

Perhaps I should have explained my goal more clearly: I wish to take a 
piece of text which may or may not contain HTML tags and turn any piece 
of text which is NOT a link, but is an URL into a link. E.g.:

   go to <a href="http://home.com">http://home.com</a>. [1]
   go <a href="http://home.com">home</a>. [2]

should remain unmodified, but

   go to http://home.com [3]

should be turned into [1]. That negative lookbehind can do the job in 
the large majority of the cases (by not matching URLs if they're 
preceded by single or double quotes or by ">"), but not always since it 
doesn't allow the lookbehind to be non-fixed length. I think one of the 
parser modules might be able to help (?) but regardless of how much I 
try, I can't get the hang of them, while I do somewhat understand regexes.

Andrei



From vicki at thepenguin.org  Mon Aug 25 14:35:57 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Mon Aug 25 14:36:04 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
Message-ID: <19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>

> This represents the length of 5 (05), and I need to convert it to the
> integer 5. The problem is that the first digit might be significant as in
> (0x32 0x35) which translates to 25. I am not sure how to put the two
> together in Python. In C, I'd use sprintf. In short, I start with 0x32
> 0x35 and need to translate it to the integer 25. Thanks.
>
> --vicki

Okay I got it to work (not so elegently) using this:

            output=port.read()
            length = chr(ord(output))
            output=port.read()
            newlength=length+chr(ord(output))
            num=int(newlength)
            print num

Anyway, it works...unless output is a letter which it can be since it is
hex. I get an error:

ValueError: invalid literal for int(): A

In that case, what I want is the base10 representation of the hexadecimal
letter. I thought that I could use

chr(ord(output), 16)

but that yields an error:

TypeError: chr() takes exactly 1 argument (2 given)

I am so close, but I can't quite get this figured out. Anyone?

--vicki



From jeff at ccvcorp.com  Mon Aug 25 12:31:14 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 25 14:38:48 2003
Subject: [Tutor] One for Kirk...
References: <BB6AAA6C.C41E%clay@shirky.com> <3F47B8D0.9000804@netzero.net>
Message-ID: <3F4A55F2.5040709@ccvcorp.com>

Kirk Bailey wrote:
> I saved the sourcecode, and placed it on my server.
>     http://www.tinylist.prg/cgi-bin/wypy.py
> 
> It generates a error:
> -----------------------------------------------------------------------
>   File "/www/www.tinylist.org/cgi-bin/wypy.py", line 23
>     main(dict([(i.name, i.value) for i in cgi.FieldStorage().list]))
>                                    ^
> SyntaxError: invalid syntax
> [Sat Aug 23 14:45:21 2003] [error] [client 67.31.207.132] Premature end 
> of script headers: /www/www.tinylist.org/cgi-bin/wypy.py
> -----------------------------------------------------------------------
> intresting. wonder why it does this?

Weren't you using Python 1.5.2 on your server still?  That's a list 
comprehension, and they were added to Python in 2.0 ...

Jeff Shannon
Technician/Programmer
Credit International




From nas-pytut at python.ca  Mon Aug 25 12:55:05 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Mon Aug 25 14:55:19 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
	<19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>
Message-ID: <20030825185505.GA26370@glacier.arctrix.com>

Vicki Stanfield wrote:
> Okay I got it to work (not so elegently) using this:
> 
>             output=port.read()
>             length = chr(ord(output))
>             output=port.read()
>             newlength=length+chr(ord(output))
>             num=int(newlength)
>             print num

chr(ord(x)) does is an identity function (i.e. is does nothing).  I
don't completely understand what you want but how about:

    length = port.read(2)
    num = int(length, 16)

Does that do what you want?

  Neil

From jeff at ccvcorp.com  Mon Aug 25 13:03:04 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 25 15:05:17 2003
Subject: [Tutor] more py revisited
References: <001001c36a6e$16969520$2a34c6d1@whiterhino2>
Message-ID: <3F4A5D68.2050608@ccvcorp.com>

SGD wrote:

> I would like to install multiple instances of python on windows XP,
> specifically 2.2.3 and 2.3.    
> Is this possible? 

Yes, it is.  They'll be installed (by default) in C:\Python22 and 
C:\Python23 respectively.  There's a few things to be aware of, though...

First off, compiled extensions (pyd files) are only usable with the 
Python version that they were compiled for, and each version has its 
own site-packages directory.  So (as you apparently already know) each 
version needs to have packages installed for it independently.

Of course, Windows can only associate the .py and .pyw extensions with 
a single executable, so the normal file association will follow 
whatever version of Python was installed last.

> Say I'm using an IDE connected to 2.3, how would I run
> a 2.2.3 script from that same IDE (any IDE really, I use so many, so
> hard to decide which I like best)? Or better yet, specifying which run
> time version I would like to run a script from explorer? Is it legal to
> rename one of the exe's to say, python.exe->py22.exe and
> pythonw.exe->pyw22.exe, to use windows "right click" "open with", or
> something similar?

You won't be able to get them both to work well from a Python IDE 
(IDLE or PythonWin), because those are Python packages that are 
limited to a single version.  However, if you're using a completely 
separate IDE, you should be able to identify the executables as 
c:\python22\python.exe and c:\python23\python.exe respectively. 
Changing the name of the executables would probably work. 
(Effectively the same thing does work on *nix, using symlinks; I see 
no reason why it wouldn't on Windows.)  You could also set up 
batchfiles (py22.bat and py23.bat) that would pass the script name 
(and any commandline options) along to the correct executable. 
Depending on how demanding Python is about modules' file extensions, 
it may be possible to rename some files .py2 and associate that 
extension with a different executable than .py (I haven't tried this 
and I'm not sure whether this will interfere with import mechanisms).

The only real problems you're facing here are ones of Windows 
configuration -- you have a single file extension that you want to 
alternately associate with two different executables.  Looking at it 
from this perspective, it may be possible to write a script that 
changes that association back and forth.  Run the script and all .py 
files run in Py22, run it again and all .py files run in Py23.  It 
really depends on how extensively you want to get into your Windows 
configuration.

Jeff Shannon
Technician/Programmer
Credit International


From vicki at thepenguin.org  Mon Aug 25 15:05:09 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Mon Aug 25 15:05:42 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <20030825185505.GA26370@glacier.arctrix.com>
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org> 
	<19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org> 
	<20030825185505.GA26370@glacier.arctrix.com>
Message-ID: <36399.206.53.226.4.1061838309.squirrel@www.thepenguin.org>

> Vicki Stanfield wrote:
>> Okay I got it to work (not so elegently) using this:
>>
>>             output=port.read()
>>             length = chr(ord(output))
>>             output=port.read()
>>             newlength=length+chr(ord(output))
>>             num=int(newlength)
>>             print num
>
> chr(ord(x)) does is an identity function (i.e. is does nothing).  I
> don't completely understand what you want but how about:
>
>     length = port.read(2)
>     num = int(length, 16)
>
> Does that do what you want?
>
>   Neil
>
Yes, that is exactly what I needed. The problem I was running into was
that I was trying to pull it in one at a time and then put the two digits
together and translate them into a single number. Your solution is far
more useful! This is an example of me making things more complicated than
necessary. Thanks.

--vicki





From pythontutor at venix.com  Mon Aug 25 16:18:25 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Aug 25 15:19:11 2003
Subject: [Tutor] How do you execute a stored function?
In-Reply-To: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
References: <000b01c36b08$ea1ff860$0a6d2f44@tallboy>
Message-ID: <3F4A6101.6050803@venix.com>

http://www.norvig.com/python-lisp.html
Python for Lisp Programmers

This might be a useful guide you.

Bruce Williams wrote:

> I new to Python and am looking for something like the Lisp "eval" function.
> I have had no trouble storing functions in a dictionary, but haven't
> stumbled upon a way to use them. 
> 
> Regards,
> Bruce Williams
>  
> "So, we caught one of our interns out back with our mission critical C++
> code, a couple of scripting languages, and SWIG. 
> He had the project half done.
> We killed him--had no other choice." -- Anonymous 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From rick at niof.net  Mon Aug 25 16:01:23 2003
From: rick at niof.net (Rick Pasotto)
Date: Mon Aug 25 15:23:47 2003
Subject: [Tutor] sprintf-like functionality in Python
In-Reply-To: <19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
	<19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>
Message-ID: <20030825190123.GR6254@niof.net>

On Mon, Aug 25, 2003 at 01:35:57PM -0500, Vicki Stanfield wrote:
> > This represents the length of 5 (05), and I need to convert it to the
> > integer 5. The problem is that the first digit might be significant as in
> > (0x32 0x35) which translates to 25. I am not sure how to put the two
> > together in Python. In C, I'd use sprintf. In short, I start with 0x32
> > 0x35 and need to translate it to the integer 25. Thanks.
> >
> > --vicki
> 
> Okay I got it to work (not so elegently) using this:
> 
>             output=port.read()
>             length = chr(ord(output))
>             output=port.read()
>             newlength=length+chr(ord(output))
>             num=int(newlength)
>             print num
> 
> Anyway, it works...unless output is a letter which it can be since it is
> hex. I get an error:
> 
> ValueError: invalid literal for int(): A
> 
> In that case, what I want is the base10 representation of the hexadecimal
> letter. I thought that I could use
> 
> chr(ord(output), 16)
> 
> but that yields an error:
> 
> TypeError: chr() takes exactly 1 argument (2 given)
> 
> I am so close, but I can't quite get this figured out. Anyone?
> 
> --vicki

I think you're doing too much.

	c1 = 0x32
	c2 = 0x35

So now c1 and c2 are the results of your port.read(), right?

	c = chr(c1) + chr(c2)

This gives: c => '35'

Now all you need is int(c).

Drop the 'ord()' and what you have should work.

-- 
"Every election is a sort of advance auction of stolen goods."
   --- H. L. Mencken
    Rick Pasotto    rick@niof.net    http://www.niof.net

From idiot1 at netzero.net  Mon Aug 25 16:35:14 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 15:49:52 2003
Subject: [Tutor] One for Kirk...
In-Reply-To: <3F4A55F2.5040709@ccvcorp.com>
References: <BB6AAA6C.C41E%clay@shirky.com> <3F47B8D0.9000804@netzero.net>
	<3F4A55F2.5040709@ccvcorp.com>
Message-ID: <3F4A64F2.9070407@netzero.net>

Ah. yes, I am still using 1.6.2, and when my hosting provider can find the time, 
Critter is due for an upgrade. When that is effected, I will step up to 2.foo.

And the wiki appears ready for the hammering of all.
http://www.tinylist.org/cgi-win/wikinehesa.py


Jeff Shannon wrote:

> Kirk Bailey wrote:
> 
>> I saved the sourcecode, and placed it on my server.
>>     http://www.tinylist.prg/cgi-bin/wypy.py
>>
>> It generates a error:
>> -----------------------------------------------------------------------
>>   File "/www/www.tinylist.org/cgi-bin/wypy.py", line 23
>>     main(dict([(i.name, i.value) for i in cgi.FieldStorage().list]))
>>                                    ^
>> SyntaxError: invalid syntax
>> [Sat Aug 23 14:45:21 2003] [error] [client 67.31.207.132] Premature 
>> end of script headers: /www/www.tinylist.org/cgi-bin/wypy.py
>> -----------------------------------------------------------------------
>> intresting. wonder why it does this?
> 
> 
> Weren't you using Python 1.5.2 on your server still?  That's a list 
> comprehension, and they were added to Python in 2.0 ...
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> 
> 
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From jeff at ccvcorp.com  Mon Aug 25 13:46:19 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 25 15:52:27 2003
Subject: [Tutor] sprintf-like functionality in Python
References: <27867.206.53.226.4.1061823612.squirrel@www.thepenguin.org>
	<19092.206.53.226.4.1061836557.squirrel@www.thepenguin.org>
Message-ID: <3F4A678B.20504@ccvcorp.com>

Vicki Stanfield wrote:
>>This represents the length of 5 (05), and I need to convert it to the
>>integer 5. The problem is that the first digit might be significant as in
>>(0x32 0x35) which translates to 25. I am not sure how to put the two
>>together in Python. In C, I'd use sprintf. In short, I start with 0x32
>>0x35 and need to translate it to the integer 25. Thanks.
>>
>>--vicki
> 
> 
> Okay I got it to work (not so elegently) using this:
> 
>             output=port.read()
>             length = chr(ord(output))
>             output=port.read()
>             newlength=length+chr(ord(output))
>             num=int(newlength)
>             print num
> 

I think that you're working too hard on this, perhaps as a result of 
being accustomed to working in C.  I suspect that what you're getting 
from port.read() is simply a string, and that if you just print the 
string, you'll get what you want.

Note that, if you're wanting a string representation of what you 
receive, there's really no need to convert it with int().

In fact, you're doing a lot of converting in this snippet that makes 
no difference at all.  'chr(ord(x))' returns x, as chr() and ord() are 
inverse functions, while 'print int(x)' is implicitly 'print 
str(int(x))', and str() and int() are inverse functions (presuming 
appropriate values of x) so this is equivalent to 'print x'.  In other 
words, what you're printing is exactly what you're reading from the 
port, despite a lot of handwaving that makes it *look* like you've 
transformed it several times.

Now, if you eliminate the redundancies, you'll have something like this:

output = port.read()
newlength = output + port.read()
print newlength

If, at this point, what's printed is a two-digit hex code (say, '32'), 
then we can convert that into an ASCII character like so:

print chr(int(newlength, 16))

but you should probably look carefully at what newlength is before you 
assume that you'll need to make this conversion.  What in C is a 
series of bytes (normally represented using hex), in Python is just an 
ordinary string, and that's exactly what you're getting from read(). 
I suspect (though I can't be sure) that Python is already doing all of 
the conversion that you need done, automatically.

Jeff Shannon
Technician/Programmer
Credit International


From idiot1 at netzero.net  Mon Aug 25 16:46:19 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 15:53:20 2003
Subject: [Tutor] upgrade
Message-ID: <3F4A678B.8050605@netzero.net>

when I *DO* finally upgrade Critter, should I go to 2.1,2.2, or the new and 
improved 2.3? Is the latest edition declared STABLE?

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From aicolburn at yahoo.com  Mon Aug 25 13:52:41 2003
From: aicolburn at yahoo.com (Alan Colburn)
Date: Mon Aug 25 15:54:38 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
Message-ID: <20030825195241.2712.qmail@web41608.mail.yahoo.com>

I'd like to start learning about how to write
web-based Python scripts. My campus server, however,
will not support Python--just Perl and CGI. So, I'm
assuming my best option is to run a small server from
my (WindowsXP) desktop. The rest of my web site will
remain where it is, and I'll simply link to the
scripts running of my desktop; only the script based
pages will run off the desktop. I only anticipate
needing the scripts during select parts of the
academic year. The rest of the time the desktop-based
server does not need to be on.

So, here are my questions. First, does this seem
logical? If it does, can anyone offer a suggestion for
a free, secure, simple, easy to set up server?
[Actually, while I'm at it, how does one check to see
whether their web-based scripts work without actually
being connected to the web? HTML pages can easily be
read on a desktop; do cgi-Python pages work the same
way?]

Thanks, as always, for your help! -- Al C.

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From jeff at ccvcorp.com  Mon Aug 25 14:04:45 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Aug 25 16:03:18 2003
Subject: [Tutor] upgrade
References: <3F4A678B.8050605@netzero.net>
Message-ID: <3F4A6BDD.3040708@ccvcorp.com>

Kirk Bailey wrote:
> when I *DO* finally upgrade Critter, should I go to 2.1,2.2, or the new 
> and improved 2.3? Is the latest edition declared STABLE?

The answer to this, of course, is "it depends".  Do you require 
particular third-party extensions, and if so, are they available for 
2.3?  Is there any critical applications that you're running that 
break under some of the backwards-incompatibilities introduced in 2.3? 
(This isn't likely, but it is possible.)  Presuming that neither of 
these issues are a problem, then there's little reason to use any 
"older" versions of Python.  If either of these are a problem, then 
you'll want to install (the latest bugfixed release of) 2.2 -- IIRC, 
PythonLabs has declared that they will keep supporting 2.2 for quite 
some time, whereas they've dropped direct support of 2.0 and 2.1, and 
almost every third-party extension packages that you'd be interested 
in will already be available for it.  (Note, however, that there's 
some backwards-incompatibilities introduced between 1.6 and 2.2, so 
you'll want to test everything right away regardless of whether you 
choose 2.2 or 2.3 ...)

2.2 is the more conservative choice, but 2.3 should be stable and 
ready for production use as well.

Jeff Shannon
Technician/Programmer
Credit International


From tpc at csua.berkeley.edu  Mon Aug 25 14:14:23 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Aug 25 16:14:41 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
In-Reply-To: <20030825195241.2712.qmail@web41608.mail.yahoo.com>
Message-ID: <20030825125914.L33672-100000@localhost.name>


I have been using mod_python with Apache.  It's simple enough, you add an
Apache directive in your httpd.conf and you can call .py files to print
'Hello World' to your local machine's browser or use a python
script to process user input.

http://www.modpython.org/

On Mon, 25 Aug 2003, Alan Colburn wrote:

> I'd like to start learning about how to write
> web-based Python scripts. My campus server, however,
> will not support Python--just Perl and CGI. So, I'm
> assuming my best option is to run a small server from
> my (WindowsXP) desktop. The rest of my web site will
> remain where it is, and I'll simply link to the
> scripts running of my desktop; only the script based
> pages will run off the desktop. I only anticipate
> needing the scripts during select parts of the
> academic year. The rest of the time the desktop-based
> server does not need to be on.
>
> So, here are my questions. First, does this seem
> logical? If it does, can anyone offer a suggestion for
> a free, secure, simple, easy to set up server?
> [Actually, while I'm at it, how does one check to see
> whether their web-based scripts work without actually
> being connected to the web? HTML pages can easily be
> read on a desktop; do cgi-Python pages work the same
> way?]
>
> Thanks, as always, for your help! -- Al C.
>
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free, easy-to-use web site design software
> http://sitebuilder.yahoo.com
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From dyoo at hkn.eecs.berkeley.edu  Mon Aug 25 15:11:02 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 25 17:11:20 2003
Subject: [Tutor] Re: Regex  [example:HTMLParser, unittest, StringIO]
In-Reply-To: <bidj1v$d98$1@sea.gmane.org>
Message-ID: <Pine.LNX.4.44.0308251338190.6483-100000@hkn.eecs.berkeley.edu>



On Mon, 25 Aug 2003, Andrei wrote:

> Perhaps I should have explained my goal more clearly: I wish to take a
> piece of text which may or may not contain HTML tags and turn any piece
> of text which is NOT a link, but is an URL into a link. E.g.:
>
>    go to <a href="http://home.com">http://home.com</a>. [1]
>    go <a href="http://home.com">home</a>. [2]
>
> should remain unmodified, but
>
>    go to http://home.com [3]
>
> should be turned into [1]. That negative lookbehind can do the job in
> the large majority of the cases (by not matching URLs if they're
> preceded by single or double quotes or by ">"), but not always since it
> doesn't allow the lookbehind to be non-fixed length. I think one of the
> parser modules might be able to help (?) but regardless of how much I
> try, I can't get the hang of them, while I do somewhat understand
> regexes.


Hi Andrei,


Hmm... The example in:

    http://mail.python.org/pipermail/tutor/2003-August/024902.html

should be really close to what you're looking for.


Here's another example that shows how to use the handle_starttag() and
handle_endtag() methods.  The example also shows how we can use "unit
tests" to make sure our class is doing the right thing.


###
class Parser(HTMLParser.HTMLParser):
    """A small example for HTMLParser that pays attention to anchored
       text."""
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.in_anchor = False

    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.in_anchor = True

    def handle_endtag(self, tag):
        if tag == 'a':
            self.in_anchor = False

    def handle_data(self, data):
        if self.in_anchor:
            print "Anchored text:", data



"""Here a small unit test to see if it's actually working."""
import sys
import unittest
from cStringIO import StringIO

class TestParser(unittest.TestCase):
    def setUp(self):
        self.buffer = StringIO()
        sys.stdout = self.buffer

    def testParsing(self):
        text = """<html><body>
                  This is a <a>test</a>
                  What is <a>thy bidding,</a> my master?"""
        parser = Parser()
        parser.feed(text)
        self.assertEqual('Anchored text: test\n'
                         + 'Anchored text: thy bidding,\n',
                         self.buffer.getvalue())

if __name__ == '__main__':
    unittest.main()
###


Warning: the code above is not really that well designed.  *grin*


We can see this already because the testing of the class is awkward: I'm
forced to do some calistenics --- I'm redirecting standard output in order
to reliably test the parser class --- and that's a little ugly.


It would be much better if we redesign the Parser to make it easier to
test.  Perhaps something like:

###
class TestParser(unittest.TestCase):
    def setUp(self):
        self.parser = Parser()

    def testParsing(self):
        text = """<html><body>
                  This is a <a>test</a>
                  What is <a>thy bidding,</a> my master?"""
        parser.feed(text)
        self.assertEqual('Anchored text: test\n'
                         + 'Anchored text: thy bidding,\n',
                         parser.getAnchoredText())
###


Anyway, please feel free to ask more questions about HTMLParser.  Hope
this helps!


From idiot1 at netzero.net  Mon Aug 25 18:13:20 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 17:13:59 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
In-Reply-To: <20030825195241.2712.qmail@web41608.mail.yahoo.com>
References: <20030825195241.2712.qmail@web41608.mail.yahoo.com>
Message-ID: <3F4A7BF0.2010009@netzero.net>

hmmm... ok, for local fun, download and install IDLE.

Care to grab some geeks and install FreeBSD or Linux? Any old box will do. Grab 
a entry level pentium and stick un*x in it, and see if the school will let you 
do your hosting on a box wired into their network. if so, great, you now can 
have your very own sandbox to play in. Now, you can install python and they have 
not a thing to say about it.

BUT IF THEY REFUSE:
The Dirty cads, the rotton rat finks, the bums!

Get independant wire to your room, then screw the !#%@^#&$! Hmmm, that takes cash.

There are pyhon friendly hosting firms, but even a slice off the end of the box 
costs a little. There are FREE hosts, but not a lot anymore, and not many offer 
python- or let you install it. I  have an inquiry out regarding one; if all is 
as hoped, I will post a referral to the service on the list for intrested persons.



Alan Colburn wrote:

> I'd like to start learning about how to write
> web-based Python scripts. My campus server, however,
> will not support Python--just Perl and CGI. So, I'm
> assuming my best option is to run a small server from
> my (WindowsXP) desktop. The rest of my web site will
> remain where it is, and I'll simply link to the
> scripts running of my desktop; only the script based
> pages will run off the desktop. I only anticipate
> needing the scripts during select parts of the
> academic year. The rest of the time the desktop-based
> server does not need to be on.
> 
> So, here are my questions. First, does this seem
> logical? If it does, can anyone offer a suggestion for
> a free, secure, simple, easy to set up server?
> [Actually, while I'm at it, how does one check to see
> whether their web-based scripts work without actually
> being connected to the web? HTML pages can easily be
> read on a desktop; do cgi-Python pages work the same
> way?]
> 
> Thanks, as always, for your help! -- Al C.
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free, easy-to-use web site design software
> http://sitebuilder.yahoo.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From SWidney at ci.las-vegas.nv.us  Mon Aug 25 15:22:46 2003
From: SWidney at ci.las-vegas.nv.us (Scott Widney)
Date: Mon Aug 25 17:25:49 2003
Subject: [Tutor] parsing woes
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC878B@SOVEREIGN>

> I am attempting to parse a string which is in the form:
> 
> 1 F 5
> 
> I need to make parameter[0]= 1, parameter[1] = F, and 
> parameter[2] = 5.
> The difficulty is that there might be no parameters or any 
> number up to 3. They won't always be a single digit or letter
> but they will always be space-delimited.
.
.
.
> I am parsing them this way:
> 
> if arguments:
>     parameters=arguments.split(" ")
> else: parameters = ""
> 
> 
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.

Maybe I'm missing something, but why not use a for loop to iterate through
the parameters (if any)? And

#####
>>> args1 = "1 F 5"
>>> args2 = "2 G"
>>> args3 = "3"
>>> args4 = ""
>>> def parse_and_print(parameters=""):
...     for param in parameters.split(): print param
...     
>>> parse_and_print(args1)
1
F
5
>>> parse_and_print(args2)
2
G
>>> parse_and_print(args3)
3
>>> parse_and_print(args4)
>>> parse_and_print()
>>> parse_and_print("")
>>> parse_and_print("1 F 5 2 G 3")
1
F
5
2
G
3
>>> 
#####

There are safety precautions one could take, but if you're sure the argument
is always going to be a string then this should suffice.


Scott

From dyoo at hkn.eecs.berkeley.edu  Mon Aug 25 15:27:54 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Aug 25 17:33:45 2003
Subject: [Tutor] sprintf-like functionality in Python (fwd)
Message-ID: <Pine.LNX.4.44.0308251424420.6483-100000@hkn.eecs.berkeley.edu>

Hi Vicki,


I'm forwarding this to the Tutor list.  Please be more careful to send
your replies to tutor@python.org next time.

I do not want to become a bottleneck!  Why settle for one brain when you
can use the whole community's?  *grin*



Anyway, for the error you're getting, take a closer look at the original
example.  The original code passes two arguments to the int() function.


Hope this helps!


---------- Forwarded message ----------
Date: Mon, 25 Aug 2003 12:25:14 -0500 (EST)
From: Vicki Stanfield <vicki@thepenguin.org>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] sprintf-like functionality in Python


> We can find out more about String Formatting here:
>
>     http://www.python.org/doc/lib/typesseq-strings.html
>     http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000
>
>
>> What I am trying to do is take data with comes into my program as hex
>> and convert it to ASCII. For instance, I get:
>>
>> 0x30
>> 0x35
>>
>> This represents the length of 5 (05), and I need to convert it to the
>> integer 5. The problem is that the first digit might be significant as
>> in (0x32 0x35) which translates to 25.
>
>
> Is this what you're looking for?
>
>
> ###
>>>> chr(int('0x32', 16))
> '2'
>>>> chr(int('0x35', 16))
> '5'
> ###

Thanks. I am closer, and this helps, but I am now getting an error. I am
trying to do:

print "converted " +chr(int(output),16)

and am getting this:
TypeError: chr() takes exactly 1 argument (2 given)

You give two arguments above. What is MY problem?

--vicki



From project5 at redrival.net  Tue Aug 26 01:14:38 2003
From: project5 at redrival.net (Andrei)
Date: Mon Aug 25 18:16:30 2003
Subject: [Tutor] Re: Regex  [example:HTMLParser, unittest, StringIO]
In-Reply-To: <Pine.LNX.4.44.0308251338190.6483-100000@hkn.eecs.berkeley.edu>
References: <bidj1v$d98$1@sea.gmane.org>
	<Pine.LNX.4.44.0308251338190.6483-100000@hkn.eecs.berkeley.edu>
Message-ID: <bie1rn$s4d$1@sea.gmane.org>

Danny Yoo wrote:
> Hmm... The example in:
> 
>     http://mail.python.org/pipermail/tutor/2003-August/024902.html
> 
> should be really close to what you're looking for.

I didn't (and still don't) see how to extend that to suit my purposes.

> Here's another example that shows how to use the handle_starttag() and
> handle_endtag() methods.  The example also shows how we can use "unit
> tests" to make sure our class is doing the right thing.
> 
> 
> ###
> class Parser(HTMLParser.HTMLParser):
>     """A small example for HTMLParser that pays attention to anchored
>        text."""
>     def __init__(self):
>         HTMLParser.HTMLParser.__init__(self)
>         self.in_anchor = False
> 
>     def handle_starttag(self, tag, attrs):
>         if tag == 'a':
>             self.in_anchor = True
> 
>     def handle_endtag(self, tag):
>         if tag == 'a':
>             self.in_anchor = False
> 
>     def handle_data(self, data):
>         if self.in_anchor:
>             print "Anchored text:", data

<snip>

Excellent example (that in_anchor bit did the trick, only I need to 
check for not in_anchor), now I might be able to solve my problem. 
Thanks, also for reminding me about unit tests. I should write some of 
those myself :).

Andrei


=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From python.tutorial at jarava.org  Tue Aug 26 01:18:38 2003
From: python.tutorial at jarava.org (Javier JJ)
Date: Mon Aug 25 18:18:49 2003
Subject: [Tutor] Python - XML: How to write UNICODE to a file ?? (when using
	LATIN-1 Chars)
Message-ID: <001301c36b56$d64436a0$0100a8c0@uno>

Hi all!!

I'm getting my feet wet with Python + XML processing and I've run into
something that's stopping me:

I have an xml file with ASCII characters (no encoding is specified; it
contains characters valid in the latin-1 charset - it's a log file
generated by MSN Messenger 6.0).

I am processing it with mindom as follows:

doc = minidom.parse(log_file.xml)
rootNode = doc.childNodes[1]

Now, I can do all sorts of manipulation on the nodes w/o any problem

But afterwards I want to write the result back to disk as XML, so I do:

>>> out = open("salida.txt", "wb")
>>> listado = rootNode.toxml()

Now "listado" has a xml-looking unicode string; it looks quite fine to
me... but when I try to write it to disk, I get:

>>> out.write(listado)

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in -toplevel-
    out.write(listado)
UnicodeEncodeError: 'ascii' codec can't encode character '\ued' in
position 2274: ordinal not in range(128)

The "offending" character is:

>>> listado[2274]
u'\xed'
>>> print listado[2274]
?

In the original XML file (after all, I'm writing back the same thing I'm
reading) the char appears as follows:

</To><Text Style="font-family:Comic Sans MS; color:#000080; ">bien
aqu??</Text></Message>

If I cut&paste the text from IDLE into UltraEdit and then save it, and
try to view the result, the XSL bombs on the same character:

I've tried using both IDLE (python2.3 on cygwin) and PythonWin 2.2.2
(ActiveState) and both complain....

I _know_ that there has to be a way to be able to write back the XML to
the file, but I can't figure it out.

Any suggestions?

    Thanks a lot!

        Javier J





From idiot1 at netzero.net  Mon Aug 25 21:52:56 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 20:53:28 2003
Subject: [Tutor] uploading files with a form (long)
Message-ID: <3F4AAF68.5060203@netzero.net>

ok, back to the uploader issue, last task in the wiki.
http://www.tinylist.org/testform.html
the things sourcecode looks like this:
<HTML><HEAD>
<STYLE TYPE="text/css">
<!--  A { text-decoration: none; }  A:visited, A:hover, A:active 
text-decoration:none; } // -->
</STYLE>
<TITLE>Testing form for devlopment of the upload script</TITLE>
</HEAD>
<BODY TEXT="#000000"  BGCOLOR="#FFFFFF"  LINK="#0000FF" ALINK="FF0000" 
VLINK="0000FF"><blockquote
 >
<center><h2>Test form for uploading files<br>
to the images directory of this site.</h2>
<P>
<FORM ENCTYPE="multipart/form-data" 
ACTION="http://www.tinylist.org/cgi-bin/upload.py" METHOD=POS
T >

Send this file: <INPUT NAME="userfile" TYPE="file">

<INPUT TYPE="submit" VALUE="Send File">

</FORM>
</center>

<P>
<br>
ODD#8/14/03/kdb/testform.html
<P>
Peace.
<p>
</BODY>
</HTML>

The script of the moment looks like this:
#!/usr/local/bin/python
#
import os, cgi, sys                               # swallow the batteries...
#
footer='<P><br></body></html>'                    # define footer for later use.
form = cgi.FieldStorage()                         # extract data to a dictionary
# filename=form['userfile'].value
# filedata=form.getvalue('userfile','')
print 'Content-type:text/html\n'                  # warn apache what's coming...
print '<html><head>'                              # open the webpage up,
print "<title>Upload results</title></head>"      # name it,
print '<body bgcolor="FFFFFF" links="0000FF"><P>' # set up the bage body,
print '<center><h2>RESULTS</h2></center><P>'      #
print 'form=',form,'<P>That\'s the entire thing recovered from the cgi \ 
object.<P>',footer
print form.has_keys
sys.exit()



This is what appears on the page it is outputting:        the file's name
                                                           VVVVVVVVVVVVVVVVVVV
form= FieldStorage(None, None, [FieldStorage('userfile', 'wikinehesalogo3.png', 
'\211PNG\015\012\032\012\000\000\000\015IHDR\000\000\001;\000\000\000.\010\003\000\000\000`nNi\000\000\003\000PLTE\002\002\002\376\306\003\344}\003\265d\002\220Q\002n:\002\\1\002L)\002\376\326\002:\036\002\350\240\0024\035\002\376\342\003\276\222\002(\030\003\375\272\002\376\352\002\266w\002\234x\032"\022\002\362\266\002\312v\005\222`\004\034\021\002z^\012\376\365\002\350\247\005\343\212\004\375\212\003pJ\005\026\016\002\306\205\002\234`\003hK\002\373\362-\302\272&\306\3062\356\241\002\237r\002\356\250\005]?\003\210M\002\345\230\003\022\014\002\356\261\002\306\306.\270\207\004\376\372\002\364\331/\321q\002V?\003\322\203\002\366\3542\276\252.\312\225\004\376\376"\233f\002\245Y\002D2\003\362\300+\376\322\003{Z\006J7\006\264j\002\361\343.\375\220\002\016\011\002\363\315\'\323\215\003\365\217\003\264\200\005\362\237\002\310p\002xJ\003\332\242\012\364\332%\246i\002\352\230\004?+\004\323\224\004\362\250\002\242\232&\376\376\031\201F\002\376\276\003\225n\002\372\204\002\211R\002\33
3{\002{V\005d@\003\253z\'\346\2660,\037\005\375\226\002L0\0034"\004\342\222\002\332\322.\233R\002\361\344#\012\006\002\365\363"\376\316\003\326\236\002\376\332\003\220c\032\254a\002h9\002\366\236\002\365\3202\370\301\037\326v\002\375\256\002\312\216\002\276j\002\274~(\357\306\036\302\201\002\375\246\002T0\002\223W\002zv\036\314\230*\376\376\016\247{\036\\8\002\302w\002zE\002\356\215\002eF\003\221g\004o>\002\336\214\002\253r\004zP\004\272v 
\363\333\036\376\376\002\232f\036\375\252\002nE\004\362\266*@%\002\342\222*\362\262\002pR\004\370\354"\331\204\002\347\206\003\362\342\036\372\322&\245x\002\311|\003\333\224\002\360\230\002\211a\033\246k\036\254~\004\352\2362\372\312\032\375\242\002\342\252*\256i\003\361\313.\344\230 
\376\302\003\264q\002\245a\002\372\272"\274\200\003F+\005\275q\002\336\246\002\376\312\003]F\003\322\236.fO\026\314\212\002\327\267+\201_\005\306\234"\372\226\032\356\246*\356\326\036\306f\002\362\232*\306~"\256r"\234l\006\301\216\003\352\214\002\322\232"\211Y\032\366\362\032\035\026\004b8\002\351\222\002\373\373-R8\005\352\262\002\276x\002\211b\006uC\002\202J\002\376\262\002.\032\002\370\322\032\202Q\002\270x\022\376\356\003\356\177\002FB\026\334\232\002\376\336\002\376\266\002\375\232\002\316\216&\274\224\033"\027\003j@\004\336\205\002\210Y\003\234Y\002\236b\036\376\236\002\317|\003\241r\027\245n\002\374\266\026\366\231\002\366\346\032\372\246\036\254x\005\374\364\026\222o\032\356\222"\376\346\003\356\262&\332\215\005\006\006\002\345\216\002\366\272\0325&\005\302~"\276e\002^B\032\356\316\036\314\204\003\323\251 
\301\206\002\276\216"\326}\004F&\002:$\003\000\000\000n\224\221\217\000\000\001\000tRNS\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\3
77\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\000S\367\007%\000\000\021\352IDATx\332\355\233\177\\\033\347y\300\357\014\001Y0N\224\000\225!\004\267\263\021"C\261\311\022pd\260\010\2068\301\210\215\213\177\320\202\304\250\202\025 
\366\341\005\311["cl\254\204\036c!\270\345G\352\371\232T0\254\310\263K\232d\235\315\3621\012\005\373\250\203g\235\032\004D\304\361\3062f\023\352N\311\000\365$\235\356N\322I8i\222\356\363\231\337\277\320\373>\357\373<\317\367}\336\347}\337\273\003p\336-_\266\000w\021\334ew\227\335]v\377\037\331=\264\355A\377v\262\312\277\356\241\227\036\373\032\014yh\333\263\217r\325?MZ\360\330\377qv\217<\337J\025\351g\236\232\367\036i\245\313\376\017()W\335\363\255\022\365\233\214\323\017\276\3161\356\243\037\254\242x\033\013\210W\221\3403?!\332\250\3507\357\330\243G\337\374\206\331\375%\203I\310\373\325\005\027\222VV\021\032.\014\272qR\277\347\357\335\367\',\347x\017\237e\217\371\0369\232`\337\231\340J\037q\253\023\334{\324\207\034I\310\360\204\217\034=\235\002\350\344\231\304\325\235y\317eNH\315_\003\273\377dq\262\274\361\324\372\016\347\237\262\321I\300\223[\000\227\244\220\372\375\300S\337\356z\201\366M\260\257\243\342\026m\277\247\362\336\216\374\240\344\250Q\341\247r/\272~3z\324\320\02
3\231[\031\301\237\012\275\372\177\2655\003X-3{c\364\201\340\232\277\026v 
o\202\346\264n\375-\322\316\317xj!\355\223i\020\000\334\266w=\374\206\224\374\235Izr\353\223?\363\366\350\312\000(\317\336\363F\212zkP_\275"\017\224xz}k\335\313&\357\264\221\341\\\310\204\360\'\017\357\273W\340\252\317\004\000`\025vt\360\252\007\001\340\033ew\364\251\215\231\367ztCg\334\206\002%\353\307\012\015\024\272\016\257\355\025\233;\216^\200\007=\022\363\236\326\243\000\355\031\275\306Z\273\202\372\272_\342\026x\231\3515\262Y\324Q(u\257Y\210dw\262\203\226\335\274Y\2645S*8\003\254\312n\376\0164\177]\371nqqK\363F\302bQ\277L\201!K\305\226\365\'\341y\013\017\246\350\270E\027;\006;\274\002[\316\344\322\302\256\306O\005^\007\326\005w\266\260!sL\351\323\315\011\334J,\321\357\223F\317\253\015\017<\234y\362\344 
-\234QQ"\032\024\261e\203\024\010\264x4\277<\011|c\360\274j2&K\316t\245A\3605\021mh\306\342\34619h\202\327u\260m\337\330%\0028\013\031\275\231\027\370\356\345g*\011\356l\356\242_/\227\021)\213\2337>`\252\251\001\011\376\205\314\223]\014\274\213\271\353\007\225w\300\356\333\347\273.\020d\222Qw\254\036\243_\375\031\245b\213h\260\201\200\236\330\313\260\333\254\337x\015\006!\376Q\025\313\240k\373\006\203\261s\226\3446\017\016@\226\232\256P\316\002\201\354\310\\\260\367x\032h\200`\003\261\256\341\363\302\256\363\264t\307\330\371\305;`\347T\346\256\037;\007\326\310\027\377(\354rE[\013\371i\015[Sh\355[\273\006\326Ap\232\374\251\012\306\240o\031\340\221`\350\\\364\316\2145\300\320\371\220\316r\261\3538z\222o\300K\021\002\202\326\3113O\316\321\360\006c\013s\201;\341\241l\336:\227f\370\343\260\2738\322\334q^^z\3558\263\336\316\312\371\204\024\304\367\0154\253h\203>U\253\031\267\003!,n=\336@\340c\241\275\015\350\345\2548z\2741\215\214\271\264R\310\000\245\311\007\346\346\316\257\367\2
64d\256+=\3165\332\203\317>\347;\350\305\275\331\205\353\014\362\025\226\354\203\317\375\035\267\001\317\276\316y\205\241\307\374)G\333c\217~\032\374N6R\33616\320s\355\363\216\024\257\362\243\020\\\243\006Q\276\347\033`\026;\352\3242\301\223\373\300\373\267\277\370\321\3335=c%\336\232\271\314\202R\010\341\247\225\2420L\244\3113\013\347\346\365\337\241\256\007/EK\204R9G\323\363\022A\315\023A\330\225\210\332\366^\227\363\033\262\225^SOIy\321\363 
\272\241\247\260Y\231\2221\351\252\372\276P2\301r\345\257^\361\034\235\033\3133<\203\234\275\277g\203\001N\360\262\373s\357\275D\215\236\317\315\360j\372\356\323\356s\212\264\241\231\276+\334\177\356\032\002\343|\262l\340\243\244\306\201\330\271\330W]\015\247\242\005\204\037;\372\016$\261\230\220\217\350\352\317\035|\034\344S\033\231\363i\317\224\325\340=\203>\344\350c\324\004\017\346\263\032\250A\205\255\317?\337:\001\237\323s\364h\235\227\302\245\037q?\013\020\225\3377\326X\304\037\020M\252R*\334\267\010\201P(0\240\374\242\202\354\021e\305\351E\317\005$\237v\345\025/\031D\237A\215\263U\316G\0140\235\357(\011\001|\375"\355\375\217\274\306\300\323\211\264\366\302\236\0158Hhz\012\316\235\223\213\021\004\355i\034\030\220\313=\012\371>\350\276\3439\001\337\357\020JZ%5\245\005\317x\033\344=E\220\011\235\216\001\362\311\330{\232\002d\3320:\235\353O\310P(v\033\305\277\177\257\337\201\335bR\273\346\244t\314s\343\241\033\346\015\256\343\227\204G\210\007\3068\331)D\315W\346\344U\347\
022\024\213+\345\025dP\271\217\253D)_L\366\020\215\254?\012\270\357O4\272hz>\346\350\033\323\253\342"\004\204\347\022)\241\017\334\355h"+rNI\274\304\033/2D\336\027o 
\014\210#;a\254\270\261`\247\206@{\012\012\304\370)\267\302l6;7:O\332\230DZ\205hc\266\367(\335#.%L\245\305\271\223\025\345\300\333\364=\274`,w\022\360!\204\273;\227\013Z\325E\261\011"O\003u\253*\212q\337\012\012\246+(}\317\272j\345\356\016m\010\011\003o\310./\341bW\241k\326g\367`\033\032\247\233\327\'|\0048]N\012\360\233\216\202*qA\337\264>\241\340\023\347\266\326\326Q/\207\027\010\220\242\207*i\347\236q\261\003\035\256\375&\337U\365$\331<\355\2631\3400\317s\331\203\024,$s\342"\034\272\277y2e\262\244\355\374\300N\015\256\331PT\012{n\013\012\026\273\'\031t\000\240\'ZM\003{u\213\236&q\257\006\002\221QQ\242jR/$#\310\245f\002>\256K\241\225\270\321Q\031 
.;\272\0259\336\241\253p\267x,*\0108\001H\350X\001&\365d\260\342\261\367)\363\001\256\347w#\345m\323\261-U7c\263S\033\3617\177\340\262\362\346}\242+\307\013\304U\216\321\276F\214\36763\024)^\034\353\320H]s\253g\224\035%\331\031\014=\372\250D%\271r\316\272: 
\276\346d_\037\025\303\244\255\322Tv\032+\254*B\261r\352>\243o\254\252Gq\234\000\335\354$\371,9\267\217Wg\255\221\266\004\007\252\351V\262\330\211Iv\006\354\346hq#&\365l\206J\377\303\234Rt\345\372NM\201\017\273\367\315\275\365m\264`\206.\265\240\027\205j\242I#x\323\214\334[\026\001\351\177Q\024%vJm\261\024\347{\033\315;1\334`V0\276+\333\372z[F\350\316\373\243]Y\255/\005p\273\237\033\255\216\266\264Qm\030\246!j\014\005\272\024?v\027Y\277\3460\324 
Eu@0v[\312\313\257\364e\3554\223\231\203\'Pw{=i\213mYp%\023\251\251\317\227\202hwv\026\212t\263\256\035\317T\365b\004\214\366\366.h`\317\355\034\036\367\277R)\333\246\373\314H\213/\273\252\336^\226\241*E\366\354\0029\220\311\004%i\031\271\217k,\023\255\022q\271B\267\327\361\334\017^\221X\240b\246\261\312|\003\205Z\230@\211Q\350\257/d\215\320\002R\365\274\2445:V\247h\033\253\372\237m\222\011\236\206\3165\243\243\243\335-\275\216C"\205nG[\014\313^\026\307\027AP\312\303N\007e\247$3^\252ca\301\214!\004\266\203q$\301A\302\303\260\336T?\014\242\342\276\254\0337\212Y\333\350\253d_\202\260\367\336\250\307\245\356\247*\026s\300s\201\230\351\376Q\263\306\241\364a\267\340\303\016\000\264\331\335\275v2\036\314\261\355\214\0349}\363B\336\302\016\235-\025#s\241!\201\035\322I\013\365\344<&\322U%\227\023F{\263t\336\366\337\200&\236@\010\367\331tmF\\B\356\3206\246\263M\257\277<]|x\324\230\235\332\347\250:\037\343s\370\247\376|\335\242\266\360\314>\023\356{\323\321\016\333\246\215\013\346\005
\363\320,3t\306\351\364\303-SI\013\263\251\371~\354~g\354N\302\260\327RXq\227\264\035\303q\353BK\213Y\003\363,<\020\311\262\215\337\362\273\026\024\033\227z\261\245(\037vI\333\255\276\331F1\323=5\225\2244\325\307b\207\222\233t4a\\\341\274M\'\015Y\021|\211Yv\242\324\274%\373B\233\267\375g8\004\252y\326\351\030\216\316Q\212\222\250\250\222\035\306\244\316\254\251\244\241\226\342\323,>\000\360\302\337>\367\366KO\012\347\243-`R\010v%:\333\216~\322\346\251\245if\350\230\310\246\342\245N\322\013\255\377\352\323ww\336@5\207\331q\227d&=\250\234\355\2339\246\033\336\2357K\216T\254[\031\217Id\3539\334\335bE[|\343n\350\206\335\317\243\305\246\276\331\316\251\205>F\356#\253]\003\031n\224s?\211X0[Q")\206\256\030\311\033m\301\354\207\274?o\332Q\002\204;\3339;G\305\220IP\265\222j\266\333\255\275\235\306i\005m\356\317\377\235\274\037\010\310\274k\2511\201\370\322JpvN\335\260\355\2201kj\312\310\354\216\252\012\205-!>\253s\351P\206?\273w;\223*5\230\3217\356\3548~\303\330\344\316r\371\332\324\3
56\251\331\231rE{\373$K\311R\347\220\035\235\362\215\273!+\352\357R\234\355\265\331\254\331\376IZ.a\212T\2471\306q\263\033\332nE\240Nf\275\335\027\277t\004\303hv\357\2378bG\3543\334\217\200&=\335b\372\355\010j\2352\036\262)\345\023w\277\254\304\300\200\024=\336Tk4\24624\364F\343\354\221\312\274\024nv\333\255\030\202\3073\322{\263\246nh\254\351\336\337\251\306\303K\333\267\247\007y|Fmh\2233V\034\353\314K\327E\256\270\321M\220\027?aM\277;si\323\215S\306\366\020\354\242"\206\217\315\030\367\204\015\263\206^Q\350.\025/\305\317D\005<\203\374a\262\314\216\323\201\340\256\331.\303\020\315\211+L\332"\341\205\355>\026\241U0J\266WZ5\310\032\0373\254V\224\027\220\241\201\213u\207\302f\230\323\343H\377L\177\336lm\024\367\303CrP\202\330\303\260{\227\234"\024\273\354\225h;Dv>\234\036\354\311#\365\367rX\245}\350\265K\247\243\334\013e~\236\204gir\267\334\322\3566\236\230\325\205`\347\324\352lW\362\016\024G\261F\036\217\324\326\205\037<\330\024\020v\316\237T\222I\004{\234\225\004~B\246$B\263\
246\216\226M\034\256\235Z\012\013\267\325\015k\351n.\031|\312\'\355\222\007\254\3508\300\'E\273\257\016\021\273/\2632BSSYz\377\214N\305\345\375\213\230\006\205\210Y\206\364\207\'dv\324\233\357\000g\311\245\266\246\360\332C\343\034\350\376\351\324\217\317z\343d\367\236\312\344\376\210\304[\031J\247\363\327j\213@"\\\242n;3yk*\217\204\253B\260k\'\003/\274\366\230\217Y\221Z\335\245\360C\313\201\217\276\177i\'\227Ie\030\213]\222\035C\021Y-+#\217\327\325\306?\236\267\373\222\355\330\210\267\233F\203\342\330\246\010\366h\010\002\253#}\316N\324\036\277<\314z\340\257\320j\265\307\302\303\265qq\3431^\321\237\235\360D\364oI\305\204=\207\311\037\037&\313\254\232#\341\264\321\021\012\355pz\355\245\250\304\270\250|\252\363\357\260x\327\315\276&Z\310s\317d\306\332\341\360\003k\016\332\\\355\267\200\263&\320\244\236\000)_\332Nl\257\304d\324*\340fW\241\215\250+\013_\361\341\244\214\324\016_.\313\010d\367\013\024\301\021\231w\201\273kH,x\345kZ\206]~{\331\301\003\233j\323/]*\243\226\355\337\223
WUH\263\207\012(w\325?C\260\311R\3463:\275c\260\264^\\;\036\023\025\021\036~\251\256i\3465\327#\220\357\3757\210\334\366\014\373_\010B@\225\375L2\177\221\\\304\250\254\226N(\025k\307\307W\206\253/\327\331.\327&\264\223\002\277\331\017\332g\\\235\241\032\201\351\204\353P\235\330\037\266\347\304\236p\212\377\017\255\225v\304p\225\032\361\267(\246\301da\021\211\301\3319\333\265\332\210{T\276\234"##\352"\003\227,\031-\004\271@k\357a(hH\232\2325\325\021\2545\221\261\266\256l\246:\274\254\351r\370\016w\257\217!\010B\222o\037\213aF# 
\030\004\253\343\310\333%\020\362\245P\212+"\342\216\345\344\324\276s\265\022\205MR)\274)\316\323F\256\000\002\271\032\316\254\331$\253U\203\255\231\241\023\240*\203\364\352\326JuNN\330\201d;n\250\221\326\240\351n\3115v\036/\331\235y\226d\262\3440o\276\212\011\317\011;\270)\247=#\245\235\004\366)\244\251\334\365\370\214\207\035\300\315\256by\355\332\014?Nk\333Wb8\320a\250\006K\316\211\244f\326\365\014\370?pD#\313Y\346\330\011S\326F\336\323T\326\377\241\323\371\217\006\002\267\277\0231\356\231\037\327\367\017\377\000\021\004\216=\276\254\362\033\237\343\245\020\225\321s\336Y#\263#\020\010B\341T\333/fyyy%*&n|\370\240\371\327R\353\2462m\234\312g\177\011x\2531\036\247\362\347\224\022\223\002\004\262KN\336\265\251\214\225\267\225\316\2171\331\256\2348 
h\311_\276\375\275\375\204}W\355ZV\235\363\2575\262\344591\034o\022\203\261#\'\252\372\300.\253]F\347\314\331]W\017T\307\261\245\343\257n\252^\366{\207N\225\310\333WeV\373U\272%\261}\271n\327\201d8\232\007UVs\331\255Z\236\331\025\311\2617\007\260\313\010|\215\345Tq\240{7\247\314w<\300v\273\272N\005\254R""\374\316\030\316\323e\367\254\345\320\311\375F-\310\373\315\262\364\210|\337\232\352K\313\301\016"\001\311\300c\364\261]\357D\000wZ\202|\367\311\341\006\247kQ\300WS\234\234oz\203\331\302\355H`\260\253B\234\342\374\033\356\320\260/\307\316\011\254\262\242B\250\370\203\3309C\316c\010-N\340\013\260s~q\333\203}o\034*\000B}\037\021\372\310~\307|9U\204R\032d[^](T}h\333\203\177\253\035<\000B~[\0028\235wjX\250\211\347\264&\244\326 
\2732\347\240A\202<\010S\347\027f\347\014\306)\344\267%\301\316\025\201i 
\244\215\234\326\254\372U\306j\033\313j\235\235\301\362\006\327\024\177\205\377#\300\265\314\356\244\027\360\207)\015\302y\265\212\220\026\006\013\374\325\377G\340n\371r\337A\335-_\270\374\036\177\034\036#D\324\245\376\000\000\000\000IEND\256B`\202')])

That's the entire thing recovered from the cgi object.

ok, I have tried, and failed. Someone give me a clue please. IN fact, give me 
SEVERAL clues. This may well be a 'can't see the forest for the trees' issue.
-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From Futurug at aol.com  Mon Aug 25 22:00:05 2003
From: Futurug at aol.com (Futurug@aol.com)
Date: Mon Aug 25 21:00:47 2003
Subject: [Tutor] creating a list of data . . . 
Message-ID: <184.1f8aff73.2c7c0b15@aol.com>

Thank you for 

I am absolutely new to programming with python, and I am learning quickly

I am trying to create a tuple with 14 data in.

my current code: 

    frug = frug , rug

where frug is the final tuple and rug is the data I am trying to add

I curretly get all 14 fields of data, but it only lets me call up 

I do not want to create one long string of data as the length of the 
individual data fields can vary.

Thanks

Kenny Sodbuster
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030825/010a5bce/attachment.htm
From idiot1 at netzero.net  Mon Aug 25 22:29:14 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 21:30:56 2003
Subject: [Tutor] creating a list of data . . .
In-Reply-To: <184.1f8aff73.2c7c0b15@aol.com>
References: <184.1f8aff73.2c7c0b15@aol.com>
Message-ID: <3F4AB7EA.8080701@netzero.net>

Tuples are immutable. That means they cannot be changed, they can only be 
created or destroyed.

So do so. Kill it. and create it. In the process of creating it anew, do so with 
the extra data thrown in. A temporary variable would probably  be a good idea 
here to hold the old content of your tuple.

A libation to the lord Shiva is at this time appropriate to be offered. After 
pouring out a little, sip the rest while reading about tupples and their 
methods. May I reccomend Henessy XO for the brain lubrication fluid?






Futurug@aol.com wrote:

> Thank you for
>  
> I am absolutely new to programming with python, and I am learning quickly
>  
> I am trying to create a tuple with 14 data in.
>  
> my current code:
>  
>     frug = frug , rug
>  
> where frug is the final tuple and rug is the data I am trying to add
>  
> I curretly get all 14 fields of data, but it only lets me call up
>  
> I do not want to create one long string of data as the length of the 
> individual data fields can vary.
>  
> Thanks
>  
> Kenny Sodbuster
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From gus.tabares at verizon.net  Tue Aug 26 02:35:08 2003
From: gus.tabares at verizon.net (Gus Tabares)
Date: Mon Aug 25 21:35:09 2003
Subject: [Tutor] creating a list of data . . .
In-Reply-To: <3F4AB7EA.8080701@netzero.net>
References: <184.1f8aff73.2c7c0b15@aol.com>  <3F4AB7EA.8080701@netzero.net>
Message-ID: <1061861728.28337.1.camel@blackbetty>

On Mon, 2003-08-25 at 21:29, Kirk Bailey wrote:
> Tuples are immutable. That means they cannot be changed, they can only be 
> created or destroyed.
> 
> So do so. Kill it. and create it. In the process of creating it anew, do so with 
> the extra data thrown in. A temporary variable would probably  be a good idea 
> here to hold the old content of your tuple.

Hello,

	Concatenation is perfectly legal:

>>> tuple = (1, 2, 3, 4)
>>> tuple = tuple + (5, 6, 7, 8)
>>> tuple
(1, 2, 3, 4, 5, 6, 7, 8)
>>>


HTH,

-- 
/Gus


From darnold02 at sprynet.com  Mon Aug 25 21:52:20 2003
From: darnold02 at sprynet.com (Don Arnold)
Date: Mon Aug 25 21:53:10 2003
Subject: [Tutor] creating a list of data . . . 
References: <184.1f8aff73.2c7c0b15@aol.com>
Message-ID: <0b6201c36b74$b9a51cd0$8f10ba3f@defaultcomp>

----- Original Message -----
From: <Futurug@aol.com>
To: <tutor@python.org>
Sent: Monday, August 25, 2003 8:00 PM
Subject: [Tutor] creating a list of data . . .


> Thank you for
>
> I am absolutely new to programming with python, and I am learning quickly
>
> I am trying to create a tuple with 14 data in.
>
> my current code:
>
>     frug = frug , rug
>
> where frug is the final tuple and rug is the data I am trying to add
>
> I curretly get all 14 fields of data, but it only lets me call up
>
> I do not want to create one long string of data as the length of the
> individual data fields can vary.
>
> Thanks
>
> Kenny Sodbuster

As Kurt has pointed out, tuples are immutable: once they're created, they
can't be modified. They can, however, be rebound:

someTuple = ()

for i in range(10):
    someTuple = someTuple + (i,)

print someTuple

>>> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Lists, on the other hand,  _are_ mutable, so it's often cleaner (and more
efficient) to build a list and then convert it to a tuple when you're done:

someList = []

for i in range(10):
    someList.append(i)

someOtherTuple = tuple(someList)

print someOtherTuple

>>> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)


HTH,
Don


From darnold02 at sprynet.com  Mon Aug 25 21:55:02 2003
From: darnold02 at sprynet.com (Don Arnold)
Date: Mon Aug 25 21:55:37 2003
Subject: [Tutor] creating a list of data . . . 
Message-ID: <0b7101c36b75$18fd1250$8f10ba3f@defaultcomp>


----- Original Message -----
From: "Don Arnold" <darnold02@sprynet.com>
To: <Futurug@aol.com>; <tutor@python.org>
Sent: Monday, August 25, 2003 8:52 PM
Subject: Re: [Tutor] creating a list of data . . .


<snip>
> As Kurt has pointed out, tuples are immutable: once they're created, they
<snip>

And apologies to Kirk Bailey for referring to him as 'Kurt' (though he
probably gets that quite often).  ; )

Don


From darnold02 at sprynet.com  Mon Aug 25 21:58:21 2003
From: darnold02 at sprynet.com (Don Arnold)
Date: Mon Aug 25 21:58:53 2003
Subject: [Tutor] creating a list of data . . .
References: <184.1f8aff73.2c7c0b15@aol.com> <3F4AB7EA.8080701@netzero.net>
	<1061861728.28337.1.camel@blackbetty>
Message-ID: <0b7801c36b75$90b5b900$8f10ba3f@defaultcomp>


----- Original Message -----
From: "Gus Tabares" <gus.tabares@verizon.net>
To: <tutor@python.org>
Sent: Monday, August 25, 2003 8:35 PM
Subject: Re: [Tutor] creating a list of data . . .


> On Mon, 2003-08-25 at 21:29, Kirk Bailey wrote:
> > Tuples are immutable. That means they cannot be changed, they can only
be
> > created or destroyed.
> >
> > So do so. Kill it. and create it. In the process of creating it anew, do
so with
> > the extra data thrown in. A temporary variable would probably  be a good
idea
> > here to hold the old content of your tuple.
>
> Hello,
>
> Concatenation is perfectly legal:
>

True, but the rebinding it entails is inefficient.

> >>> tuple = (1, 2, 3, 4)
> >>> tuple = tuple + (5, 6, 7, 8)
> >>> tuple
> (1, 2, 3, 4, 5, 6, 7, 8)
> >>>
>

And rebinding a built in type (as was done with here 'tuple'), is equally
legal, but _never_ a good idea.

>
> HTH,
>
> --
> /Gus

Ditto,
Don


From idiot1 at netzero.net  Mon Aug 25 23:17:57 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 22:18:26 2003
Subject: [Tutor] creating a list of data . . .
In-Reply-To: <0b6201c36b74$b9a51cd0$8f10ba3f@defaultcomp>
References: <184.1f8aff73.2c7c0b15@aol.com>
	<0b6201c36b74$b9a51cd0$8f10ba3f@defaultcomp>
Message-ID: <3F4AC355.5080008@netzero.net>

KIRK! KIRK! KIRK! (counting the cadence by pounding on crt with a large fuzzy 
stuffed monkey from the bookshelf to the right...) :-)

Scottish, not German!
(Dad's band of vikings went north, not east.)

But read on, this is more than a egotistical rant.

Don Arnold wrote:

> ----- Original Message -----
> From: <Futurug@aol.com>
> To: <tutor@python.org>
> Sent: Monday, August 25, 2003 8:00 PM
> Subject: [Tutor] creating a list of data . . .
> 
> 
> 
>>Thank you for
>>
>>I am absolutely new to programming with python, and I am learning quickly
>>
>>I am trying to create a tuple with 14 data in.
>>
>>my current code:
>>
>>    frug = frug , rug
>>
>>where frug is the final tuple and rug is the data I am trying to add
>>
>>I curretly get all 14 fields of data, but it only lets me call up
whups, this escaped me earlier. you can only access PART of it? data is acessed 
numerically, just like a list, address starting with 0 of course.  If you can't 
access all of it at will, something is TERRIBLY WRONG.
>>
>>I do not want to create one long string of data as the length of the
>>individual data fields can vary.
Right. You want some form of data construct that contains each datum in it's own 
'cell', and you simply access that cell.
>>
>>Thanks
>>
>>Kenny Sodbuster
> 
> 
> As Kurt has pointed out, tuples are immutable: once they're created, they
> can't be modified. They can, however, be rebound:
> 
KIRK! And rebinding is a pain.

> someTuple = ()
> 
> for i in range(10):
>     someTuple = someTuple + (i,)
> 
> print someTuple
> 
> 
>>>>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
> 
> 
> Lists, on the other hand,  _are_ mutable, so it's often cleaner (and more
> efficient) to build a list and then convert it to a tuple when you're done:
> 
Also reccomended in some tutorials.

> someList = []
> 
> for i in range(10):
>     someList.append(i)
> 
> someOtherTuple = tuple(someList)
> 
> print someOtherTuple
> 
> 
Veryfine, and much preferred to messing with tuples. Turn it into a list, play 
with the list, then turn it into a tuple- which is meaning what I said, but at 
much greater detail and length: Destroy it and recreate it.

>>>>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
> 
> 
> 
> HTH,
> Don
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Mon Aug 25 23:23:17 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Aug 25 22:24:17 2003
Subject: [Tutor] creating a list of data . . .
In-Reply-To: <0b7101c36b75$18fd1250$8f10ba3f@defaultcomp>
References: <0b7101c36b75$18fd1250$8f10ba3f@defaultcomp>
Message-ID: <3F4AC495.7070008@netzero.net>

Actually, rather rare. First time in at least 3 weeks.

Kurt is a fine Germain name, and had dad thought it up, it may have been. His 
was a old line of Danish seacaptains, going back to the long old Dragonheaded 
widowmakers of long ago when the dark and swarthy Danes went forth A'viking. 
(cue the viking corus!) But mom is English, from right next to the Scottish 
boarder, and has family all over that fine land, and she picked it.

But I still like Frank Zappa for daring to name his daughter 'Moon Unit'; That's 
my kind of nut.

Don Arnold wrote:

> ----- Original Message -----
> From: "Don Arnold" <darnold02@sprynet.com>
> To: <Futurug@aol.com>; <tutor@python.org>
> Sent: Monday, August 25, 2003 8:52 PM
> Subject: Re: [Tutor] creating a list of data . . .
> 
> 
> <snip>
> 
>>As Kurt has pointed out, tuples are immutable: once they're created, they
> 
> <snip>
> 
> And apologies to Kirk Bailey for referring to him as 'Kurt' (though he
> probably gets that quite often).  ; )
> 
> Don
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From alex at gabuzomeu.net  Tue Aug 26 11:17:30 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Tue Aug 26 04:17:30 2003
Subject: [Tutor] Python - XML: How to write UNICODE to a file ?? (when
	using	LATIN-1 Chars)
In-Reply-To: <001301c36b56$d64436a0$0100a8c0@uno>
References: <001301c36b56$d64436a0$0100a8c0@uno>
Message-ID: <3F4B179A.8010408@gabuzomeu.net>

Hi Javier,


Javier JJ wrote:

>I have an xml file with ASCII characters (no encoding is specified; it
>contains characters valid in the latin-1 charset - it's a log file
>generated by MSN Messenger 6.0).
>
>I am processing it with mindom as follows:
>doc = minidom.parse(log_file.xml)
>

> Now "listado" has a xml-looking unicode string; it looks quite fine to
>
>me... but when I try to write it to disk, I get:
>  
>
>>>>out.write(listado)
>>>>Traceback (most recent call last):
>>>>  File "<pyshell#34>", line 1, in -toplevel-
>>>>    out.write(listado)
>>>>UnicodeEncodeError: 'ascii' codec can't encode character '\ued' in
>>>>position 2274: ordinal not in range(128)
>>>>        
>>>>
The string is being converted to the default encoding, ASCII. As ASCII 
does not support "extended" characters (eg. accented chars), you get an 
error. Try to encode the string before writing it:

# Latin-1 encoding
s = listado.encode('iso-8859-1')
# UTF-8 encoding
s = listado.encode('utf-8')
out.write(s)

Also, take a look at the "codecs" module for related tools.


Cheers.

Alexandre




From tpc at csua.berkeley.edu  Tue Aug 26 09:46:41 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Tue Aug 26 11:47:32 2003
Subject: [Tutor] Network stuff
In-Reply-To: <20030823223328.73715.qmail@web20207.mail.yahoo.com>
Message-ID: <20030826084433.F40752-100000@localhost.name>


hi Gerardo, I am wondering if both applications are running on top of a
web server, in which case you can use HTTP POST or GET to pass the strings
along using key, value pairs.

On Sat, 23 Aug 2003, Gerardo Arnaez wrote:

> Hello all, enjoying the heck out of python. using to
> help set up user accounts at a public internet cafe
> where they will sell these accoutnts in 30 min
> sessions.
>
> Right now I can get a list of any user and total time
> logged in to one computer.  I break this up into a
> dictionary.
>
> The problem is that I am not sure how to transmit this
> information.  Ie I have some data I want to sent to
> another application on another computer.
>
> At first twisted was mentioned to me,
> and I see socket and socketServer modules,
> but I need some hints in what would be the pythonic
> way to go about this.
>
> All I really want to do is send a dictionary from a
> client app and have it examined in the server app.
>
> Anyway, I would should could but its so simplistic
> that is amounts to parseing the output of 'ac' an gnu
> account procces and logins
> and storing them into a dictionary.
>
> Anyway, Thanks for all your help
>
> G
>
>
>
>
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free, easy-to-use web site design software
> http://sitebuilder.yahoo.com
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From SWidney at ci.las-vegas.nv.us  Tue Aug 26 09:45:34 2003
From: SWidney at ci.las-vegas.nv.us (Scott Widney)
Date: Tue Aug 26 11:47:59 2003
Subject: [Tutor] creating a list of data . . .
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8790@SOVEREIGN>

> 	Concatenation is perfectly legal:
> 
> >>> tuple = (1, 2, 3, 4)
> >>> tuple = tuple + (5, 6, 7, 8)
> >>> tuple
> (1, 2, 3, 4, 5, 6, 7, 8)

Ah, but that is not what the OP did! Look:

  " frug = frug , rug "

Let's expand on this a little in the interpreter.

>>> frug = (1, 2, 3, 4)
>>> rug = (5, 6, 7, 8, 9)
>>> frug = frug, rug

Remember Python evaluates the right-hand expression in its entirety first,
then binds the result to the left side. What happens in that third line can
be better understood if entered like this:

>>> frug = (frug, rug)

Keep in mind that Python only requires parentheses around a tuple in cases
where not doing so could be misinterpreted. Here we created a new tuple and
assigned it to frug. Look at the new value of frug:

>>> frug
((1, 2, 3, 4), (5, 6, 7, 8, 9))

You have a tuple which contains these two tuples: (1, 2, 3, 4) and (5, 6, 7,
8, 9). If you mistakenly assume that frug was the concatenation of the two
tuples, and attempt to access, oh say, the fourth element (index=3) you'd
get an exception:

>>> frug[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: tuple index out of range

That's because, as stated previously, frug only has two elements. You're
going to need to do a little more work to access the individual elements.

>>> frug[0]
(1, 2, 3, 4)
>>> frug[1]
(5, 6, 7, 8, 9)
>>> frug[0][0]
1
>>> frug[1][0]
5

Previous replies have provided a solution (concatenation). I just wanted to
point out a possible source of misunderstanding. Hope that helps someone!


Scott

From holysmoke at amaltaas.biz  Tue Aug 26 23:07:23 2003
From: holysmoke at amaltaas.biz (Sukrit K Mehra)
Date: Tue Aug 26 12:34:49 2003
Subject: [Tutor] Linked Lists
Message-ID: <20030826163723.GA332@Joss>

Hi,
I had posted a lot of general questions about learning CS using python
about a fortnight back. Thanks everyone for all the suggestions. 

This time I am here with a more concrete problem. I want to learn about
linked lists in python such that I can say -

mylist = linked() 
#initialize list, that is have a class named linked

and have following methods (or functions if you will) 

addbeginning(x) #to add an element at beginning
addposition(x, pos) #to add an elemnt at specified position
addend(x) #to add at end
print() #to print 
sort() #to sort
search() #to search

... and so forth.

Questions

I am having trouble with the basic structure of the list. I
understand that you need a node, so I have a node
class Node:
    def __init__(self, data=NULL, next=NULL):
        self.next = next
        self.data = data

I don't know how to make a list class


Please help and advice.

regards
sukrit

From jeff at ccvcorp.com  Tue Aug 26 10:51:50 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Aug 26 12:51:36 2003
Subject: [Tutor] creating a list of data . . .
References: <0E5508EBA1620743B409A2B8365DE16FDC8790@SOVEREIGN>
Message-ID: <3F4B9026.30700@ccvcorp.com>

Scott Widney wrote:


>>>>frug = (frug, rug)
>>>
> 
> Keep in mind that Python only requires parentheses around a tuple in cases
> where not doing so could be misinterpreted. Here we created a new tuple and
> assigned it to frug. Look at the new value of frug:
> 
>>>>frug
>>>
> ((1, 2, 3, 4), (5, 6, 7, 8, 9))


What makes this even worse is that the O.P. spoke of having 14 data 
elements that should end up in this tuple.  If we presume that this 
means the above was done 14 times....

 >>> frug = ()
 >>> frug
()
 >>> for n in range(14):
... 	frug = frug, n
... 	
 >>> frug
(((((((((((((((), 0), 1), 2), 3), 4), 5), 6), 7), 8), 9), 10), 11), 
12), 13)
 >>> frug[0][0][0][0][0][0][0][0][0][0][0][0][0][0]
()
 >>>

Well, that's a bit ugly.  It's possible to nest tuples (and lists) 
arbitrarily deep, but that doesn't mean it's a good idea.  (The Zen of 
Python, line 5 -- "Flat is better than nested.")  However, note that 
the only change necessary to make the above into something reasonable 
is to change the nesting into addition:

 >>> frug = ()
 >>> for n in range(14):
... 	frug = frug + (n,)
... 	
 >>> frug
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
 >>>

Note that I had to make n into a one-element tuple before I could add 
it to the existing tuple, because sequences can only be added to other 
sequences of similar type.

Jeff Shannon
Technician/Programmer
Credit International


From aicolburn at yahoo.com  Tue Aug 26 12:21:54 2003
From: aicolburn at yahoo.com (Alan Colburn)
Date: Tue Aug 26 14:22:28 2003
Subject: [Tutor] Python on Windows and other processes
Message-ID: <20030826182154.31761.qmail@web41612.mail.yahoo.com>

I was working on a web page today (on a WinXP machine)
and took a little break with Python. (Doesn't
everyone?!) When I closed IDLE and went back to
Dreamweaver, I got this odd message:

"This file has been modified outside Dreamweaver. Do
you want to reload it?"

The message is odd because I didn't do anything to the
file outside Dreamweaver. Do any of you understand
what's going on? I don't know much about what Python
does in the background when running on Windows, and
thought some of you might. Even more oddly, [wx]Python
might sometimes also interfere with the touchpad
driver on my laptop (...I'm much less certain it's
Python, in this case, but pass this comment on anyway,
just in case).

Does Python actually do stuff in the background that
might interfere with other programs, or am I simply in
the Twilight Zone?

Thanks, as always! -- Al C.

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

From man00000 at rediffmail.com  Tue Aug 26 21:37:51 2003
From: man00000 at rediffmail.com (MANDAR SHASHIKANT TULJAPURKAR)
Date: Tue Aug 26 16:37:53 2003
Subject: [Tutor] QUESTION
Message-ID: <20030826203653.13266.qmail@webmail17.rediffmail.com>

Plz let me know if i must know C very well first.I have the basic 
knowledge of c.

MANDAR SHASHIKANT TULJAPURKAR
___________________________________________________
Art meets Army ; Swapna Weds Capt. Rajsekhar.
Find interesting matches on Rediff Matchmaker !
Visit http://matchmaker.rediff.com?1


From carroll at tjc.com  Sat Aug 23 01:34:32 2003
From: carroll at tjc.com (Terry Carroll)
Date: Tue Aug 26 16:53:06 2003
Subject: [Tutor] __all__ cf. _foo, _bar, etc.
Message-ID: <Pine.LNX.4.44.0308230024410.5954-100000@mauve.rahul.net>

I'm trying to get straight about the difference and interaction between 
the __all__ variable and the prefixing a variable name with a single 
underscore (e.g., _foo, _bar).

My understanding is that if you code:

 from ModuleName import *

if __all__ is initialized in the module, all of the names listed in that 
list are made available; if __all_ is not initialized, every name not 
beginning with an underscore is made available.

If you code:

 import ModuleName

Neither the __all__ or the underscore-prefixed names make any difference, 
because the names from the module are not made available except through an 
explicit reference to them (e.g., ModuleName.spam), regardless of whether 
__all__ was initialized or whether the variable is prefixed with an 
underscore (i.e., you can reference ModuleName._spam if you wish, but of 
course do so at your own risk).

Is this correct?

If I understand this right, then, if the coder of a module initializes
__all__, he need not worry about the _foo convention;  the __all_
overrides that for the "from ModuleName import *"  form of import, and the
importing namespace is unaffected if using the "import ModuleName" form.

Right?

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982



From david at graniteweb.com  Tue Aug 26 17:15:47 2003
From: david at graniteweb.com (David Rock)
Date: Tue Aug 26 17:16:26 2003
Subject: [Tutor] QUESTION
In-Reply-To: <20030826203653.13266.qmail@webmail17.rediffmail.com>
References: <20030826203653.13266.qmail@webmail17.rediffmail.com>
Message-ID: <20030826211547.GA7262@wdfs.graniteweb.com>

* MANDAR SHASHIKANT TULJAPURKAR <man00000@rediffmail.com> [2003-08-26 20:36]:
> Plz let me know if i must know C very well first.I have the basic 
> knowledge of c.

Absolutely not. The fact that you DO have some previous programming
experience will only make it easier to understand the concepts of
programming in Python, but it is in no way a prerequisite for learning
Python.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030826/4751a484/attachment.bin
From gus.tabares at verizon.net  Tue Aug 26 23:06:26 2003
From: gus.tabares at verizon.net (Gus Tabares)
Date: Tue Aug 26 18:06:46 2003
Subject: [Tutor] QUESTION
In-Reply-To: <20030826203653.13266.qmail@webmail17.rediffmail.com>
References: <20030826203653.13266.qmail@webmail17.rediffmail.com>
Message-ID: <1061935654.30026.2.camel@blackbetty>

On Tue, 2003-08-26 at 16:36, MANDAR SHASHIKANT TULJAPURKAR wrote:
> Plz let me know if i must know C very well first.I have the basic 
> knowledge of c.
> 

Hi Mandar,

    Knowing C certainly doesn't hurt, but it is not needed in order to
learn Python. In fact, IMO, it is better to learn Python before C. While
C is very powerful, it contains a lot of other tedious stuff like memory
management that just isn't need in Python!
    I suggest learning Python and then try tackling C or C++. This list
can help you on your way!


-- 
/Gus


From SWidney at ci.las-vegas.nv.us  Tue Aug 26 16:48:22 2003
From: SWidney at ci.las-vegas.nv.us (Scott Widney)
Date: Tue Aug 26 18:50:46 2003
Subject: [Tutor] Linked Lists
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8793@SOVEREIGN>

> This time I am here with a more concrete problem. I want to 
> learn about linked lists in python such that I can say -
> 
> mylist = linked() 
> #initialize list, that is have a class named linked
> 
> and have following methods (or functions if you will) 
> 
> addbeginning(x) #to add an element at beginning
> addposition(x, pos) #to add an elemnt at specified position
> addend(x) #to add at end
> print() #to print 
> sort() #to sort
> search() #to search
> 
> ... and so forth.

If all you need simple singly-linked-list functionality for a project you're
working on, let me say -- "Don't reinvent the wheel!". Python's built-in
[list] already provides you with the functionality you mentioned. Try this
is the interpreter:

Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
'__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>

Look at the last few words in that list. They're the methods that every list
inherits. Let's look at the functions you mention and show how they are done
with Python lists. We'll start with a simple list...

>>> L = [1, 2, 3, 4]

# addbeginning(x) add an element at beginning
>>> L.insert(0, 'a')
>>> L
['a', 1, 2, 3, 4]

# addposition(x, pos) add an elemnt at specified position
>>> L.insert(2, 'b')
>>> L
['a', 1, 'b', 2, 3, 4]

# addend(x) add at end
>>> L.append('foo')
>>> L
['a', 1, 'b', 2, 3, 4, 'foo']

# print() to print
>>> print L
['a', 1, 'b', 2, 3, 4, 'foo']

# sort() #to sort
>>> L.sort()
>>> L
[1, 2, 3, 4, 'a', 'b', 'foo']

# search() #to search
>>> L.index('foo')
6
>>> L[6]
'foo'
>>> L.index('bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list

There's also slicing, concatenating, popping, etc.

>>> L.insert(3, 'r')
>>> L[1:4]
['b', 'a', 'r']
>>> L
['foo', 'b', 'a', 'r', 4, 3, 2, 1]
>>> L[4:] + L[:4]
[4, 3, 2, 1, 'foo', 'b', 'a', 'r']
>>> L.insert(0, L.pop())
>>> L.insert(0, L.pop())
>>> L.insert(0, L.pop())
>>> L.insert(0, L.pop())
>>> L
[4, 3, 2, 1, 'foo', 'b', 'a', 'r']
>>> L.append(L.pop(0))
>>> L.append(L.pop(0))
>>> L.append(L.pop(0))
>>> L.append(L.pop(0))
>>> L
['foo', 'b', 'a', 'r', 4, 3, 2, 1]
>>> L.insert(0, L.pop())
>>> L.insert(1, L.pop())
>>> L.insert(2, L.pop())
>>> L.insert(3, L.pop())
>>> L
[1, 2, 3, 4, 'foo', 'b', 'a', 'r']

Try typing: help(list) at the >>> prompt for more information.

Now if it were a doubly-linked list, I think that would be another
matter....


Hope this helps!
Scott

From idiot1 at netzero.net  Tue Aug 26 20:22:46 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Tue Aug 26 19:23:23 2003
Subject: [Tutor] uploading files, the latest and final migrain source
Message-ID: <3F4BEBC6.60504@netzero.net>

ok, still trying to crack the last tough nut- all the rest of the wiki is ready.

Uploading with a http form/post method.

here's a form"
http://www.tinylist.org/testform/html
it is reproduced on the footer of the wiki'e editor page. TO access it, go here
http://www.tinylist.org/cgi-bin/wikinehesa.py/SandBox
which brings up the sandbox, a playpen page, don't worry about the possibility 
of altering or even emptying it, that's what the sandbox is there for- it's the 
scratchmonkey. Click EDIT THIS PAGE in the footer. Up comes the editor. Look at 
the footer. Nice features here, but right now let's look at the middle at the 
upload image file utility. The form part works fine. It feeds to a script, which 
is like this at the moment:

#!/usr/local/bin/python
#
import os, cgi, sys				# swallow the batteries...
#
footer='<P><br>That\'s all, folks.<P></body></html>'			# define the webpage 
footer for later use.
form = cgi.FieldStorage()			# extract the datapackage into a dictionary 'form',
data=form['userfile'].value
# filedata=form.getvalue('userfile','')
print 'Content-type:text/html\n'		# warn apache what's coming down the pipe,
print '<html><head>'				# open the webpage up,
print "<title>Upload results</title></head>"	# name it,
print '<body bgcolor="FFFFFF" links="0000FF"><P>' # set up the bage body,
print '<center><h2>RESULTS</h2></center><P>'			# generate a descriptive header
print 'form=',form,'<P>That\'s the entire thing recovered from the 
cgi.FieldStorage() object.<P>'
print 'the form has these keys:',form.keys(),'<P>'
print 'we assign to "data" the value form[\'userfile\'].value and get:<br>'
print 'data has this in it:',data,'<P>'
print footer
sys.exit()

There's more after that, but it never runs, and never will until I get this part 
cracked. This is the sort of stuff you get to see on your browser as a result of 
it running:
form= FieldStorage(None, None, [FieldStorage('userfile', 'wikinehesalogo3.png', 
'\211PNG\015\012\032\012\000\000\000\015IHDR\000\000\001;\000\000\000.\0(etc...)
and further on:
That's the entire thing recovered from the cgi.FieldStorage() object.

the form has these keys: ['userfile']

we assign to "data" the value form['userfile'].value and get:
data has this in it: ?PNG  (etc...)

it's a lot, but not in anything I can manipulate, or use. TAKE A LOOK. it will 
abort before writing anything to my server. See if you have a clue you can spare me.



-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.



From holysmoke at amaltaas.biz  Wed Aug 27 06:55:35 2003
From: holysmoke at amaltaas.biz (Sukrit K Mehra)
Date: Tue Aug 26 20:23:10 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC8793@SOVEREIGN>
References: <0E5508EBA1620743B409A2B8365DE16FDC8793@SOVEREIGN>
Message-ID: <20030827002535.GA268@Joss>

On Tue, Aug 26, 2003 at 03:48:22PM -0700, Scott Widney wrote:
 
> If all you need simple singly-linked-list functionality for a project you're

I don't need it, I want it. I am trying to learn.


> >>> dir(list)
> ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
> '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
> '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
> '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
> '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__',
> '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert',
> 'pop', 'remove', 'reverse', 'sort']

Umm I know. Maybe I should look at the implementation. There is this
linked list project at sf, that I forgot the url of, but it's too obtuse
for me.

> Now if it were a doubly-linked list, I think that would be another
> matter....

Ok, how would you do a doubly-linked list?

Thanks,
sukrit

From learning.python at dbmail.dk  Wed Aug 27 03:04:39 2003
From: learning.python at dbmail.dk (Ole Jensen)
Date: Tue Aug 26 20:34:24 2003
Subject: [Tutor] Thank you
Message-ID: <000d01c36c2e$cf0df640$b84c73d5@BAERBAR>

I just want to thank the tutor, for beeing such a good tool. It seems that whenever I have a problem with my code. And I finally give up and write a mail to you, then when I'm halfway through the mail I solve the problem my self...

So, thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030827/e2a2b680/attachment.htm
From idiot1 at netzero.net  Tue Aug 26 21:38:14 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Tue Aug 26 20:38:53 2003
Subject: [Tutor] Re: Regex
In-Reply-To: <bidj1v$d98$1@sea.gmane.org>
References: <bib0iu$mqp$1@sea.gmane.org>	<Pine.LNX.4.44.0308242046290.23261-100000@hkn.eecs.berkeley.edu>
	<bidj1v$d98$1@sea.gmane.org>
Message-ID: <3F4BFD76.3010205@netzero.net>

Prehaps I can help.

I am writing a wiki. something very much like this comes up in convertingt the 
page into html for the recipient's browser. If one types
http://www.tinylist.org
into the page, it should be converted into a link
<a href="http://www.tinylist.org">http://www.tinylist.org</a>
is the result it renders.

But if it is parsing the page, and it finds somthing that appears to be an 
operational link already, it should leave it alone. This is because a different 
function turns some code into an image tag with a src declaration pointing at 
the host's website, and this must not be broken.

The critical difference is one simple character. the " at the start of the address.
<img src="http://www.tinylist.org/images/wikinehesalogo2.gif">
http://www.tinylist.org/images/wikinehesalogo2.gif
The second is converted into a link. The first is disabled, by
turning the < and > into &lt; and &gt; respectively.
&lt.img src="http://www.tinylist.org/images/wikinehesalogo2.gif"&gt;
will not operate when examined by the browser. Morover, the link constructor 
will not turn the address into a hotlink, because of the leading '"'.

This is the sourcecode of the program. Please feel free to steal as needed.
http://www.tinylist.org/wikinehesa.txt

To witness it in action, click this:
http;//www.tinylist.org/cgi-bin/wikinehesa.py
Notice there is a image displayed in the body of the page, as well as a hotlink 
back to the main website. To examine the page's wikicode source, just click the 
EDIT THIS PAGE button.

I hope this is of some help.


Andrei wrote:

> Thanks, it *almost* helps, but I'm not trying to harvest the links. The 
> issue is that I do *not* want to get URLs if they're in between <a> 
> tags, nor if they're an attribute to some tag (img, a, link, whatever).
> 
> Perhaps I should have explained my goal more clearly: I wish to take a 
> piece of text which may or may not contain HTML tags and turn any piece 
> of text which is NOT a link, but is an URL into a link. E.g.:
> 
>   go to <a href="http://home.com">http://home.com</a>. [1]
>   go <a href="http://home.com">home</a>. [2]
> 
> should remain unmodified, but
> 
>   go to http://home.com [3]
> 
> should be turned into [1]. That negative lookbehind can do the job in 
> the large majority of the cases (by not matching URLs if they're 
> preceded by single or double quotes or by ">"), but not always since it 
> doesn't allow the lookbehind to be non-fixed length. I think one of the 
> parser modules might be able to help (?) but regardless of how much I 
> try, I can't get the hang of them, while I do somewhat understand regexes.
> 
> Andrei
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From idiot1 at netzero.net  Tue Aug 26 22:00:48 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Tue Aug 26 21:01:24 2003
Subject: [Tutor] Thank you
In-Reply-To: <000d01c36c2e$cf0df640$b84c73d5@BAERBAR>
References: <000d01c36c2e$cf0df640$b84c73d5@BAERBAR>
Message-ID: <3F4C02C0.8040400@netzero.net>

So   often it give you a gentle nudge in the right direction- and sometimes a 
good hard SHOVE. I love this community!


Ole Jensen wrote:

> I just want to thank the tutor, for beeing such a good tool. It seems 
> that whenever I have a problem with my code. And I finally give up and 
> write a mail to you, then when I'm halfway through the mail I solve the 
> problem my self...
>  
> So, thank you.
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Promethieus
  +                              think                                +

Fnord.


From tim at johnsons-web.com  Tue Aug 26 18:57:06 2003
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue Aug 26 21:57:39 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <20030827002535.GA268@Joss>
References: <0E5508EBA1620743B409A2B8365DE16FDC8793@SOVEREIGN>
	<20030827002535.GA268@Joss>
Message-ID: <20030827015706.GP3712@johnsons-web.com>

> > If all you need simple singly-linked-list functionality for a project you're
> 
> I don't need it, I want it. I am trying to learn.
 
  I think that the productivity of python has to do with the
  fact that it 'manages' some of these issues.
  
  Python is written in C, and it is in looking a C code that
  you can learn about linked lists.

  Thomas Niemann has a nice site at
  http://www.planetoid.org/technical/sort_cookbook/

  and I believe that his Red-Black Trees implementation
  may have been used (at least indirectly) to influence
  some python add-ons.

  Regardless, if you look at his section on Skip Lists,
  you will see some information on single-linked lists,
  it's really a well-laid-out tutorial.

  There is lots of reference to double linked lists on
  the internet 
   I briefly scanned this one at:
   http://www.geocities.com/SiliconValley/Lakes/7504/old_stuff/Dlist.html

   thoroughly documented but I didn't run the code :-)
   tj

> 
> > >>> dir(list)
> > ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
> > '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
> > '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
> > '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
> > '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__',
> > '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert',
> > 'pop', 'remove', 'reverse', 'sort']
> 
> Umm I know. Maybe I should look at the implementation. There is this
> linked list project at sf, that I forgot the url of, but it's too obtuse
> for me.
> 
> > Now if it were a doubly-linked list, I think that would be another
> > matter....
> 
> Ok, how would you do a doubly-linked list?
> 
> Thanks,
> sukrit
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com

From carroll at tjc.com  Tue Aug 26 21:19:37 2003
From: carroll at tjc.com (Terry Carroll)
Date: Tue Aug 26 23:19:41 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <20030827002535.GA268@Joss>
Message-ID: <Pine.LNX.4.44.0308262017040.32491-100000@mauve.rahul.net>

On Wed, 27 Aug 2003, Sukrit K Mehra wrote:

> On Tue, Aug 26, 2003 at 03:48:22PM -0700, Scott Widney wrote:
>  
> > If all you need simple singly-linked-list functionality for a project you're
> 
> I don't need it, I want it. I am trying to learn.

You might find http://www.ibiblio.org/obp/thinkCSpy/chap17.htm helpful.

> Ok, how would you do a doubly-linked list?

Doubly-link lists are almost the same except that, in addition to each 
node ccontaining a pointer to the next node, each node also contains a 
pointer to the previous node.  


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 27 01:53:28 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 27 03:53:38 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <20030827002535.GA268@Joss>
Message-ID: <Pine.LNX.4.44.0308270051180.1508-100000@hkn.eecs.berkeley.edu>



On Wed, 27 Aug 2003, Sukrit K Mehra wrote:

> On Tue, Aug 26, 2003 at 03:48:22PM -0700, Scott Widney wrote:
>
> > If all you need simple singly-linked-list functionality for a project
> > you're
>
> I don't need it, I want it. I am trying to learn.

Hi Sukrit,

Have you had a chance to look at:

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

yet?  There's a chapter on linked lists that you might like:

    http://www.ibiblio.org/obp/thinkCSpy/chap17.htm

Please feel free to ask questions on Tutor; we'll be happy to chat about
linked lists.  *grin*


From alex at gabuzomeu.net  Wed Aug 27 11:08:41 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Wed Aug 27 04:08:39 2003
Subject: [Tutor] Python on Windows and other processes
In-Reply-To: <20030826182154.31761.qmail@web41612.mail.yahoo.com>
References: <20030826182154.31761.qmail@web41612.mail.yahoo.com>
Message-ID: <3F4C6709.7010301@gabuzomeu.net>

Hi Alan,

Alan Colburn wrote:

>I was working on a web page today (on a WinXP machine)
>and took a little break with Python. (Doesn't
>everyone?!) When I closed IDLE and went back to
>Dreamweaver, I got this odd message:
>
>"This file has been modified outside Dreamweaver. Do
>you want to reload it?"
>
I remember getting this message fairly often when I was working in DW. 
It seemed to appear when a DW window got the focus again after loosing 
it. I'm not sure it's Python-related.

>Does Python actually do stuff in the background that
>might interfere with other programs, or am I simply in
>the Twilight Zone?
>
Sounds like the Twilight Zone to me :-)


Cheers.

Alexandre




From alex at gabuzomeu.net  Wed Aug 27 11:32:05 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Wed Aug 27 04:31:57 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <20030827002535.GA268@Joss>
References: <0E5508EBA1620743B409A2B8365DE16FDC8793@SOVEREIGN>
	<20030827002535.GA268@Joss>
Message-ID: <3F4C6C85.2080802@gabuzomeu.net>

Hello Sukrit,


Sukrit K Mehra wrote:

>> On Tue, Aug 26, 2003 at 03:48:22PM -0700, Scott Widney wrote: 
>  
>
>>> If all you need simple singly-linked-list functionality for a project
>>
>>I don't need it, I want it. I am trying to learn.
>>

For examples of linked list, see also these messages:

http://mail.python.org/pipermail/tutor/2002-April/014011.html

http://mail.python.org/pipermail/tutor/2002-April/014014.html

http://mail.python.org/pipermail/tutor/2002-April/014039.html

http://mail.python.org/pipermail/tutor/2002-April/014085.html


Cheers.

Alexandre




From john at rte.ie  Wed Aug 27 09:43:42 2003
From: john at rte.ie (John Moylan)
Date: Wed Aug 27 04:43:44 2003
Subject: [Tutor] checking for a process
Message-ID: <1061973782.2308.44.camel@localhost.localdomain>

Hi, 
 
I have written a script for Linux that I want to have run from Crontab every 3 
minutes. But I don't want to run a new copy of the script if another is still 
running. With BASH I would put something like the following at the start of my 
script: 
 
if [ -e $PIDFILE ] && ps >/dev/null -p `cat $PIDFILE`; do 
	exit 
else 
	echo $$ > $PIDFILE 
. 
. 
. 
.(script) 
. 
rm $PIDFILE 
 
The problem is that I don't want to have to create a BASH wrapper script 
around my python script ....but I can't find any way of finding out if a 
process is running ala the ps bit of my script above...without spawning a 
shell. Is there any way to do this natively in Python? or is there a better 
way of creating the same functionality in Python? 
 
Kind Regards, 
John Moylan 
 
John Moylan 
RTE Technology 
Donnybrook, 
Dublin 4. 
+353 1 2083564 


******************************************************************************
The information in this e-mail is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this e-mail by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in reliance
on it, is prohibited and may be unlawful.
Please note that emails to, from and within RTÉ may be subject to the Freedom
of Information Act 1997 and may be liable to disclosure.
******************************************************************************

From ATrautman at perryjudds.com  Wed Aug 27 09:48:13 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Wed Aug 27 09:49:15 2003
Subject: [Tutor] Python on Windows and other processes
Message-ID: <06738462136C054B8F8872D69DA140DB0108C7@corp-exch-1.pjinet.com>





Hi Alan,

Dreamweaver used to, don't know about MX, maintain an ftp link on the system
http processes to see if any of it's managed pages have changed. I think it
possible that you have used the newer Python help pages that are provided
through http. Dreamweaver may be trying to "manage" that system as a site.
This would be a change to its site and it asks you if you want to save. It
doesn't really do any harm but I remember having problems maintain
separation between a site we managed manually and a dreamweaver site. I
believe it's another case of software being "helpful" unless you use it the
way they want.

I wouldn't worry about it but you can check dreamweaver's ftp managed pages
and make sure that none of your Python pages are in there.

HTH,
Alan

Alan Colburn wrote:

>I was working on a web page today (on a WinXP machine)
>and took a little break with Python. (Doesn't
>everyone?!) When I closed IDLE and went back to
>Dreamweaver, I got this odd message:
>
>"This file has been modified outside Dreamweaver. Do
>you want to reload it?"
>
I remember getting this message fairly often when I was working in DW. 
It seemed to appear when a DW window got the focus again after loosing 
it. I'm not sure it's Python-related.

>Does Python actually do stuff in the background that
>might interfere with other programs, or am I simply in
>the Twilight Zone?
>
Sounds like the Twilight Zone to me :-)


Cheers.

Alexandre




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

From VICKI.STANFIELD at ROCHE.COM  Wed Aug 27 10:58:59 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Wed Aug 27 11:32:45 2003
Subject: [Tutor] Locating Serial module
Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E68@ridmsem02.nala.roche.com>

When I began working with serial com in Python, I tried several different packages. I think I finally ended up using the Sioserial stuff for Python 2.2 (which is what I have). I do not use Windows often but am doing this code on a Windows 2000 system. I wanted to verify what Serial module I am using, so I looked at the Add/Remove Programs and found two: Python 2.2 combined Win32 extensions and Python 2.2 pyserial-1.18. I also have wxPython 2.4.0.7 for Python 2.2 and of course Python 2.2. I (think) I need to determine which serial module I am using since I want to find documentation on the write command. I attempted to remove the Serial folder under my Python2.2 directory and my program still runs. Doesn't that mean that that is not the one I am using? Does wxPython by chance come with serial built in? I'm not really sure on a Windows system how to determine which is being used. 

The import statement that I am using is:

from wxPython.wx import *
import os, string, serial

The port is opened thusly:

port = serial.Serial(0, 9600, 8, 'N', 2, timeout=60)

Doesn't this mean that there should be a serial.py file on my system which contains a function Serial?

I apologize for my naivete.

--vicki
        

Best Regards,
--vicki stanfield


From yduppen at xs4all.nl  Wed Aug 27 18:43:12 2003
From: yduppen at xs4all.nl (Yigal Duppen)
Date: Wed Aug 27 11:43:32 2003
Subject: [Tutor] Locating Serial module
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355E68@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F355E68@ridmsem02.nala.roche.com>
Message-ID: <200308271743.12868.yduppen@xs4all.nl>

> Doesn't this mean that there should be a serial.py file on my system
> which contains a function Serial?

That, or a file called serial.pyc (compiled).

But using the interpreter, you can see directly where a module comes from:

Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys
<module 'sys' (built-in)>
>>> import types;
>>> types
<module 'types' from '/usr/lib/python2.2/types.pyc'>
>>>

So in your case, "import serial", followed by "serial" might do the trick.

Regards,
YDD

From pythontutor at venix.com  Wed Aug 27 13:02:14 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Aug 27 12:03:58 2003
Subject: [Tutor] __all__ cf. _foo, _bar, etc.
In-Reply-To: <Pine.LNX.4.44.0308230024410.5954-100000@mauve.rahul.net>
References: <Pine.LNX.4.44.0308230024410.5954-100000@mauve.rahul.net>
Message-ID: <3F4CD606.6080105@venix.com>

The documentation matches what you've written.

You can test things using the dir function.  If you start a python
session and type dir() you will get a list of the names defined in
your namespace.  This should be something along the lines of:
['__builtins__', '__doc__', '__name__']

Now do:
from ModuleName import *
and then type:
dir()
You will get the names that have been added to your namespace along with
the original names.  This should allow you to verify that import is
loading the names that you expect.

Terry Carroll wrote:

> I'm trying to get straight about the difference and interaction between 
> the __all__ variable and the prefixing a variable name with a single 
> underscore (e.g., _foo, _bar).
> 
> My understanding is that if you code:
> 
>  from ModuleName import *
> 
> if __all__ is initialized in the module, all of the names listed in that 
> list are made available; if __all_ is not initialized, every name not 
> beginning with an underscore is made available.
> 
> If you code:
> 
>  import ModuleName
> 
> Neither the __all__ or the underscore-prefixed names make any difference, 
> because the names from the module are not made available except through an 
> explicit reference to them (e.g., ModuleName.spam), regardless of whether 
> __all__ was initialized or whether the variable is prefixed with an 
> underscore (i.e., you can reference ModuleName._spam if you wish, but of 
> course do so at your own risk).
> 
> Is this correct?
> 
> If I understand this right, then, if the coder of a module initializes
> __all__, he need not worry about the _foo convention;  the __all_
> overrides that for the "from ModuleName import *"  form of import, and the
> importing namespace is unaffected if using the "import ModuleName" form.
> 
> Right?
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From tpc at csua.berkeley.edu  Wed Aug 27 10:09:02 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Wed Aug 27 12:09:12 2003
Subject: [Tutor] Thank you
In-Reply-To: <000d01c36c2e$cf0df640$b84c73d5@BAERBAR>
Message-ID: <20030827090411.T48857-100000@localhost.name>


Word to the mother, peer review can be helpful, the preparation for peer
review even more so to debugging code.  You guys rock, even though more
than half the time you don't even know you've helped me through.

On Wed, 27 Aug 2003, Ole Jensen wrote:

> I just want to thank the tutor, for beeing such a good tool. It seems that whenever I have a problem with my code. And I finally give up and write a mail to you, then when I'm halfway through the mail I solve the problem my self...
>
> So, thank you.
>


From john at rte.ie  Wed Aug 27 17:18:13 2003
From: john at rte.ie (John Moylan)
Date: Wed Aug 27 12:18:20 2003
Subject: [Tutor] checking for a process
In-Reply-To: <20030827085518.GA25231@digitalanytime.com>
References: <1061973782.2308.44.camel@localhost.localdomain>
	<20030827085518.GA25231@digitalanytime.com>
Message-ID: <1062001054.2308.518.camel@localhost.localdomain>

This looked like a usefull but really dirty hack at first, on on later
inspection - it will probably have the effect of not allowing the script
to run if the same file is open in an editor or in less somewhere else
on the system.

so I wrote the following class to check /proc to see if a process is
running:

class IsPidRunning:
    def __init__(self,pidfile="/var/run/enc.pid"):
        self.pidfile = pidfile

    def set_pidfile(self,pidfile):
        self.pidfile = pidfile

    def doesitexist(self):
        if  os.path.exists(self.pidfile):
            pidf = open(self.pidfile, 'r')

            if os.path.exists('/proc/'+pidf.read()):
                print "Script already running"
                sys.exit()
            else: self.writepid()
        else: self.writepid()

    def writepid(self):
        pidf = open(self.pidfile, 'w')
        pid = os.getpid()
        print pid
        pidf.write(str(pid))
        pidf.close()


John


On Wed, 2003-08-27 at 09:55, David Dorgan wrote:
> Quoting John Moylan (john@rte.ie):
> > The problem is that I don't want to have to create a BASH wrapper script 
> > around my python script ....but I can't find any way of finding out if a 
> > process is running ala the ps bit of my script above...without spawning a 
> > shell. Is there any way to do this natively in Python? or is there a better 
> > way of creating the same functionality in Python? 
> 
> 
> If you want a real awful hack, but probably
> a little better than what you have, use popen2,
> run ps aux | grep -v grep | grep -c whatever  
> 
> if the return is greater than 0, it's running,
> else, run it.
-- 
John Moylan
----------------------
Radio Telefis Eireann,
Donnybrook,
Dublin 4,
Eire
t:+353 1 2083564
e:john.moylan@rte.ie



******************************************************************************
The information in this e-mail is confidential and may be legally privileged.
It is intended solely for the addressee.  Access to this e-mail by anyone else
is unauthorised.  If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in reliance
on it, is prohibited and may be unlawful.
Please note that emails to, from and within RTÉ may be subject to the Freedom
of Information Act 1997 and may be liable to disclosure.
******************************************************************************

From VICKI.STANFIELD at ROCHE.COM  Wed Aug 27 12:58:16 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Wed Aug 27 13:07:12 2003
Subject: [Tutor] Locating Serial module
Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E69@ridmsem02.nala.roche.com>

Okay. Thanks. I got back the following:

<module 'serial' from 'C:\Python22\lib\site-packages\serial\__init__.pyc'>

so I guess that means that I am using serial via the init under that directory instead of any of the 4 serial.py files on my system. No wonder I couldn't find it. 

Thanks.
--vicki


-----Original Message-----
From: Yigal Duppen [mailto:yduppen@xs4all.nl]
Sent: Wednesday, August 27, 2003 10:43 AM
To: tutor@python.org
Subject: Re: [Tutor] Locating Serial module


> Doesn't this mean that there should be a serial.py file on my system
> which contains a function Serial?

That, or a file called serial.pyc (compiled).

But using the interpreter, you can see directly where a module comes from:

Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys
<module 'sys' (built-in)>
>>> import types;
>>> types
<module 'types' from '/usr/lib/python2.2/types.pyc'>
>>>

So in your case, "import serial", followed by "serial" might do the trick.

Regards,
YDD

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

From riccardo at reflab.it  Wed Aug 27 20:07:36 2003
From: riccardo at reflab.it (Riccardo Lemmi)
Date: Wed Aug 27 13:09:44 2003
Subject: [Tutor] Re: checking for a process
References: <1061973782.2308.44.camel@localhost.localdomain>
Message-ID: <biiog2$2mh$1@sea.gmane.org>

John Moylan wrote:

> Hi,
>  
> I have written a script for Linux that I want to have run from Crontab
> every 3 minutes. But I don't want to run a new copy of the script if
> another is still running. With BASH I would put something like the
> following at the start of my script:
>  ...

This is a very simple example but it do the job, modify the 'main wait' with 
t=180 (3 minutes) and substitute wait(...,'exec id') with your code:

import time
import thread

def time_stamp():
  return time.strftime("%H:%M:%S", time.gmtime())

def wait(t=10, msg=''):
  print "%s start at %s"%(msg, time_stamp())
  time.sleep(t)
  print "%s done at %s"%(msg,time_stamp())


def loop_function(mtx):
  id = thread.get_ident()
  acq = 0
  while not acq:
    acq = mtx.acquire(1)
  #Note: substituite 'wait' with your code
  wait(t= 30, msg="exec id: %s"%id)
  mtx.release()
  thread.exit()


if __name__=="__main__":
  mtx = thread.allocate_lock()
  for i in range(1,10):
    print "start:",thread.start_new_thread(loop_function,(mtx,))
    wait(t=10, msg='main wait')

-- 

                             Riccardo Lemmi


From dyoo at hkn.eecs.berkeley.edu  Wed Aug 27 12:18:40 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Aug 27 14:18:48 2003
Subject: [Tutor] uploading files [cgi/cgitb/form file uploads]
In-Reply-To: <3F4CD216.2090103@netzero.net>
Message-ID: <Pine.LNX.4.44.0308271048030.27568-100000@hkn.eecs.berkeley.edu>



On Wed, 27 Aug 2003, Kirk Bailey wrote:

> Danny, I am not getting anywhere on this uploader thing; I am stumped.
> Can you advise me please?


Hi Kirk,


Please don't email me personally with questions, but send them to the
Tutor list.  The reasons for this are listed under:

    http://www.catb.org/~esr/faqs/smart-questions.html#uselists



Have you been able to use the 'file' attribute of the 'uservalue'?  In
your original source, you have:

    data = form['userfile'].value
    filedata = form.getvalue('userfile','')


According to the text near the bottom of:

    http://www.python.org/doc/lib/node403.html


you may really want to use:

    userfile = form['userfile'].file
    filedata = userfile.read()

to grab the file object out.





> > it's a lot, but not in anything I can manipulate, or use. TAKE A LOOK.
> > it will abort before writing anything to my server. See if you have a
> > clue you can spare me.

Ok, so this sounds more of a debugging problem now.  We need to isolate
the problem.  Is the script really exiting prematurely, or is it running
to completion?  Is an exception being thrown midway, and if so, where?


These are the things we need to find out.  Have you tried using the
'cgitb' module?

    http://www.python.org/doc/lib/module-cgitb.html



If you're still running Python 1.52, you may need to get the original
sources from:

    http://lfw.org/python/inspect.py
    http://lfw.org/python/pydoc.py
    http://lfw.org/python/cgitb.py

In either case, using cgitb should provide a lot more diagnostic
information to help us figure out what's happening.




> print 'form=',form,'<P>That\'s the entire thing recovered from the
> cgi.FieldStorage() object.<P>'
> print 'the form has these keys:',form.keys(),'<P>'
> print 'we assign to "data" the value form[\'userfile\'].value and
> get:<br>'
> print 'data has this in it:',data,'<P>'


Finally, it might be good to avoid printing out the form or the 'data'
literally to the browser.  It appears that you're reading in image files,
and sending that kind of binary data to a browser that is expecting HTML
text may confuse it.  It's also too much information.  *grin*

You may want to simplify this to:

    print '''
          form keys: %s form data length: %s
          ''' % (form.keys(), len(data))



From speno at isc.upenn.edu  Wed Aug 27 15:43:32 2003
From: speno at isc.upenn.edu (John P Speno)
Date: Wed Aug 27 14:43:37 2003
Subject: [Tutor] buffering IO
In-Reply-To: <20030825033450.GL27693@station>
References: <20030825004416.GK27693@station>
	<20030825025451.GA9465@isc.upenn.edu>
	<20030825033450.GL27693@station>
Message-ID: <20030827184332.GA11969@isc.upenn.edu>

On Mon, Aug 25, 2003 at 07:34:50AM +0400, Denis Dzyubenko wrote:
> How should I launch python-program in this case - should I use
> 'popen("/usr/bin/python2.2 -u /tmp/pychat.py")' or there is another way
> to launch it?

That makes it look like you're trying to start your program inside of
another applications (maybe in C?). That looks like it will work. You can
also probably edit the shbang line in your pychat.py script to be:

    #!/usr/bin/python2.2 -u

From alan.gauld at blueyonder.co.uk  Wed Aug 27 21:56:02 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug 27 15:57:05 2003
Subject: [Tutor] creating a list of data . . . 
References: <184.1f8aff73.2c7c0b15@aol.com>
	<0b6201c36b74$b9a51cd0$8f10ba3f@defaultcomp>
Message-ID: <005001c36cd5$3e5927d0$6401a8c0@xp>

> As Kurt has pointed out, tuples are immutable: once they're created,
they
> can't be modified. They can, however, be rebound:

And just to make it clear what rebvound means in practice:

> someTuple = ()

The above creates a reference to an empty tuple.

> for i in range(10):
>     someTuple = someTuple + (i,)

Inside the loop we then create 2 new tuples.
The first is (i,) a single element one, which is
added to the existing tuple to create the second
new tuple comprising the combined data.

Thus in the above example we create a total of 21 tuples!

> Lists, on the other hand,  _are_ mutable, so it's often cleaner
> (and more efficient) to build a list and then convert it to
> a tuple when you're done:

The efficiency coming from the fact that you only have 1 list
which we manipulate instead of creating 21 distinct tuples!

Alan G.


From alan.gauld at blueyonder.co.uk  Wed Aug 27 22:04:25 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug 27 16:04:47 2003
Subject: [Tutor] Thank you
References: <000d01c36c2e$cf0df640$b84c73d5@BAERBAR>
Message-ID: <008701c36cd6$6a548130$6401a8c0@xp>

> I just want to thank the tutor, for being such a good tool. 
> ...whenever I have a problem with my code. And .... write a 
> mail to you, then ... I solve the problem my self...

Wow, that is a good tool, I wish Microsoft had one that worked 
like that! :-)

Alan G.

From alan.gauld at blueyonder.co.uk  Wed Aug 27 22:18:44 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Aug 27 16:36:37 2003
Subject: [Tutor] checking for a process
References: <1061973782.2308.44.camel@localhost.localdomain>
Message-ID: <00b001c36cd8$6a1ce480$6401a8c0@xp>

JOhn,

There are python tools you can use to check processes
in the os module. However really you are just using the 
PID to create a temporary file to act as a lock. 
You can do that with any file provided you keep the 
name consistent and just check for its existence.

> ....but I can't find any way of finding out if a 
> process is running ala the ps bit of my script above...
> without spawning a shell. 

You were spawning an extra shell in your Bash script too 
with the `cat` command...

In summary you can just create a lock file and check 
for its existence, or you can replicate your Bash approach 
using PIDs if thats what you really want, for example 
writing the pid to the file using os.getpid() and then 
using os.waitpid() on the content. Alternatively use 
os.popen() to run a ps and search the resulting list 
for the pid.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From zak at harlekin-maus.com  Wed Aug 27 15:25:00 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Wed Aug 27 17:25:10 2003
Subject: [Tutor] Copying a list?
In-Reply-To: <Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
References: <BB653BD3.C000%clay@shirky.com>
	<Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
Message-ID: <2486.192.206.201.218.1062019500.squirrel@mail.harlekin-maus.com>

I feel pretty silly asking this, but is there a way to quickly copy a
list? I'd love to be able to type:

###
>>> a = [1,2,3]
>>> b = a
###

But that's a pass-by-reference. The quickest thing that comes to mind is:

###
>>> a = [1,2,3]
>>> b = [i for i in a]
###

Which is okay, but not as obvious as, say:

###
>>> a = [1,2,3]
>>> b= a.__copy__()
###

or something. Am I forgetting something?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From pythontutor at venix.com  Wed Aug 27 18:31:50 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Aug 27 17:32:24 2003
Subject: [Tutor] translating some python code to perl
Message-ID: <3F4D2346.4020605@venix.com>

I need to provide the contents of a python dictionary to a perl
programmer as a perl hash table.  However, the python dictionary
contains dictionaries, and I have been unable to figure out the perl
syntax for nexting and referencing hash tables.

Here's a python sample:
#python
d1 = {'1': 'one',
     '2': 'two',
     'd2': {'nest1': 'nest one',
         'nest2': 'nest two',}
}
d1['1'] # returns 'one'
d1['d2'] # returns the d2 hash
d1['d2']['nest1'] # returns 'nest one'

Here is my attempted perl equivalent:
#!/usr/bin/perl
# testhash.pl

%d1 = (
     '1' => 'one',
     '2' => 'two',
     %d2 = ('nest1' => 'nest one',
     	'nest2' => 'nest two',)
     );

print "\nlookup 1 in d1: $d1{'1'}\n";
print "\nlookup d2 within d1: %d1{'d2'}\n";
print "\nlookup nest1 in d2 within d1: $d1{d2}{'nest1'}\n";
###end of perl script

$d1{'1'} returns the scalar 'one'

So that's as far as I was able to go.  I am not sure if my hash table
is correct.

Please help me fix the hash table definition and the references so that
I can verify that it works.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From bgailer at alum.rpi.edu  Wed Aug 27 16:53:31 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed Aug 27 17:55:22 2003
Subject: [Tutor] Copying a list?
In-Reply-To: <2486.192.206.201.218.1062019500.squirrel@mail.harlekin-mau s.com>
References: <Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
	<BB653BD3.C000%clay@shirky.com>
	<Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
Message-ID: <5.2.1.1.0.20030827155015.04240ea8@66.28.54.253>

At 02:25 PM 8/27/2003 -0700, Zak Arntson wrote:

>I feel pretty silly asking this, but is there a way to quickly copy a
>list? I'd love to be able to type:
>
>###
> >>> a = [1,2,3]
> >>> b = a
>###
>
>But that's a pass-by-reference. The quickest thing that comes to mind is:
>
>###
> >>> a = [1,2,3]
> >>> b = [i for i in a]
>###
>
>Which is okay, but not as obvious as, say:
>
>###
> >>> a = [1,2,3]
> >>> b= a.__copy__()
>###
>
>or something. Am I forgetting something?

Can't answer that, as we don't know what you formerly remembered.

To the original question:
b = a[:]
OR b = list(a)

Note that these are "shallow" copies; any object reference in the list will 
be copied as is. See the copy module for deepcopy and more comments on copying.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003
From pythontutor at venix.com  Wed Aug 27 18:58:51 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Aug 27 17:59:31 2003
Subject: [Tutor] Copying a list?
In-Reply-To: <2486.192.206.201.218.1062019500.squirrel@mail.harlekin-maus.com>
References: <BB653BD3.C000%clay@shirky.com>	<Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
	<2486.192.206.201.218.1062019500.squirrel@mail.harlekin-maus.com>
Message-ID: <3F4D299B.5010202@venix.com>

import copy
b = copy.copy(a)

This is a "shallow" copy.  b is a new list, but contains the same
elements as a.  For your example with numeric (immutable) elements
this is fine.  If a contains mutable elements, and you wish b to
have COPIES of those mutable elements then:

b = copy.deepcopy(a)

This handles the case where:
a = [ [], [] ,[], ]
after the deepcopy, b will have its own set of empty lists.

Zak Arntson wrote:

> I feel pretty silly asking this, but is there a way to quickly copy a
> list? I'd love to be able to type:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b = a
> 
> ###
> 
> But that's a pass-by-reference. The quickest thing that comes to mind is:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b = [i for i in a]
> 
> ###
> 
> Which is okay, but not as obvious as, say:
> 
> ###
> 
>>>>a = [1,2,3]
>>>>b= a.__copy__()
> 
> ###
> 
> or something. Am I forgetting something?
> 
> ---
> Zak Arntson
> www.harlekin-maus.com - Games - Lots of 'em
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From zak at harlekin-maus.com  Wed Aug 27 16:16:48 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Wed Aug 27 18:16:52 2003
Subject: [Tutor] Copying a list?
In-Reply-To: <3F4D299B.5010202@venix.com>
References: <BB653BD3.C000%clay@shirky.com>	<Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
	<2486.192.206.201.218.1062019500.squirrel@mail.harlekin-maus.com>
	<3F4D299B.5010202@venix.com>
Message-ID: <2705.192.206.201.218.1062022608.squirrel@mail.harlekin-maus.com>

> import copy
> b = copy.copy(a)
>
<SNIP!>
> --
> Lloyd Kvam
> Venix Corp.

I want to keep the elements as references. Sorry about that, I should've
pointed out my situation:

I am creating a GUI, which consists of AppObjects with children. For
drawing the objects, I want to go through the list of children in normal
order. So that's easy:

###
class GraphicObject(AppObject):

def draw(self):
    for child in self.children:
        if isinstance(child, GraphicObject):
            child.draw()
    self._draw()
###

But for event handling, I want the object on the "top" (meaning drawn
LAST, so it's on top of all other objects), to be first to get the event.

###
import copy

class AppObject:

def handle(self, event):
    event_children = copy.copy(self.children)
    event_children.reverse()

    for child in event_children:
        child.handle(event)

    self._handle(event)
###

Does that make sense?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From pythontutor at venix.com  Wed Aug 27 19:37:01 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Aug 27 18:37:42 2003
Subject: [Tutor] Copying a list?
In-Reply-To: <2705.192.206.201.218.1062022608.squirrel@mail.harlekin-maus.com>
References: <BB653BD3.C000%clay@shirky.com>	<Pine.LNX.4.44.0308172013460.26899-100000@hkn.eecs.berkeley.edu>
	<2486.192.206.201.218.1062019500.squirrel@mail.harlekin-maus.com>
	<3F4D299B.5010202@venix.com>
	<2705.192.206.201.218.1062022608.squirrel@mail.harlekin-maus.com>
Message-ID: <3F4D328D.5050001@venix.com>

That looks OK to me.  Bob's suggestion of b = a[:] avoids importing
the copy module.  This is good, so long as you're comfortable using
slice notation to signify a copy.  Personally, I would not use list(a)
to get a copy simply because it looks more like a transformation (e.g.
turning a tuple into a list).

(I keep my pythontutor email folder sorted by thread.  When someone
simply repliese to another email - even if they change the subject,
the email gets added to the original thread.  I assume that this
would also apply to the mail-list archives.  It's better to start
a new thread with a new message.  Add tutor@python.org to your address
book if you have to.)

Zak Arntson wrote:

> import copy
> 
> class AppObject:
> 
> def handle(self, event):
>     event_children = copy.copy(self.children)
>     event_children.reverse()
> 
>     for child in event_children:
>         child.handle(event)
> 
>     self._handle(event)
> ###
> 
> Does that make sense?
> 
> ---
> Zak Arntson
> www.harlekin-maus.com - Games - Lots of 'em
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From shalehperry at comcast.net  Wed Aug 27 18:26:25 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 27 20:42:22 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
In-Reply-To: <20030825195241.2712.qmail@web41608.mail.yahoo.com>
References: <20030825195241.2712.qmail@web41608.mail.yahoo.com>
Message-ID: <200308271726.25017.shalehperry@comcast.net>

On Monday 25 August 2003 12:52, Alan Colburn wrote:
> I'd like to start learning about how to write
> web-based Python scripts. My campus server, however,
> will not support Python--just Perl and CGI. So, I'm
> assuming my best option is to run a small server from
> my (WindowsXP) desktop. The rest of my web site will
> remain where it is, and I'll simply link to the
> scripts running of my desktop; only the script based
> pages will run off the desktop. I only anticipate
> needing the scripts during select parts of the
> academic year. The rest of the time the desktop-based
> server does not need to be on.
>

Or you could just code it up in perl .......

Yeah I know, we all like Python.  But sometimes you have the choice between 
getting the job done and not.

Or you could always ask them to install Python.  It is dirt easy since usually 
the admin can just install a package made for their system.  Takes about as 
long to install as it does to download.


From shalehperry at comcast.net  Wed Aug 27 18:49:33 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 27 20:50:08 2003
Subject: [Tutor] Linked Lists
In-Reply-To: <20030826163723.GA332@Joss>
References: <20030826163723.GA332@Joss>
Message-ID: <200308271749.33393.shalehperry@comcast.net>

On Tuesday 26 August 2003 09:37, Sukrit K Mehra wrote:
>
> mylist = linked()
> #initialize list, that is have a class named linked
>
> and have following methods (or functions if you will)
>
> addbeginning(x) #to add an element at beginning
> addposition(x, pos) #to add an elemnt at specified position
> addend(x) #to add at end
> print() #to print
> sort() #to sort
> search() #to search
>
> ... and so forth.
>

ok, obviously (right?) you know about Python's built in list construct.

mylist = list() # or [] for the older than 2.3 releases
mylist.append('123')
mylist.insert(3, 'bar')
print mylist
mylist.sort() # note this is destructive and does NOT return the list
mylist.index('123')

So, that said, it can still be fun to make you own stuff.

> Questions
>
> I am having trouble with the basic structure of the list. I
> understand that you need a node, so I have a node
> class Node:
>     def __init__(self, data=NULL, next=NULL):
>         self.next = next
>         self.data = data
>
> I don't know how to make a list class
>

In languages like C you do this by using pointers.

NodeType* head;
NodeType* next = NULL;

head = &mynode;
/* fill up the list */

for(next = head->next; next; next = head->next) { /* or use a do .. while */
    printNode(next);
}

We can be sneaky and use Python's shallow copy semantics though .....

class Node:
  def __init__(self, data=None, next=None):
    self.next = next
    self.data = data

  def __repr__(self):
    return self.data

class MyList:
  def __init__(self):
    self.head = None
    self.tail = self.head

  def append(self, node):
    if self.tail is None:
      self.tail = node
      self.head = self.tail
    else:
      self.tail.next = node
      self.tail = node
    node.next = None

  def walk(self, func):
    item = self.head
    while item is not None:
      print item
      item = item.next

def printer(item):
  print item

mylist = MyList()

print 'add foo'
node = Node('foo')
mylist.append(node)
mylist.walk(printer)

print 'add bar'
node = Node('bar')
mylist.append(node)
mylist.walk(printer)

print 'add baz'
node = Node('baz')
mylist.append(node)
mylist.walk(printer)

Note, you probably do not want to use this in real code, but for learning 
exercises it can be fun.

You get to implement the other functions (and try to figure out how append() 
works).


From carroll at tjc.com  Wed Aug 27 20:23:38 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Aug 27 22:23:42 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
In-Reply-To: <200308271726.25017.shalehperry@comcast.net>
Message-ID: <Pine.LNX.4.44.0308271922540.32491-100000@mauve.rahul.net>

On Wed, 27 Aug 2003, Sean 'Shaleh' Perry wrote:

> [Python] Takes about as long to install as it does to download.

Yeah, I used to have an ISP like that, too.

-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From shalehperry at comcast.net  Wed Aug 27 21:56:31 2003
From: shalehperry at comcast.net (Sean 'Shaleh' Perry)
Date: Wed Aug 27 23:57:07 2003
Subject: [Tutor] [slightly ot]python, web servers, and learning cgi
In-Reply-To: <Pine.LNX.4.44.0308271922540.32491-100000@mauve.rahul.net>
References: <Pine.LNX.4.44.0308271922540.32491-100000@mauve.rahul.net>
Message-ID: <200308272056.31188.shalehperry@comcast.net>

On Wednesday 27 August 2003 19:23, Terry Carroll wrote:
> On Wed, 27 Aug 2003, Sean 'Shaleh' Perry wrote:
> > [Python] Takes about as long to install as it does to download.
>
> Yeah, I used to have an ISP like that, too.

Can't tell if you meant that in a good way or a bad way (-:  Miss having 
bandwidth or did it take hours for anything?

If they run most any flavor of linux python is as far away as:

package_thingy --install python.package

The BSD's have it in ports.  So you might have to wait for it to compile.


From klhjhm at hotmail.com  Thu Aug 28 17:18:07 2003
From: klhjhm at hotmail.com (kamariah lamim)
Date: Thu Aug 28 04:18:54 2003
Subject: [Tutor] cp file
Message-ID: <BAY1-F76RIqVDokSUIw00001f1e@hotmail.com>

i want to copy a file from current directory to another directory using 
shutil . However , it failed giving error:
File "/usr/lib/python2.2/shutil.py", line 29, in copyfile
    fdst = open(dst, 'wb')
IOError: [Errno 21] Is a directory: 'usr_20_0.3_0.2/'

could anyone trace my problem?
this is the code (simple enough as i want to test it before going into 
detailed ):
shutil.copy('disper.exe','usr_20_0.3_0.2/')

_________________________________________________________________
Get MSN 8 and help protect your children with advanced parental controls.  
http://join.msn.com/?page=features/parental


From klhjhm at hotmail.com  Thu Aug 28 17:30:28 2003
From: klhjhm at hotmail.com (kamariah lamim)
Date: Thu Aug 28 04:31:04 2003
Subject: [Tutor] cp file
Message-ID: <BAY1-F110j7XGeFaata00002d86@hotmail.com>

I have solved the problem -  just a typing error ; suppose to be 
user_20_0.3_0.2/ instead of usr_20_0.3_0.2/'



>From: "kamariah lamim" <klhjhm@hotmail.com>
>To: tutor@python.org
>Subject: [Tutor] cp file
>Date: Thu, 28 Aug 2003 16:18:07 +0800
>
>i want to copy a file from current directory to another directory using 
>shutil . However , it failed giving error:
>File "/usr/lib/python2.2/shutil.py", line 29, in copyfile
>    fdst = open(dst, 'wb')
>IOError: [Errno 21] Is a directory: 'usr_20_0.3_0.2/'
>
>could anyone trace my problem?
>this is the code (simple enough as i want to test it before going into 
>detailed ):
>shutil.copy('disper.exe','usr_20_0.3_0.2/')
>
>_________________________________________________________________
>Get MSN 8 and help protect your children with advanced parental controls.  
>http://join.msn.com/?page=features/parental
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Download ringtones, logos and picture messages from MSN Malaysia 
http://www.msn.com.my/mobile/ringtones/default.asp


From knguyen at seri.co.uk  Thu Aug 28 12:20:32 2003
From: knguyen at seri.co.uk (Khai Nguyen)
Date: Thu Aug 28 06:21:38 2003
Subject: [Tutor] Locating Serial module
Message-ID: <341710540F08E34498A057DEE04DAAD7F9E2B4@ex1.seri.co.uk>

Hi,

IF you are not sure about which libray is installed on your system, unix
or PC, you go to the interpreter, or idle and type "modules", without
paranthese, python will display all libs installed on your system.

To receive details of each library you can use import serial etc as
Yigal has described.

Regards

ntk

-----Original Message-----
From: Yigal Duppen [mailto:yduppen@xs4all.nl] 
Sent: Wednesday, August 27, 2003 4:43 PM
To: tutor@python.org
Subject: Re: [Tutor] Locating Serial module


> Doesn't this mean that there should be a serial.py file on my system 
> which contains a function Serial?

That, or a file called serial.pyc (compiled).

But using the interpreter, you can see directly where a module comes
from:

Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys
<module 'sys' (built-in)>
>>> import types;
>>> types
<module 'types' from '/usr/lib/python2.2/types.pyc'>
>>>

So in your case, "import serial", followed by "serial" might do the
trick.

Regards,
YDD

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


*****************************************************************************
The information contained in this email and in any attachments 
may be privileged and confidential.  
The information is designated solely for the attention and use of 
the intended recipient(s).  
If you are not the intended recipient(s), please be aware that any 
disclosure, copying, distribution or use of the contents of this 
information is prohibited. 
If you have received this email in error, please notify the sender 
by telephone or email immediately.
*****************************************************************************


From carroll at tjc.com  Thu Aug 28 12:12:25 2003
From: carroll at tjc.com (Terry Carroll)
Date: Thu Aug 28 14:12:30 2003
Subject: [Tutor] Locating Serial module
In-Reply-To: <341710540F08E34498A057DEE04DAAD7F9E2B4@ex1.seri.co.uk>
Message-ID: <Pine.LNX.4.44.0308281111050.11595-100000@mauve.rahul.net>

On Thu, 28 Aug 2003, Khai Nguyen wrote:

> IF you are not sure about which libray is installed on your system, unix
> or PC, you go to the interpreter, or idle and type "modules", without
> paranthese, python will display all libs installed on your system.

That doesn't work for me.  Is that syntax correct?

 >python
 ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on
 Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> modules
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 NameError: name 'modules' is not defined
 >>>


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From gerrit at nl.linux.org  Thu Aug 28 21:16:16 2003
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Thu Aug 28 14:16:41 2003
Subject: [Tutor] Locating Serial module
In-Reply-To: <Pine.LNX.4.44.0308281111050.11595-100000@mauve.rahul.net>
References: <341710540F08E34498A057DEE04DAAD7F9E2B4@ex1.seri.co.uk>
	<Pine.LNX.4.44.0308281111050.11595-100000@mauve.rahul.net>
Message-ID: <20030828181615.GA29110@nl.linux.org>

<quote name="Terry Carroll" date="1062065545" email="carroll@tjc.com">
> On Thu, 28 Aug 2003, Khai Nguyen wrote:
> > IF you are not sure about which libray is installed on your system, unix
> > or PC, you go to the interpreter, or idle and type "modules", without
> > paranthese, python will display all libs installed on your system.
> 
> That doesn't work for me.
</quote>

You need to type "help modules"

Gerrit.

-- 
Mozilla _is_ the web: it grows faster than you can download it.
1011001 1101111 1110101 1110010 1110011 0101100
1000111 1100101 1110010 1110010 1101001 1110100

From carroll at tjc.com  Thu Aug 28 12:27:04 2003
From: carroll at tjc.com (Terry Carroll)
Date: Thu Aug 28 14:28:25 2003
Subject: [Tutor] Locating Serial module
In-Reply-To: <20030828181615.GA29110@nl.linux.org>
Message-ID: <Pine.LNX.4.44.0308281124000.11595-100000@mauve.rahul.net>

On Thu, 28 Aug 2003, Gerrit Holl wrote:

> <quote name="Terry Carroll" date="1062065545" email="carroll@tjc.com">
> > On Thu, 28 Aug 2003, Khai Nguyen wrote:
> > > IF you are not sure about which libray is installed on your system, unix
> > > or PC, you go to the interpreter, or idle and type "modules", without
> > > paranthese, python will display all libs installed on your system.
> > 
> > That doesn't work for me.
> </quote>
> 
> You need to type "help modules"

Ah, thanks for the hint.  I find that (on my Windows system, at least), 
it's:

  >>> help()

followed by 

  help> modules


-- 
Terry Carroll        |   "I say to you that the VCR is to the American
Santa Clara, CA      |   film producer and the American public as the 
carroll@tjc.com      |   Boston strangler is to the woman home alone."  
                     |       Jack Valenti, MPAA President
Modell delendus est  |       Testimony before Congress, 1982


From pythontutor at venix.com  Thu Aug 28 19:58:52 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Aug 28 19:00:27 2003
Subject: [Tutor] translating some python code to perl
In-Reply-To: <3F4D2346.4020605@venix.com>
References: <3F4D2346.4020605@venix.com>
Message-ID: <3F4E892C.7040205@venix.com>

This did not generate any responses, but I thought I'd post my
solution anyway.

#!/usr/bin/perl
# testhash.pl

%d1 = (
     '1' => 'one',
     '2' => 'two',
     'd2' => {'nest1' => 'nest one',
     	'nest2' => 'nest two',}
     );

print "\nlookup 1 in d1: $d1{'1'}\n";
print "\nlookup d2 within d1: $d1{'d2'}\n";
print "\nlookup nest1 in d2 within d1: $d1{'d2'}{'nest1'}\n";
#############
There's probably a better way, but this seems to work.  The initial
variable name is prefixed with a % rather than the usual $ and the
hash is delimited with parentheses.  However, nested hashes do not
require the % and are delimited with curly braces.

My python code (version 2.2) follows:
#!/usr/bin/python
# py2perl.py
'''module to handle some python to perl transformations.
'''
class Py2perl_dict(dict):

	def __init__(self, arg):
	    super(Py2perl_dict, self).__init__(arg)
	    for key,val in self.items():
		if isinstance(val, dict) and not isinstance(val, Py2perl_dict):
		    self[key] = Py2perl_dict(val)

	def __repr__(self):
	    keylist = self.keys()
	    keylist.sort()
	    return ''.join(['{',
                 ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]),
                 '}'])


if __name__ == '__main__':
	d1 = {'1': 'one',
		'2': 'two',
		'd2': {'nest1': 'nest one',
			'nest2': 'nest two',},
         '3': 'four',
         'd3': {'nest3': 'nest three', 'nest4': 'nest four'},
	}
	perl_d1 = Py2perl_dict(d1)
	print "%%perl_d1 = (%s);" % (repr(perl_d1)[1:-1])
#############(indenting got slightly mangled in pasting to email)#####

The key assumption here is that only dict datatypes must have a different
representation for perl.  So I only provided an alternative dict class
with a perlish __repr__ method.  This should work for my case (unless
the perl guy complains) since the python dictionaries I'm converting
only contain strings and perl seems to accept python's string
representation.

I am certainly open to suggestions for improvements.

Lloyd Kvam wrote:

> I need to provide the contents of a python dictionary to a perl
> programmer as a perl hash table.  
-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From dyoo at hkn.eecs.berkeley.edu  Thu Aug 28 18:42:10 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Aug 28 20:42:52 2003
Subject: [Tutor] translating some python code to perl
In-Reply-To: <3F4E892C.7040205@venix.com>
Message-ID: <Pine.LNX.4.44.0308281720340.318-100000@hkn.eecs.berkeley.edu>



On Thu, 28 Aug 2003, Lloyd Kvam wrote:

> This did not generate any responses, but I thought I'd post my solution
> anyway.
>
> #!/usr/bin/perl
> # testhash.pl
>
> %d1 = (
>      '1' => 'one',
>      '2' => 'two',
>      'd2' => {'nest1' => 'nest one',
>      	'nest2' => 'nest two',}
>      );
>
> print "\nlookup 1 in d1: $d1{'1'}\n";
> print "\nlookup d2 within d1: $d1{'d2'}\n";
> print "\nlookup nest1 in d2 within d1: $d1{'d2'}{'nest1'}\n";
> #############
> There's probably a better way, but this seems to work.  The initial
> variable name is prefixed with a % rather than the usual $ and the
> hash is delimited with parentheses.


Hi Lloyd,


Yes.  In Perl, there's a distinction between a "hash" and a "hash
reference".  In Python, there's no such distinction, so technically, that
means that if we're trying to convert something like:


        d1 = {'1' : 'one',
              '2' : 'two',
              'd2': {'nest1': 'nest one',
                     'nest2': 'nest two',
                    },
              '3' : 'four',
              'd3': {'nest3': 'nest three',
                     'nest4': 'nest four'
                    },
             }

then our emitted Perl code should be something like:


       $d1 = {'1'  => 'one',
              '2'  => 'two',
              'd2' => {'nest1' => 'nest one',
                       'nest2' => 'nest two',
                      },
              '3'  => 'four',
              'd3' => {'nest3': 'nest three',
                       'nest4': 'nest four'
                      },
             }



> My python code (version 2.2) follows:
> #!/usr/bin/python
> # py2perl.py
> '''module to handle some python to perl transformations.
> '''
> class Py2perl_dict(dict):
>
> 	def __init__(self, arg):
> 	    super(Py2perl_dict, self).__init__(arg)
> 	    for key,val in self.items():
> 		if isinstance(val, dict) and not isinstance(val, Py2perl_dict):
> 		    self[key] = Py2perl_dict(val)
>
> 	def __repr__(self):
> 	    keylist = self.keys()
> 	    keylist.sort()
> 	    return ''.join(['{',
>                  ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]),
>                  '}'])



This code works, but also does modifications to our original dictionary.
Seems a harsh price to pay for compatibility.  *grin*



Here's an alternative approach:

###
def renderObject(obj):
    if isinstance(obj, dict):
        return renderDictionary(obj)
    if isinstance(obj, str):
        return renderString(obj)
    raise Exception, ("I don't know how to handle %s" % obj)

def renderDictionary(d):
    rendered_items = []
    for key, value in d.items():
        rendered_items.append("%s => %s" % (renderObject(key),
                                            renderObject(value)))
    return ("{\n%s\n}" % indent(",\n".join(rendered_items)))

def renderString(s):
    return repr(s)

def indent(s):
    indented_lines = ['    ' + l for l in s.split('\n')]
    return '\n'.join(indented_lines)
###



Here's what it looks like when we apply this to our 'd1' dictionary:

###
>>> print renderObject(d1)
{
    '1' => 'one',
    '3' => 'four',
    '2' => 'two',
    'd2' => {
        'nest2' => 'nest two',
        'nest1' => 'nest one'
    },
    'd3' => {
        'nest4' => 'nest four',
        'nest3' => 'nest three'
    }
}
###


Hope this helps!


From andrea.pertosa at mscsoftware.com  Thu Aug 28 23:54:14 2003
From: andrea.pertosa at mscsoftware.com (Andrea Pertosa)
Date: Thu Aug 28 22:55:14 2003
Subject: [Tutor] libsip, pyqt and other pains....
Message-ID: <000001c36dd8$dafcccf0$64c8a8c0@Pasta>

Hello all and thank you for reading this. I assure you I did my part
researching the problem that I'm encountering but without luck, so I'm
afraid I'm going to have to ask.

I'm experimenting with QT, PyQt, and Python and I'm having some
difficulties. 

First of all let me tell you that I'm a Windows illiterate since my
primary development platform is a SGI IRIX, so please bear with me. 

I'm running on a Dell laptop with WinXP Pro. I installed Qt version
3.2.0. 

I installed PyQt (the compiled package from riverbank) PyQt-WinNC-3.8
that, according to the web site, contains the SIP. 

I installed the python.org distribution of Python, version 2.3 (July
29th 2003).

I build my widget in QT designer, I can create the corresponding python
script but when I try to run the python script I get  a DLL load error:

 

Traceback (most recent call last):

  File "C:\Documents and Settings\Andrea\Desktop\Adams\Pyqt\sdi
editor\sdi_editor.py", line 5, in -toplevel-

    from qt import *

  File "C:\Python23\lib\site-packages\qt.py", line 17, in -toplevel-

    import libsip

ImportError: DLL load failed: The specified module could not be found.

 

Of course just invoking the python interpreter and trying to "import qt"
cause the same error. 

Can anyone suggest a way to resolve this problem?

Note that the only suggestion I could find on the Internet was to copy
manually the libsip.dll to the C:\windows\system32 folder, but that did
not work.

 

Any help greatly appreciated.

Andrea.

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030828/59eeaa26/attachment.htm
From yduppen at xs4all.nl  Fri Aug 29 11:53:11 2003
From: yduppen at xs4all.nl (Yigal Duppen)
Date: Fri Aug 29 05:00:17 2003
Subject: [Tutor] libsip, pyqt and other pains....
In-Reply-To: <000001c36dd8$dafcccf0$64c8a8c0@Pasta>
References: <000001c36dd8$dafcccf0$64c8a8c0@Pasta>
Message-ID: <200308291053.11568.yduppen@xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> I build my widget in QT designer, I can create the corresponding python
> script but when I try to run the python script I get  a DLL load error:
>
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Andrea\Desktop\Adams\Pyqt\sdi
> editor\sdi_editor.py", line 5, in -toplevel-
>     from qt import *
>   File "C:\Python23\lib\site-packages\qt.py", line 17, in -toplevel-
>     import libsip
> ImportError: DLL load failed: The specified module could not be found.

It looks like you haven't installed SIP. It can be found on the same site as 
PyQT: 
http://www.riverbankcomputing.co.uk/sip/download.php

If this doesn't work, you might get better help at the PyKDE mailinglist 
(which, despite its name, is more of a PyQt/SIP mailinglist): 
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

HTH,
YDD
- -- 
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQE/TxR3LsKMuCf5EdwRAq1GAJ9JOKhrQWpgoUMze65Vx4iCAonpbQCgsJ0C
LDm1RVFI32ryx7ljVTVTZ4Q=
=JiKG
-----END PGP SIGNATURE-----


From mwagman at charter.net  Fri Aug 29 11:14:48 2003
From: mwagman at charter.net (Mike Wagman)
Date: Fri Aug 29 06:14:49 2003
Subject: [Tutor] Reading directory contents
Message-ID: <1062152289.2478.6.camel@66-188-81-143.mad.wi.charter.com>

I need some code to load and parse file directories. Can anyone either
send me some sample code, or a site that talks about this issue. 
	Thanks
	Mike


From gus.tabares at verizon.net  Fri Aug 29 13:27:06 2003
From: gus.tabares at verizon.net (Gus Tabares)
Date: Fri Aug 29 08:27:08 2003
Subject: [Tutor] Reading directory contents
In-Reply-To: <1062152289.2478.6.camel@66-188-81-143.mad.wi.charter.com>
References: <1062152289.2478.6.camel@66-188-81-143.mad.wi.charter.com>
Message-ID: <1062160097.7632.1.camel@blackbetty>

On Fri, 2003-08-29 at 06:18, Mike Wagman wrote:
> I need some code to load and parse file directories. Can anyone either
> send me some sample code, or a site that talks about this issue. 

Hi Mike,

	You might want to take a look at listdir function in the os module. It
returns a list of filename strings in the current working directory.


-- 
Gus Tabares


From goki75 at vsnl.net  Fri Aug 29 19:43:03 2003
From: goki75 at vsnl.net (G Kiran)
Date: Fri Aug 29 09:13:44 2003
Subject: [Tutor] Matrix Transpose
Message-ID: <001101c36e2f$48d4f4e0$aa4c41db@VULCAN>

I was writing a small module to input a m x n matrix and print out the
transpose of it
how do i check if any of the rows has more elements  than others

if i have
1,2,3
1,2,3,4
4,5,6,7

i want

1,1,4
2,2,5
3,3,6
0,4,7

as  output
right now it only caters if in the input matrix
all rows have same no of elements

****i don't want to increase the prog size . my limit is the two lines

 my prog is


##########k=k=[ input() for i in range(input('Enter no of Rows:'))]
####Alternative input..for comma seperated values only

k=[[int(p) for p in raw_input(",").split()] for i in range(input('Enter no
of Rows:'))]
for a in [[k[x][y] for x in range(len(k))] for y in range(len(k[0]))]:print
a





---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.509 / Virus Database: 306 - Release Date: 8/12/2003


From erikprice at mac.com  Fri Aug 29 12:18:37 2003
From: erikprice at mac.com (Erik Price)
Date: Fri Aug 29 11:19:09 2003
Subject: [Tutor] Matrix Transpose
Message-ID: <56516.1062170317141.JavaMail.erikprice@mac.com>

 
On Friday, August 29, 2003, at 09:13AM, G Kiran <goki75@vsnl.net> wrote:

>I was writing a small module to input a m x n matrix and print out the
>transpose of it
>how do i check if any of the rows has more elements  than others
>
>if i have
>1,2,3
>1,2,3,4
>4,5,6,7
>
>i want
>
>1,1,4
>2,2,5
>3,3,6
>0,4,7



Have you seen the built-in "zip" function?  It does something similar to this, but I must confess I don't know enough about matrix transposition ( ;) ) to tell if it does what you are asking.


Erik

From pythontutor at venix.com  Fri Aug 29 14:11:00 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Aug 29 13:11:35 2003
Subject: [Fwd: Re: [Tutor] Matrix Transpose]
Message-ID: <3F4F8924.6030008@venix.com>

I must have clicked Reply rather than reply-All.
-------------- next part --------------
An embedded message was scrubbed...
From: Lloyd Kvam <pythontutor@venix.com>
Subject: Re: [Tutor] Matrix Transpose
Date: Fri, 29 Aug 2003 09:38:56 -0400
Size: 2270
Url: http://mail.python.org/pipermail/tutor/attachments/20030829/8b03f3c8/TutorMatrixTranspose-0001.eml
From project5 at redrival.net  Fri Aug 29 20:31:39 2003
From: project5 at redrival.net (Andrei)
Date: Fri Aug 29 13:35:57 2003
Subject: [Tutor] Re: Regex (almost solved, parser problem remaining)
In-Reply-To: <3F4BFD76.3010205@netzero.net>
References: <bib0iu$mqp$1@sea.gmane.org>	<Pine.LNX.4.44.0308242046290.23261-100000@hkn.eecs.berkeley.edu>	<bidj1v$d98$1@sea.gmane.org>
	<3F4BFD76.3010205@netzero.net>
Message-ID: <bio2p6$uhk$1@sea.gmane.org>

I've looked at all tips I got. Kirk, I tried the Wiki's parser but it 
has the obvious problem that a plain-text link in between double quotes 
will not be recognized as being a link (that being the reason I didn't 
use the backward-looking regex in the first place). I have not looked 
what happens if an <a>-tag contains invalid HTML, for example because a 
link is constructed like this: <a href=http://invalidlink.com>Invalid</a>.

Based on Danny's example, I ended up using the SGML parser combined with 
a regex (code and a test included at the bottom of this message). It 
also converts invalid HTML links (like the one shown above) to valid 
HTML and chops long links up a bit.

With my tests it works OK except for one thing: the SGML parser chokes 
on "&". The original says:

    go to news://bl_a.com/?ha-ha&query=tb for more info

and it's modified to:

    go to <a 
href="news://bl_a.com/?ha-ha">news://bl_a.com/?ha-ha</a>&query=tb for 
more info

The bit starting with "&" doesn't make it into the href attribute and 
hence also falls outside the link.
The parser recognizes "&" as being the start of an entity ref or a char 
ref and by default would like to remove it entirely. I use 
handle_entityref to put it back in, but at that time the preceding text 
has already been run through the linkify method, which generates the 
links. This means that the "&query" stuff is added behind the generated 
link instead of inside it.

Any suggestions on how I can deal with this particular problem?

Andrei



===[ EXAMPLE RESULTS ]========
Put them in a html file and view in browser.

<pre>
<b><u>ORIGINAL</u></b>
Plain old link: http://www.mail.yahoo.com.
Containing numbers: ftp://bla.com/ding/co.rt,39,%93 or other
Go to news://bl_a.com/?ha-ha&query=tb for more info.
A real link: <a href="http://x.com">http://x.com</a>.
ftp://verylong.org/url/must/be/chopped/to/pieces/oritwontfit.html (long one)
<IMG src="http://b.com/image.gif" /> (a plain image tag)
<IMG src="http://images.com/image.gif" ALT="Nice image"/> (image tag 
with alt text)
<a href=http://fixedlink.com/orginialinvalid.html>fixed</a> (original 
invalid HTML)
Link containing an anchor <b>"http://myhomepage.com/index.html#01"</b>.

<b><u>MODIFIED</u></b>
Plain old link: <a 
href="http://www.mail.yahoo.com">http://www.mail.yahoo.com</a>.
Containing numbers: <a 
href="ftp://bla.com/ding/co.rt,39,%93">ftp://bla.com/ding/co.rt,39,%93</a> 
or other
Go to <a 
href="news://bl_a.com/?ha-ha">news://bl_a.com/?ha-ha</a>&query=tb for 
more info.
A real link: <a href="http://x.com">http://x.com</a>.
<a 
href="ftp://verylong.org/url/must/be/chopped/to/pieces/oritwontfit.html">ftp://verylong.org...s/oritwontfit.html</a> 
(long one)
<a href="http://b.com/image.gif">http://b.com/image.gif (image)</a> (a 
plain image tag)
<a href="http://images.com/image.gif">Nice image (image)</a> (image tag 
with alt text)
<a href="http://fixedlink.com/orginialinvalid.html">fixed</a> (original 
invalid HTML)
Link containing an anchor <b>"<a 
href="http://myhomepage.com/index.html#01">http://myhomepage.com/index.html#01</a>"</b>.
</pre>



===[ CODE ]====================
mytext = """
Plain old link: http://www.mail.yahoo.com.
Containing numbers: ftp://bla.com/ding/co.rt,39,%93 or other
Go to news://bl_a.com/?ha-ha&query=tb for more info.
A real link: <a href="http://x.com">http://x.com</a>.
ftp://verylong.org/url/must/be/chopped/to/pieces/oritwontfit.html (long one)
<IMG src="http://b.com/image.gif" /> (a plain image tag)
<IMG src="http://images.com/image.gif" ALT="Nice image"/> (image tag 
with alt text)
<a href=http://fixedlink.com/orginialinvalid.html>fixed</a> (original 
invalid HTML)
Link containing an anchor <b>"http://myhomepage.com/index.html#01"</b>.
"""


import sgmllib, re
class LinkMaker(sgmllib.SGMLParser):
     """A parser which converts any stand-alone URL (meaning it is not
        inside a link, nor an attribute to a tag) to a proper link and
        can regenerate the modified HTML code.
        It also replaces IMG-tags with links to the images."""
     def __init__(self):
         sgmllib.SGMLParser.__init__(self)
         self.anchorlevel = 0 # pays attention to nested anchors
         self.elements = [] # stores the bits and pieces which will be 
joined
         # don't allow generation of links which are huge. If the MAXLENGTH
         # is exceeded by an URL, it will be chopped a bit in self.makeLink.
         self.MAXLENGTH = 40

     def unknown_starttag(self, tag, attrs):
         """Handle all start tags."""
         if tag == 'a':
             self.anchorlevel += 1 # store nested anchor depth
         if tag == 'img':
             # convert img-tag to link
             tag = 'a'
             # make a dictionary of attributes in order to convert those 
as well
             attribs = {"src": "", "alt": ""}
             for attrib in attrs:
                 attribs[attrib[0]] = attrib[1].strip()
             # generate alt attribute from link if otherwise not available
             if not attribs["alt"]:
                 attribs["alt"] = self.limitLength(attribs["src"])
             # only convert to link if a src attribute is present
             if attribs["src"]:
                 self.elements.append('<a href="%s">%s (image)</a>' % \
                                      (attribs["src"], attribs["alt"]))
         else: # for non-img tags normal handling
             # build a string containing the attribs
             attribsstring = " ".join([ '%s=\"%s\"' % (attrib) for 
attrib in attrs ])
             if attribsstring:
                 elem = " ".join([tag, attribsstring])
             else:
                 elem = tag
             self.elements.append("<%s>" % elem)

     def unknown_endtag(self, tag):
         """Handle all end tags."""
         if tag == 'a':
             self.anchorlevel -= 1
             # don't allow anchorlevel <0 (invalid HTML in fact)
             self.anchorlevel = max(0, self.anchorlevel)
         # convert img-tag to link
         if tag == 'img':
             tag = 'a'
         self.elements.append("</%s>" % tag)

     def handle_entityref(self, ref):
         """Is called when a character reference (&...) is found.
            These must pass through unmodified."""
         self.elements.append("&%s" % ref)

     def limitLength(self, text):
         """Returns a string with a maximum length of self.MAXLENGTH."""
         if len(text)>self.MAXLENGTH:
             # don't allow the text to become too large
             text = "%s...%s" % (text[:self.MAXLENGTH//2-2],
                                 text[-(self.MAXLENGTH//2-2):])
         return text

     def makeLink(self, matchobj):
         """Function called whenever linkify matches. Takes the
            match object and returns a link."""
         url = matchobj.group() # this will be in the href
         text = self.limitLength(url) # this will be the data of the tag 
(the visible link)
         return '<a href="%s">%s</a>' % (url, text)

     def linkify(self, text):
         """Regex for finding URLs:
            URL's start with http(s)/ftp/news ((http)|(ftp)|(news))
            followed by ://
            then any number of non-whitespace characters including
            numbers, dots, forward slashes, commas, question marks,
            ampersands, equality signs, dashes, underscores and plusses,
            but ending in a non-dot!
              ([@a-zA-Z0-9,/%:&#\?=\-_]+\.*)+[a-zA-Z0-9,/%:\&#\?=\-_]

            Result:
 
(?:http|https|ftp|news)://(?:[@a-zA-Z0-9,/%:\&#\?=\-_]+\.*)+[a-zA-Z0-9,/%:\&#\?=\-_]

            Tests:
               Plain old link: http://www.mail.yahoo.com.
               Containing numbers: ftp://bla.com/ding/co.rt,39,%93 or other
               Go to news://bl_a.com/?ha-ha&query=tb for more info.
               A real link: <a href="http://x.com">http://x.com</a>.
 
ftp://verylong.org/url/must/be/chopped/to/pieces/oritwontfit.html (long one)
               <IMG src="http://b.com/image.gif" /> (a plain image tag)
               <a 
href=http://fixedlink.com/orginialinvalid.html>fixed</a> (original 
invalid HTML)
               Link containing an anchor 
<b>"http://myhomepage.com/index.html#01"</b>.
         """
         expression = 
r"(?:http|https|ftp|news)://(?:[a-zA-Z0-9,@/%:\&#\?=\-_]+\.*)+[a-zA-Z0-9,/%:\&#\?\=\-_]"
         linkparser = re.compile(expression, re.I)
         text = linkparser.sub(self.makeLink, text)
         return text

     def handle_data(self, data):
         """Handle data between tags. If not inside a link
            (anchorlevel==0), then make sure any URLs are
            converted to links."""
         if self.anchorlevel == 0:
             data = self.linkify(data)
         self.elements.append(data)

     def getResult(self):
         """Returns the updated HTML. This just consists of
            joining the elements."""
         return "".join(self.elements)


parser = LinkMaker()
parser.feed(mytext)
print parser.getResult()



From tpc at csua.berkeley.edu  Fri Aug 29 12:01:14 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Aug 29 14:01:41 2003
Subject: [Tutor] Reading directory contents
In-Reply-To: <1062152289.2478.6.camel@66-188-81-143.mad.wi.charter.com>
Message-ID: <20030829105109.J65832-100000@localhost.name>


hi Mike, what are you trying to do ?  For what it's worth, I have some
code that traverses a directory tree recursively, starting at my web
server document root, and indexes all *.HTML pages.  Not sure if this is
up your alley:

<code>
APACHE_ROOT_DIR = ''   # you put in your path here
newList = []
def htmlFinder(arg, dirname, fnames):
	for fn in fnames:
		if fn.endswith('.html'):
			path = os.path.join(dirname, fn)
			newList.append(path)
	os.path.walk(APACHE_ROOT_DIR, htmlFinder, None)
	return newList
</code>

I hope that helps you.

On 29 Aug 2003, Mike Wagman wrote:

> I need some code to load and parse file directories. Can anyone either
> send me some sample code, or a site that talks about this issue.
> 	Thanks
> 	Mike
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From tpc at csua.berkeley.edu  Fri Aug 29 13:29:52 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Aug 29 15:31:01 2003
Subject: [Tutor] Reading directory contents (Correction)
In-Reply-To: <20030829105109.J65832-100000@localhost.name>
Message-ID: <20030829122426.R66484-100000@localhost.name>


hi Mike,
I apologize, there was an error in my last email when I took the code out
of a function and deleted the extra indentation.  The last two lines of
the code paste should be further left, that is, with no indentation.
The corrected version is below:

<code>
APACHE_ROOT_DIR = ''   # you put in your path here
newList = []
def htmlFinder(arg, dirname, fnames):
       for fn in fnames:
               if fn.endswith('.html'):
                       path = os.path.join(dirname, fn)
                       newList.append(path)
os.path.walk(APACHE_ROOT_DIR, htmlFinder, None)
return newList
</code>

On Fri, 29 Aug 2003 tpc@csua.berkeley.edu wrote:

>
> hi Mike, what are you trying to do ?  For what it's worth, I have some
> code that traverses a directory tree recursively, starting at my web
> server document root, and indexes all *.HTML pages.  Not sure if this is
> up your alley:
>
> <code>
> APACHE_ROOT_DIR = ''   # you put in your path here
> newList = []
> def htmlFinder(arg, dirname, fnames):
> 	for fn in fnames:
> 		if fn.endswith('.html'):
> 			path = os.path.join(dirname, fn)
> 			newList.append(path)
> 	os.path.walk(APACHE_ROOT_DIR, htmlFinder, None)
> 	return newList
> </code>
>
> I hope that helps you.
>
> On 29 Aug 2003, Mike Wagman wrote:
>
> > I need some code to load and parse file directories. Can anyone either
> > send me some sample code, or a site that talks about this issue.
> > 	Thanks
> > 	Mike
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>


From jonathan.hayward at pobox.com  Fri Aug 29 22:55:23 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 29 16:55:28 2003
Subject: [Tutor] Setup so I can import thread.
Message-ID: <3F4FBDBB.4050000@pobox.com>

I built Python.2.3.tgz on a NetBSD box and there was no module thread to 
import. What do I do to get thread working?

TIA,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From ATrautman at perryjudds.com  Fri Aug 29 17:02:52 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Fri Aug 29 17:04:14 2003
Subject: [Tutor] Setup so I can import thread.
Message-ID: <06738462136C054B8F8872D69DA140DB0108CF@corp-exch-1.pjinet.com>

I believe the module Thread was deprecated I can't find the docs on the
Python site right now. However, the threading module should be available and
does every thing I know to use threads for.

http://www.python.org/doc/2.2p1/lib/module-threading.html

for reference

HTH,
Alan

-----Original Message-----
From: Jonathan Hayward http://JonathansCorner.com
[mailto:jonathan.hayward@pobox.com]
Sent: Friday, August 29, 2003 3:55 PM
To: tutor@python.org
Subject: [Tutor] Setup so I can import thread.


I built Python.2.3.tgz on a NetBSD box and there was no module thread to 
import. What do I do to get thread working?

TIA,

-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



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

From alan.gauld at blueyonder.co.uk  Sat Aug 30 00:03:18 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Aug 29 18:04:54 2003
Subject: [Tutor] Matrix Transpose
References: <001101c36e2f$48d4f4e0$aa4c41db@VULCAN>
Message-ID: <014201c36e79$5aec7550$6401a8c0@xp>

> ##########k=k=[ input() for i in range(input('Enter no of Rows:'))]
> ####Alternative input..for comma seperated values only
>
> k=[[int(p) for p in raw_input(",").split()] for i in
range(input('Enter no
> of Rows:'))]
> for a in [[k[x][y] for x in range(len(k))] for y in
range(len(k[0]))]:print
> a

I assume this is for some kind of obfuscated Python contest?
One of the attractions of Python is that it's normally difficult
to write code that's hard to read, but you have proved that
it is undoubtedly possible!

As a matter of interest do you ever intend to update this program
in, say, 6 months time?

Alan G.


From logiplex at qwest.net  Fri Aug 29 16:14:39 2003
From: logiplex at qwest.net (Cliff Wells)
Date: Fri Aug 29 18:14:44 2003
Subject: [Tutor] Matrix Transpose
In-Reply-To: <56516.1062170317141.JavaMail.erikprice@mac.com>
References: <56516.1062170317141.JavaMail.erikprice@mac.com>
Message-ID: <1062195279.32726.813.camel@software1.logiplex.internal>

On Fri, 2003-08-29 at 08:18, Erik Price wrote:
>  On Friday, August 29, 2003, at 09:13AM, G Kiran <goki75@vsnl.net> wrote:
> 
> >I was writing a small module to input a m x n matrix and print out the
> >transpose of it
> >how do i check if any of the rows has more elements  than others
> >
> >if i have
> >1,2,3
> >1,2,3,4
> >4,5,6,7
> >
> >i want
> >
> >1,1,4
> >2,2,5
> >3,3,6
> >0,4,7
> 
> 
> 
> Have you seen the built-in "zip" function?  It does something similar
> to this, but I must confess I don't know enough about matrix
> transposition ( ;) ) to tell if it does what you are asking.

Like this?

>>> m = [range(4), range(4), range(4)]
>>> m
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
>>> zip(*m)
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3)]
>>>

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555


From logiplex at qwest.net  Fri Aug 29 16:47:18 2003
From: logiplex at qwest.net (Cliff Wells)
Date: Fri Aug 29 18:47:31 2003
Subject: [Fwd: Re: [Tutor] Matrix Transpose]
In-Reply-To: <3F4F8924.6030008@venix.com>
References: <3F4F8924.6030008@venix.com>
Message-ID: <1062197237.32726.817.camel@software1.logiplex.internal>

On Fri, 2003-08-29 at 10:11, Lloyd Kvam wrote:
> I must have clicked Reply rather than reply-All.
> 
> ______________________________________________________________________
> From: Lloyd Kvam <pythontutor@venix.com>
> To: G Kiran <goki75@vsnl.net>
> Subject: Re: [Tutor] Matrix Transpose
> Date: Fri, 29 Aug 2003 09:38:56 -0400

> 
>  >>> tb = map(None,*a)
>  >>> tb
> [(1, 1, 1), (2, 2, 2), (3, 3, 3), (None, 4, None)]
> This pads with None's.

Please forgive this one-liner:

data = """
1,2,3
1,2,3,4
4,5,6,7
"""

zip(*map(lambda *args: map(lambda a: a is not None and int(a) or 0,
args), *[row.split(',') for row in data.split('\n') if row]))

Regards,        

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555


From dyoo at hkn.eecs.berkeley.edu  Fri Aug 29 17:09:03 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Aug 29 19:09:13 2003
Subject: [Tutor] Matrix Transpose
In-Reply-To: <001101c36e2f$48d4f4e0$aa4c41db@VULCAN>
Message-ID: <Pine.LNX.4.44.0308291555300.9533-100000@hkn.eecs.berkeley.edu>



On Fri, 29 Aug 2003, G Kiran wrote:

> I was writing a small module to input a m x n matrix and print out the
> transpose of it
> how do i check if any of the rows has more elements  than others
>
> if i have
> 1,2,3
> 1,2,3,4
> 4,5,6,7
>
> i want
>
> 1,1,4
> 2,2,5
> 3,3,6
> 0,4,7
>
> as  output


Hi Kiran,


We need a little more information --- what kind of representation are you
using for your matricies?  Are you using a list of lists?


Representation is important for your question: if we're using a sparse
matrix representation, like:

###
>>> class Sparse:
...     def __init__(self):
...         self.data = {}
...     def put(self, i, j, value):
...         self.data[i,j] = value
...     def get(self, i, j):
...         return self.data[i,j]
...
>>> m = Sparse()
>>> m.put(0, 0, 1)
>>> m.put(0, 1, 1)
>>> m.put(0, 2, 4)
>>> m.put(1, 0, 1)
###


then there's a kludgy and evil "cheat" to get it transposed:

###
>>> m.get = lambda x, y, get=m.get: get(y,x)
>>> m.get(2,0)
4
###

Don't worry if it looks funny --- it is!  I really shouldn't be doing it
this way.  *grin* But to do it properly, without cheating, isn't that much
harder.



> ****i don't want to increase the prog size . my limit is the two lines

Out of curiosity, why?




> right now it only caters if in the input matrix all rows have same no of
> elements

It then sounds like you'd like to ensure that all your matrix rows have
the same number of columns.  Here's one way to to expand a list:

###
>>> l = []
>>> l = [1,2,3]
>>> l.extend([0] * 5)
>>> l
[1, 2, 3, 0, 0, 0, 0, 0]
###



Good luck!


From jonathan.hayward at pobox.com  Sat Aug 30 01:25:44 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Fri Aug 29 19:25:49 2003
Subject: [Tutor] Setup so I can import thread.
In-Reply-To: <06738462136C054B8F8872D69DA140DB0108CF@corp-exch-1.pjinet.com>
References: <06738462136C054B8F8872D69DA140DB0108CF@corp-exch-1.pjinet.com>
Message-ID: <3F4FE0F8.5020201@pobox.com>

Alan Trautman wrote:

>I believe the module Thread was deprecated I can't find the docs on the
>Python site right now. However, the threading module should be available and
>does every thing I know to use threads for.
>
>http://www.python.org/doc/2.2p1/lib/module-threading.html
>  
>
I'm converting the program and it seems to move like molasses, and as 
yet doesn't work. Errors have a good ten second delay compared to with 
thread. Is there something I should be doing differently?

>for reference
>
>HTH,
>Alan
>
>-----Original Message-----
>From: Jonathan Hayward http://JonathansCorner.com
>[mailto:jonathan.hayward@pobox.com]
>Sent: Friday, August 29, 2003 3:55 PM
>To: tutor@python.org
>Subject: [Tutor] Setup so I can import thread.
>
>
>I built Python.2.3.tgz on a NetBSD box and there was no module thread to 
>import. What do I do to get thread working?
>
>TIA,
>
>  
>


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From peterabrown at froggy.com.au  Sat Aug 30 19:57:19 2003
From: peterabrown at froggy.com.au (Peter Brown)
Date: Sat Aug 30 04:53:16 2003
Subject: [Tutor] Executing Store Procedures using PygreSQL
Message-ID: <3.0.6.32.20030830185719.00b40a30@mail.froggy.com.au>

Hi list,

I've been searching for a reference to executing stored procedures via a
select call without luck.

Is this function available via PygreSQL? And if so what is the statement
format needed to have PostgreSQL execute it.

TIA

Peter


From erikprice at mac.com  Sat Aug 30 10:37:59 2003
From: erikprice at mac.com (Erik Price)
Date: Sat Aug 30 09:17:20 2003
Subject: [Tutor] Reading directory contents
In-Reply-To: <1062152289.2478.6.camel@66-188-81-143.mad.wi.charter.com>
Message-ID: <2BDD5878-DAEF-11D7-A208-00039351FE6A@mac.com>


On Friday, August 29, 2003, at 06:18  AM, Mike Wagman wrote:

> I need some code to load and parse file directories. Can anyone either
> send me some sample code, or a site that talks about this issue.

I just read a short, simple chunk of code that generates a listing of 
directories the other day.

<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/217212>


Erik


From erikprice at mac.com  Sat Aug 30 10:41:02 2003
From: erikprice at mac.com (Erik Price)
Date: Sat Aug 30 09:21:35 2003
Subject: [Tutor] Re: Regex (almost solved, parser problem remaining)
In-Reply-To: <bio2p6$uhk$1@sea.gmane.org>
Message-ID: <98EA8E5C-DAEF-11D7-A208-00039351FE6A@mac.com>


On Friday, August 29, 2003, at 01:31  PM, Andrei wrote:

> With my tests it works OK except for one thing: the SGML parser chokes 
> on "&". The original says:
>
>    go to news://bl_a.com/?ha-ha&query=tb for more info
>
> and it's modified to:
>
>    go to <a 
> href="news://bl_a.com/?ha-ha">news://bl_a.com/?ha-ha</a>&query=tb for 
> more info
>
> The bit starting with "&" doesn't make it into the href attribute and 
> hence also falls outside the link.
> The parser recognizes "&" as being the start of an entity ref or a 
> char ref and by default would like to remove it entirely. I use 
> handle_entityref to put it back in, but at that time the preceding 
> text has already been run through the linkify method, which generates 
> the links. This means that the "&query" stuff is added behind the 
> generated link instead of inside it.

I thought that it was invalid to have a "&" character that is not being 
used as an entity reference in SGML or XML documents.  In other words, 
the document should have "&amp;", not "&".  Most browsers don't enforce 
it in HTML, though.


Erik


From jonathan.hayward at pobox.com  Sat Aug 30 18:20:42 2003
From: jonathan.hayward at pobox.com (Jonathan Hayward http://JonathansCorner.com)
Date: Sat Aug 30 12:21:05 2003
Subject: [Tutor] URGENT: Getting Python to work on NetBSD
In-Reply-To: <06738462136C054B8F8872D69DA140DB0108CF@corp-exch-1.pjinet.com>
References: <06738462136C054B8F8872D69DA140DB0108CF@corp-exch-1.pjinet.com>
Message-ID: <3F50CEDA.2050308@pobox.com>

Alan Trautman wrote:

>I believe the module Thread was deprecated I can't find the docs on the
>Python site right now. However, the threading module should be available and
>does every thing I know to use threads for.
>
>http://www.python.org/doc/2.2p1/lib/module-threading.html
>  
>
I migrated to threading and ran:

Traceback (most recent call last):
  File "./server", line 262, in ?
    import cgi, cgitb, cPickle, re, os, random, sgmllib, socket, string, 
sys, \
  File "/home/jonathan/Python-2.3/Lib/threading.py", line 6, in ?
    import thread
ImportError: No module named thread

2.3's threading seems to be built on top of thread, and is breaking. Can 
anyone tell me how to get Python working with threading on 
NetBSD--including e-mailing me the URL to the package and instructions 
(pkg_add <name_of_tarball>?)

TIA:

>for reference
>
>HTH,
>Alan
>
>-----Original Message-----
>From: Jonathan Hayward http://JonathansCorner.com
>[mailto:jonathan.hayward@pobox.com]
>Sent: Friday, August 29, 2003 3:55 PM
>To: tutor@python.org
>Subject: [Tutor] Setup so I can import thread.
>
>
>I built Python.2.3.tgz on a NetBSD box and there was no module thread to 
>import. What do I do to get thread working?
>
>TIA,
>
>  
>


-- 
++ Jonathan Hayward, jonathan.hayward@pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com



From project5 at redrival.net  Sat Aug 30 19:39:35 2003
From: project5 at redrival.net (Andrei)
Date: Sat Aug 30 12:41:35 2003
Subject: [Tutor] Re: Regex (almost solved, parser problem remaining)
In-Reply-To: <98EA8E5C-DAEF-11D7-A208-00039351FE6A@mac.com>
References: <bio2p6$uhk$1@sea.gmane.org>
	<98EA8E5C-DAEF-11D7-A208-00039351FE6A@mac.com>
Message-ID: <biqk3j$lr7$1@sea.gmane.org>


Erik Price wrote:
> 
> On Friday, August 29, 2003, at 01:31  PM, Andrei wrote:
> 
>> With my tests it works OK except for one thing: the SGML parser chokes 
>> on "&". The original says:
>>
>>    go to news://bl_a.com/?ha-ha&query=tb for more info
>>
>> and it's modified to:
>>
>>    go to <a 
>> href="news://bl_a.com/?ha-ha">news://bl_a.com/?ha-ha</a>&query=tb for 
>> more info
> I thought that it was invalid to have a "&" character that is not being 
> used as an entity reference in SGML or XML documents.  In other words, 
> the document should have "&amp;", not "&".  Most browsers don't enforce 
> it in HTML, though.

I don't know for sure that the source is valid HTML (and in fact I know 
for sure that some of the strings I process are plain text URLs). 
Anyway, I've eventually solved the issue by pre-processing the string 
(replacing the &'s with a longish string which is extremely unlikely to 
appear in the text), followed by the normal manipulation. At the end of 
course the instances of that magic string are converted back to &'s. Not 
very elegant, but it works :).

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From dyoo at hkn.eecs.berkeley.edu  Sun Aug 31 01:55:45 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 31 03:55:51 2003
Subject: [Tutor] URGENT: Getting Python to work on NetBSD
In-Reply-To: <3F50CEDA.2050308@pobox.com>
Message-ID: <Pine.LNX.4.44.0308310032560.13794-100000@hkn.eecs.berkeley.edu>



On Sat, 30 Aug 2003, Jonathan Hayward http://JonathansCorner.com wrote:

>   File "./server", line 262, in ?
>     import cgi, cgitb, cPickle, re, os, random, sgmllib, socket, string,
> sys, \
>   File "/home/jonathan/Python-2.3/Lib/threading.py", line 6, in ?
>     import thread
> ImportError: No module named thread

[Small note: Your question is Python-related, but it is more of an
installation question than a tutoring question.  Few of us compile Python
directly from source, and even fewer of us run NetBSD.  Next time, you may
want to ask on comp.lang.python, as there would be people with more NetBSD
expertise there.]


Hi Johnathan,

The path that your system is reporting for 'threading.py' is suspicious.
I expected to see something along the lines of:

    /home/jonathan/Python-2.3/lib/python2.3/threading.py

because Python will place all of its libraries in a version-specific
directory under 'lib'.  The path that you're announcing, on the other
hand, does look like the directory structure of the source installation
files!  Ok, I think we know what's going on now.


It appears that you're trying to run a local installation of Python.  Did
you try copying any files manually?  If so, don't!  *grin* You really need
to do all of the configure; make; make install dance.  In your case, this
should do the trick:

    ./configure --prefix=/home/jonathan/local
    ./make
    ./make install

(You can change the name of the 'prefix' to another location, of course;
the idea is to override the default location of /usr/local/.)  If you're
interested, you can take a closer look at the README that comes with the
source code; it'll give more information about compiling Python from
source.

Without doing the 'make install' step, your files won't be where the
Python runtime expects to find them.  This is precisely why Python can't
find the 'thread' low level library.  It is a C extension that's built in
a different directory --- in Modules --- and it's the 'make install' step
that migrates both pure Python and the C extensions into a common library
directory.

I know I'm making a few big assumptions here, so if I'm wildly off target,
please forgive me.  *grin* But my best guess right now is that your Python
installation isn't finalized yet.


> anyone tell me how to get Python working with threading on
> NetBSD--including e-mailing me the URL to the package and instructions
> (pkg_add <name_of_tarball>?)

If you really want to use NetBSD's package management system, your best
bet is to talk with the NetBSD folks.  It looks like they are trying to
get things working with 2.3:

    http://mail-index.netbsd.org/tech-pkg/2003/08/17/0003.html

and the necessary stuff does appear to be in their CVS tree, but needs
further testing.  So check with the NetBSD folks; it may make it
unnecessary to install Python from source.

If it's unnecessary to go straight to 2.3, I'd recommend just using
NetBSD's packages for 2.2 for now, and avoid the hassle since your
question sounds urgent.  You can always install 2.3 on top of a working
2.2 install later once things calm down.


Good luck to you.


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 31 02:18:19 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 31 04:18:30 2003
Subject: [Tutor] OT: spec file
In-Reply-To: <20030830113715.A6036@localhost.localdomain>
Message-ID: <Pine.LNX.4.44.0308310017500.13794-100000@hkn.eecs.berkeley.edu>



On Sat, 30 Aug 2003, Silviu Cojocaru wrote:

> Does someone here has a specfile for building python 2.3 rpms ?

[Hmmm... We're getting a lot of installation sort of questions on
Python-Tutor lately.  Does anyone know what's going on here?  Not that I
don't like answering questions, but I really don't like 'install'
questions that much.  Bluntly, I do too much system admin stuff at work
already, and I don't want to get bogged down with it here.  What do people
think?]


Hi Silviu,

Have you had a chance to look at:

    http://www.python.org/2.3/rpms.html

The page there refers to the 'python2.3.-2.3-4pydotorg.src.rpm' file,
which should have the spec file you're looking for.


>From your subject line, you mentioned that your question might be off
topic.  You're right: it is.  You might have better luck asking on
comp.lang.python for this one next time, so please be more careful.


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


From dyoo at hkn.eecs.berkeley.edu  Sun Aug 31 02:32:03 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Aug 31 04:32:16 2003
Subject: [Tutor] Executing Store Procedures using PygreSQL
In-Reply-To: <3.0.6.32.20030830185719.00b40a30@mail.froggy.com.au>
Message-ID: <Pine.LNX.4.44.0308310124240.13794-100000@hkn.eecs.berkeley.edu>



On Sat, 30 Aug 2003, Peter Brown wrote:

> Hi list,
>
> I've been searching for a reference to executing stored procedures via a
> select call without luck.

Hi Peter,


According to:

    http://www.python.org/peps/pep-0249.html

you can call a stored procedure by using the 'callproc()' method of your
cursor.  PyGreSQL should support it, as it's part of the DB-API 2.0
standard.  Unfortunately, I don't have enought experience with PostGreSQL
to test this out; can someone confirm that callproc() works with PyGreSQL?


Good luck to you!


From thomi at imail.net.nz  Sun Aug 31 22:01:23 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Sun Aug 31 05:01:37 2003
Subject: [Tutor] problems with win32com.client and excel.
Message-ID: <200308312101.23309.thomi@imail.net.nz>


Hi guys,

For the last month or so I've been trying to develop a piece of a program 
which enters numbers into an excel spreadsheet. I've managed to get it to go 
from the interactive interpreter, but as soon as I put those same commands 
into a file, I get errors:

--<snip>--
Traceback (most recent call last):
  File "wedderburn.py", line 467, in idle
    self.xlapp.adddata((command,args))
  File "C:\Documents and 
Settings\Administrator\Desktop\wedderburn\excelspread.py", line 58, in 
adddata
    self.app.ActiveSheet.Cells(self.x,self.y).Value = d #insert the data into 
the sheet.
  File "C:\PYTHON23\lib\site-packages\win32com\client\dynamic.py", line 154, 
in __call__
    return 
self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, 
None, 0, -2146827284), None)
--</snip>--

This is the file "excelspread.py":

-<snip>-
#!/usr/bin/python

import os,sys

if os.name != 'nt':
	print "we're not in a win32 environment, so excel logging will not be 
available."
	sys.exit(1)

try:
	import win32com.client
except:
		print "you don't seem to have the python windows/COM extensions 
installed!\n\nget them from: http://www.python.org/windows/"
		sys.exit(1)


'''This file contains functions and classes to append information to an excel 
spreadsheet.'''

class app:
	def __init__(self,title="Weight SpreadSheet:"):

		#we have to start excel with a spreadsheet, and put up the title.

		self.x = self.y = self.width = 0
		
		self.app = win32com.client.Dispatch("Excel.Application")
		self.app.Visible = 1
		self.app.Workbooks.Add()

		#set the title:
		self.app.ActiveSheet.Cells(1,1).Value = title
		self.y += 1

		self.initial = 1
		self.cols = {}


		#that's it as far as initialisation goes...

	def adddata(self,values):
		# values will be a two part list. he first part will always contain the
		# text string 'DATA'. THe second part will be a list of lists. these
		# inner lists will contain two values. the first will be a header code,
		# the second item will be the actual data. this from the dummy driver:
		#
		# return 
['DATA',[['CODENO','0125846'],['NETWEIGHT',netw],['GROSSWEIGHT',grossw],['TARE',tare]]]
		#
		code,data = values	#unpack the values.

		self.x = 0
		self.y += 1
		
		if self.initial:
			#this is the first time we have added data to the spreadsheet. we need to 
set up
			#the column headers.
			for chunk in data:
				c,d = chunk						#unpack the code chunk
				self.cols[c] = self.x			#add entry to cols dictionary.
				self.app.ActiveSheet.Cells(self.x,self.y).Value = d	#insert the data into 
the sheet.
				self.x += 1 					#incriment the x column
			self.initial = 0
		else:
			for chunk in data:
				c,d = chunk #unpack the code chunk.
				self.x = self.cols.get(c,10)    #put error messages in col 10
				self.app.ActiveSheet.Cells(self.x,self.y).Value = d
			
					
if __name__ == '__main__':
	xl = app()
	# this is the format that data is sent to the class:
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
xl.adddata(['DATA'[['HEADER1','VALUE1'],['HEADER2','VALUE2'],['HEADER3','VALUE3'],['HEADER4','VALUE','4']]])
	
-</snip>-


Normally I wouldn't paste an entire file in anemail, but I'm really stuck. Can 
anyone point me in the right direction? part of the problem is that the 
exception error messages are so meaninglkess, and there is almost no 
documentation about library calls for the com32.client module. (guess I could 
always try and read the source code...)

Thanks,
-- 
Thomi Richards,
http://once.sourceforge.net/




From exnihilo at myrealbox.com  Sun Aug 31 10:46:26 2003
From: exnihilo at myrealbox.com (nihilo)
Date: Sun Aug 31 05:48:07 2003
Subject: [Tutor] regular expression question
Message-ID: <1062323186.8cd28ba0exnihilo@myrealbox.com>

hi,

I'm stuck on a regular expression. I want to match everything starting from a word up to and including the next occurence of the word.

If the word were a single character (say 'a'), then I could do the following:

pat = re.compile('a[^a]*a')

The problem is that I haven't been able to find out how to exclude the word if it is more than one character. [^word] excludes the individual letters, not the word as a whole, and I tried grouping with braces and parentheses  [^(word)], but these don't work.  I've checked many re tutorials, and they all say how to exclude a single character from the set of characters inside the brackets, but not how to exclude more than 1 character.

thanks for any help or pointers to resources...


From python at kubieziel.de  Sun Aug 31 15:56:56 2003
From: python at kubieziel.de (Jens Kubieziel)
Date: Sun Aug 31 09:12:06 2003
Subject: [Tutor] regular expression question
In-Reply-To: <1062323186.8cd28ba0exnihilo@myrealbox.com>
References: <1062323186.8cd28ba0exnihilo@myrealbox.com>
Message-ID: <20030831125656.GB3628@kubieziel.de>

On Sun, Aug 31, 2003 at 09:46:26AM +0000, nihilo wrote:
> pat = re.compile('a[^a]*a')
> 
> The problem is that I haven't been able to find out how to exclude the
> word if it is more than one character. [^word] excludes the individual
> letters, not the word as a whole, and I tried grouping with braces and
> parentheses  [^(word)], but these don't work.  I've checked many re
> tutorials, and they all say how to exclude a single character from the
> set of characters inside the brackets, but not how to exclude more than
> 1 character.

AFAIK the only way you can do this, is like:

pat = re.compile('a[^w][^o][^r][^d]')

-- 
Jens Kubieziel                                   http://www.kubieziel.de
Another such victory over the Romans, and we are undone.
		-- Pyrrhus

From amk at amk.ca  Sun Aug 31 09:01:39 2003
From: amk at amk.ca (A.M. Kuchling)
Date: Sun Aug 31 09:16:41 2003
Subject: [Tutor] regular expression question
In-Reply-To: <1062323186.8cd28ba0exnihilo@myrealbox.com>
Message-ID: <E111C564-DBAA-11D7-B771-000A956F1D08@amk.ca>

On Sunday, August 31, 2003, at 05:46 AM, nihilo wrote:
> I'm stuck on a regular expression. I want to match everything starting 
> from a word up to and including the next occurence of the word.

Most regular expression tutorials will also discuss grouping and 
backreferences, which are the solution to this problem.  Grouping with 
(...) lets you retrieve the contents of what's
matched by the expression inside the parentheses; backreferences (\1 or 
\g<1>) let you say 'match the contents of group N.

So, for your problem you want:

 >>> p = re.compile(r'(\b\w+\b).*\1')
 >>> m = p.search('get to the heart of the matter')
 >>> m.group()
'the heart of the'
 >>>

(Note the use of a raw string (r'') for the pattern; both \b and \1 get 
interpreted differently and incorrectly without it.)

--amk


From alex at gabuzomeu.net  Sun Aug 31 16:36:55 2003
From: alex at gabuzomeu.net (Alexandre Ratti)
Date: Sun Aug 31 09:32:09 2003
Subject: [Tutor] regular expression question
In-Reply-To: <1062323186.8cd28ba0exnihilo@myrealbox.com>
References: <1062323186.8cd28ba0exnihilo@myrealbox.com>
Message-ID: <3F51F9F7.5020301@gabuzomeu.net>

Hello,


nihilo wrote:
> I'm stuck on a regular expression. I want to match everything
> starting  from a word up to and including the next occurence of the word.

If you are trying to match text between instances of a specific word, 
you can try using "non-greedy" forms so that the expression matches as 
little text as possible (i.e. only up to the 2nd instance and no 
further). Example:

 >>> import re
 >>> s = "Nobody expects the FNORD Spanish Inquisition FNORD and they 
have FNORD nice uniforms."
 >>> pattern = re.compile("FNORD.*?FNORD")
 >>> pattern.findall(s)
['FNORD Spanish Inquisition FNORD']

The question mark in ".*?" says it's the non-greedy form. For more 
details, see:

    http://www.python.org/doc/current/lib/re-syntax.html

If you haven't found it yet, see also the Regular Expression Howto:

    http://www.amk.ca/python/howto/regex/regex.html

If the text between word instances can contain new lines, you'll have to 
add "re.DOTALL" when compiling the expression.


Cheers.

Alexandre




From icewind_bilbo at hotmail.com  Sun Aug 31 20:54:15 2003
From: icewind_bilbo at hotmail.com (Matthew Bielby)
Date: Sun Aug 31 14:54:50 2003
Subject: [Tutor] using the modules and command prompt
Message-ID: <BAY1-F7998Bi89QtpfT0001b91f@hotmail.com>

i am new to all forms of programming and python was suggested to me as 
simple to use and i have found the simple commands easy to do. Now i want to 
use the winsound module - but i dont know how. I would also like to know/if 
how you can python to open up cmd.exe or similar and run commands such as 
ping.
Many thanks
Matthew

_________________________________________________________________
On the move? Get Hotmail on your mobile phone http://www.msn.co.uk/msnmobile


From mwagman at charter.net  Sun Aug 31 20:15:40 2003
From: mwagman at charter.net (Mike Wagman)
Date: Sun Aug 31 15:15:42 2003
Subject: [Tutor] using the modules and command prompt
In-Reply-To: <BAY1-F7998Bi89QtpfT0001b91f@hotmail.com>
References: <BAY1-F7998Bi89QtpfT0001b91f@hotmail.com>
Message-ID: <1062357551.2479.1.camel@66-188-81-143.mad.wi.charter.com>

I think you are looking for interactive mode.

from a command prompt

python -i 

from there you can import and work with modules - test code etc.

You can also go python -i (name of your program)

This runs the program and when it exits you have a prompt with all
modules and variables still intact. 

On Sun, 2003-08-31 at 13:54, Matthew Bielby wrote:
> i am new to all forms of programming and python was suggested to me as 
> simple to use and i have found the simple commands easy to do. Now i want to 
> use the winsound module - but i dont know how. I would also like to know/if 
> how you can python to open up cmd.exe or similar and run commands such as 
> ping.
> Many thanks
> Matthew
> 
> _________________________________________________________________
> On the move? Get Hotmail on your mobile phone http://www.msn.co.uk/msnmobile
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor