From smichr at hotmail.com  Fri Apr  1 00:12:49 2005
From: smichr at hotmail.com (C Smith)
Date: Fri Apr  1 00:13:42 2005
Subject: [Tutor] I am puzzled - help needed
In-Reply-To: <20050331190212.65FC01E4018@bag.python.org>
Message-ID: <BAY101-DAV17F9B5CB55E066B5798B24C1470@phx.gbl>

>> I need to rewrite the high_low.py program (see below) to use the last 
>> two digits of time at that moment to be the "random number".

Be sure you understand what format the time number has and that you 
understand the problem statement.  Here are two time values:

1112306463.0
1112306463.01

Do you see what is going to happen if you blindly take the last two 
characters of the time in the first case and try to convert it to an 
integer? Are you suppose to take the last two digits of the integer 
portion?

Also, a neat way to get the last 2 digits of a number is to use the 
"remainder/modulus" operator:

###
 >>> from time import *
 >>> t=int(time())
 >>> t
1112306749
 >>> t%10 #last 1
9
 >>> t%100 #last 2
49
 >>> t%1000 #last 3
749
###


Also, note that when you "import *" you no longer need (or can) use the 
"time." prefix for times functions; when you import them that way it is 
as if they are part of your own function set:

###
 >>> from time import *
 >>> time.time()
Traceback (most recent call last):
   File "<input>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 
'time'
###

..you get this error because time's function "time()" is part of your 
programs functions; there is not module "time" for you to interact 
with, only time's functions. So go ahead and just use the function:

###
 >>> time()
1112306900.8461709
###

If you import the whole module, though, and try the same thing...

###
 >>> import time
 >>> time()
Traceback (most recent call last):
   File "<input>", line 1, in ?
TypeError: 'module' object is not callable
###

python knows about the *module* time but you are now treating the 
module like a function. Instead, you should access the function through 
the module's name:

###
 >>> time.time()
1112306919.518116
###

/c


From michael.hall at critterpixstudios.com  Fri Apr  1 00:14:19 2005
From: michael.hall at critterpixstudios.com (Mike Hall)
Date: Fri Apr  1 00:13:56 2005
Subject: [Tutor] Launching a file browser
In-Reply-To: <fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com>
	<424B3CA7.9010906@tds.net>
	<fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
Message-ID: <a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>

On Mar 31, 2005, at 12:21 AM, Max Noel wrote:

>> It's been too long since I used Python on MacOSX, but IIRC you can't 
>> just run a Python GUI program from the shell. Or something like 
>> that...you should ask this one on the python-mac SIG mailing list:
>> http://www.python.org/sigs/pythonmac-sig/
>>
>> Kent
>
> 	You have to launch your script with pythonw, not with python.

I'm unclear on why a command like webbrowser.open() will comfortably 
launch your default web browser (in my case Safari), but something as 
ubiquitous to an OS as a file browser has special needs to launch. 
Perhaps each application has custom written their file browser, and I'm 
assuming they are each essentially doing system calls to the same 
thing...?

-MH

From 3dbernard at gmail.com  Fri Apr  1 00:39:27 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri Apr  1 00:39:31 2005
Subject: [Tutor] test
Message-ID: <61d0e2b4050331143977eaff6d@mail.gmail.com>

test!
From jeannot18 at hotmail.com  Fri Apr  1 01:05:19 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Fri Apr  1 01:05:23 2005
Subject: [Tutor] I am puzzled - help needed
In-Reply-To: <04DEA566-A232-11D9-AEBD-000393C0D100@hotmail.com>
Message-ID: <BAY20-F152E038C6190FFD65333C4B3470@phx.gbl>

C Smith, Danny and Kent, thanks for the replies.

Here is my programme (I have reinstated the "while loop"

C Smith I like very much your method to get the last digits of a number.

It is WORKING NOW!! You can imagine how long I have spent on that, but I 
have learnt so much. Many thanks to all the people that have helped me, you 
will probably see me around asking a zillion other (very basics) questions.

________________________________________________________
from time import *

b = int(time())
b%100
running = True


while running:
    guess = int(raw_input ("Guess a number: "))

    if guess == b%100:
        print "Bravo, you guessed the right number"

    elif guess > b%100:
        print "Too high"

    else:
        print "Too low"

else:

    print "just right"

print "Done"


_______________________________________________________


From maxnoel_fr at yahoo.fr  Fri Apr  1 02:02:54 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr  1 02:02:58 2005
Subject: [Tutor] A simple question about creating a program
In-Reply-To: <01b301c53635$a034ab20$61cb8751@xp>
References: <d082fff8050330130079b4c91b@mail.gmail.com>
	<e268b8144f73d60e0100d5433a33a356@yahoo.fr>
	<01b301c53635$a034ab20$61cb8751@xp>
Message-ID: <e1abb9e6bcbeeca71966f255290af371@yahoo.fr>


On Mar 31, 2005, at 23:07, Alan Gauld wrote:

> And if Sun ever get round to finishing their JVM on a chip
> we'll have a chip that is both OO and procedural!

	At that point it would be a JRM, then, wouldn't it? :D

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From maxnoel_fr at yahoo.fr  Fri Apr  1 02:09:05 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr  1 02:09:09 2005
Subject: [Tutor] Launching a file browser
In-Reply-To: <a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com>
	<424B3CA7.9010906@tds.net>
	<fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
	<a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
Message-ID: <6974da4c579579cfaae504ea77d76583@yahoo.fr>


On Apr 1, 2005, at 00:14, Mike Hall wrote:

> On Mar 31, 2005, at 12:21 AM, Max Noel wrote:
>
>>> It's been too long since I used Python on MacOSX, but IIRC you can't 
>>> just run a Python GUI program from the shell. Or something like 
>>> that...you should ask this one on the python-mac SIG mailing list:
>>> http://www.python.org/sigs/pythonmac-sig/
>>>
>>> Kent
>>
>> 	You have to launch your script with pythonw, not with python.
>
> I'm unclear on why a command like webbrowser.open() will comfortably 
> launch your default web browser (in my case Safari), but something as 
> ubiquitous to an OS as a file browser has special needs to launch. 
> Perhaps each application has custom written their file browser, and 
> I'm assuming they are each essentially doing system calls to the same 
> thing...?

	No, the reason for that, IIRC, is that for the program to be able to 
interact with the window manager, it has to be launched with pythonw. 
When the program starts to display stuff elsewhere than in STDOUT or 
STDERR, an application launch is somehow triggered (icon appears in the 
Dock), which for some reason enables the user to interact with the 
program.
	Launching a web browser requires no interaction whatsoever with the 
WM, and can therefore be done with python.

	Yes, the python/pythonw distinction in Mac OS X is stupid, I'll give 
you that. I don't even know why it exists in the first place.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From keridee at jayco.net  Fri Apr  1 01:22:56 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr  1 02:35:45 2005
Subject: [Tutor] A Newbie Printing Question
References: <424950C6.1020909@cheqnet.net> <4249AAE3.30706@paradise.net.nz>
Message-ID: <006901c53652$e3d85170$5c5428cf@JSLAPTOP>

Cool! Does anybody know of... I guess a rather *thorough* tutorial of win32?
for the very reason that I don't know that this existed, and there may be 
other things I can use that I'm missing...

TIA,
Jacob

> Richard Lyons wrote:
>> I have little experience with programming.  I have Python installed on a 
>> Windows XP system.  What code do I need to use to send output from a 
>> Python script to a local printer attached to my workstation?  to a 
>> network printer?
>
> The win32print module (in Matt Hammond's windows modules) may help.
> eg:
>
>     pid = win32print.OpenPrinter(win32print.GetDefaultPrinter())
>     win32print.StartDocPrinter(pid, 1, ('My print job', None, 'raw'))
>     win32print.WritePrinter(pid, s)
>     win32print.EndDocPrinter(pid)
>     win32print.ClosePrinter(pid)
>
> When I did this, I was printing to a postscript printer, and I wasn't 
> printing anything that required complex layout.  So I generated the 
> postscript code myself, and then just sent it straight to the printer...
>
> -- 
> John.
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From keridee at jayco.net  Fri Apr  1 01:23:32 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr  1 02:35:48 2005
Subject: [Tutor] Float precision untrustworthy~~~
References: <BAY101-DAV13503214ABBA7EB77ADE04C1450@phx.gbl>
Message-ID: <006a01c53652$e4c39bd0$5c5428cf@JSLAPTOP>


> I understand what you are talking about, but I tend toward just making
> it one of the things to remember when working with floats.  (I've been
> bitten a lot when I forget to use '==' instead of '=', too!)

Yeah, but it threw me for a loop, because I could find *no*e way to compare 
a
float and an integer and get it to come out right before I remembered round.

> As you say, the problems arise when you try to make comparisons. To get
> around the difficulties with comparisons, I wrote a helper function:
>
> ###
> Python 2.3 (#2, Jul 30 2003, 11:45:28)
> [GCC 3.1 20020420 (prerelease)]
> Type "copyright", "credits" or "license" for more information.
> MacPython IDE 1.0.1
> >>> from math import floor, log10
> >>> def Round(x, n=0, sigfigs=False):
> '''An enhanced rounder which rounds to the nth significant digit
> (the nth digit from the first non-zero digit, not the nth decimal place)
>     if the parameter sigfigs is not zero.
>     This uses "round-up" decisions when the digit following the one of
>     interest is a 5, i.e. 1.35 and 1.45 Round to 1.4 and 1.5 when sigfigs
> = 2.
> '''
> if x==0: return 0
> if not sigfigs:
> return round(x,n)
> else:
> return round(x,n-1-int(floor(log10(abs(x)))))
> ###
>
> And here's a helper that uses it to check for equality of two numbers
> (floats, or otherwise)
> to whatever number of digits you desire --starting from the first non-zero
> digit, The default is for high precision.
>
> ###
> >>> def same(x,y,prec=9):
> """Return True if x and y are the same after being rounded to the same
> degree of precision."""
> return Round(x,prec,1)==Round(y,prec,1)
> ..
> >>> print same(1.3,1.31,3) #at the 3rd digit these are different
> False
> >>> print same(1.3,1.31,2) #at the second digit they are (rounded to)
> the same digit number
> True
> >>> same(64.0**(1/3.0) ,4) #here's your example
> True
> ###
>
> You can be bitten by any comparison, not only tests for equality, too.
>
> ###
> >>> while 1:
> ..  i+=.1
> ..  if i>2.1:break
> ..
> >>> print i
> 2.1
> ###
>
> It doesn't look like the last value of i was really greater than 2.1--it's
> actually 2.1000000000000005 so the result is correct (though not what we
> expected). We don't have the problem with a step size of 0.7 in this case,
> though, because the value before 2.8 was 2.0999999999999996--just a little
> smaller than 2.1.
>
> Here, we specify the precision and get the desired result.
>
> ###
> >>> i=0
> >>> while 1:
> ..  i+=.1
> ..  if round(i,9)>round(2.1,9):break
> ..
> >>> print i
> 2.2
> ###
>
>
> Wish granted in version 2.4 ;-) I don't have it on the mac, but there is a
> write-up at

I meant in the scripts -- even better, as a builtin.

Your above helper function is fine... but I believe that it should be part
of the __cmp__ method of the float types. Perhaps with optional parameter?
Such as oldway=True

Jacob Schmidt

From keridee at jayco.net  Fri Apr  1 01:25:33 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr  1 02:35:52 2005
Subject: [Tutor] A Newbie Printing Question
References: <424950C6.1020909@cheqnet.net> <008001c53485$eeb521f0$61cb8751@xp>
Message-ID: <006b01c53652$e5ec1640$5c5428cf@JSLAPTOP>

> 1) For plain text use the old DOS trick of sending output direct
>   to the PRN: file/device - I can't remember if this still works
>   in XP but I can't think why not...

The only reason I can think of is that Windows XP is not directly based on
DOS, wereas the other versions were.  In so doing, they have lost a lot of 
compatibility with many things. Old DOS games no longer work, some DOS 
commands do not work in their mock command prompt, etc.

Jacob 

From keridee at jayco.net  Fri Apr  1 01:17:46 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr  1 02:35:53 2005
Subject: [Tutor] Float precision untrustworthy~~~
References: <000901c5340d$52bd6410$da5428cf@JSLAPTOP><5d0204a1050330100579512ab8@mail.gmail.com>
	<017d01c5360f$f3e249b0$61cb8751@xp>
Message-ID: <006801c53652$e29c00e0$5c5428cf@JSLAPTOP>

> An early language translator app was fed
>
> 'Out of sight, out of mind'
>
> and then the result fed back in for reverse translation.
>
> The output was:
>
> 'Invisible, lunatic'

Cute, Alan. I like it!

Jeff - thanks for the insight. I guess I think more in theory than in 
reality sometimes.

Kent - thanks for your help.

Okay, I guess it works. I'll just have to indirectly call str method instead 
of repr or something.
For all of you, I had a stroke of genius one day and wrote my own (limited) 
rational class and called it Fract (fraction)

--Jacob 

From jfouhy at paradise.net.nz  Fri Apr  1 02:53:07 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Fri Apr  1 02:53:12 2005
Subject: [Tutor] A Newbie Printing Question
In-Reply-To: <006901c53652$e3d85170$5c5428cf@JSLAPTOP>
References: <424950C6.1020909@cheqnet.net> <4249AAE3.30706@paradise.net.nz>
	<006901c53652$e3d85170$5c5428cf@JSLAPTOP>
Message-ID: <1112316787.424c9b7327dbe@www.paradise.net.nz>

Quoting "Jacob S." <keridee@jayco.net>:

> Cool! Does anybody know of... I guess a rather *thorough* tutorial of
> win32? for the very reason that I don't know that this existed, and there may
> be other things I can use that I'm missing...

I don't know of anything online ... It seems a very poorly-documented corner of
Python.

Oreilly have a book which may be of help to you if you do a lot of programming
on Windows: http://www.oreilly.com/catalog/pythonwin32/

The only other thing I can suggest is try running pydoc on the win32 modules and
looking at the docstrings.

-- 
John.
From michael.hall at critterpixstudios.com  Fri Apr  1 03:06:34 2005
From: michael.hall at critterpixstudios.com (Mike Hall)
Date: Fri Apr  1 03:10:18 2005
Subject: [Tutor] Launching a file browser
In-Reply-To: <6974da4c579579cfaae504ea77d76583@yahoo.fr>
References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com>
	<424B3CA7.9010906@tds.net>
	<fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
	<a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
	<6974da4c579579cfaae504ea77d76583@yahoo.fr>
Message-ID: <ac2e52da1a3851eaaaa8be069f9c4fd4@critterpixstudios.com>

Ah, so it has to do with access to the window manager. That answers a 
lot, thanks.


On Mar 31, 2005, at 4:09 PM, Max Noel wrote:

>
> On Apr 1, 2005, at 00:14, Mike Hall wrote:
>
>> On Mar 31, 2005, at 12:21 AM, Max Noel wrote:
>>
>>>> It's been too long since I used Python on MacOSX, but IIRC you 
>>>> can't just run a Python GUI program from the shell. Or something 
>>>> like that...you should ask this one on the python-mac SIG mailing 
>>>> list:
>>>> http://www.python.org/sigs/pythonmac-sig/
>>>>
>>>> Kent
>>>
>>> 	You have to launch your script with pythonw, not with python.
>>
>> I'm unclear on why a command like webbrowser.open() will comfortably 
>> launch your default web browser (in my case Safari), but something as 
>> ubiquitous to an OS as a file browser has special needs to launch. 
>> Perhaps each application has custom written their file browser, and 
>> I'm assuming they are each essentially doing system calls to the same 
>> thing...?
>
> 	No, the reason for that, IIRC, is that for the program to be able to 
> interact with the window manager, it has to be launched with pythonw. 
> When the program starts to display stuff elsewhere than in STDOUT or 
> STDERR, an application launch is somehow triggered (icon appears in 
> the Dock), which for some reason enables the user to interact with the 
> program.
> 	Launching a web browser requires no interaction whatsoever with the 
> WM, and can therefore be done with python.
>
> 	Yes, the python/pythonw distinction in Mac OS X is stupid, I'll give 
> you that. I don't even know why it exists in the first place.
>
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting 
> and sweating as you run through my corridors... How can you challenge 
> a perfect, immortal machine?"
>
>
>
>
-MH

From py at runsun.info  Fri Apr  1 03:16:18 2005
From: py at runsun.info (py)
Date: Fri Apr  1 03:16:25 2005
Subject: [Tutor] Sorting more than one list
Message-ID: <20050401011618.28157.qmail@station172.com>



An alternative way of doing this (if you have python 2.4):

>>> ppl =   ['john', 'mary', 'lary', 'jane']
>>> age =   [15, 30, 23, 25]
>>> height= [160, 165, 178, 170]

>>> sortby = lambda a, b: [a[b.index(x)] for x in sorted(b)]
>>> sortby(ppl, age)
['john', 'lary', 'jane', 'mary']
>>> sortby(ppl, height)
['john', 'mary', 'jane', 'lary']

>>> age    # age is not changed
[15, 30, 23, 25]

 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050401/64033487/attachment.html
From cyresse at gmail.com  Fri Apr  1 03:32:32 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Fri Apr  1 03:32:34 2005
Subject: [Tutor] A Newbie Printing Question
In-Reply-To: <1112316787.424c9b7327dbe@www.paradise.net.nz>
References: <424950C6.1020909@cheqnet.net> <4249AAE3.30706@paradise.net.nz>
	<006901c53652$e3d85170$5c5428cf@JSLAPTOP>
	<1112316787.424c9b7327dbe@www.paradise.net.nz>
Message-ID: <f2ff2d050331173244b0684f@mail.gmail.com>

First off, print <stuff> stills works from an XP cmd.exe, but only for
LPT printers, not USB.

Secondly, Win32's methods are well documented, using them isn't. 
There are some tutorials included with the download, and you get a chm
help file filled with the objects and methods, but as far as tutorials
go, buy Mark Hammond's book if you want the full picture.

For what it's worth, PyWin32 is one of the simplest interfaces to the
Windows API / COM I've seen, so if you intend to do a lot of XP stuff,
you'll need it.

Oh yeah, and there's bugger all docstrings.



Regards,


Liam Clarke

On Fri, 01 Apr 2005 12:53:07 +1200 (NZST), jfouhy@paradise.net.nz
<jfouhy@paradise.net.nz> wrote:
> Quoting "Jacob S." <keridee@jayco.net>:
> 
> > Cool! Does anybody know of... I guess a rather *thorough* tutorial of
> > win32? for the very reason that I don't know that this existed, and there may
> > be other things I can use that I'm missing...
> 
> I don't know of anything online ... It seems a very poorly-documented corner of
> Python.
> 
> Oreilly have a book which may be of help to you if you do a lot of programming
> on Windows: http://www.oreilly.com/catalog/pythonwin32/
> 
> The only other thing I can suggest is try running pydoc on the win32 modules and
> looking at the docstrings.
> 
> --
> John.
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From kent37 at tds.net  Fri Apr  1 05:19:18 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  1 05:19:22 2005
Subject: [Tutor] I am puzzled - help needed
In-Reply-To: <BAY20-F152E038C6190FFD65333C4B3470@phx.gbl>
References: <BAY20-F152E038C6190FFD65333C4B3470@phx.gbl>
Message-ID: <424CBDB6.9000703@tds.net>

John Carmona wrote:
> It is WORKING NOW!! You can imagine how long I have spent on that, but I 
> have learnt so much. Many thanks to all the people that have helped me, 
> you will probably see me around asking a zillion other (very basics) 
> questions.

Congratulations! I have one^H^H^Htwo small notes below.

> ________________________________________________________
> from time import *
> 
> b = int(time())
> b%100

If you say
b = b%100
then you remember the target number and you don't have to keep writing b%100, just use b.

> running = True
> 
> 
> while running:
>    guess = int(raw_input ("Guess a number: "))
> 
>    if guess == b%100:
>        print "Bravo, you guessed the right number"
> 
>    elif guess > b%100:
>        print "Too high"
> 
>    else:
>        print "Too low"
> 
> else:
> 
>    print "just right"
> 
> print "Done"

OK one more note, I don't see how you will ever get out of the loop, you never set running to False 
or break.

Kent

From cyresse at gmail.com  Fri Apr  1 05:20:38 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Fri Apr  1 05:20:42 2005
Subject: [Tutor] Sorting more than one list
In-Reply-To: <20050401011618.28157.qmail@station172.com>
References: <20050401011618.28157.qmail@station172.com>
Message-ID: <f2ff2d050331192035e8e66f@mail.gmail.com>

What's b.index(x) do?

I'm guessing the for a list Delta = ["a,"b","c"], you get 

Delta.index("b")

1

Am I right? 

On Apr 1, 2005 1:16 PM, py <py@runsun.info> wrote:
> 
> 
> An alternative way of doing this (if you have python 2.4): 
> 
> >>> ppl =   ['john', 'mary', 'lary', 'jane']
> >>> age =   [15, 30, 23, 25]
> >>> height= [160, 165, 178, 170]
> 
> >>> sortby = lambda a, b: [a[b.index(x)] for x in sorted(b)]
> >>> sortby(ppl, age)
> ['john', 'lary', 'jane', 'mary']
> >>> sortby(ppl, height)
> ['john', 'mary', 'jane', 'lary'] 
> 
> >>> age    # age is not changed
> [15, 30, 23, 25] 
> 
>   
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From tameyer at ihug.co.nz  Fri Apr  1 05:25:46 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Fri Apr  1 05:26:00 2005
Subject: [Tutor] Sorting more than one list
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8027DD8E8@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0011@its-xchg4.massey.ac.nz>

> What's b.index(x) do?
> 
> I'm guessing the for a list Delta = ["a,"b","c"], you get 
> 
> Delta.index("b")
> 
> 1
> 
> Am I right? 

Yes.  For future use, the easiest way to answer a question like that is to
do:

>>> help([].index)
Help on built-in function index:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of
value

Or, if you have an idea, just try it out:

>>> Delta = ["a","b","c"]
>>> Delta.index("b")
1

=Tony.Meyer

From alan.gauld at freenet.co.uk  Fri Apr  1 09:59:20 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 09:59:04 2005
Subject: [Tutor] Sorting more than one list
References: <1112235561.1983.7.camel@rossum>
Message-ID: <01d601c53690$b63f7610$61cb8751@xp>

> I need to sort 4 lists but I need that they make the "sort
together".
> I'll sort just one but when I change the position of the items of
the
> 1st list I have to change the positions of the other 3 lists. Can I
do
> this just using the sort() method of the list object?
> If I can't, someone know a site that have one sort method in python
that
> its easily to implement and fast?

Since the data are obviously related (since you need to keep them
linked),
I'd be inclined to merge the lists into a list of tuples

merged = [(a,b,c,d) for a in l1 for b in l2 for c in l3 for d in l4]

Then you can sort 'merged' and it should just work.... The default
sort will order the tuples by the first member...

Alan G.

From maxnoel_fr at yahoo.fr  Fri Apr  1 10:04:02 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr  1 10:04:06 2005
Subject: [Tutor] Sorting more than one list
In-Reply-To: <01d601c53690$b63f7610$61cb8751@xp>
References: <1112235561.1983.7.camel@rossum>
	<01d601c53690$b63f7610$61cb8751@xp>
Message-ID: <dfea95ca05a29109d95e846cd94ae310@yahoo.fr>


On Apr 1, 2005, at 09:59, Alan Gauld wrote:

> Since the data are obviously related (since you need to keep them
> linked),
> I'd be inclined to merge the lists into a list of tuples
>
> merged = [(a,b,c,d) for a in l1 for b in l2 for c in l3 for d in l4]
>
> Then you can sort 'merged' and it should just work.... The default
> sort will order the tuples by the first member...
>
> Alan G.

	What's the advantage of this compared to the "zip" method (which 
yields the same result AFAICT)?

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From alan.gauld at freenet.co.uk  Fri Apr  1 10:05:16 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 10:04:58 2005
Subject: [Tutor] What is the best book to start?
References: <20050331040859.6589.qmail@web60008.mail.yahoo.com>
Message-ID: <01f401c53691$8a604550$61cb8751@xp>

> I am starting to studying Python. I have some previous
> experience with C (beginner level).

Probably the standard tutorial on the web site is the best
place for you to start.

> "Learning Python" by Lutz & Ascher,

And this is very good supporting material.

> "Python How to Program" by Deitel and others.

And this is particularly good as an intro into the wider areas
such as PyGame, XML/HTML GUIs and Network programming. The early
chapters are done better IMHO by Lutz, aand the official tutor.

Your next purchase should be either or both of:

Python in a Nutshell - a great 'pocket' reference and
Python Programming on Win32 - but only if you are using Windows of
course!

You have more than enough beginner material already.

Alan G.

From alan.gauld at freenet.co.uk  Fri Apr  1 10:08:47 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 10:08:30 2005
Subject: [Tutor] What is the best book to start?
References: <20050331040859.6589.qmail@web60008.mail.yahoo.com>
	<148eea7105033021057544da2f@mail.gmail.com>
Message-ID: <01ff01c53692$08406450$61cb8751@xp>


> I really think alan gauld books, learning how to program is one of
the
> best esp if you are new.

Thanks for the kind words! :-)

However if the OP has some C - my book will likely be too basic,
it starts from ground zero, but anyone who has used C will find
the pace too slow I suspect.

OTOH The Advanced Topics section of my web tutorial might be worth
a visit when newer concepts like OOP and Functuional programming
get reached.

But thanks again for the plug! :-)

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

From alan.gauld at freenet.co.uk  Fri Apr  1 10:11:20 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 10:11:01 2005
Subject: [Tutor] wxPython / Tkinter Grid
References: <f2ff2d050330214613a10151@mail.gmail.com>
Message-ID: <020601c53692$6353ab40$61cb8751@xp>

> I know a wxPython grid is totally different to a Tkinter grid, but
is
> there a Tkinter equivalent of a wxPython grid? I'm finding wxPython
to
> be fiddly and restrictive...

Then Tkinter will be more so. Tk is a fairly basic toolkit, fine for
wrapping a command line app in a glossy front end but not for
sophisticated GUI work.

There is no grid component in Tk out of the box, but some add on
toolkits
supply one. Try searching on the Vaults of Parnassus or on the
ActiveState site if you are determined to try Tkinter...

Alan G.

From ralf.steckel at online.ms  Fri Apr  1 10:30:31 2005
From: ralf.steckel at online.ms (ralf.steckel@online.ms)
Date: Fri Apr  1 10:30:48 2005
Subject: [Tutor] updating Oracle tables via python
Message-ID: <166717132@web.de>

Hi all,

1) this are the *correct* quotation marks:

strUpdate = " UPDATE table SET firstname = 'JOSEPH'  WHERE lastname = 'SMITH' "

because SQL uses single quotation marks for character strings in column values.
Double quotation marks are used to quote a column name when the column name
is defined in mixed case letters (if the column name is all in small or capital letters there is
no need for quoting the column name)

2) I guess that the problem is that there's no finishing semicolon (;) for the statement,
because the native Oracle SQL-command interpreter 'sqlplus' requires a semicolon at
the end of each SQL statement

3) Don't call the table which You want to update 'table'
'table' is a reserved word in SQL and for the update-statement You have to specify
the name of the table (i.e.: namelist ) - and make sure that You have created the 
table via a 'CREATE TABLE ...' statement before and inserted some values in it

That's my five cent...

best wishes,

Ralf

Liam Clarke <cyresse@gmail.com> schrieb am 30.03.05 02:14:05:
> 
> >From what little SQL I know, 
> 
> try using your quotation marks differently, see if it helps.
> 
> strUpdate = 'UPDATE table SET firstname = "JOSEPH" WHERE lastname = "SMITH" '
> 
> Good luck, 
> 
> Liam Clarke
-snip
> > script will print all of the print commands up to the
> > cursor.execute(strUpdate) command, but not those after it.  Therefore, I
> > think that the cursor.execute(strUpdate) is the source of the problem.
> > Also, when I manually query the database, the records within the table have
> > not been changed.
> > 
> > Thanks,
> > 
> > Tom
-snip
> > strUpdate = " UPDATE table SET firstname = 'JOSEPH'  WHERE lastname =
> > 'SMITH' "


From alan.gauld at freenet.co.uk  Fri Apr  1 10:49:04 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 10:48:50 2005
Subject: [Tutor] I am puzzled - help needed
References: <BAY20-F300C8C7422DBBFD120C3C6B3470@phx.gbl>
Message-ID: <020d01c53697$a975abf0$61cb8751@xp>

> from time import *
>
> n = time()
> s = str(n)
> numb = s[-2:]   # last two characters of the string
> numb = int(numb) # convert back to a number
> guess = (raw_input('Enter a number: '))

You need to convert the string returned by raw_input() into a number

guess = int(raw_input('Enter a number: '))

otherwise you are comparing a string with anumber.

> if guess == numb:
>     print ("Bravo, you have just won the right to play again!")
>
> elif guess < numb:
>     print "You are just a bit too low, try again"
>
> else:
>     print "You are just a bit too high, try again"
>
>     print "The End"
> --------------------------------------------------------------------
--------------------------------

> If i write the following line:
> "n = time.time()
>
> I get the following error message:
> AttributeError: 'builtin_function_or_method' object has no attribute
'time'

Thats because you used from time import *

So when you type time.time Python sees the first 'time' as being the
time modules time() function. When you type time.tuime it tries to
access a time attribute of the time function. That doesn't exist
which is what the error says...

Use either

import time
t = time.time()

OR

from time import time
t= time()

Its considered bad practice to use

from time import *

because its easy to get collisions between names in the time module
and other names in your program.

> I feel like an idiot asking what is probably very basics questions
but my
> desire to learn is quite high right now and I don't want to lose it,
thanks
> again

Ask away, thats what the list is for. None of your questions have been
in any way stupid. And we do try to answer stupid questions too! :-)

Alan G.

From moranar at moranar.com.ar  Fri Apr  1 12:01:02 2005
From: moranar at moranar.com.ar (Adriano Varoli Piazza)
Date: Fri Apr  1 12:00:22 2005
Subject: [Tutor] function loading a file's lines to a list
Message-ID: <1112349662.18523.6.camel@localhost.localdomain>

I'm working on this coding assignment I had for a c++ class. For fun, I
decided to implement it in Python, and I'm done. Still, I found a
behaviour I can't explain:
The function loadfromfile

def loadfromfile(lines, fname):
    try:
        finput = file(fname, 'r')
        lines = []
        for line in finput:
            line = line[:-1]
            lines.append(line)
        finput.close()
        return lines
    except:
        print "Couldn't load from file %s" % (fname)

takes a file (referenced by fname) and appends each line of text in it
to a list called lines (a global var, see full code below).
Problem is, as soon as I leave the function, lines is empty. Even when
I'm returning it, non-empty. I tried putting a print statement just
before "return lines" and it shows the complete list (according to what
was in the file, obviously). But after that, the contents are emptied.
Modifying that function to

def loadfromfile(fname):
    try:
        finput = file(fname, 'r')
        global lines
        lines = []
        for line in finput:
            line = line[:-1]
            lines.append(line)
        finput.close()
        #return lines
    except:
        print "Couldn't load from file %s" % (fname)

works (with or without the return lines statements, that's why I
commented it), but I don't understand why. I know lists are modified in-
place, so I'd imagine it would work in the first case too.

-------------------------------
Full code below:

#!/usr/bin/env python
# pysimpleditor: a concept - text editor

# Global vars:
lines = []			# Holds the lines of text in memory.

# Functions:

# insertline inserts text into lines _before_ the index linenumber.
def insertline(lines, linenumber):		
	try:
			line = int(linenumber)
	except: 
		print "not a valid line number"
	text = raw_input("Input text: ")
	lines.insert(line, text)
	
#deleteline deletes the line of text at lines[linenumber]
def deleteline(lines, linenumber):
	try:
		line = int(linenumber)
	except: 
		print "not a valid line number"
	lines.pop(line)

# Print the lines to the screen
def printlines(lines):
	for line in lines:
		print line
		
# Saves list lines to file fname.
def savetofile(lines, fname):
	try:
		foutput = file(fname, 'w')
		for line in lines:
			line = line + '\n'
			foutput.write(line)
		foutput.close()

	except:
		print "Couldn't open file %s for saving" % (fname)

# Loads text from fname into list lines.
def loadfromfile(fname):
	try:
		finput = file(fname, 'r')
		global lines
		lines = []
		for line in finput:
			line = line[:-1]
			lines.append(line)
		finput.close()
	except:
		print "Couldn't load from file %s" % (fname)
	

def printhelp():
	print """
pysimpleeditor: A simple text editor.
Use:
In: inserts a line of text before line n.
En: deletes line n.
V:  prints all lines on the screen.
S:  saves the lines of text to a file.
C:  loads text from a file.
H:  this message.
F:  exit the program.
"""

#The program:
while True:
	choice = raw_input("Please enter a command (h for help): ")
	choice = choice.upper()			# Why bother the user with caps or uncaps?
	
	if choice[0] == 'I':			# Line addition
		insertline(lines, choice[1:])

	elif choice[0] == 'E':			# Line deletion
		deleteline(lines, choice[1:])

	elif choice[0] == 'V':			# Text visualization
		for line in lines:
			print line
			
	elif choice[0] == 'S':			# Save text to file
		fname = raw_input("Enter a filename to save: ")
		savetofile(lines, fname)
		
	elif choice[0] == 'C':			# Load text from file, _replaces_ list!
		fname = raw_input("Enter a filename to load: ")
		loadfromfile(fname)
			
	elif choice[0] == 'H':
		printhelp()
		
	elif choice[0] == 'F':				# Exits the program
		break
		
	else:
		print "%s is not a valid command. Press h for help" % (choice[0])

--------------------------------
-- 
Adriano Varoli Piazza
The Inside Out: http://moranar.com.ar
MSN: adrianomd@hotmail.com
ICQ: 4410132

From moranar at moranar.com.ar  Fri Apr  1 12:24:41 2005
From: moranar at moranar.com.ar (Adriano Varoli Piazza)
Date: Fri Apr  1 12:23:52 2005
Subject: [Tutor] function loading a file's lines to a list
In-Reply-To: <1112349662.18523.6.camel@localhost.localdomain>
References: <1112349662.18523.6.camel@localhost.localdomain>
Message-ID: <1112351081.18570.3.camel@localhost.localdomain>

Il giorno ven, 01-04-2005 alle 12:01 +0200, Adriano Varoli Piazza ha
scritto:
[... Massive lines of code ...]

It's possibly of interest that I'm running this with python 2.4.1
compiled from source on Fedora Core 3.

Thanks for the patience
-- 
Adriano Varoli Piazza
The Inside Out: http://moranar.com.ar
MSN: adrianomd@hotmail.com
ICQ: 4410132

From ewald.ertl at hartter.com  Fri Apr  1 12:46:57 2005
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Fri Apr  1 12:47:00 2005
Subject: [Tutor] function loading a file's lines to a list
In-Reply-To: <1112349662.18523.6.camel@localhost.localdomain>
References: <1112349662.18523.6.camel@localhost.localdomain>
Message-ID: <20050401124657.00003ea4@sunray2.hartter.com>

Hi!

on Fri, 01 Apr 2005 12:01:02 +0200  Adriano Varoli Piazza <moranar@moranar.com.ar> wrote :
---------------------------------------------------------------------------------------------

Adriano Varoli Piazza > 
Adriano Varoli Piazza > def loadfromfile(fname):
Adriano Varoli Piazza >     try:
Adriano Varoli Piazza >         finput = file(fname, 'r')
Adriano Varoli Piazza >         global lines

global say, that lines is "global" defined. Otherwise as in your first 
version the lines-List is defined local in the loadfromfile()-function. 
(You can return the local list and assign it, where you call the loadfromfile()-
function. )

Adriano Varoli Piazza >         lines = []
Adriano Varoli Piazza >         for line in finput:
Adriano Varoli Piazza >             line = line[:-1]
Adriano Varoli Piazza >             lines.append(line)
Adriano Varoli Piazza >         finput.close()
Adriano Varoli Piazza >         #return lines

As you do not use the returned value of loadfromfile(), it's useless here.

Adriano Varoli Piazza >     except:
Adriano Varoli Piazza >         print "Couldn't load from file %s" % (fname)
Adriano Varoli Piazza > 
Adriano Varoli Piazza > works (with or without the return lines statements, that's why I
Adriano Varoli Piazza > commented it), but I don't understand why. I know lists are modified in-
Adriano Varoli Piazza > place, so I'd imagine it would work in the first case too.
Adriano Varoli Piazza > 

------------------- end ----------------------

HTH Ewald

From moranar at moranar.com.ar  Fri Apr  1 12:58:51 2005
From: moranar at moranar.com.ar (Adriano Varoli Piazza)
Date: Fri Apr  1 12:58:07 2005
Subject: [Tutor] function loading a file's lines to a list
In-Reply-To: <20050401124657.00003ea4@sunray2.hartter.com>
References: <1112349662.18523.6.camel@localhost.localdomain>
	<20050401124657.00003ea4@sunray2.hartter.com>
Message-ID: <1112353131.18796.0.camel@localhost.localdomain>

Il giorno ven, 01-04-2005 alle 12:46 +0200, Ewald Ertl ha scritto:
> Hi!
> 
> on Fri, 01 Apr 2005 12:01:02 +0200  Adriano Varoli Piazza <moranar@moranar.com.ar> wrote :
> ---------------------------------------------------------------------------------------------
> 
> Adriano Varoli Piazza > 
> Adriano Varoli Piazza > def loadfromfile(fname):
> Adriano Varoli Piazza >     try:
> Adriano Varoli Piazza >         finput = file(fname, 'r')
> Adriano Varoli Piazza >         global lines
> 
> global say, that lines is "global" defined. Otherwise as in your first 
> version the lines-List is defined local in the loadfromfile()-function. 
> (You can return the local list and assign it, where you call the loadfromfile()-
> function. )

I understand now. I got confused with "lists elements are changed in
place"... Thanks


-- 
Adriano Varoli Piazza
The Inside Out: http://moranar.com.ar
MSN: adrianomd@hotmail.com
ICQ: 4410132

From klappnase at freenet.de  Fri Apr  1 12:35:13 2005
From: klappnase at freenet.de (Michael Lange)
Date: Fri Apr  1 13:31:36 2005
Subject: [Tutor] wxPython / Tkinter Grid
In-Reply-To: <020601c53692$6353ab40$61cb8751@xp>
References: <f2ff2d050330214613a10151@mail.gmail.com>
	<020601c53692$6353ab40$61cb8751@xp>
Message-ID: <20050401123513.7327a91a.klappnase@freenet.de>

On Fri, 1 Apr 2005 09:11:20 +0100
"Alan Gauld" <alan.gauld@freenet.co.uk> wrote:

> > I know a wxPython grid is totally different to a Tkinter grid, but
> is
> > there a Tkinter equivalent of a wxPython grid? I'm finding wxPython
> to
> > be fiddly and restrictive...
> 
> Then Tkinter will be more so. Tk is a fairly basic toolkit, fine for
> wrapping a command line app in a glossy front end but not for
> sophisticated GUI work.
> 
> There is no grid component in Tk out of the box, but some add on
> toolkits
> supply one. Try searching on the Vaults of Parnassus or on the
> ActiveState site if you are determined to try Tkinter...
> 
> Alan G.
> 

Or look here:

    http://tkinter.unpythonic.net/wiki/Widgets

There is a number of links to table widget implementations in Tkinter o nthe wiki page.

I hope this helps

Michael
From kent37 at tds.net  Fri Apr  1 13:33:08 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  1 13:33:14 2005
Subject: [Tutor] Sorting more than one list
In-Reply-To: <dfea95ca05a29109d95e846cd94ae310@yahoo.fr>
References: <1112235561.1983.7.camel@rossum>	<01d601c53690$b63f7610$61cb8751@xp>
	<dfea95ca05a29109d95e846cd94ae310@yahoo.fr>
Message-ID: <424D3174.8040106@tds.net>

Max Noel wrote:
> 
> On Apr 1, 2005, at 09:59, Alan Gauld wrote:
> 
>> Since the data are obviously related (since you need to keep them
>> linked),
>> I'd be inclined to merge the lists into a list of tuples
>>
>> merged = [(a,b,c,d) for a in l1 for b in l2 for c in l3 for d in l4]
>>
>> Then you can sort 'merged' and it should just work.... The default
>> sort will order the tuples by the first member...
>>
>> Alan G.
> 
> 
>     What's the advantage of this compared to the "zip" method (which 
> yields the same result AFAICT)?

Yikes! Alan must have been up too late. They are not the same at all. Alan's code creates a list 
containing *every combination* of one element from each source list:

  >>> a=[1,2,3]
  >>> b=[4,5,6]
  >>> c=[7,8,9]
  >>> [ (aa,bb,cc) for aa in a for bb in b for cc in c ]
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), 
(2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5,
  8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 
8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]

This is very different from zip(a,b,c) which makes a list of *corresponding* items from each list:

  >>> zip(a,b,c)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Kent

From kent37 at tds.net  Fri Apr  1 13:45:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  1 13:45:31 2005
Subject: [Tutor] Cryptography Toolkit
In-Reply-To: <7b969903050331063563900cc2@mail.gmail.com>
References: <7b9699030503310549339627df@mail.gmail.com>	
	<424C05AB.3030104@tds.net>
	<7b969903050331063563900cc2@mail.gmail.com>
Message-ID: <424D3455.9020309@tds.net>

It works if you make a new XOR object for the decryption:

from Crypto.Cipher import XOR

obj_xor = XOR.new("string")
str_encrypt = "encrypt this string"
print str_encrypt

xored = obj_xor.encrypt(str_encrypt)
print xored

obj_xor = XOR.new("string")
print obj_xor.decrypt(xored)

Kent

Mark Thomas wrote:
> On Thu, 31 Mar 2005 09:14:03 -0500, Kent Johnson <kent37@tds.net> wrote:
> 
>>If you post your code and the complete error message including the stack trace we may be able to help.
>>
>>Kent
> 
> 
> Thanks Ken
> 
> I'm getting closer to making this work using the XOR cipher. Here's
> what I'm doing.
> 
> <from python>
> 
> from Crypto.Cipher import XOR
> 
> obj_xor = XOR.new("string")
> str_encrypt = "encrypt this string"
> xored = obj_xor.encrypt(str_encrypt)
> xored
> '\x16\x1a\x11\x1b\x17\x17\x07T\x06\x01\x07\x14S\x07\x06\x1b\x07\t\x14'
> obj_xor.decrypt(xored)
> "bhxupds&oo`g'uou`z`" <== *confused by this output*
> 
> </from python>
> 
> Close but no cigar!! *grin*
> 

From mhansen at cso.atmel.com  Fri Apr  1 16:32:22 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Fri Apr  1 16:32:16 2005
Subject: [Tutor] What is the best book to start?
In-Reply-To: <20050401084854.EE0101E4014@bag.python.org>
References: <20050401084854.EE0101E4014@bag.python.org>
Message-ID: <424D5B76.8080503@cso.atmel.com>

> ------------------------------------------------------------------------
> 
> Subject:
> Re: [Tutor] What is the best book to start?
> From:
> "Alan Gauld" <alan.gauld@freenet.co.uk>
> Date:
> Fri, 1 Apr 2005 09:05:16 +0100
> To:
> "Hoffmann" <oasf2004@yahoo.com>, <tutor@python.org>
> 
> To:
> "Hoffmann" <oasf2004@yahoo.com>, <tutor@python.org>
> 
> 
>>I am starting to studying Python. I have some previous
>>experience with C (beginner level).
> 
> 
> Probably the standard tutorial on the web site is the best
> place for you to start.
> 
> 
>>"Learning Python" by Lutz & Ascher,
> 
> 
> And this is very good supporting material.
> 
> 
>>"Python How to Program" by Deitel and others.
> 
> 
> And this is particularly good as an intro into the wider areas
> such as PyGame, XML/HTML GUIs and Network programming. The early
> chapters are done better IMHO by Lutz, aand the official tutor.
> 
> Your next purchase should be either or both of:
> 
> Python in a Nutshell - a great 'pocket' reference and
> Python Programming on Win32 - but only if you are using Windows of
> course!
> 
> You have more than enough beginner material already.
> 
> Alan G.
> 

I'd also try to fit in Dive Into Python [http://diveintopython.org/]. This book 
really got me hooked on Python. It assumes you know some programming.

Mike
From Christian.Wyglendowski at greenville.edu  Fri Apr  1 17:19:07 2005
From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski)
Date: Fri Apr  1 17:19:11 2005
Subject: [Tutor] A Newbie Printing Question
Message-ID: <CE1475C007B563499EDBF8CDA30AB45B028B4433@empex.greenville.edu>

> -----Original Message-----
> From: tutor-bounces@python.org 
> [mailto:tutor-bounces@python.org] On Behalf Of jfouhy@paradise.net.nz
> 
> Quoting "Jacob S." <keridee@jayco.net>:
> 
> > Cool! Does anybody know of... I guess a rather *thorough* 
> tutorial of
> > win32? for the very reason that I don't know that this 
> existed, and there may
> > be other things I can use that I'm missing...
> 
> I don't know of anything online ... It seems a very 
> poorly-documented corner of
> Python.

Since the pywin32 stuff just wraps standard Win32 libraries for the most
part, the resources at MSDN (http://msdn.microsoft.com) are quite
helpful.  While it is not Python-specific, it would probably be
redundant to extensively document the pywin32 stuff with MSDN available.

> Oreilly have a book which may be of help to you if you do a 
> lot of programming
> on Windows: http://www.oreilly.com/catalog/pythonwin32/

I agree.  It is an older book, but I found it helpful.  I think I got it
used for $6 or $8 on Amazon.

Christian
http://www.dowski.com
From thomas.s.mark at gmail.com  Fri Apr  1 18:40:21 2005
From: thomas.s.mark at gmail.com (Mark Thomas)
Date: Fri Apr  1 18:40:25 2005
Subject: [Tutor] Cryptography Toolkit
In-Reply-To: <424D3455.9020309@tds.net>
References: <7b9699030503310549339627df@mail.gmail.com>
	<424C05AB.3030104@tds.net> <7b969903050331063563900cc2@mail.gmail.com>
	<424D3455.9020309@tds.net>
Message-ID: <7b96990305040108406653367e@mail.gmail.com>

On Apr 1, 2005 6:45 AM, Kent Johnson <kent37@tds.net> wrote:
> It works if you make a new XOR object for the decryption:
> 
> from Crypto.Cipher import XOR
> 
> obj_xor = XOR.new("string")
> str_encrypt = "encrypt this string"
> print str_encrypt
> 
> xored = obj_xor.encrypt(str_encrypt)
> print xored
> 
> obj_xor = XOR.new("string")
> print obj_xor.decrypt(xored)
> 
> Kent

Excellent !!
Many thanks Kent.
-- 
 _
( ) Mark Thomas     ASCII ribbon campaign
  X www.theswamp.org   - against HTML email
/ \
From alan.gauld at freenet.co.uk  Fri Apr  1 18:53:49 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 18:54:48 2005
Subject: [Tutor] A Newbie Printing Question
References: <424950C6.1020909@cheqnet.net> <008001c53485$eeb521f0$61cb8751@xp>
	<006b01c53652$e5ec1640$5c5428cf@JSLAPTOP>
Message-ID: <022401c536db$61605c90$61cb8751@xp>


> > 1) For plain text use the old DOS trick of sending output direct
> >   to the PRN: file/device - I can't remember if this still works
> >   in XP but I can't think why not...
>
> The only reason I can think of is that Windows XP is not directly
based on
> DOS, wereas the other versions were.  In so doing, they have lost a
lot of
> compatibility with many things. Old DOS games no longer work, some
DOS
> commands do not work in their mock command prompt, etc.

Whatever the reason, I can't seem to open the PRN or LPT devices for
output...
Also tried the USB002 port which my printer claims to be connected to,
so
it looks like XP finally kills easy PC printing... I'll be sticking to
my HTML technique from now on I guess.

Alan G.


From alan.gauld at freenet.co.uk  Fri Apr  1 19:32:50 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  1 19:32:30 2005
Subject: [Tutor] Sorting more than one list
References: <1112235561.1983.7.camel@rossum>	<01d601c53690$b63f7610$61cb8751@xp><dfea95ca05a29109d95e846cd94ae310@yahoo.fr>
	<424D3174.8040106@tds.net>
Message-ID: <02e401c536e0$d4c14fa0$61cb8751@xp>

> Yikes! Alan must have been up too late. They are not the same at
all.
> Alan's code creates a list containing *every combination* of one
> element from each source list:

Oops! Blush...

Lack of testing I'm afraid, I checked the syntax worked but not
the actual results! Thing is, I knew about zip but thought it was
deprecated so decided to try a comprehension instead.
Lesson: stick with what you know! :-)

Alan G.

PS. My posts seem to be taking a long time to make it to the digest.
I only got this at 5:30pm but posted it before 10 last night...

From cpu.crazy at gmail.com  Fri Apr  1 18:07:08 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri Apr  1 21:36:11 2005
Subject: [Tutor] Module Loop doesn't work (Joseph Q.)
Message-ID: <6.1.0.6.2.20050401100257.01df9180@pop.gmail.com>

Hi,
  I have some code on a geek dictionary that I'm making where the command 
geeker() opens a module for the "real" geek dictionary (where you can type 
a word to see what it is geekified). Supposedly, you type lobby() to go 
back to what I call  the lobby (where you can get info on the web site and 
email and version). But it just loops back to the Geeker>>> prompt where 
you type the word that you want geekified. I even tried having it restart 
the whole program by importing the index module that I wrote. But it still 
won't restart the program!

Thanks,
         Joseph Q.  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050401/5ba056c6/attachment.html
From project5 at redrival.net  Sat Apr  2 01:03:00 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr  2 01:03:34 2005
Subject: [Tutor] Re: Module Loop doesn't work (Joseph Q.)
References: <6.1.0.6.2.20050401100257.01df9180@pop.gmail.com>
Message-ID: <10k77t1uyukav.q6lw3qj6dzt8$.dlg@40tude.net>

Joseph Quigley wrote on Fri, 01 Apr 2005 10:07:08 -0600:

>   I have some code on a geek dictionary that I'm making where the command 
> geeker() opens a module for the "real" geek dictionary (where you can type 
> a word to see what it is geekified). Supposedly, you type lobby() to go 
> back to what I call  the lobby (where you can get info on the web site and 
> email and version). But it just loops back to the Geeker>>> prompt where 
> you type the word that you want geekified. I even tried having it restart 
> the whole program by importing the index module that I wrote. But it still 
> won't restart the program!

Without seeing your code, I doubt anyone will be able to solve your problem
except by pure chance. In addition to that, I'm confused by the use of
function calls in what seems te be essentially a menu system. 

Speaking in general terms, the way you could handle this is as follows:
- have a main menu loop (what you call the lobby) which accepts user input
and based on that input calls other functions which perform certain tasks
(e.g. open a webpage or go to the dictionary part)
- the dictionary part would in turn be another loop accepting words as
input which get 'translated', until the user gives a blank string or
whatever as input in order to terminate the loop (and automatically fall
back into the loop of the lobby)

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From python at jayloden.com  Sat Apr  2 01:20:15 2005
From: python at jayloden.com (Jay Loden)
Date: Sat Apr  2 01:19:58 2005
Subject: [Tutor] random import errors?
Message-ID: <200504020020.16226.python@jayloden.com>

I have a python script that runs on my webserver every fifteen minutes.  It 
has run for several months with absolutely no problems.  Suddenly, yesterday 
morning I got an email from cron with an import error for sre_constants (see 
below)

I logged in with ssh, manually ran the script and got the same error.  started 
a Python interpreter shell, did "import sre_constants" and got no error.  
Exited, then ran the script again...and got an error importing 'string'.  I 
manually started up Python interpreter again and imported string, again with 
no error.  Then I exited and ran the script, and it ran fine with no errors. 

I got another such email from cron at 2:30am today ... anyone have any idea 
what would cause such a seemingly random problem after months of working 
fine? 

(sample traceback is below)
-Jay

'import site' failed; use -v for traceback
Traceback (most recent call last):
? File "/usr/local/bin/last_update", line 7, in ?
? ? import os, glob, time
? File "/usr/lib/python2.2/glob.py", line 4, in ?
? ? import fnmatch
? File "/usr/lib/python2.2/fnmatch.py", line 13, in ?
? ? import re
? File "/usr/lib/python2.2/re.py", line 27, in ?
? ? from sre import *
? File "/usr/lib/python2.2/sre.py", line 97, in ?
? ? import sre_compile
? File "/usr/lib/python2.2/sre_compile.py", line 15, in ?
? ? from sre_constants import *
ImportError: No module named sre_constants
From tegmine at gmail.com  Sat Apr  2 01:27:50 2005
From: tegmine at gmail.com (Luis N)
Date: Sat Apr  2 01:27:53 2005
Subject: [Tutor] how to setup gnu.py
In-Reply-To: <2cad2090050330211349889b8f@mail.gmail.com>
References: <2cad2090050330211349889b8f@mail.gmail.com>
Message-ID: <77bfa81a0504011527446ac8da@mail.gmail.com>

I grabbed this from the docs:

Gnuplot.py uses Python distutils and can be installed by untarring the
package, changing into the top-level directory, and typing "python
setup.py install". The Gnuplot.py package is pure Python--no
compilation is necessary.


On Mar 30, 2005 11:13 PM, jrlen balane <nbbalane@gmail.com> wrote:
> hi! i don't know if this is the proper forum but i'll ask anyway...
> 
> how am i going to setup gnu.py(or gnuplot.py) gnuplot with python???
From jeffshannon at gmail.com  Sat Apr  2 02:12:21 2005
From: jeffshannon at gmail.com (Jeff Shannon)
Date: Sat Apr  2 02:12:24 2005
Subject: [Tutor] Launching a file browser
In-Reply-To: <a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com>
	<424B3CA7.9010906@tds.net> <fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
	<a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
Message-ID: <5d0204a10504011612542f41a4@mail.gmail.com>

On Mar 31, 2005 2:14 PM, Mike Hall <michael.hall@critterpixstudios.com> wrote:
> 
> >> It's been too long since I used Python on MacOSX, but IIRC you can't
> >> just run a Python GUI program from the shell. Or something like
> >> that...you should ask this one on the python-mac SIG mailing list:
> >> http://www.python.org/sigs/pythonmac-sig/
> >>
> >> Kent
> 
> I'm unclear on why a command like webbrowser.open() will comfortably
> launch your default web browser (in my case Safari), but something as
> ubiquitous to an OS as a file browser has special needs to launch.

At the OS level, these two actions are *completely* different.  The
webbrowser module launches an entirely separate program in its own
independent process, where the "file browser" is opening a standard
dialog inside of the current process and dependent upon the current
process' message loop.  (AFAIK, every GUI environment uses some sort
of message/event loop...)

I don't know Macs, but on Windows, the closest "file browser" parallel
to what the webbrowser module is doing would be
os.system("explorer.exe"), which launches a separate program in an
independent process.  However, if you're trying to get the results of
the file selection back into your own app, you need to do the file
browsing within your own process (or explicitly use some form of
inter-process communication).  In order to use a GUI file-browsing
dialog, you need to follow all the rules for a GUI program.

Jeff Shannon
From jeffshannon at gmail.com  Sat Apr  2 02:18:06 2005
From: jeffshannon at gmail.com (Jeff Shannon)
Date: Sat Apr  2 02:18:09 2005
Subject: [Tutor] random import errors?
In-Reply-To: <200504020020.16226.python@jayloden.com>
References: <200504020020.16226.python@jayloden.com>
Message-ID: <5d0204a10504011618191f97ca@mail.gmail.com>

On Apr 1, 2005 3:20 PM, Jay Loden <python@jayloden.com> wrote:
> I have a python script that runs on my webserver every fifteen minutes.  It
> has run for several months with absolutely no problems.  Suddenly, yesterday
> morning I got an email from cron with an import error for sre_constants (see
> below)

Since you're able to import these files manually, it's unlikely to be
a problem with your Python installation.  I'd suggest trying to figure
out what changed between the day before yesterday and yesterday.  I'm
just guessing here, but I'd expect that this is probably related to
either permissions or environment variables.

Jeff Shannon
From cyresse at gmail.com  Sat Apr  2 06:44:02 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sat Apr  2 06:44:06 2005
Subject: [Tutor] wxPython / Tkinter Grid
In-Reply-To: <20050401123513.7327a91a.klappnase@freenet.de>
References: <f2ff2d050330214613a10151@mail.gmail.com>
	<020601c53692$6353ab40$61cb8751@xp>
	<20050401123513.7327a91a.klappnase@freenet.de>
Message-ID: <f2ff2d05040120444b89aef5@mail.gmail.com>

Thanks for the feedback.

I should clarify - I find wxPython restrictive & fiddly in terms of
trying to use a fully featured set of widgets, which are written in
C++, trying to use them through a not overly documented Python
wrapper.

I love Pythoncard more and more.

Regards, 

Liam Clarke

On Apr 1, 2005 10:35 PM, Michael Lange <klappnase@freenet.de> wrote:
> On Fri, 1 Apr 2005 09:11:20 +0100
> "Alan Gauld" <alan.gauld@freenet.co.uk> wrote:
> 
> > > I know a wxPython grid is totally different to a Tkinter grid, but
> > is
> > > there a Tkinter equivalent of a wxPython grid? I'm finding wxPython
> > to
> > > be fiddly and restrictive...
> >
> > Then Tkinter will be more so. Tk is a fairly basic toolkit, fine for
> > wrapping a command line app in a glossy front end but not for
> > sophisticated GUI work.
> >
> > There is no grid component in Tk out of the box, but some add on
> > toolkits
> > supply one. Try searching on the Vaults of Parnassus or on the
> > ActiveState site if you are determined to try Tkinter...
> >
> > Alan G.
> >
> 
> Or look here:
> 
>     http://tkinter.unpythonic.net/wiki/Widgets
> 
> There is a number of links to table widget implementations in Tkinter o nthe wiki page.
> 
> I hope this helps
> 
> Michael
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From cyresse at gmail.com  Sat Apr  2 12:12:49 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sat Apr  2 12:12:51 2005
Subject: [Tutor] Self referencing within a dictionary
Message-ID: <f2ff2d0504020212512ce991@mail.gmail.com>

Hi, 

Out of curiosity, is it possible to create a dictionary like this - 

foo = {'a':1, 'b':2, 'c':foo['a']}

I know that as above doesn't work, but was just wondering if it's
possible, and if it's a
Bad Thing?

Regards, 

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From maxnoel_fr at yahoo.fr  Sat Apr  2 12:38:05 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr  2 12:38:15 2005
Subject: [Tutor] Self referencing within a dictionary
In-Reply-To: <f2ff2d0504020212512ce991@mail.gmail.com>
References: <f2ff2d0504020212512ce991@mail.gmail.com>
Message-ID: <e9f6ef58a9f6ea73bae8607c9822eefe@yahoo.fr>


On Apr 2, 2005, at 12:12, Liam Clarke wrote:

> Hi,
>
> Out of curiosity, is it possible to create a dictionary like this -
>
> foo = {'a':1, 'b':2, 'c':foo['a']}
>
> I know that as above doesn't work, but was just wondering if it's
> possible, and if it's a
> Bad Thing?
>
> Regards,
>
> Liam Clarke

	It doesn't work because the expression {'a':1, 'b':2, 'c':foo['a']} is 
evaluated before the assignment. It has to be, as Python doesn't do 
this kind of lazy evaluation. But when the expression is evaluated, foo 
doesn't exist yet, as the assignment hasn't happened yet. Therefore it 
fails.
	If foo existed before that line, it would work. Witness the following 
example:

 >>> foo = {'a':555, 'b':1}
 >>> foo
{'a': 555, 'b': 1}
 >>> foo = {'a':1, 'b':2, 'c':foo['a']}
 >>> foo
{'a': 1, 'c': 555, 'b': 2}

	You'd have to have a good reason to do that, though.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From rdm at rcblue.com  Sat Apr  2 16:56:12 2005
From: rdm at rcblue.com (Dick Moores)
Date: Sat Apr  2 16:56:42 2005
Subject: [Tutor] How to get user input as regex
Message-ID: <6.2.1.2.2.20050402064311.028acb50@rcblue.com>

I'm just beginning to learn regex, and am wondering how to get user input 
that can be used as a regex. Of course my attempt below doesn't work, but 
how should I modify it?

I'm practicing with phone.txt, which is 513 lines, each line having a 
name and phone number, and some other details like an address and times.

Sorry for the dumb question.

import re
s = raw_input("regex: ")
digs = re.compile(r"s")
for line in open("data//phone.txt"):
     if digs.search(line):
         print line

Thanks,

Dick Moores
rdm@rcblue.com

From pierre.barbier at cirad.fr  Sat Apr  2 17:22:01 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Sat Apr  2 17:20:57 2005
Subject: [Tutor] How to get user input as regex
In-Reply-To: <6.2.1.2.2.20050402064311.028acb50@rcblue.com>
References: <6.2.1.2.2.20050402064311.028acb50@rcblue.com>
Message-ID: <424EB899.7010604@cirad.fr>

You should do something much simpler ^_^ :

import re
s = raw_input("regex : ")
digs = re.compile(s)
[...]

That should work :)

pierre

Dick Moores a ?crit :
> I'm just beginning to learn regex, and am wondering how to get user 
> input that can be used as a regex. Of course my attempt below doesn't 
> work, but how should I modify it?
> 
> I'm practicing with phone.txt, which is 513 lines, each line having a 
> name and phone number, and some other details like an address and times.
> 
> Sorry for the dumb question.
> 
> import re
> s = raw_input("regex: ")
> digs = re.compile(r"s")
> for line in open("data//phone.txt"):
>     if digs.search(line):
>         print line
> 
> Thanks,
> 
> Dick Moores
> rdm@rcblue.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From project5 at redrival.net  Sat Apr  2 17:30:29 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr  2 17:30:53 2005
Subject: [Tutor] Re: Self referencing within a dictionary
References: <f2ff2d0504020212512ce991@mail.gmail.com>
Message-ID: <f8t2a3w97jlg$.k8te5nwpsshg$.dlg@40tude.net>

Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:

> I know that as above doesn't work, but was just wondering if it's
> possible, and if it's a
> Bad Thing?

Max has already shown it's possible. Whether it's a Bad Thing... I don't
see why it would be. But I also can't imagine right now any realistic cases
where it would be useful to have a dictionary contain itself as a value.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From rdm at rcblue.com  Sat Apr  2 17:38:17 2005
From: rdm at rcblue.com (Dick Moores)
Date: Sat Apr  2 17:38:21 2005
Subject: [Tutor] How to get user input as regex
In-Reply-To: <424EB899.7010604@cirad.fr>
References: <6.2.1.2.2.20050402064311.028acb50@rcblue.com>
	<424EB899.7010604@cirad.fr>
Message-ID: <6.2.1.2.2.20050402073713.09246b90@rcblue.com>

Pierre Barbier de Reuille wrote at 07:22 4/2/2005:
>You should do something much simpler ^_^ :
>
>import re
>s = raw_input("regex : ")
>digs = re.compile(s)
>[...]

Aha! Thanks!

Dick





From oasf2004 at yahoo.com  Sat Apr  2 19:32:29 2005
From: oasf2004 at yahoo.com (Hoffmann)
Date: Sat Apr  2 19:32:33 2005
Subject: [Tutor] What is the best book to start?  -  Many Thanks!
Message-ID: <20050402173229.12484.qmail@web60005.mail.yahoo.com>

Dear All,

I would like to thank all of you that kindly, answered
my question regarding good Python books to start. As I
told you guys before, I am a newbie and I decided to
start studying Python, that seems to be a nice
programming language. That was my first post in this
group, and I appreciated your hints. Well, I will
follow your hints...
See you later,
Hoffmann


		
__________________________________ 
Do you Yahoo!? 
Yahoo! Personals - Better first dates. More second dates. 
http://personals.yahoo.com

From jfouhy at paradise.net.nz  Sat Apr  2 23:53:56 2005
From: jfouhy at paradise.net.nz (John Fouhy)
Date: Sat Apr  2 23:53:53 2005
Subject: [Tutor] Re: Self referencing within a dictionary
In-Reply-To: <f8t2a3w97jlg$.k8te5nwpsshg$.dlg@40tude.net>
References: <f2ff2d0504020212512ce991@mail.gmail.com>
	<f8t2a3w97jlg$.k8te5nwpsshg$.dlg@40tude.net>
Message-ID: <424F1474.40603@paradise.net.nz>

Andrei wrote:
> Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:
>>I know that as above doesn't work, but was just wondering if it's
>>possible, and if it's a Bad Thing?
> Max has already shown it's possible. Whether it's a Bad Thing... I don't
> see why it would be. But I also can't imagine right now any realistic cases
> where it would be useful to have a dictionary contain itself as a value.

It wouldn't contain itself as a value.

This is basically what Liam said:

 >>> foo = { 'a':1, 'b':2 }
 >>> foo = { 'a':1, 'b':2, 'c':foo['a'] }

In this case, the second line creates a _new_ dictionary, which maps 'c' 
to whatever the previous dictionary mapped 'a' to.  The original 
dictionary is discarded.  The result looks like this:

 >>> foo
{'a': 1, 'c': 1, 'b': 2}

And it is absolutely the same as you would get if you just did:
 >>> foo = { 'a': 1, 'c': 1, 'b': 2 }

I don't think anyone would call that a Bad Thing..

You could also do this:

 >>> foo = { 'a':1, 'b':2 }
 >>> foo['c'] = foo['a']

Now we're not creating a new dictionary.  But the code still says: "Look 
up the value associated with 'a' in foo, and then associate that value 
with 'c' in foo".  And the end result is the same:

 >>> foo
{'a': 1, 'c': 1, 'b': 2}

Of course, if foo['a'] were mutable, it could cause problems.

 >>> foo = {'a':[]}
 >>> foo['b'] = foo['a']
 >>> foo
{'a': [], 'b': []}
 >>> foo['a'].append(3)
 >>> foo
{'a': [3], 'b': [3]}

But again, there are other ways of achieving this.  (eg, x = []; foo = 
{'a':x, 'b':x})  And maybe it's even what you wanted.

You could even make foo contain itself as a value.

 >>> foo = {'a':1, 'b':2}
 >>> foo['c'] = foo
 >>> foo['c']['a']
1
 >>> foo['c']['c']['c']['a']
1
 >>> foo['c']['c']['c']['c']['c']['c']['a']
1

Whether this is useful, I'm not sure... But there's no magic and it's 
not breaking any rules.

To answer what maybe the original question meant to be --- "Can I make 
it so that foo['c'] is the _same_ as foo['a'], and if I reassign to 
foo['a'], this will also change foo['c']" --- I don't think so.  Not 
with the unmodified builtin dictionary.

HTH.

-- 
John.
From project5 at redrival.net  Sun Apr  3 13:53:10 2005
From: project5 at redrival.net (Andrei)
Date: Sun Apr  3 13:54:00 2005
Subject: [Tutor] Re: Re: Self referencing within a dictionary
References: <f2ff2d0504020212512ce991@mail.gmail.com>
	<f8t2a3w97jlg$.k8te5nwpsshg$.dlg@40tude.net>
	<424F1474.40603@paradise.net.nz>
Message-ID: <1warrys9xg8mu$.12g9lr1lnr6di$.dlg@40tude.net>

John Fouhy wrote on Sun, 03 Apr 2005 09:53:56 +1200:

> Andrei wrote:
>> Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:
>>>I know that as above doesn't work, but was just wondering if it's
>>>possible, and if it's a Bad Thing?
>> Max has already shown it's possible. Whether it's a Bad Thing... I don't
>> see why it would be. But I also can't imagine right now any realistic cases
>> where it would be useful to have a dictionary contain itself as a value.
> 
> It wouldn't contain itself as a value.

My mistake, I read the messages hastily and missed the ['a']. It was a more
interesting question that way ;).

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From jeannot18 at hotmail.com  Sun Apr  3 16:42:21 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Sun Apr  3 16:42:25 2005
Subject: [Tutor] What is the best book to start? - Many Thanks!
In-Reply-To: <20050402173229.12484.qmail@web60005.mail.yahoo.com>
Message-ID: <BAY20-F50119B9EF9177E2F3EBFCB33A0@phx.gbl>

Dear Hoffmann, I am also a Newbie and I am currently going through "A Byte 
of Python" tutorial from Swaroop C H.

http://www.byteofpython.info/download?PHPSESSID=c0d52343d90f69f25942f49df9ae7944

If you are completely new to programming like me, you will find that this 
tutorial is excellent.
Good luck
JC


From alan.gauld at freenet.co.uk  Sun Apr  3 17:05:17 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun Apr  3 17:04:21 2005
Subject: [Tutor] Self referencing within a dictionary
References: <f2ff2d0504020212512ce991@mail.gmail.com>
Message-ID: <033501c5385e$8c2b5ae0$61cb8751@xp>

> foo = {'a':1, 'b':2, 'c':foo['a']}

TRy

foo = {'a':1, 'b':2}
foo['c'] = foo['a']

The only reasobn it ddidn't work before was that
foo didn't exist at the time you tried to add the reference.

foo['c'] is just a reference to whatever foo['a'] references.

foo['d'] = foo

is a tad more interesting however.

especially if you do

foo['d']['d']['b'] = 42

As a mental excercise...
Now what does foo look like? :-)


> I know that as above doesn't work, but was just wondering if it's
> possible, and if it's a
> Bad Thing?

It's possible and may be a good thing depending on what you are trying
to do. It certainly shouldn't be a regular thing!

Alan G.

From plyohaicky at kriocoucke.mailexpire.com  Sun Apr  3 17:28:31 2005
From: plyohaicky at kriocoucke.mailexpire.com (Mike Jaeger)
Date: Sun Apr  3 17:28:00 2005
Subject: [Tutor] Script (Python) for Zope
Message-ID: <003301c53861$d5bc7c90$6500a8c0@LAPTOPO>

Hello,

I am looking for a Python-script for Zope which counts the objects (files) in the current folder and all its subfolders, but I don't know how to implement this script. Can somebody help me, please?
Or ist there a newsgroup/mailing list which can help me to find a solution for this problem?
Thanks.

Mike
From shidai.liu at gmail.com  Sun Apr  3 19:31:25 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Sun Apr  3 19:31:28 2005
Subject: [Tutor] [HELP]how to test properties of a file
Message-ID: <33194d7305040310311b68405f@mail.gmail.com>

Dear all,

Here is a simple question. But I can't find a simple answer.
How to test if a file is readable, executalbe or writable, especially, writable?

-- 
With best wishes!
Shidai
From pierre.barbier at cirad.fr  Sun Apr  3 19:42:23 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Sun Apr  3 19:41:24 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <33194d7305040310311b68405f@mail.gmail.com>
References: <33194d7305040310311b68405f@mail.gmail.com>
Message-ID: <42502AFF.1020208@cirad.fr>

Tthe simplest, IMHO, is :

try:
   f = file(filename, "w")
   [...]
except IOError:
   print "The file is not writable"

Of course, not that this method empty the file if it is writable ! The 
best is to just put your IO code in such a try block ... That way, 
you're sure the file has the right mode.

If you don't want to open the file to detect its mode, then you need to 
use the os and stat modules together ...

Pierre

Shidai Liu a ?crit :
> Dear all,
> 
> Here is a simple question. But I can't find a simple answer.
> How to test if a file is readable, executalbe or writable, especially, writable?
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From shidai.liu at gmail.com  Sun Apr  3 21:44:16 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Sun Apr  3 21:44:40 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <42502AFF.1020208@cirad.fr>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr>
Message-ID: <33194d7305040312446e9987f3@mail.gmail.com>

On Apr 3, 2005 6:42 PM, Pierre Barbier de Reuille
<pierre.barbier@cirad.fr> wrote:
> Tthe simplest, IMHO, is :
> 
> try:
>   f = file(filename, "w")
>   [...]
> except IOError:
>   print "The file is not writable"
> 
> Of course, not that this method empty the file if it is writable ! The
> best is to just put your IO code in such a try block ... That way,
> you're sure the file has the right mode.
> 
> If you don't want to open the file to detect its mode, then you need to
> use the os and stat modules together ...
> 
> Pierre
> 

I thought of this first. But I wasn't sure if it's the simplest.
Thanks for your help!
From garnaez at gmail.com  Sun Apr  3 22:32:40 2005
From: garnaez at gmail.com (gerardo arnaez)
Date: Sun Apr  3 22:32:45 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <BAY101-DAV7A867D4587F0DA2A3C996C1450@phx.gbl>
References: <BAY101-DAV7A867D4587F0DA2A3C996C1450@phx.gbl>
Message-ID: <148eea71050403133225f2e2cf@mail.gmail.com>

On Mar 29, 2005 3:06 AM, C Smith <smichr@hotmail.com> wrote:

> If you have Python 2.4 you might want to check out the decimal type
> that is now part of the language.  There is a description at
> 
> http://www.python.org/doc/2.4/whatsnew/node9.html
> 
>  >>> import decimal
>  >>> a = decimal.Decimal('35.72')
>  >>> b = decimal.Decimal('1.73')
>  >>> a+b
> Decimal("37.45")
>  >>> a-b
> Decimal("33.99")
>  >>> a*b
> Decimal("61.7956")
>  >>> a/b
> Decimal("20.64739884393063583815028902")
> 

Would I used an if else: construction to determine where the INR value
lay and decide what precentage to increase it by?
From reederk at comcast.net  Mon Apr  4 07:31:23 2005
From: reederk at comcast.net (Kevin Reeder)
Date: Mon Apr  4 07:31:27 2005
Subject: [Tutor] Operator Overloading
Message-ID: <20050403223123.27ea0d86.reederk@comcast.net>

Following an example from a book, I'm getting an unexpected outcome.
The point of exercise is to extend operator overloading methods from
a superclass and track the method calls. Here's the code,

class MyList:
    def __init__(self, start):
        self.wrapped = [ ]
        for x in start: self.wrapped.append(x)

    def __add__(self, other):
        return MyList(self.wrapped + other)

    def __len__(self):
        return len(self.wrapped)

=====

from module import MyList

class MyListSub(MyList):

    calls = 0

    def __init__(self, start):
        self.adds = 0
        MyList.__init__(self, start)
        
    def __add__(self, other):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1
        return MyList.__add__(self, other)

    def __len__(self):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__len__(self)

    def stats(self):
        return self.calls, self.adds

This is not my code but is taken from the book I'm working with. My
problem is that whenever I call to the __add__ method the counters
increase by 2 while calls the __len__ method increase the counters
by 1 as expected. What I've concluded is that the method which
overloads and arithmetic operations executes the counter statements
twice while the method which overloads a sequencing operation
executes the counter statements only once. Otherwise, I can see no
difference between the two methods.

Here's an example,

>>> A = MyListSub([1, 2, 3])
>>> A.stats()
(0, 0)
>>> len(A)
3
>>> A.stats()
(1, 1)
>>> A + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> A.stats()
(3, 3)

I'm stumped and and would appreciate any help.

Kevin


From jfouhy at paradise.net.nz  Mon Apr  4 11:14:21 2005
From: jfouhy at paradise.net.nz (John Fouhy)
Date: Mon Apr  4 11:14:13 2005
Subject: [Tutor] Operator Overloading
In-Reply-To: <20050403223123.27ea0d86.reederk@comcast.net>
References: <20050403223123.27ea0d86.reederk@comcast.net>
Message-ID: <4251056D.4010109@paradise.net.nz>

Kevin Reeder wrote:
> This is not my code but is taken from the book I'm working with. My
> problem is that whenever I call to the __add__ method the counters
> increase by 2 while calls the __len__ method increase the counters
> by 1 as expected. 

Well, I can't duplicate your results..  I get the behaviour you expect. 
  Also ---


>>>>A + [4, 5, 6]
> 
> [1, 2, 3, 4, 5, 6]

This surprises me.  Here's what I get:

 >>> A + [3, 4, 5]
<__main__.MyList instance at 0x40065e4c>

because you haven't defined __repr__ for MyList.

Are you sure you've giving us all the code?

-- 
John.
From meesters at uni-mainz.de  Mon Apr  4 14:49:28 2005
From: meesters at uni-mainz.de (Christian Meesters)
Date: Mon Apr  4 14:49:31 2005
Subject: [Tutor] one line code
Message-ID: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>

Hi

Yesterday night I was thinking about the following problem:
I do have a list like l = ['1','2','3','abc','','4'] - for instance 
like a list one could get from a file import with the csv module (which 
is where my 'problem' comes from). Now I would like to generate the 
following list, preferably with one line of code:
l2 = [1.0,2.0,3.0,'abc','',4.0]
With other words I'd like to tell Python: Convert into a float if 
possible, otherwise append anyway. Is this possible in one line? (Right 
now my code is a lot longer.)
I was trying with 'filter' + lambda forms, list comprehensions etc., 
but could not find a solution. Could it be that a C-like solution with 
'?' and ':' is more straightforward than a solution with Python or am I 
just too blind to see a real pythonic solution here?

I am aware that putting a solution in one line of code might be against 
the 'Zen of Python' (... Complex is better than complicated ... 
Readability counts ...), but since I'm just asking out of curiosity, 
perhaps I'll get an answer anyway. ;-)

Thanks a lot in advance.
Cheers
Christian

From kraus at hagen-partner.de  Mon Apr  4 15:37:21 2005
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Mon Apr  4 15:38:36 2005
Subject: [Tutor] Re: one line code
In-Reply-To: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
Message-ID: <d2rfpr$tti$1@sea.gmane.org>

Christian Meesters wrote:
> Hi
> 
> Yesterday night I was thinking about the following problem: I do have
> a list like l = ['1','2','3','abc','','4'] - for instance like a list
> one could get from a file import with the csv module (which is where
> my 'problem' comes from). Now I would like to generate the following
> list, preferably with one line of code: l2 =
> [1.0,2.0,3.0,'abc','',4.0] With other words I'd like to tell Python:
> Convert into a float if possible, otherwise append anyway. Is this
> possible in one line? (Right now my code is a lot longer.)

Well, not really in one line, but one function & one line:
def f(x):
     try:
         return float(x)
     except ValueError:
         return x

l2 = [f(x) for x in l]

(I could imagine some obfuscated one-line LC using sting.digits an "or", 
but that will look too much like Perl ;-))

> I was trying with 'filter' + lambda forms, list comprehensions etc.,
> but could not find a solution. Could it be that a C-like solution
> with '?' and ':' is more straightforward than a solution with Python
> or am I just too blind to see a real pythonic solution here?
> 
> I am aware that putting a solution in one line of code might be
> against the 'Zen of Python' (... Complex is better than complicated
> ... Readability counts ...), but since I'm just asking out of
> curiosity, perhaps I'll get an answer anyway. ;-)
> 
> Thanks a lot in advance. Cheers Christian
> 
HTH,
Wolfram

From pierre.barbier at cirad.fr  Mon Apr  4 15:41:10 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Mon Apr  4 15:40:10 2005
Subject: [Tutor] one line code
In-Reply-To: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
Message-ID: <425143F6.40107@cirad.fr>

Mmmhhh ... not strictly one line but ...

import re

float_str = re.compile(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$")

val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]

It's not really "readable" but well ... it works ^_^

Pierre

Christian Meesters a ?crit :
> Hi
> 
> Yesterday night I was thinking about the following problem:
> I do have a list like l = ['1','2','3','abc','','4'] - for instance like 
> a list one could get from a file import with the csv module (which is 
> where my 'problem' comes from). Now I would like to generate the 
> following list, preferably with one line of code:
> l2 = [1.0,2.0,3.0,'abc','',4.0]
> With other words I'd like to tell Python: Convert into a float if 
> possible, otherwise append anyway. Is this possible in one line? (Right 
> now my code is a lot longer.)
> I was trying with 'filter' + lambda forms, list comprehensions etc., but 
> could not find a solution. Could it be that a C-like solution with '?' 
> and ':' is more straightforward than a solution with Python or am I just 
> too blind to see a real pythonic solution here?
> 
> I am aware that putting a solution in one line of code might be against 
> the 'Zen of Python' (... Complex is better than complicated ... 
> Readability counts ...), but since I'm just asking out of curiosity, 
> perhaps I'll get an answer anyway. ;-)
> 
> Thanks a lot in advance.
> Cheers
> Christian
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From reederk at comcast.net  Mon Apr  4 17:13:23 2005
From: reederk at comcast.net (Kevin Reeder)
Date: Mon Apr  4 17:13:29 2005
Subject: [Tutor] Operator Overloading
In-Reply-To: <4251056D.4010109@paradise.net.nz>
References: <20050403223123.27ea0d86.reederk@comcast.net>
	<4251056D.4010109@paradise.net.nz>
Message-ID: <20050404081323.289c0225.reederk@comcast.net>

On Mon, 04 Apr 2005 21:14:21 +1200
John Fouhy <jfouhy@paradise.net.nz> wrote:

> Are you sure you've giving us all the code?

No, I was trying to keep it simple. Anyway, here it is,

class MyList:
    def __init__(self, start):
        self.wrapped = [ ]
        for x in start: self.wrapped.append(x)

    def __add__(self, other):
        return MyList(self.wrapped + other)

    def __mul__(self, time):
        return MyList(self.wrapped * time)

    def __getitem__(self, offset):
        return self.wrapped[offset]

    def __len__(self):
        return len(self.wrapped)

    def __getslice__(self, low, high):
        return MyList(self.wrapped[low:high])

    def __setitem__(self, index, value):
        self.wrapped[index] = value
        print self.wrapped

    def __getattr__(self, name):
        return getattr(self.wrapped, name)

    def __repr__(self):
        return `self.wrapped`
  

=====

from mylist import MyList

class MyListSub(MyList):

    calls = 0

    def __init__(self, start):
        self.adds = 0
        MyList.__init__(self, start)
        
    def __add__(self, other):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1
        return MyList.__add__(self, other)

    def __mul__(self, time):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1
        return MyList.__mul__(self, time)

    def __getitem__(self, offset):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__getitem__(self, offset)

    def __len__(self):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__len__(self)

    def __getslice__(self, low, high):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1  
        return MyList.__getslice__(self, low, high)

    def __setitem__(self, index, value):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1
        return MyList.__setitem__(self, index, value)
  
    def __getattr__(self, name):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__getattr__(self, name)

     def __sub__(self, index):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__sub__(self, index)

    def __and__(self, value):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        MyList.__and__(self, value)

    def stats(self):
        return self.calls, self.adds


  
From project5 at redrival.net  Mon Apr  4 19:20:46 2005
From: project5 at redrival.net (Andrei)
Date: Mon Apr  4 19:23:36 2005
Subject: [Tutor] Re: one line code
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
Message-ID: <135pe1cm0ex82$.15b1cqcnd0of9$.dlg@40tude.net>

Christian Meesters wrote on Mon, 4 Apr 2005 14:49:28 +0200:

<snip>
> Could it be that a C-like solution with 
> '?' and ':' is more straightforward than a solution with Python or am I 
> just too blind to see a real pythonic solution here?

Pierre did the Python equivalent of the ternary operator in his solution.

> I am aware that putting a solution in one line of code might be against 
> the 'Zen of Python' (... Complex is better than complicated ... 
> Readability counts ...), but since I'm just asking out of curiosity, 
> perhaps I'll get an answer anyway. ;-)

>>> l = ['1','2','3','abc','','4', '9.5', 9]
>>> [(eval(compile('exec """try:t=float("%s")\nexcept:t="%s" """ in globals(),locals()'%(s,s),'','exec')),t)[1] for s in l]
[1.0, 2.0, 3.0, 'abc', '', 4.0, 9.5, 9.0]

I would recommend against it though :). Having a special function for this 
purpose is the way to go, a ternary operator doesn't really add anything to 
the quality of the code.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq 
gur yvfg, fb gurer'f ab arrq gb PP.

From jvines at arl.army.mil  Mon Apr  4 16:04:59 2005
From: jvines at arl.army.mil (Vines, John  (Civ, ARL/CISD))
Date: Mon Apr  4 20:40:37 2005
Subject: [Tutor] building strings of specific length
Message-ID: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>

Hello. I have a question regarding strings.  How do I format a string to be a specific length?
For example I need 'string1' to be 72 characters long.
 
Thanks for your time,
John
 
From smiles at saysomething.com  Mon Apr  4 20:08:46 2005
From: smiles at saysomething.com (Christopher Smith)
Date: Mon Apr  4 20:40:39 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <20050404100100.77EF51E4012@bag.python.org>
Message-ID: <96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>


On Monday, Apr 4, 2005, at 05:01 America/Chicago, 
tutor-request@python.org wrote:

> Would I used an if else: construction to determine where the INR value
> lay and decide what precentage to increase it by?
>

Yes, that seems to be the right way to do that.  The caveat is that 
when you are using boolean tests like "if INR < 1.15:" you are using 
floating point numbers that *by definition* have limited ability to 
represent the numbers you type.

"1.15" is actually "1.1499999999999999", so calculation that "on paper" 
would have led to a value of 1.15 will appear to be larger than the 
floating point value of 1.15. When you are checking to see if your 
program is running right and you find that a test like "if INR < 1.15" 
doesn't work like you think it should this can lead to a lot of hair 
pulling...until you remember the floating point issue.  e.g. on paper, 
a and b as shown below should be the same, but they aren't

###
 >>> a=.23*5 # which equals 1.15 on paper
 >>> b=1.15
 >>> a==b
False
 >>> a
1.1500000000000001
 >>> b
1.1499999999999999
###

If one cares about what side of the boundary values get evaluated to 
then either exact numbers should be used (e.g. the new decimal type of 
python 2.4) or else the tests should use the round function to get both 
numbers to a compatible precision for comparison (e.g. use "if 
round(INR,2) < round(1.15,2):" instead of "if INR < 1.15".

It is instructive to see what the round function does to the a and b 
used in the example above:

###
 >>> a,b=round(.23*5,2),round(1.15,2)
 >>> a==b
True
 >>> a
1.1499999999999999
 >>> b
1.1499999999999999
###

Both numbers are still floats, but they are floats that both best 
represent, to 2 decimal places, their respective values.

/c

From project5 at redrival.net  Mon Apr  4 20:57:10 2005
From: project5 at redrival.net (Andrei)
Date: Mon Apr  4 21:00:21 2005
Subject: [Tutor] Re: building strings of specific length
References: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
Message-ID: <6tu1valmxj08$.19tdo7wqjtf02.dlg@40tude.net>

Vines, John  (Civ, ARL/CISD) wrote on Mon, 4 Apr 2005 10:04:59 -0400:

> Hello. I have a question regarding strings.  How do I format a string to be a specific length?
> For example I need 'string1' to be 72 characters long.

You could do (I'll use 20 instead of 72 to keep it readable):

>>> s = "%20s" % "xyz"
>>> len(s), s
(20, '                 xyz')

or:

>>> s = "xyz"
>>> s = s + (20 - len(s)) * ' '
>>> s, len(s)
('xyz                 ', 20)

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From michael.hall at critterpixstudios.com  Mon Apr  4 21:12:14 2005
From: michael.hall at critterpixstudios.com (Mike Hall)
Date: Mon Apr  4 21:11:46 2005
Subject: [Tutor] Launching a file browser
In-Reply-To: <5d0204a10504011612542f41a4@mail.gmail.com>
References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com>
	<424B3CA7.9010906@tds.net>
	<fae3747750e1ec8befc4501fcd7e6579@yahoo.fr>
	<a666e6c3129330c4fd804410af81e38e@critterpixstudios.com>
	<5d0204a10504011612542f41a4@mail.gmail.com>
Message-ID: <ea41ec193bb432e30e85a829f81ac7b2@critterpixstudios.com>

On Apr 1, 2005, at 4:12 PM, Jeff Shannon wrote:

> At the OS level, these two actions are *completely* different.  The
> webbrowser module launches an entirely separate program in its own
> independent process, where the "file browser" is opening a standard
> dialog inside of the current process and dependent upon the current
> process' message loop.  (AFAIK, every GUI environment uses some sort
> of message/event loop...)
>
> I don't know Macs, but on Windows, the closest "file browser" parallel
> to what the webbrowser module is doing would be
> os.system("explorer.exe"), which launches a separate program in an
> independent process.  However, if you're trying to get the results of
> the file selection back into your own app, you need to do the file
> browsing within your own process (or explicitly use some form of
> inter-process communication).  In order to use a GUI file-browsing
> dialog, you need to follow all the rules for a GUI program.

Thanks Jeff. This further clarifies it for me.


-MH

From maxnoel_fr at yahoo.fr  Mon Apr  4 21:13:57 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Mon Apr  4 21:14:02 2005
Subject: [Tutor] building strings of specific length
In-Reply-To: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
References: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
Message-ID: <be099da9560a23d65029e4c65976f371@yahoo.fr>


On Apr 4, 2005, at 16:04, Vines, John (Civ, ARL/CISD) wrote:

> Hello. I have a question regarding strings.  How do I format a string 
> to be a specific length?
> For example I need 'string1' to be 72 characters long.
>
> Thanks for your time,
> John

	You can use the string methods ljust, rjust and zfill:

 >>> "xxx".rjust(10)
'       xxx'
 >>> "xxx".ljust(10)
'xxx       '
 >>> "xxx".zfill(10)
'0000000xxx'

	Note that the string will not be truncated if it's more than (here) 10 
characters long, but you can use slicing to get around that:

 >>> "xxxxxxxxxxxxxxxx".rjust(10)[:10]
'xxxxxxxxxx'


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From michael.hall at critterpixstudios.com  Mon Apr  4 21:17:30 2005
From: michael.hall at critterpixstudios.com (Mike Hall)
Date: Mon Apr  4 21:16:53 2005
Subject: [Tutor] building strings of specific length
In-Reply-To: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
References: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
Message-ID: <993567a735343000ce67b0860919c301@critterpixstudios.com>

You can chop off anything past 72 characters with:

s2 = s[:72]


On Apr 4, 2005, at 7:04 AM, Vines, John (Civ, ARL/CISD) wrote:

> Hello. I have a question regarding strings.  How do I format a string 
> to be a specific length?
> For example I need 'string1' to be 72 characters long.
>
> Thanks for your time,
> John
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-MH

From garnaez at gmail.com  Mon Apr  4 21:56:15 2005
From: garnaez at gmail.com (gerardo arnaez)
Date: Mon Apr  4 21:56:20 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
References: <20050404100100.77EF51E4012@bag.python.org>
	<96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
Message-ID: <148eea71050404125655f05cf5@mail.gmail.com>

Hi all. I would like to post the  very small py files I have written
while doing this.
Would anyone object.
I think at most there be 20 lines of code all the files put together.
I woul dlike to hear some crituqe on them
Thanks

On Apr 4, 2005 11:08 AM, Christopher Smith <smiles@saysomething.com> wrote:
> 
> On Monday, Apr 4, 2005, at 05:01 America/Chicago,
> tutor-request@python.org wrote:
> 
> > Would I used an if else: construction to determine where the INR value
> > lay and decide what precentage to increase it by?
> >
> 
> Yes, that seems to be the right way to do that.  The caveat is that
> when you are using boolean tests like "if INR < 1.15:" you are using
> floating point numbers that *by definition* have limited ability to
> represent the numbers you type.
> 
> "1.15" is actually "1.1499999999999999", so calculation that "on paper"
> would have led to a value of 1.15 will appear to be larger than the
> floating point value of 1.15. When you are checking to see if your
> program is running right and you find that a test like "if INR < 1.15"
> doesn't work like you think it should this can lead to a lot of hair
> pulling...until you remember the floating point issue.  e.g. on paper,
> a and b as shown below should be the same, but they aren't
> 
> ###
> >>> a=.23*5 # which equals 1.15 on paper
> >>> b=1.15
> >>> a==b
> False
> >>> a
> 1.1500000000000001
> >>> b
> 1.1499999999999999
> ###
> 
> If one cares about what side of the boundary values get evaluated to
> then either exact numbers should be used (e.g. the new decimal type of
> python 2.4) or else the tests should use the round function to get both
> numbers to a compatible precision for comparison (e.g. use "if
> round(INR,2) < round(1.15,2):" instead of "if INR < 1.15".
> 
> It is instructive to see what the round function does to the a and b
> used in the example above:
> 
> ###
> >>> a,b=round(.23*5,2),round(1.15,2)
> >>> a==b
> True
> >>> a
> 1.1499999999999999
> >>> b
> 1.1499999999999999
> ###
> 
> Both numbers are still floats, but they are floats that both best
> represent, to 2 decimal places, their respective values.
> 
> /c
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From dianahawks at optusnet.com.au  Mon Apr  4 22:28:54 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr  4 22:30:29 2005
Subject: [Tutor] using the enter key
Message-ID: <000801c53954$ed021560$2007a4cb@dianahawks>

Hello list!

At the moment I have some user input tied to a button that allows the input to be "submitted" and then an answer is supplied.  How can I get rid of this submit button, and have the user just press the "enter" key and have the same result happen?

TIA.  Diana
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050405/399041ef/attachment.html
From kent37 at tds.net  Mon Apr  4 23:19:05 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr  4 23:19:10 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <148eea71050404125655f05cf5@mail.gmail.com>
References: <20050404100100.77EF51E4012@bag.python.org>	<96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
	<148eea71050404125655f05cf5@mail.gmail.com>
Message-ID: <4251AF49.1010403@tds.net>

gerardo arnaez wrote:
> Hi all. I would like to post the  very small py files I have written
> while doing this.
> Would anyone object.
> I think at most there be 20 lines of code all the files put together.
> I woul dlike to hear some crituqe on them

That's no problem, for 20 lines just put it in the body of your email.

Kent

From kent37 at tds.net  Mon Apr  4 23:20:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr  4 23:20:32 2005
Subject: [Tutor] using the enter key
In-Reply-To: <000801c53954$ed021560$2007a4cb@dianahawks>
References: <000801c53954$ed021560$2007a4cb@dianahawks>
Message-ID: <4251AF99.9060205@tds.net>

Diana Hawksworth wrote:
  > At the moment I have some user input tied to a button that allows the
> input to be "submitted" and then an answer is supplied.  How can I get 
> rid of this submit button, and have the user just press the "enter" key 
> and have the same result happen?

How is the user interface built? Are you using a GUI toolkit like Tkinter or wxPython or is it a web 
form?

Kent

From alan.gauld at freenet.co.uk  Mon Apr  4 23:43:37 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr  4 23:43:19 2005
Subject: [Tutor] [HELP]how to test properties of a file
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr>
Message-ID: <037701c5395f$5c697a60$61cb8751@xp>


> The simplest, IMHO, is :
>
> try:
>    f = file(filename, "w")
>    [...]
> except IOError:
>    print "The file is not writable"
>
> Of course, not that this method empty the file if it is writable !
The
> best is to just put your IO code in such a try block ... That way,
> you're sure the file has the right mode.

Its not really the simplest, its not efficient and it might be
dangerous
if the file is not empty. At the very least open using 'a' to avoid
obliterating the file!!

However the os.stat function and stat module do what you want safely
and more comprehensively:

-----------------------------------
Help on module stat:

NAME
    stat - Constants/functions for interpreting results of
    os.stat() and os.lstat().

FILE
    /usr/lib/python2.3/stat.py

DESCRIPTION
    Suggested usage: from stat import *

DATA
    ST_ATIME = 7
    ST_CTIME = 9
    ST_DEV = 2
    ST_GID = 5
    ST_INO = 1
    ST_MODE = 0
    ST_MTIME = 8
    ST_NLINK = 3
    ST_SIZE = 6
    ST_UID = 4
    S_ENFMT = 1024

-----------------------------------------

The constants above are the indices into the tuple returned by
os.stat()
That will tell you most of the things you need to know,
check the docs to find out what they all mean.
For your purposes the important one is ST_MODE.

So

import os
from stat import *
status = os.stat('somefile.txt')[ST_MODE]
if status & S_IWRITE: print 'writable'
elif staus &  S_IREAD: print 'readable'
else: print 'status is ', status

Notice you have to use bitwise AND (&) to extract the status bits.

HTH

Alan G.

From alan.gauld at freenet.co.uk  Mon Apr  4 23:51:54 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr  4 23:51:45 2005
Subject: [Tutor] one line code
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
Message-ID: <039401c53960$84cb0b30$61cb8751@xp>

> With other words I'd like to tell Python: Convert into a float if 
> possible, otherwise append anyway. 

[ (type(x) == type(5) and float(x) or x) for x in mylist ]

Should do it...

Alan G.
From nick at javacat.f2s.com  Mon Apr  4 23:54:40 2005
From: nick at javacat.f2s.com (Nick Lunt)
Date: Mon Apr  4 23:54:01 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <037701c5395f$5c697a60$61cb8751@xp>
References: <33194d7305040310311b68405f@mail.gmail.com>	<42502AFF.1020208@cirad.fr>
	<037701c5395f$5c697a60$61cb8751@xp>
Message-ID: <4251B7A0.3080709@javacat.f2s.com>

I've gotten into the habit of just using the os.?_OK stuff.

eg

 >>> import os
 >>> os.access('/', os.W_OK)
False
 >>> os.access('/tmp', os.W_OK)
True

Thats gotta be simple if I understand it lol :)

Nick .


Alan Gauld wrote:

>>The simplest, IMHO, is :
>>
>>try:
>>   f = file(filename, "w")
>>   [...]
>>except IOError:
>>   print "The file is not writable"
>>
>>Of course, not that this method empty the file if it is writable !
>>    
>>
>The
>  
>
>>best is to just put your IO code in such a try block ... That way,
>>you're sure the file has the right mode.
>>    
>>
>
>Its not really the simplest, its not efficient and it might be
>dangerous
>if the file is not empty. At the very least open using 'a' to avoid
>obliterating the file!!
>
>However the os.stat function and stat module do what you want safely
>and more comprehensively:
>
>-----------------------------------
>Help on module stat:
>
>NAME
>    stat - Constants/functions for interpreting results of
>    os.stat() and os.lstat().
>
>FILE
>    /usr/lib/python2.3/stat.py
>
>DESCRIPTION
>    Suggested usage: from stat import *
>
>DATA
>    ST_ATIME = 7
>    ST_CTIME = 9
>    ST_DEV = 2
>    ST_GID = 5
>    ST_INO = 1
>    ST_MODE = 0
>    ST_MTIME = 8
>    ST_NLINK = 3
>    ST_SIZE = 6
>    ST_UID = 4
>    S_ENFMT = 1024
>
>-----------------------------------------
>
>The constants above are the indices into the tuple returned by
>os.stat()
>That will tell you most of the things you need to know,
>check the docs to find out what they all mean.
>For your purposes the important one is ST_MODE.
>
>So
>
>import os
>from stat import *
>status = os.stat('somefile.txt')[ST_MODE]
>if status & S_IWRITE: print 'writable'
>elif staus &  S_IREAD: print 'readable'
>else: print 'status is ', status
>
>Notice you have to use bitwise AND (&) to extract the status bits.
>
>HTH
>
>Alan G.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>

From jfouhy at paradise.net.nz  Tue Apr  5 00:22:40 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Tue Apr  5 00:22:45 2005
Subject: [Tutor] Re: building strings of specific length
In-Reply-To: <6tu1valmxj08$.19tdo7wqjtf02.dlg@40tude.net>
References: <D9A8D98DDC682044806D5B46AF5C11E2078944@ARLABML01.DS.ARL.ARMY.MIL>
	<6tu1valmxj08$.19tdo7wqjtf02.dlg@40tude.net>
Message-ID: <1112653360.4251be30b402e@www.paradise.net.nz>

Quoting Andrei <project5@redrival.net>:

> You could do (I'll use 20 instead of 72 to keep it readable):
> 
> >>> s = "%20s" % "xyz"
> >>> len(s), s
> (20, ' xyz')
> 
> or:
> 
> >>> s = "xyz"
> >>> s = s + (20 - len(s)) * ' '
> >>> s, len(s)
> ('xyz ', 20)

Just a comment ---

You can do the second example using string formatting as well:

>>> s = '%-20s' % 'xyz'
>>> s, len(s)
('xyz                 ', 20)

-- 
John.
From cyresse at gmail.com  Tue Apr  5 00:40:25 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Tue Apr  5 00:40:30 2005
Subject: [Tutor] one line code
In-Reply-To: <039401c53960$84cb0b30$61cb8751@xp>
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
	<039401c53960$84cb0b30$61cb8751@xp>
Message-ID: <f2ff2d050404154018e4be37@mail.gmail.com>

[(eval(compile('exec """try:t=float("%s")\nexcept:t="%s" """ in
globals(),locals()'%(s,s),'','exec')),t)[1] for s in l]

Now that's ugly.



On Apr 5, 2005 9:51 AM, Alan Gauld <alan.gauld@freenet.co.uk> wrote:
> > With other words I'd like to tell Python: Convert into a float if
> > possible, otherwise append anyway.
> 
> [ (type(x) == type(5) and float(x) or x) for x in mylist ]
> 
> Should do it...
> 
> Alan G.
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From jfouhy at paradise.net.nz  Tue Apr  5 00:56:40 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Tue Apr  5 00:56:44 2005
Subject: [Tutor] Operator Overloading
In-Reply-To: <20050404081323.289c0225.reederk@comcast.net>
References: <20050403223123.27ea0d86.reederk@comcast.net>
	<4251056D.4010109@paradise.net.nz>
	<20050404081323.289c0225.reederk@comcast.net>
Message-ID: <1112655400.4251c62846dd1@www.paradise.net.nz>

Quoting Kevin Reeder <reederk@comcast.net>:

> On Mon, 04 Apr 2005 21:14:21 +1200
> John Fouhy <jfouhy@paradise.net.nz> wrote:
> > Are you sure you've giving us all the code?
> No, I was trying to keep it simple. Anyway, here it is,

Fine, but always test the simplified version, unless you're absolutely certain
what you're throwing out!

This is the key to your problem:
 
>  def __getattr__(self, name):
>      MyListSub.calls = MyListSub.calls + 1
>      self.adds = self.adds + 1 
>      return MyList.__getattr__(self, name)

When you do 'A + [4, 5, 6]', python first calls A.__getattr__('__coerce__').

__coerce__ appears to be used to implement mixed-mode arithmetic (eg, adding an
int to a float).  Presumably, you could define your own numeric types; if you
then defined __coerce__, you could add, mulitply, etc. your type with the
builtin types.

I guess the reasoning looks something like this:
  "If both operands are the same, then call the appropriate __add__ method.
   Otherwise, look to see if either has a __coerce__ method.
      If so, try to use coerce to make them the same.
   Call the appropriate __add__ method."

I found this out by putting all your code into a file, and then using pdb.

ie: The file 'mylist.py' contains all your code, and ends with:

--------------------------------
A = MyListSub([1,2,3])
print A.stats()
print len(A)
print A.stats()
print A + [4, 5, 6]
print A.stats()
--------------------------------

I then run:  $ python /usr/lib/python2.4/pdb.py mylist.py

I put a break point on the line with 'A + [4, 5, 6]', and use the step command
to see what happens.  This immediately showed the call to __getattr__.

pdb is useful :-)

-- 
John.
From shidai.liu at gmail.com  Tue Apr  5 01:19:19 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Tue Apr  5 01:19:23 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <037701c5395f$5c697a60$61cb8751@xp>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>
Message-ID: <33194d7305040416198e85f18@mail.gmail.com>

On Apr 4, 2005 10:43 PM, Alan Gauld <alan.gauld@freenet.co.uk> wrote:
> 
> Its not really the simplest, its not efficient and it might be
> dangerous
> if the file is not empty. At the very least open using 'a' to avoid
> obliterating the file!!
> 
> However the os.stat function and stat module do what you want safely
> and more comprehensively:
> ... 
> ...

Thanks a lot, Alan. This is new to me.
-- 
With best wishes!
Shidai
From shidai.liu at gmail.com  Tue Apr  5 01:34:00 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Tue Apr  5 01:34:04 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <4251B7A0.3080709@javacat.f2s.com>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>
	<4251B7A0.3080709@javacat.f2s.com>
Message-ID: <33194d7305040416346a07de92@mail.gmail.com>

On Apr 4, 2005 10:54 PM, Nick Lunt <nick@javacat.f2s.com> wrote:
> I've gotten into the habit of just using the os.?_OK stuff.
> 
> eg
> 
> >>> import os
> >>> os.access('/', os.W_OK)
> False
> >>> os.access('/tmp', os.W_OK)
> True
> 
> Thats gotta be simple if I understand it lol :)
> 
> Nick .
> 

I found out in the following situation, it fails to work.
Say, 'somefile.csv' is opened by EXCEL,
>>> os.access('somefile.csv', os.W_OK)
True
>>> file('somefile.csv', 'w')
IOError: [Errno 13] Permission denied: 'somefile.csv'

By the way, using os.stat & stat as suggested by Alan doesn't work either.
Any idea how solve it?
From oasf2004 at yahoo.com  Tue Apr  5 03:37:10 2005
From: oasf2004 at yahoo.com (Hoffmann)
Date: Tue Apr  5 03:37:13 2005
Subject: [Tutor] What is the best book to start? - Many Thanks!
In-Reply-To: 6667
Message-ID: <20050405013710.97945.qmail@web60007.mail.yahoo.com>

Hi John,

Certainly, I will check it out.
Many thanks!
Hoffmann

--- John Carmona <jeannot18@hotmail.com> wrote:
> Dear Hoffmann, I am also a Newbie and I am currently
> going through "A Byte 
> of Python" tutorial from Swaroop C H.
> 
>
http://www.byteofpython.info/download?PHPSESSID=c0d52343d90f69f25942f49df9ae7944
> 
> If you are completely new to programming like me,
> you will find that this 
> tutorial is excellent.
> Good luck
> JC
> 
> 
> 


		
__________________________________ 
Yahoo! Messenger 
Show us what our next emoticon should look like. Join the fun. 
http://www.advision.webevents.yahoo.com/emoticontest
From reederk at comcast.net  Tue Apr  5 06:16:26 2005
From: reederk at comcast.net (Kevin Reeder)
Date: Tue Apr  5 06:16:30 2005
Subject: [Tutor] Operator Overloading
In-Reply-To: <1112655400.4251c62846dd1@www.paradise.net.nz>
References: <20050403223123.27ea0d86.reederk@comcast.net>
	<4251056D.4010109@paradise.net.nz>
	<20050404081323.289c0225.reederk@comcast.net>
	<1112655400.4251c62846dd1@www.paradise.net.nz>
Message-ID: <20050404211626.53b4a266.reederk@comcast.net>

On Tue, 05 Apr 2005 10:56:40 +1200 (NZST)
jfouhy@paradise.net.nz wrote:

> Fine, but always test the simplified version, unless you're
> absolutely certain what you're throwing out!

Point taken.

> When you do 'A + [4, 5, 6]', python first calls
> A.__getattr__('__coerce__').

Everything's working fine now.

> pdb is useful :-)

Thanks,

Kevin
From smichr at hotmail.com  Tue Apr  5 07:45:08 2005
From: smichr at hotmail.com (C Smith)
Date: Tue Apr  5 07:46:19 2005
Subject: [Tutor] one line code
In-Reply-To: <20050404224030.1B0301E4011@bag.python.org>
Message-ID: <BAY101-DAV12D54D542609D3EB252B6FC13C0@phx.gbl>

> From: "Alan Gauld" <alan.gauld@freenet.co.uk>
>
>> With other words I'd like to tell Python: Convert into a float if
>> possible, otherwise append anyway.
>
> [ (type(x) == type(5) and float(x) or x) for x in mylist ]
>

This is a perfect opportunity to give the reminder that the conversion 
functions are also types that can be used more transparently for such 
type tests:

###
 >>> type(int)
<type 'type'>
 >>> type(1)==int
True
 >>> type(1)==float
False
###

If you really want a float and not an int then you should use the 
following 1-liner as suggested by the programming FAQ 1.2.11 ( 
http://www.python.org/doc/faq/programming.html ):

[ (type(x) == int and [float(x)] or [x])[0] for x in mylist]

###
 >>> l=['foo', 0]
 >>> [(type(x)==int and float(x) or x) for x in l]
['foo', 0]
 >>> # notice that 0 is still an int, not a float
 >>> [(type(x)==int and [float(x)] or [x])[0] for x in l]
['foo', 0.0]
 >>> # ok, that's better
###

/c


From dianahawks at optusnet.com.au  Tue Apr  5 08:53:34 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Tue Apr  5 08:55:04 2005
Subject: [Tutor] enter key
Message-ID: <004901c539ac$30465140$0607a4cb@dianahawks>

I am using the tkinter toolkit.  Just wish to have the button I have formed
replaced by the Enter key - if possible.  Would the raw_input() work, as
Bernard has suggested, or do I need another piece of code that refers to the
Enter key?

Thanks. Diana
----- Original Message ----- 
From: "Kent Johnson" <kent37@tds.net>
Cc: <tutor@python.org>
Sent: Tuesday, April 05, 2005 7:20 AM
Subject: Re: [Tutor] using the enter key


> Diana Hawksworth wrote:
>   > At the moment I have some user input tied to a button that allows the
> > input to be "submitted" and then an answer is supplied.  How can I get
> > rid of this submit button, and have the user just press the "enter" key
> > and have the same result happen?
>
> How is the user interface built? Are you using a GUI toolkit like Tkinter
or wxPython or is it a web
> form?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050405/5794503f/attachment.html
From klappnase at freenet.de  Tue Apr  5 11:55:39 2005
From: klappnase at freenet.de (Michael Lange)
Date: Tue Apr  5 11:52:16 2005
Subject: [Tutor] using the enter key
In-Reply-To: <000801c53954$ed021560$2007a4cb@dianahawks>
References: <000801c53954$ed021560$2007a4cb@dianahawks>
Message-ID: <20050405115539.009a2283.klappnase@freenet.de>

On Tue, 5 Apr 2005 06:28:54 +1000
"Diana Hawksworth" <dianahawks@optusnet.com.au> wrote:

> Hello list!
> 
> At the moment I have some user input tied to a button that allows the input to be "submitted" and then an answer is supplied.  How can I get rid of this submit button, and have the user just press the "enter" key and have the same result happen?
> 
> TIA.  Diana

You need to create an event handler for the Entry widget that is called each time the Enter key is pressed over the widget:

    entry.bind('<Return>', submit)

where "entry" is of course your Entry widget and "submit" the function to be called.

Please note that the "enter" key's event descriptor is "'<Return>'" in Tk (there's an '<Enter>' event, too, which is when the mouse
pointer enters the widget) and that the callback gets an event instance passed, so the function definition
has to look like this:

    def submit(event):
        (...)

I hope this helps

Michael
From kent37 at tds.net  Tue Apr  5 11:57:57 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr  5 11:58:02 2005
Subject: [Tutor] using the enter key
In-Reply-To: <000c01c53961$f412a240$4007a4cb@dianahawks>
References: <000801c53954$ed021560$2007a4cb@dianahawks>
	<4251AF99.9060205@tds.net>
	<000c01c53961$f412a240$4007a4cb@dianahawks>
Message-ID: <42526125.30705@tds.net>

Here is a simple example. It is not well structured but it should give you the idea.

from Tkinter import *

def showText(evt):
     print 'Text is:', text.get('0.0', END)
     return 'break'  # Prevent the event from propagating to the Text widget

root = Tk()
text = Text()

# This line binds the showText handler to the <Return> key event
text.bind('<Return>', showText)
text.pack()
root.mainloop()


Kent

Diana Hawksworth wrote:
> I am using the tkinter toolkit.  Just wish to have the button I have formed
> replaced by the Enter key - if possible.  Would the raw_input() work, as
> Bernard has suggested, or do I need another piece of code that refers to the
> Enter key?
> 
> Thanks. Diana
> ----- Original Message ----- 
> From: "Kent Johnson" <kent37@tds.net>
> Cc: <tutor@python.org>
> Sent: Tuesday, April 05, 2005 7:20 AM
> Subject: Re: [Tutor] using the enter key
> 
> 
> 
>>Diana Hawksworth wrote:
>>  > At the moment I have some user input tied to a button that allows the
>>
>>>input to be "submitted" and then an answer is supplied.  How can I get
>>>rid of this submit button, and have the user just press the "enter" key
>>>and have the same result happen?
>>
>>How is the user interface built? Are you using a GUI toolkit like Tkinter
> 
> or wxPython or is it a web
> 
>>form?
>>
>>Kent
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 


From jfouhy at paradise.net.nz  Tue Apr  5 12:16:59 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Tue Apr  5 12:17:04 2005
Subject: [Tutor] enter key
In-Reply-To: <004901c539ac$30465140$0607a4cb@dianahawks>
References: <004901c539ac$30465140$0607a4cb@dianahawks>
Message-ID: <1112696219.4252659bc9537@www.paradise.net.nz>

Quoting Diana Hawksworth <dianahawks@optusnet.com.au>:

> I am using the tkinter toolkit. Just wish to have the button I have
> formed replaced by the Enter key - if possible. Would the raw_input() work, as
> Bernard has suggested, or do I need another piece of code that refers to
> the Enter key?

A couple of people have mentioned event bindings.  Another alternative you could
look into is using Python Megawidgets.  These are some widgets built on top of
Tk.  Get them from http://pmw.sourceforge.net/.  Using Pmw, you could replace
your Entry widget with a Pmw.EntryWidget, and then just set the 'command' option.

I recommend Pmw if you are going to do much with Tkinter, since they give you
some nice stuff :-)

-- 
John.
From project5 at redrival.net  Tue Apr  5 13:14:14 2005
From: project5 at redrival.net (Andrei)
Date: Tue Apr  5 13:17:34 2005
Subject: [Tutor] Re: one line code
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
	<039401c53960$84cb0b30$61cb8751@xp>
Message-ID: <loom.20050405T131217-478@post.gmane.org>

Alan Gauld <alan.gauld <at> freenet.co.uk> writes:

> > With other words I'd like to tell Python: Convert into a float if 
> > possible, otherwise append anyway. 
> 
> [ (type(x) == type(5) and float(x) or x) for x in mylist ]

Almost fell for it too, but the original list contains numbers 
stored as strings :).

Andrei


From alan.gauld at freenet.co.uk  Tue Apr  5 14:45:53 2005
From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk)
Date: Tue Apr  5 14:50:34 2005
Subject: [Tutor] one line code
Message-ID: <380-22005425124553572@freenet.co.uk>


>This is a perfect opportunity to give the reminder that the
>conversion 
>functions are also types that can be used more transparently for such

Neat I didn't know\ that. How dioes Python equate a function object
to a type? Is it hard wired?

> >>> [(type(x)==int and float(x) or x) for x in l]
>['foo', 0]
> >>> # notice that 0 is still an int, not a float
> >>> [(type(x)==int and [float(x)] or [x])[0] for x in l]
>['foo', 0.0]
> >>> # ok, that's better

And a nice subtle catch.

Alan G.

From pierre.barbier at cirad.fr  Tue Apr  5 15:07:12 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue Apr  5 15:06:13 2005
Subject: [Tutor] one line code
In-Reply-To: <380-22005425124553572@freenet.co.uk>
References: <380-22005425124553572@freenet.co.uk>
Message-ID: <42528D80.8080004@cirad.fr>



alan.gauld@freenet.co.uk a ?crit :
>>This is a perfect opportunity to give the reminder that the
>>conversion 
>>functions are also types that can be used more transparently for such
> 
> 
> Neat I didn't know\ that. How dioes Python equate a function object
> to a type? Is it hard wired?

No, you see it the wrong way !
"int" is a type, not a function ! But, in Python, types append to be 
callable (ie. to behave like functions). For example when you define a 
class Foo with :

class Foo:
   def __init__(self):
     pass

Foo is a type but you can also *call* Foo with :

f = Foo()

But this construct an object (and involves many function calls) and is 
not a "simple" function call.
So there is no need to hardwire that kind of things (even if it _may_ be 
hardwired to improve efficiency).

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From kent37 at tds.net  Tue Apr  5 15:26:27 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr  5 15:26:34 2005
Subject: [Tutor] one line code
In-Reply-To: <42528D80.8080004@cirad.fr>
References: <380-22005425124553572@freenet.co.uk> <42528D80.8080004@cirad.fr>
Message-ID: <42529203.1090002@tds.net>

Pierre Barbier de Reuille wrote:
> alan.gauld@freenet.co.uk a ?crit :
> 
>>> This is a perfect opportunity to give the reminder that the
>>> conversion functions are also types that can be used more 
>>> transparently for such
>>
>> Neat I didn't know\ that. How dioes Python equate a function object
>> to a type? Is it hard wired?
> 
> No, you see it the wrong way !
> "int" is a type, not a function ! But, in Python, types append to be 
> callable (ie. to behave like functions). 

Yes, that's right. int was changed from a function to a type in Python 2.2 as part of the 
introduction of new-style classes. See
http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000310000000000000000

Kent

From work at infomaniak.ch  Tue Apr  5 15:57:06 2005
From: work at infomaniak.ch (BRINER Cedric)
Date: Tue Apr  5 15:57:27 2005
Subject: [Tutor] pickle in unicode format
Message-ID: <1112709426.13679.6.camel@obslin15.unige.ch>

hi,

I have this dictionnary :

a={'partition': u'/export/diskH1/home_evol/ricquebo',
 'rsmFirstname': u'Fran\xe7ois',
 'rsmLastname': u'Ricquebourg',
 'size': u'8161222.0',
 'size_max': '1'}

and I'd like to *serialize* it with pickle and that the output format
will be of type unicode.

unicode(pickle.dumps(a)) doesn't work !
or
pickle.dumps(a,protocol=2,bin='V')

doesn't seem to work :(

what am I doing wrong ??

Cedric BRINER

From cpu.crazy at gmail.com  Tue Apr  5 16:00:11 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue Apr  5 16:05:38 2005
Subject: [Tutor] Py2exe (Joseph Q.)
Message-ID: <6.1.0.6.2.20050405075348.01e468f0@pop.gmail.com>

Maybe I shouldn't be posting this...
I downloaded py2exe and can't get it to make exe's of my python files. 
There are a list of instructions:

# A very simple setup script to create 2 executables.
#
# hello.py is a simple "hello, world" type program, which alse allows
# to explore the environment in which the script runs.
#
# test_wx.py is a simple wxPython program, it will be converted into a
# console-less program.
#
# If you don't have wxPython installed, you should comment out the
#   windows = ["test_wx.py"]
# line below.
#
#
# Run the build process by entering 'setup.py py2exe' or
# 'python setup.py py2exe' in a console prompt.
#
# If everything works well, you should find a subdirectory named 'dist'
# containing some files, among them hello.exe and test_wx.exe.


from distutils.core import setup
import py2exe

setup(
     # The first three parameters are not required, if at least a
     # 'version' is given, then a versioninfo resource is built from
     # them and added to the executables.
     version = "0.5.0",
     description = "py2exe sample script",
     name = "py2exe samples",

     # targets to build
     # windows = ["test_wx.py"],
     console = ["hello.py"],
     )

What does it mean by the 'console prompt'? I tried Command Prompt (Windows 
XP) but I get errors when I type 'setup.py py2exe' or 'python setup.py 
py2exe'. I also don't get anything when I run the setup.py in IDLE (or the 
Python command line). In fact I get an error:
Traceback (most recent call last):
   File "C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py", 
line 22, in ?
     import py2exe
ImportError: No module named py2exe

If you have used or are using py2exe, please tell me what I'm doing wrong!
Thanks,
   Joseph Q.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050405/8c8a695f/attachment.htm
From glingl at aon.at  Tue Apr  5 16:27:29 2005
From: glingl at aon.at (Gregor Lingl)
Date: Tue Apr  5 16:27:38 2005
Subject: [Tutor] one line code
In-Reply-To: <425143F6.40107@cirad.fr>
References: <7e0b678c4f8defc076274d8d00bd95fb@uni-mainz.de>
	<425143F6.40107@cirad.fr>
Message-ID: <4252A051.1000104@aon.at>



Pierre Barbier de Reuille schrieb:
> Mmmhhh ... not strictly one line but ...
> 
> import re
> 
> float_str = re.compile(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$")
> 
> val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]
> 
> It's not really "readable" but well ... it works ^_^
> 
> Pierre
> 

This can be done in strictly 1 line (having already imported re):

 >>> l = ['1','2','3','abc','0', '','4']
 >>> [(re.match(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$",s) 
and [float(s)] or [s])[0] for s in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]

or, if one doesn't have to take into account exponential format:

 >>> [(x and not[y for y in x if y not in "0123456789."] and 
x.count(".")<2 and [float(x)] or [x])[0] for x in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]
 >>>

hmmm, unfortunately "Useless Python" isn't maintained anymore...

(^o^)

Gregor
From 3dbernard at gmail.com  Tue Apr  5 16:40:41 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue Apr  5 16:40:44 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <33194d7305040416346a07de92@mail.gmail.com>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>
	<4251B7A0.3080709@javacat.f2s.com>
	<33194d7305040416346a07de92@mail.gmail.com>
Message-ID: <61d0e2b4050405074064c3c497@mail.gmail.com>

As far as I'm aware, this is very normal. The file is being used by an
application, so there is a lock on it.


Cheers
Bernard


On Apr 4, 2005 7:34 PM, Shidai Liu <shidai.liu@gmail.com> wrote:
> I found out in the following situation, it fails to work.
> Say, 'somefile.csv' is opened by EXCEL,
> >>> os.access('somefile.csv', os.W_OK)
> True
> >>> file('somefile.csv', 'w')
> IOError: [Errno 13] Permission denied: 'somefile.csv'
From kent37 at tds.net  Tue Apr  5 17:50:04 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr  5 17:50:09 2005
Subject: [Tutor] pickle in unicode format
In-Reply-To: <1112709426.13679.6.camel@obslin15.unige.ch>
References: <1112709426.13679.6.camel@obslin15.unige.ch>
Message-ID: <4252B3AC.3090301@tds.net>

BRINER Cedric wrote:
> hi,
> 
> I have this dictionnary :
> 
> a={'partition': u'/export/diskH1/home_evol/ricquebo',
>  'rsmFirstname': u'Fran\xe7ois',
>  'rsmLastname': u'Ricquebourg',
>  'size': u'8161222.0',
>  'size_max': '1'}
> 
> and I'd like to *serialize* it with pickle and that the output format
> will be of type unicode.

I'm not sure what you mean by this. Do you mean that you want the actual pickled data to be a 
unicode string? Or that you want to be able to pickle something that contains unicode strings?
> 
> unicode(pickle.dumps(a)) doesn't work !

pickle.dumps() doesn't return a value, it puts the data into 'a' which must be a file-like object.

> or
> pickle.dumps(a,protocol=2,bin='V')
> 
> doesn't seem to work :(

The bin parameter is replaced by the protocol parameter, you don't need to use both. Also the bin 
parameter takes a True or False value so passing it a string is kind of strange.

Can you say some more about the problem you are trying to solve? If you are just trying to pickle 
and unpickle the dictionary above then pickle.dumps() and pickle.loads() should work:

  >>> a={'partition': u'/export/diskH1/home_evol/ricquebo',
  ...  'rsmFirstname': u'Fran\xe7ois',
  ...  'rsmLastname': u'Ricquebourg',
  ...  'size': u'8161222.0',
  ...  'size_max': '1'}
  >>> a
{'rsmLastname': u'Ricquebourg', 'rsmFirstname': u'Fran\xe7ois', 'partition': 
u'/export/diskH1/home_evol/ricquebo', 'size_max': '1', 'size': u'8161222.
0'}

  >>> import pickle
  >>> s = pickle.dumps(a)
  >>> s
"(dp0\nS'rsmLastname'\np1\nVRicquebourg\np2\nsS'rsmFirstname'\np3\nVFran\xe7ois\np4\nsS'partition'\np5\nV/export/diskH1/home_evol/ricquebo\np6\nsS'siz
e_max'\np7\nS'1'\np8\nsS'size'\np9\nV8161222.0\np10\ns."

  >>> b = pickle.loads(s)
  >>> b
{'rsmLastname': u'Ricquebourg', 'rsmFirstname': u'Fran\xe7ois', 'partition': 
u'/export/diskH1/home_evol/ricquebo', 'size_max': '1', 'size': u'8161222.
0'}
  >>> b == a
True
  >>>

Kent

From jeannot18 at hotmail.com  Tue Apr  5 18:26:29 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Tue Apr  5 18:26:34 2005
Subject: [Tutor] Calendar question
Message-ID: <BAY20-F4082B88D6798DE2FDBE38EB33C0@phx.gbl>

I am back, thanks again all to help me sorting out the High_Low guessing 
game using time.

Can somebody put me on the right track for the following script. I know how 
to use the calendar.prcal command to print the 12 months of choosen year. 
But how do you use the prmonth command, if you, for example, want to write 
something asking you:

to enter a year (this I know)
to enter a month of that year
and print just the month

I look and some of the previous posts, search the net but could not find 
anything specific. Thanks

Also, I have been looking for some exercises to do using Python, obviously 
(and unfortunately) they need to be at a beginner level. Or better if anyone 
wants to send me one to do I would be very grateful

Thanks
JC


From cpu.crazy at gmail.com  Tue Apr  5 18:31:01 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue Apr  5 18:30:29 2005
Subject: [Tutor] Py2exe (Joseph Q.)
Message-ID: <6.1.0.6.2.20050405102939.01e468f0@pop.gmail.com>

Joseph Q. (Uspantan, Guatemala) Using Python 2.4

I downloaded py2exe and can't get it to make exe's of my python files. 
There are a list of instructions:

# A very simple setup script to create 2 executables.
#
# hello.py is a simple "hello, world" type program, which alse allows
# to explore the environment in which the script runs.
#
# test_wx.py is a simple wxPython program, it will be converted into a
# console-less program.
#
# If you don't have wxPython installed, you should comment out the
#   windows = ["test_wx.py"]
# line below.
#
#
# Run the build process by entering 'setup.py py2exe' or
# 'python setup.py py2exe' in a console prompt.
#
# If everything works well, you should find a subdirectory named 'dist'
# containing some files, among them hello.exe and test_wx.exe.


from distutils.core import setup
import py2exe

setup(
     # The first three parameters are not required, if at least a
     # 'version' is given, then a versioninfo resource is built from
     # them and added to the executables.
     version = "0.5.0",
     description = "py2exe sample script",
     name = "py2exe samples",

     # targets to build
     # windows = ["test_wx.py"],
     console = ["hello.py"],
     )

What does it mean by the 'console prompt'? I tried Command Prompt (Windows 
XP) but I get errors when I type 'setup.py py2exe' or 'python setup.py 
py2exe'. I also don't get anything when I run the setup.py in IDLE (or the 
Python command line). In fact I get an error:
Traceback (most recent call last):
   File "C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py", 
line 22, in ?
     import py2exe
ImportError: No module named py2exe

If you have used or are using py2exe, please tell me what I'm doing wrong!
Thanks,
   Joseph Q.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050405/80677932/attachment.html
From kristian.zoerhoff at gmail.com  Tue Apr  5 18:34:49 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Tue Apr  5 18:34:52 2005
Subject: [Tutor] Calendar question
In-Reply-To: <BAY20-F4082B88D6798DE2FDBE38EB33C0@phx.gbl>
References: <BAY20-F4082B88D6798DE2FDBE38EB33C0@phx.gbl>
Message-ID: <3511dc7505040509343274bc49@mail.gmail.com>

On Apr 5, 2005 11:26 AM, John Carmona <jeannot18@hotmail.com> wrote:
> But how do you use the prmonth command, if you, for example, want to write
> something asking you:
> 
> to enter a year (this I know)
> to enter a month of that year
> and print just the month

>>> import calendar
>>> year = int(raw_input("Year? "))
>>> month = int(raw_input("Month? "))
>>> calendar.prmonth(year, month)

This assumes all input as integers; if you want months entered by
name, you'll have to write a conversion routine (hint: use a dict).

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From jeannot18 at hotmail.com  Tue Apr  5 18:45:45 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Tue Apr  5 18:45:49 2005
Subject: [Tutor] Calendar question
In-Reply-To: <3511dc7505040509343274bc49@mail.gmail.com>
Message-ID: <BAY20-F13E9F87B70BB9FB4D79131B33C0@phx.gbl>

Thanks Kristian, it works a treat. Now you have set me up with finding out 
how to use the months entered by name. If I am stuck I will post again.

Thanks very much
JC


From kent37 at tds.net  Tue Apr  5 19:16:45 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr  5 19:16:43 2005
Subject: [Tutor] pickle in unicode format
In-Reply-To: <4252B3AC.3090301@tds.net>
References: <1112709426.13679.6.camel@obslin15.unige.ch>
	<4252B3AC.3090301@tds.net>
Message-ID: <4252C7FD.8090801@tds.net>

Kent Johnson wrote:
> BRINER Cedric wrote:
>> unicode(pickle.dumps(a)) doesn't work !
> 
> 
> pickle.dumps() doesn't return a value, it puts the data into 'a' which 
> must be a file-like object.

Oops, pickle.dumps() does return a value and the parameter is the object to be pickled. I even knew 
that before I sent the email, but I forgot to correct it.

Kent

From nick at javacat.f2s.com  Tue Apr  5 19:33:32 2005
From: nick at javacat.f2s.com (Nick Lunt)
Date: Tue Apr  5 19:32:53 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <33194d7305040416346a07de92@mail.gmail.com>
References: <33194d7305040310311b68405f@mail.gmail.com>	
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>	
	<4251B7A0.3080709@javacat.f2s.com>
	<33194d7305040416346a07de92@mail.gmail.com>
Message-ID: <4252CBEC.60201@javacat.f2s.com>

Shidai Liu wrote:

>>    
>>
>
>I found out in the following situation, it fails to work.
>Say, 'somefile.csv' is opened by EXCEL,
>  
>
>>>>os.access('somefile.csv', os.W_OK)
>>>>        
>>>>
>True
>  
>
>>>>file('somefile.csv', 'w')
>>>>        
>>>>
>IOError: [Errno 13] Permission denied: 'somefile.csv'
>
>By the way, using os.stat & stat as suggested by Alan doesn't work either.
>Any idea how solve it?
>
>  
>
I havent got access to a windows box unfortunately at the moment. And I 
have no idea about permissions on windows boxes anyway :)
However, did you already have the .csv file open in Excel or some other 
app ? Or is is password protected maybe ?

Sorry not much help.

Nick .
From dyoo at hkn.eecs.berkeley.edu  Tue Apr  5 20:33:23 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr  5 20:33:27 2005
Subject: [Tutor] pickle in unicode format
In-Reply-To: <4252B3AC.3090301@tds.net>
Message-ID: <Pine.LNX.4.44.0504051102240.19586-100000@hkn.eecs.berkeley.edu>



> > I have this dictionnary :
> >
> > a={'partition': u'/export/diskH1/home_evol/ricquebo',
> >  'rsmFirstname': u'Fran\xe7ois',
> >  'rsmLastname': u'Ricquebourg',
> >  'size': u'8161222.0',
> >  'size_max': '1'}
> >
> > and I'd like to *serialize* it with pickle and that the output format
> > will be of type unicode.
>
> I'm not sure what you mean by this. Do you mean that you want the actual
> pickled data to be a unicode string? Or that you want to be able to
> pickle something that contains unicode strings?

The first interpretation doesn't make sense to me either: pickled data is
a 'byte' representation of your data structures.  Why do you need it to be
treated as a unicode string?



> > unicode(pickle.dumps(a)) doesn't work !

Can you show us why this doesn't work for you?  I can guess why, but it is
much better if we don't have to guess what the error message looks like.
I suspect you're seeing something like this:

######
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
ordinal not in range(128)
######

but again, I hate guessing.  *grin*

Show us exactly what you're seeing as an error message: don't just say it
doesn't work, because that doesn't give us enough to know if the error or
bug that we're seeing is the same one that you're seeing.  Problems often
can have multiple causes, which is why we need to see the one you're
getting stuck on.



I think it'll help if we see what you intend to do with the result of
pickle.dumps().


Are you trying to send it off to someone else as a part of an XML
document?  If you are including some byte string into an XML document, you
can encode those bytes as base64:

######
>>> bytes = 'Fran\xe7ois'
>>> encodedBytes = bytes.encode('base64')
>>> encodedBytes
'RnJhbudvaXM=\n'
######

This produces a transformed byte string that pass through the unicode()
function with no damage:

#######
>>> unicodeEncodedBytes = unicode(encodedBytes)
>>> unicodeEncodedBytes
u'RnJhbudvaXM=\n'
#######

and this can written right into an XML document.  It can also be later
decoded back to get the original byte string:

######
>>> str(unicodeEncodedBytes).decode("base64")
'Fran\xe7ois'
######


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

From dyoo at hkn.eecs.berkeley.edu  Tue Apr  5 21:02:01 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr  5 21:02:04 2005
Subject: [Tutor] pickle in unicode format
In-Reply-To: <Pine.LNX.4.44.0504051102240.19586-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504051146590.29721-100000@hkn.eecs.berkeley.edu>

> Are you trying to send it off to someone else as a part of an XML
> document?  If you are including some byte string into an XML document,
> you can encode those bytes as base64:
>
> ######
> >>> bytes = 'Fran\xe7ois'
> >>> encodedBytes = bytes.encode('base64')
> >>> encodedBytes
> 'RnJhbudvaXM=\n'
> ######

[note: this is an example of exploratory programming with Python.]


As a followup to this: this does appear to be a standard technique for
encoding binary data in XML.  Apple does this in their property list
implementation.

For example, in Apple's reference documentation on plists:

    http://developer.apple.com/documentation/CoreFoundation
        /Conceptual/CFPropertyLists/index.html


they use an example where they encode the following bytes:

/******/
   // Fake data to stand in for a picture of John Doe.
   const unsigned char pic[kNumBytesInPic] = {0x3c, 0x42, 0x81,
            0xa5, 0x81, 0xa5, 0x99, 0x81, 0x42, 0x3c};
/******/


into an ASCII string.  That string looks like this:

######
    <data>
        PEKBpYGlmYFCPA==
    </data>
######


and although they don't explicitely say it out loud, we can infer that
this is a pass through a base64 encoding, because when we decode that
string through base64:

######
>>> mysteryText = "        PEKBpYGlmYFCPA=="
>>> mysteryText.decode("base64")
'<B\x81\xa5\x81\xa5\x99\x81B<'
>>>
>>>
>>> [hex(ord(byte)) for byte in mysteryText.decode('base64')]
['0x3c', '0x42', '0x81', '0xa5', '0x81', '0xa5', '0x99', '0x81', '0x42',
'0x3c']
######

we get the same bytes back.


(Actually, Apple's documentation does briefly mention that they do use
base64 by default, in:

http://developer.apple.com/documentation/WebObjects/Reference/API5.2.2/com/webobjects/foundation/xml/NSXMLObjectOutput.html#setUseBase64ForBinaryData(boolean)

but that's really obscure.  *grin*)



Anyway, hope that was interesting to folks!

From jeannot18 at hotmail.com  Tue Apr  5 22:08:47 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Tue Apr  5 22:08:50 2005
Subject: [Tutor] Calendar question
In-Reply-To: <3511dc7505040509343274bc49@mail.gmail.com>
Message-ID: <BAY20-F19478A409E93CA2D76F13FB33C0@phx.gbl>

Kristian you wrote:

---------------------------------------------------------------------------------------------
This assumes all input as integers; if you want months entered by
name, you'll have to write a conversion routine (hint: use a dict).
---------------------------------------------------------------------------------------------

I have been looking for a while about doing a conversion routine (using a 
dictionary??), are you saying that I should convert a string (January, 
February, etc.) into integers. Could you please give me some light (do not 
write the code please but just point me to the right direction if you can)

Many thanks
JC


From python at kapitalisten.no  Tue Apr  5 22:18:47 2005
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Tue Apr  5 22:18:45 2005
Subject: [Tutor] Mouseclick
Message-ID: <3556.193.216.161.244.1112732327.squirrel@mail.sporck.net>

I am creating a little application that demonstrates some tasks on the
screen for the user, but cannot seem to click the left mousebutton.

I have moved the cursor to the correct position by

>>> from ctypes import *
>>> windll.user32.SetCursorPos(100, 400)

and would like to click the left mousebutton at that position. Is that
possible? I have just been able to find ways to click the button on
buttons that I can name such as:

def findAButtonCalledOK(hwnd, windowText, windowClass): # Define a
function to find our button
    return windowClass == "Button" and windowText == "OK"
okButton = findControl(optDialog, findAButtonCalledOK)
click(okButton)

or how to track if a button is pressed. But neither of those are what I
need. I need to press the button at a specific coordinate... Can I do that
with Python? If so, how? 3 hours of Googling didn't help me....

Thanks in advance...

-- 
This email has been scanned for viruses & spam by Decna as - www.decna.no
Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no

From kristian.zoerhoff at gmail.com  Tue Apr  5 22:33:53 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Tue Apr  5 22:33:55 2005
Subject: Fwd: [Tutor] Calendar question
In-Reply-To: <3511dc750504051333464942b8@mail.gmail.com>
References: <3511dc7505040509343274bc49@mail.gmail.com>
	<BAY20-F19478A409E93CA2D76F13FB33C0@phx.gbl>
	<3511dc750504051333464942b8@mail.gmail.com>
Message-ID: <3511dc7505040513332bb0b6e@mail.gmail.com>

Forgot to Reply-All. Dagnabbit.

---------- Forwarded message ----------
From: Kristian Zoerhoff <kristian.zoerhoff@gmail.com>
Date: Apr 5, 2005 3:33 PM
Subject: Re: [Tutor] Calendar question
To: John Carmona <jeannot18@hotmail.com>


On Apr 5, 2005 3:08 PM, John Carmona <jeannot18@hotmail.com> wrote:
> Kristian you wrote:
>
> ---------------------------------------------------------------------------------------------
> This assumes all input as integers; if you want months entered by
> name, you'll have to write a conversion routine (hint: use a dict).
> ---------------------------------------------------------------------------------------------
>
> I have been looking for a while about doing a conversion routine (using a
> dictionary??), are you saying that I should convert a string (January,
> February, etc.) into integers. Could you please give me some light (do not
> write the code please but just point me to the right direction if you can)

Create a dictionary whose keys are month names (lowercase, for
simplicity), and whose values are integers. Get the month name from
the user (don't convert to an int directly this time, but do convert
to lowercase), then use that to get the appropriate integer value from
the dictionary for passing to calendar.prmonth.

It's really more of a lookup than a conversion. There are probably
other ways to do this as well, but this will give you a nice
introduction to using dictionaries in Python.

--
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org


-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From glaevsky at ECE.NEU.EDU  Tue Apr  5 21:49:26 2005
From: glaevsky at ECE.NEU.EDU (glaevsky@ECE.NEU.EDU)
Date: Tue Apr  5 22:46:34 2005
Subject: [Tutor] Major Newbie Here
Message-ID: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>

Hello all,

I'm a cell biologist that is learning python.  I've been following Alan 
Gauld's tutorial online and I've hit a wall.

I'm typing

class Spam:
	"""A meat for combining with other foods

	It can be used with other foods to make interesting meals.
	It comes with lots of nutrients and can be cooked using many
	different techniques"""

	
 >>> def__init__(self):
	
SyntaxError: invalid syntax

and I get that error.  I've tried several different versions over several 
days and I'm stuck.

Little help please.  Thanks

long time first time
Best,

Gary



Gary Laevsky, Ph.D.
Keck Facility Manager, CenSSIS
Northeastern University
302 Stearns
360 Huntington Ave.
Boston, MA 02115
voice(617) 373 - 2589<br>
fax(617) 373 - 7783<br><br>

http://www.censsis.neu.edu

http://www.ece.neu.edu/groups/osl

http://www.keck3dfm.neu.edu

From kristian.zoerhoff at gmail.com  Tue Apr  5 22:49:32 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Tue Apr  5 22:49:35 2005
Subject: [Tutor] Major Newbie Here
In-Reply-To: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>
Message-ID: <3511dc7505040513495a2205a5@mail.gmail.com>

On Apr 5, 2005 2:49 PM, glaevsky@ece.neu.edu <glaevsky@ece.neu.edu> wrote:
> Hello all,
> 
> I'm a cell biologist that is learning python.  I've been following Alan
> Gauld's tutorial online and I've hit a wall.
> 
> I'm typing
> 
> class Spam:
>         """A meat for combining with other foods
> 
>         It can be used with other foods to make interesting meals.
>         It comes with lots of nutrients and can be cooked using many
>         different techniques"""
> 
>  >>> def__init__(self):
          ^
----------|
You seem to be missing a space here, if this is what you're really typing.

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From rschroev_nospam_ml at fastmail.fm  Tue Apr  5 22:47:41 2005
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Tue Apr  5 22:50:19 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <BAY20-F19478A409E93CA2D76F13FB33C0@phx.gbl>
References: <3511dc7505040509343274bc49@mail.gmail.com>
	<BAY20-F19478A409E93CA2D76F13FB33C0@phx.gbl>
Message-ID: <d2utdj$5vj$1@sea.gmane.org>

John Carmona wrote:

> Kristian you wrote:
> 
> ---------------------------------------------------------------------------------------------
> 
> This assumes all input as integers; if you want months entered by
> name, you'll have to write a conversion routine (hint: use a dict).
> ---------------------------------------------------------------------------------------------
> 
> 
> I have been looking for a while about doing a conversion routine (using
> a dictionary??), are you saying that I should convert a string (January,
> February, etc.) into integers. Could you please give me some light (do
> not write the code please but just point me to the right direction if
> you can)

A dictionary is a data structure containing keys and values that defines
a mapping from each key to its corresponding value. You define it like this:

 >>> squares = {1: 1, 10: 100, 4: 15, 5: 25}

Or an empty dictionary:

 >>> emptydict = {}

Once defined, you can access individual elements via their keys:

 >>> print squares[4]
15

This way you can also assign values to existing elements:
 >>> squares[4] = 4*4
 >>> print squares[4]
16

Or add new elements:
 >>> squares[6] = 16
 >>> squares[7] = 49

Python raises a KeyError exception if you try to read an element with a
non-existing key:
 >>> print squares[9]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    print squares[9]
KeyError: 9

I used numbers for the keys and the values, but in fact any Python
object can be used as a value. Any immutable object can be used as a
key; for now, just remember that you can use numbers, strings and tuples
as keys.

So what you could do is create a dictionary with the names of the months
as keys and the corresponding numbers as values and use that dictionary
to convert the names in the numbers.

Try to play a bit with dictionaries in IDLE (or your Python shell of
choice). If anything's not clear, just give a yell.


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

From dyoo at hkn.eecs.berkeley.edu  Tue Apr  5 22:57:37 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr  5 22:57:43 2005
Subject: [Tutor] Major Newbie Here
In-Reply-To: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>
Message-ID: <Pine.LNX.4.44.0504051348310.11692-100000@hkn.eecs.berkeley.edu>



> I'm a cell biologist that is learning python.  I've been following Alan
> Gauld's tutorial online and I've hit a wall.
>
> I'm typing
>
> class Spam:
> 	"""A meat for combining with other foods
>
> 	It can be used with other foods to make interesting meals.
> 	It comes with lots of nutrients and can be cooked using many
> 	different techniques"""
>
>
>  >>> def__init__(self):
>
> SyntaxError: invalid syntax


Hi Gary,

Side note: please subscribe yourself to the mailing list; otherwise, a
silly list admin has to go through and manually allow your posts to get to
the list.  You can find instructions on subscribing here:

    http://mail.python.org/mailman/listinfo/tutor


Welcome aboard!  From what you've shown us so far, it looks like you're
trying to code the class in the interactive interpreter.  You can do this,
but it's probably easier to do this by writing your class in a text file,
and run Python over that file.


I'm guessing that you're entering something like this:

######
class Spam:
    """A meat for combining with other foods
    It can be used with other foods to make interesting meals.
    It comes with lots of nutrients and can be cooked using many
    different techniques"""

def__init__(self):
    ## ... rest of code follows
######


The "class" statement introduces a level of indentation, so you need to
indent all the "methods" that belong to the Spam class.  It's a pure
syntax thing.

Try:

######
class Spam:
    """A meat for combining with other foods
    It can be used with other foods to make interesting meals.
    It comes with lots of nutrients and can be cooked using many
    different techniques"""

    def__init__(self):
        ## ... rest of code follows
######


Tell us if this works out better for you.


By the way, are you using a specialized text editor to work with your
Python programs?  A good text editor makes programming much more pleasant.
Programs like IDLE or PythonWin or the others listed on:

    http://www.python.org/moin/IntegratedDevelopmentEnvironments

can be very helpful.  I've written a somewhat out-of-date IDLE tutorial
here:

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


Best of wishes to you!

From rschroev_nospam_ml at fastmail.fm  Tue Apr  5 23:03:10 2005
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Tue Apr  5 23:04:55 2005
Subject: [Tutor] Re: Major Newbie Here
In-Reply-To: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050405154620.020e2be8@pop.ece.neu.edu>
Message-ID: <d2uuak$903$1@sea.gmane.org>

glaevsky@ECE.NEU.EDU wrote:

> Hello all,
> 
> I'm a cell biologist that is learning python.  I've been following Alan
> Gauld's tutorial online and I've hit a wall.
> 
> I'm typing
> 
> class Spam:
>     """A meat for combining with other foods
> 
>     It can be used with other foods to make interesting meals.
>     It comes with lots of nutrients and can be cooked using many
>     different techniques"""
> 
>     
>>>> def__init__(self):
>     
> SyntaxError: invalid syntax
> 
> and I get that error.  I've tried several different versions over
> several days and I'm stuck.

You should include a space between 'def' and '__init__'. Not doing so is
what the SyntaxError complains about.

Also, did you type that in IDLE? You shouldn't type two enters after the
line with 'different techniques' since IDLE stops the definition of the
class if you do that; you should use only one enter in this case. That's
a limitation of IDLE, not of Python: if you put that definition in a
file, you can use as many empty lines as you like.


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

From missive at hotmail.com  Tue Apr  5 23:22:10 2005
From: missive at hotmail.com (Lee Harr)
Date: Tue Apr  5 23:22:14 2005
Subject: [Tutor] Re: random import errors
Message-ID: <BAY2-F6DB3CD164A53F2C582B50B13C0@phx.gbl>

>I have a python script that runs on my webserver every fifteen minutes.  It
>has run for several months with absolutely no problems.  Suddenly, 
>yesterday
>morning I got an email from cron with an import error for sre_constants 
>(see
>below)
>

>   File "/usr/lib/python2.2/sre_compile.py", line 15, in ?
>     from sre_constants import *
>ImportError: No module named sre_constants


Do you have more than one version of python installed?
Can you copy sre_constants.py from another system?

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

From missive at hotmail.com  Tue Apr  5 23:25:38 2005
From: missive at hotmail.com (Lee Harr)
Date: Tue Apr  5 23:25:43 2005
Subject: [Tutor] Re: Script (Python) for Zope
Message-ID: <BAY2-F41731AB461B9F8EB22025DB13C0@phx.gbl>

>Hello,
>
>I am looking for a Python-script for Zope which counts
>the objects (files) in the current folder and all its subfolders,
>but I don't know how to implement this script. Can somebody
>help me, please? Or ist there a newsgroup/mailing list which
>can help me to find a solution for this problem?
>
>Thanks.
>
>Mike
>


I recommend you join the zope@zope.org mailing list.

I also recommend you post plain text (as opposed to
base 64 encoded text) to make reading your posts
easier.

_________________________________________________________________
FREE pop-up blocking with the new MSN Toolbar - get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/

From python at jayloden.com  Tue Apr  5 23:35:54 2005
From: python at jayloden.com (Jay Loden)
Date: Tue Apr  5 23:35:55 2005
Subject: [Tutor] Re: random import errors
In-Reply-To: <BAY2-F6DB3CD164A53F2C582B50B13C0@phx.gbl>
References: <BAY2-F6DB3CD164A53F2C582B50B13C0@phx.gbl>
Message-ID: <200504052235.54949.python@jayloden.com>

Only one version installed, and I could copy it over from elsewhere, but I 
wouldn't be inclined to do so since it works right now. 

-Jay

On Tuesday 05 April 2005 10:22 pm, Lee Harr wrote:
> >I have a python script that runs on my webserver every fifteen minutes. 
> > It has run for several months with absolutely no problems.  Suddenly,
> > yesterday
> >morning I got an email from cron with an import error for sre_constants
> >(see
> >below)
> >
> >
> >   File "/usr/lib/python2.2/sre_compile.py", line 15, in ?
> >     from sre_constants import *
> >ImportError: No module named sre_constants
>
> Do you have more than one version of python installed?
> Can you copy sre_constants.py from another system?
>
> _________________________________________________________________
> Express yourself instantly with MSN Messenger! Download today it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From jfouhy at paradise.net.nz  Wed Apr  6 00:47:17 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Wed Apr  6 00:47:24 2005
Subject: [Tutor] Major Newbie Here
In-Reply-To: <Pine.LNX.4.44.0504051348310.11692-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504051348310.11692-100000@hkn.eecs.berkeley.edu>
Message-ID: <1112741237.42531575f004e@www.paradise.net.nz>

Quoting Danny Yoo <dyoo@hkn.eecs.berkeley.edu>:

> Try:
> 
> ######
> class Spam:
>  """A meat for combining with other foods
>  It can be used with other foods to make interesting meals.
>  It comes with lots of nutrients and can be cooked using many
>  different techniques"""
> 
>  def__init__(self):
>  ## ... rest of code follows
> ######
> 
> 
> Tell us if this works out better for you.

Actually, that still won't work.

Firstly, because, as others have pointed out, there is a missing space between
the 'f' and the '_'.

But even then, if you do that at the interpreter, it won't work.

>>> class Spam:
...  """A meat for combining with other foods
...  It can be used with other foods to make interesting meals.
...  It comes with lots of nutrients and can be cooked using many
...  different techniques"""
...
>>>  def __init__(self):
  File "<stdin>", line 1
    def __init__(self):
    ^
SyntaxError: invalid syntax
>>>

The problem is that the interpreter will treat a blank line as the end of an
indented block.  If you want to define classes, functions, etc. in the
interactive interpreter, you have to do so without leaving any blank lines.

...which is another good reason to write things in scripts instead :-)

-- 
John.
From shidai.liu at gmail.com  Wed Apr  6 01:03:44 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Wed Apr  6 01:03:48 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <4252CBEC.60201@javacat.f2s.com>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>
	<4251B7A0.3080709@javacat.f2s.com>
	<33194d7305040416346a07de92@mail.gmail.com>
	<4252CBEC.60201@javacat.f2s.com>
Message-ID: <33194d7305040516035b9f0be2@mail.gmail.com>

On Apr 5, 2005 6:33 PM, Nick Lunt <nick@javacat.f2s.com> wrote:
> I havent got access to a windows box unfortunately at the moment. And I
> have no idea about permissions on windows boxes anyway :)
> However, did you already have the .csv file open in Excel or some other
> app ? Or is is password protected maybe ?
> 
> Sorry not much help.
> 
> Nick .
> 

Here's where my question.
The file is already opened by Excel. os.access indicates it's
writable, but it's actully not.
From shidai.liu at gmail.com  Wed Apr  6 01:06:03 2005
From: shidai.liu at gmail.com (Shidai Liu)
Date: Wed Apr  6 01:06:06 2005
Subject: [Tutor] [HELP]how to test properties of a file
In-Reply-To: <61d0e2b4050405074064c3c497@mail.gmail.com>
References: <33194d7305040310311b68405f@mail.gmail.com>
	<42502AFF.1020208@cirad.fr> <037701c5395f$5c697a60$61cb8751@xp>
	<4251B7A0.3080709@javacat.f2s.com>
	<33194d7305040416346a07de92@mail.gmail.com>
	<61d0e2b4050405074064c3c497@mail.gmail.com>
Message-ID: <33194d73050405160628dd25f4@mail.gmail.com>

On Apr 5, 2005 3:40 PM, Bernard Lebel <3dbernard@gmail.com> wrote:
> As far as I'm aware, this is very normal. The file is being used by an
> application, so there is a lock on it.
> 

However, os.access('somefile.csv', os.W_OK) returns True. Shouldn't it
return False?
From jeannot18 at hotmail.com  Wed Apr  6 02:05:16 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr  6 02:05:20 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <d2utdj$5vj$1@sea.gmane.org>
Message-ID: <BAY20-F154869321B67B29CA5C744B33D0@phx.gbl>



Roel you wrote:
>

---------------------------------------------------------------------------------------------
A dictionary is a data structure containing keys and values that defines
a mapping from each key to its corresponding value. You define it like this:

 >>> squares = {1: 1, 10: 100, 4: 15, 5: 25}

Or an empty dictionary:

 >>> emptydict = {}

Once defined, you can access individual elements via their keys:

 >>> print squares[4]
15

This way you can also assign values to existing elements:
 >>> squares[4] = 4*4
 >>> print squares[4]
16

Or add new elements:
 >>> squares[6] = 16
 >>> squares[7] = 49

Python raises a KeyError exception if you try to read an element with a
non-existing key:
 >>> print squares[9]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    print squares[9]
KeyError: 9

I used numbers for the keys and the values, but in fact any Python
object can be used as a value. Any immutable object can be used as a
key; for now, just remember that you can use numbers, strings and tuples
as keys.

So what you could do is create a dictionary with the names of the months
as keys and the corresponding numbers as values and use that dictionary
to convert the names in the numbers.
---------------------------------------------------------------------------------------------

Thanks Roel for the reply   (same to Kristian and Alan- I will check that 
website, thanks)

OK below you can see what I have written so far, I am a bit confused when 
you say
<<to convert the names in the numbers>>. At this stage when I run the script 
it is asking me to use a string or a number, and if I remove the line 
converting the string into an integer, it is asking me to use integers.
Thanks
JC

---------------------------------------------------------------------------------------------
import calendar

MonthName = {'January': 1,'February': 2, 'March': 3,'April': 4\
         ,'May': 5,'June': 6,'July': 7,'August': 8,\
       'September': 9,'October': 10,'November': 11,'December': 12}

##By the way do the number have to be under that format??

calendar.setfirstweekday(0)
              ##setfirstweekday change the day to what you want it be
              ## 0=Monday, 6=Sunday.
year = int(raw_input("Enter a year: "))
month = (raw_input("Enter a month: "))
MonthName_int = int(MonthName)


print calendar.prmonth(year,month)


---------------------------------------------------------------------------------------------


From jfouhy at paradise.net.nz  Wed Apr  6 03:15:53 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Wed Apr  6 03:15:57 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <BAY20-F154869321B67B29CA5C744B33D0@phx.gbl>
References: <BAY20-F154869321B67B29CA5C744B33D0@phx.gbl>
Message-ID: <1112750153.4253384945d14@www.paradise.net.nz>

Quoting John Carmona <jeannot18@hotmail.com>:

Hi John,

Some comments ---

> import calendar
> 
> MonthName = {'January': 1,'February': 2, 'March': 3,'April': 4\
>  ,'May': 5,'June': 6,'July': 7,'August': 8,\
>  'September': 9,'October': 10,'November': 11,'December': 12}

You can actually get away with leaving out the backslashes.  ie, if I were
writing this code, I would probably write something like this:

MonthName = { 'January':1, 'February':2, 'March':3, 'April':4,
              'May':5, 'June':6, 'July':7, 'August':8,
              'September':9, 'October':10, 'November':11, 'December':12 }

(I'm not sure what the preferred convention for whitespace is ... I always leave
a space after the comma, but have no whitespace surrounding the colon, because
that makes it clearer that the two things either side of the ':' are a linked unit)

> ##By the way do the number have to be under that format??

I don't understand the question, sorry..

> calendar.setfirstweekday(0)
>  ##setfirstweekday change the day to what you want it be
>  ## 0=Monday, 6=Sunday.
> year = int(raw_input("Enter a year: "))
> month = (raw_input("Enter a month: "))            # ***
> MonthName_int = int(MonthName)                    # ***
> 
> 
> print calendar.prmonth(year,month)

Try replacing the lines I have marked with:

monthString = raw_input("Enter a month: ")
month = MonthName[monthString]

You might want to review the tutorial section on dictionaries:

http://python.org/doc/2.4.1/tut/node7.html#SECTION007500000000000000000

If you want more robustness, you could try replacing those two lines with this:

monthString = raw_input('Enter a month: ')
while monthString not in MonthName:
    print "Unknown month!"
    monthString = raw_input('Enter a month: ')
month = MonthName[monthString]

This will check to see if the user's input is one of the keys in your
dictionary, and if not, it will ask again.

HTH!

-- 
John.
From flaxeater at yahoo.com  Wed Apr  6 03:20:22 2005
From: flaxeater at yahoo.com (Chad Crabtree)
Date: Wed Apr  6 03:20:25 2005
Subject: [Tutor] Py2exe (Joseph Q.)
Message-ID: <20050406012022.92704.qmail@web54310.mail.yahoo.com>

The symptoms you explain mean you don't have py2exe installed 
correctly.  Try uninstalling it and reinstalling it.


Joseph Quigley wrote:

> Joseph Q. (Uspantan, Guatemala) Using Python 2.4
>
> I downloaded py2exe and can't get it to make exe's of my python
files. 
> There are a list of instructions:
>
> # A very simple setup script to create 2 executables.
> #
> # hello.py is a simple "hello, world" type program, which alse
allows
> # to explore the environment in which the script runs.
> #
> # test_wx.py is a simple wxPython program, it will be converted
into a
> # console-less program.
> #
> # If you don't have wxPython installed, you should comment out the
> #   windows = ["test_wx.py"]
> # line below.
> #
> #
> # Run the build process by entering 'setup.py py2exe' or
> # 'python setup.py py2exe' in a console prompt.
> #
> # If everything works well, you should find a subdirectory named
'dist'
> # containing some files, among them hello.exe and test_wx.exe.
>
>
> from distutils.core import setup
> import py2exe
>
> setup(
>     # The first three parameters are not required, if at least a
>     # 'version' is given, then a versioninfo resource is built from
>     # them and added to the executables.
>     version = "0.5.0",
>     description = "py2exe sample script",
>     name = "py2exe samples",
>
>     # targets to build
>     # windows = ["test_wx.py"],
>     console = ["hello.py"],
>     )
>
> What does it mean by the 'console prompt'? I tried Command Prompt 
> (Windows XP) but I get errors when I type 'setup.py py2exe' or
'python 
> setup.py py2exe'. I also don't get anything when I run the setup.py
in 
> IDLE (or the Python command line). In fact I get an error:
> Traceback (most recent call last):
>   File
"C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py", 
> line 22, in ?
>     import py2exe
> ImportError: No module named py2exe
>
> If you have used or are using py2exe, /please/ tell me what I'm
doing 
> wrong!
> Thanks,
>   Joseph Q.
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>



		
__________________________________ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/ 
From keridee at jayco.net  Wed Apr  6 04:06:56 2005
From: keridee at jayco.net (Jacob S.)
Date: Wed Apr  6 04:07:09 2005
Subject: [Tutor] Calendar question
References: <BAY20-F4082B88D6798DE2FDBE38EB33C0@phx.gbl>
Message-ID: <005301c53a4d$7d4517a0$155328cf@JSLAPTOP>

> Also, I have been looking for some exercises to do using Python, obviously 
> (and unfortunately) they need to be at a beginner level. Or better if 
> anyone wants to send me one to do I would be very grateful

I know a few exercises -- those that I have done. Some are beginner, some 
are difficult.
Use your discretion...

1) Make a program to compute the areas of several figures. Make it display a 
menu on startup,         ask for a choice, and then compute the area of the 
figure chosen by asking for dimensions.

2) Good at math? Make a library module with three functions. First 
function --  calculate the             derivative of a function passed as a 
parameter at a particular point. Should return float.  Second 
    function -- calculate definite integral; function, lower bound, and 
upper bound passed as                 parameters Should return float.  Third 
function -- find the zeros of a function passed as a              parameter. 
## This is more difficult

3) Make a cute little joke -- How to keep a blonde busy. (Press enter) -- it 
loops forever

4) Make another script similiar to #1 using volumes instead of areas

5) Combine script one and script four

6) Use the os module to make a copy module that copies files -- similiar to, 
but with less                 functionality than shutil

7) Use the calender module to get the day of week function -- make the user 
input a date - parse     the date, and return the day of the week. An extra 
to advance it a little. Use regular expressions     to have any non-digit 
seperator.

8) Use the random module and a fibonacci sequence to generate long numbers 
that you can             seemingly  "memorize"  i.e. 
random.randint(10,100)  gives you say...  45... then the number 
would be 459437077415617853...  strip off the tens digit when you add.

9) Make a library module containing functions such as get greatest common 
denominator of a             sequence; lowest common multiple; factors of an 
integer; etc.

10) Download an extension package such as VPython or something and make a 
function grapher -       - try making it a little more advanced than their 
example in the docs....

11) Make a grade program for teachers that asks for a grade, prints the 
percentage for that                 grade, and prints the percentage of the 
class i.e. average all of the grades for each grade                 added.

12) Use random to create a lottery scenario.

13) Make a simple word counter that takes a file name, open the file and 
split by whitespace and         get length of resulting list


If you have any questions at all, run out of ideas, or these are too 
difficult, or something else, just ask. ;-)

Jacob 

From keridee at jayco.net  Wed Apr  6 02:59:57 2005
From: keridee at jayco.net (Jacob S.)
Date: Wed Apr  6 04:07:28 2005
Subject: [Tutor] Py2exe (Joseph Q.)
References: <6.1.0.6.2.20050405075348.01e468f0@pop.gmail.com>
Message-ID: <005201c53a4d$7aba2700$155328cf@JSLAPTOP>

Type this into the interpreter and post the results - copy and pasted, not 
hand typed.

import sys
for x in sys.path:
    print x            ## This is indented

It should give you a list of paths -- these are all of the paths that python 
looks for modules in.
My guess is that you don't have the folder with py2exe in your sys.path...

HTH,
Jacob

--------------------------------------------------------------------------------
Maybe I shouldn't be posting this...
I downloaded py2exe and can't get it to make exe's of my python files. There 
are a list of instructions:

# A very simple setup script to create 2 executables.
#
# hello.py is a simple "hello, world" type program, which alse allows
# to explore the environment in which the script runs.
#
# test_wx.py is a simple wxPython program, it will be converted into a
# console-less program.
#
# If you don't have wxPython installed, you should comment out the
#   windows = ["test_wx.py"]
# line below.
#
#
# Run the build process by entering 'setup.py py2exe' or
# 'python setup.py py2exe' in a console prompt.
#
# If everything works well, you should find a subdirectory named 'dist'
# containing some files, among them hello.exe and test_wx.exe.


from distutils.core import setup
import py2exe

setup(
    # The first three parameters are not required, if at least a
    # 'version' is given, then a versioninfo resource is built from
    # them and added to the executables.
    version = "0.5.0",
    description = "py2exe sample script",
    name = "py2exe samples",

    # targets to build
    # windows = ["test_wx.py"],
    console = ["hello.py"],
    )

What does it mean by the 'console prompt'? I tried Command Prompt (Windows 
XP) but I get errors when I type 'setup.py py2exe' or 'python setup.py 
py2exe'. I also don't get anything when I run the setup.py in IDLE (or the 
Python command line). In fact I get an error:
Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py", line 
22, in ?
    import py2exe
ImportError: No module named py2exe

If you have used or are using py2exe, please tell me what I'm doing wrong!
Thanks,
  Joseph Q.




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

From garnaez at gmail.com  Wed Apr  6 05:00:16 2005
From: garnaez at gmail.com (gerardo arnaez)
Date: Wed Apr  6 05:00:38 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <4251AF49.1010403@tds.net>
References: <20050404100100.77EF51E4012@bag.python.org>
	<96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
	<148eea71050404125655f05cf5@mail.gmail.com> <4251AF49.1010403@tds.net>
Message-ID: <148eea710504052000582e43a1@mail.gmail.com>

Hi all.

I would like some crituqe on this code.
It is three separate files (all put on one web page)
Each one is labeled in the comment that begins each section of code.

It is a little longer when I put it all on one page, so I have it up on a link.
If any kind souls would critique it before I move on,
to make it webbased (What would be a good interface php?)
The link is at 
http://mung.net/~dude/coumadinAll.html

Thanks all all for your time,
G
From kedart at gmail.com  Wed Apr  6 05:13:26 2005
From: kedart at gmail.com (Kedar Tangudu)
Date: Wed Apr  6 05:17:05 2005
Subject: [Tutor] Birthday Book
Message-ID: <29520363.1112757206002.JavaMail.Administrator@win01>

Hi 

I am building a birthday book for myself and would appreciate some quick help from you. Just click on the link below and enter your birthday details. It's easy and you can keep your age secret!... 

 http://www.BirthdayAlarm.com/bd1/38729335a575244353b530591538c915052256d1386 

Thanks 
Kedar

From bvande at po-box.mcgill.ca  Wed Apr  6 06:17:42 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Wed Apr  6 06:20:26 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <148eea710504052000582e43a1@mail.gmail.com>
References: <20050404100100.77EF51E4012@bag.python.org>
	<96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
	<148eea71050404125655f05cf5@mail.gmail.com>
	<4251AF49.1010403@tds.net>
	<148eea710504052000582e43a1@mail.gmail.com>
Message-ID: <425362E6.40104@po-box.mcgill.ca>

gerardo arnaez said unto the world upon 2005-04-05 23:00:
> Hi all.
> 
> I would like some crituqe on this code.
> It is three separate files (all put on one web page)
> Each one is labeled in the comment that begins each section of code.
> 
> It is a little longer when I put it all on one page, so I have it up on a link.
> If any kind souls would critique it before I move on,
> to make it webbased (What would be a good interface php?)
> The link is at 
> http://mung.net/~dude/coumadinAll.html
> 
> Thanks all all for your time,
> G
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


Hi Gerardo,

Two factors conspire to make it difficult to follow your code: 1) I am
not the most experienced, either, and 2) there are, IMHO, some style 
difficulties with it.

It could well be that the first is the more influential here. But
given that its true, most of my comments are on style. And away we go:


> import input #input coumadin data and return it as workable date
> import inr #calulate percent increases in dose given an INR
> import math #to allow for rounding

Try that as:

import input     # input coumadin data and return it as workable date
import inr       # calculate percent increases in dose given an INR

etc. *Much* easier to take in at a glance.

Better still, move the explanatory information from the imports and
give the modules docstrings that tell this story. Oh, wait, you did
that. Then leave these out, I'd say. The docstrings speak for
themselves, and anyone (you even) who is curious later can find the
story out quite quickly.


> CurrentINR, UnitDose, TotalCurrentDose, CurrentDoseList, CurrentDoseRegimenWeek = input.AddItUp()

That is painfully long. It doesn't fit on my laptop screen at any
readable font size. Perhaps

# temp_container for unpacking the returned tuple
temp_container = input.AddItUp()
CurrentINR, UnitDose, TotalCurrentDose = temp_container[0:3]
CurrentDoseList, CurrentDoseRegimenWeek = temp_container[3:]

But I think I'd break it down one line per name. Again, I think much
easier to quickly parse, even with the overhead of the indirection.

> CurrentDoseUnit  = TotalCurrentDose/UnitDose

Easier to read as

CurrentDoseUnit  = TotalCurrentDose / UnitDose

Similar comments throughout on your use of operators. The extra space
is cheap, and oh so handy for ease of understanding.

The next line is
> print TotalCurrentDose/UnitDose, "is the Curent Coumadin Dose(%smg) in units" % TotalCurrentDose

so why not use the name you built? As in:

print CurrentDoseUnit, "is ..."

> print "The rounded dose, due to pill dose limitation is either %s" % math.floor(NewDoseUnit),\
>       "or %s" % math.ceil(NewDoseUnit), "units." 

I'd do:

print '''The rounded dose, due to pill dose limitation is either %s
or %s units.''' %(math.floor(NewDoseUnit), math.ceil(NewDoseUnit))

(With triple quotes you don't need the '\' -- I try to avoid them as
they are easy to miss.)

> WeekOrderedlist = 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'

But:

>>> type(WeekOrderedlist)
<type 'tuple'>

1) You name lies. That's bad :-)
2) I think clarity is enhanced by explicitly putting in the optional
'(' and ')' on tuples. People differ, but I like the instant (in
assignments) indication of tupleness.

>     x = decimal.Decimal(str((float(x)))) # make sure x is a number

I think (str(float(x))) would be fine.

A last general comment: I really like long_and_descriptive_names_too.
But, that said, some of yours seem too long to me. For instance,
CurrentDoseRegimenWeek could probably go to current_regimen without
loss of clarity. And, as you can see, I am a fan of underscore_names.
Religious wars have started for less, so no trying to convince you
here. :-)  but, I believe the convention that a leading cap indicates
a class name is pretty strong.

Hope these are of some help. Best to all,

Brian vdB





From marilyn at deliberate.com  Wed Apr  6 07:19:16 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Wed Apr  6 07:27:15 2005
Subject: [Tutor] str.split and quotes
Message-ID: <Pine.LNX.4.44.0504052214060.18776-100000@Kuna>

Hi Tutors,

I need a little help with this, if anyone has the time and inclination:

>>> s = 'Hi "Python Tutors" please help'
>>> s.split()
['Hi', '"Python', 'Tutors"', 'please', 'help']
>>> 

I wish it would leave the stuff in quotes in tact:

['Hi', '"Python Tutors"', 'please', 'help']

Any suggestions?

Thank you.

Marilyn Davis


From tameyer at ihug.co.nz  Wed Apr  6 07:59:23 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr  6 07:59:56 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802875440@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0043@its-xchg4.massey.ac.nz>

> >>> s = 'Hi "Python Tutors" please help'
> >>> s.split()
> ['Hi', '"Python', 'Tutors"', 'please', 'help']
> >>> 
> 
> I wish it would leave the stuff in quotes in tact:
> 
> ['Hi', '"Python Tutors"', 'please', 'help']

You can do this with a regular expression:

>>> import re
>>> re.findall(r'\".*\"|[^ ]+', s)
['Hi', '"Python Tutors"', 'please', 'help']

The regular expression says to find patterns that are either a quote (\")
then any number of any characters (.*)then a quote (/") or (|) more than one
of any character except a space ([^ ]).

Or you can just join them back up again:

>>> combined = []
>>> b = []
>>> for a in s.split():
... 	if '"' in a:
... 		if combined:
... 			combined.append(a)
... 			b.append(" ".join(combined))
... 			combined = []
... 		else:
... 			combined.append(a)
... 	else:
... 		b.append(a)
... 		
>>> b
['Hi', '"Python Tutors"', 'please', 'help']

(There are probably tidier ways of doing that).

Or you can do the split yourself:

def split_no_quotes(s):
    index_start = 0
    index_end = 0
    in_quotes = False
    result = []
    while index_end < len(s):
        if s[index_end] == '"':
            in_quotes = not in_quotes
        if s[index_end] == ' ' and not in_quotes:
            result.append(s[index_start:index_end])
            index_start = index_end + 1
        index_end += 1
    if s[-1] != ' ':
        result.append(s[index_start:index_end])
    return result

>>> print split_no_quotes(s)
['Hi', '"Python Tutors"', 'please', 'help']            

=Tony.Meyer

From cyresse at gmail.com  Wed Apr  6 08:05:36 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Wed Apr  6 08:05:39 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504052214060.18776-100000@Kuna>
References: <Pine.LNX.4.44.0504052214060.18776-100000@Kuna>
Message-ID: <f2ff2d05040523051acf1169@mail.gmail.com>

Hi Marilyn, 

Before you get numerous suggestions to use regexes (which was my first idea), 
you could use the split method to do it - 

>>> q = 'Hi "Python Tutors" please help'
>>> w = q.split('\"')
>>> print w
['Hi ', 'Python Tutors', ' please help']

I'm splitting using a double speech mark as the argument, which I've expressed 
as \" which is a hangover from regexes.

But, there are limitations to that -

>>> x = 'Hi "Python Tutors" how " are you?'
>>> print x.split('\"')
['Hi ', 'Python Tutors', ' how ', ' are you?']

It won't differentiate between an item between two speech marks, or one.

So, a regex method could be - 

>>> import re 
>>> j = re.compile('\"(.*?)\"', re.IGNORECASE)
>>> q = 'Hi "Python Tutors" please help'
>>> j.findall(q)
['Python Tutors']
>>> j.findall(x)
['Python Tutors']
>>> w = ' he "Foo foo" bob marley " fee fee " '
>>> j.findall(w)
['Foo foo', ' fee fee ']

I recommend this http://www.amk.ca/python/howto/regex/ 
and python2x/tools/scripts/redemo.py to learn how to use regexes well.


Regards, 

Liam Clarke




On Apr 6, 2005 5:19 PM, Marilyn Davis <marilyn@deliberate.com> wrote:
> Hi Tutors,
> 
> I need a little help with this, if anyone has the time and inclination:
> 
> >>> s = 'Hi "Python Tutors" please help'
> >>> s.split()
> ['Hi', '"Python', 'Tutors"', 'please', 'help']
> >>>
> 
> I wish it would leave the stuff in quotes in tact:
> 
> ['Hi', '"Python Tutors"', 'please', 'help']
> 
> Any suggestions?
> 
> Thank you.
> 
> Marilyn Davis
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From tameyer at ihug.co.nz  Wed Apr  6 08:11:46 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr  6 08:12:14 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802875472@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0044@its-xchg4.massey.ac.nz>

> I recommend this http://www.amk.ca/python/howto/regex/ 
> and python2x/tools/scripts/redemo.py to learn how to use regexes well.

I also highly recommend <http://www.amk.ca/python/howto/regex/> for learning
how to use regexes.

In addition, Kodos is a great tool to both experiment around with regexes
and to test them out:

<http://kodos.sourceforge.net>

(It will work with Windows, Linux, Mac...)

=Tony.Meyer

From bvande at po-box.mcgill.ca  Wed Apr  6 08:45:30 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Wed Apr  6 08:47:24 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0043@its-xchg4.massey.ac.nz>
References: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0043@its-xchg4.massey.ac.nz>
Message-ID: <4253858A.1090406@po-box.mcgill.ca>

Tony Meyer said unto the world upon 2005-04-06 01:59:
>>>>>s = 'Hi "Python Tutors" please help'
>>>>>s.split()
>>
>>['Hi', '"Python', 'Tutors"', 'please', 'help']
>>
>>I wish it would leave the stuff in quotes in tact:
>>
>>['Hi', '"Python Tutors"', 'please', 'help']
> 
> 
> You can do this with a regular expression:
> 
>

<SNIP re solution>

> Or you can just join them back up again:
> 
> 
>>>>combined = []
>>>>b = []
>>>>for a in s.split():
> 
> ... 	if '"' in a:
> ... 		if combined:
> ... 			combined.append(a)
> ... 			b.append(" ".join(combined))
> ... 			combined = []
> ... 		else:
> ... 			combined.append(a)
> ... 	else:
> ... 		b.append(a)
> ... 		
> 
>>>>b
> 
> ['Hi', '"Python Tutors"', 'please', 'help']
> 
> (There are probably tidier ways of doing that).

That won't work for the general case. I spent about 30 minutes trying 
to come up with a reliably non-re way and kept hitting bugs like the 
one here. Given that Tony_combine is a function wrapping Tony's logic:

 >>> Tony_combine('This will not work as "more than two words" are 
quoted')
['This', 'will', 'not', 'work', 'as', 'than', 'two', '"more words"', 
'are', 'quoted']

Happily, the other solution Tony offered works for my case and thus 
saves me the hassle of fixing my attempt :-)

> Or you can do the split yourself:
> 
> def split_no_quotes(s):
<SNIP code which works for my test case>


Best to all,

Brian vdB

From tameyer at ihug.co.nz  Wed Apr  6 09:02:04 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr  6 09:03:08 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802875498@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0045@its-xchg4.massey.ac.nz>

> That won't work for the general case. I spent about 30 minutes trying 
> to come up with a reliably non-re way and kept hitting bugs like the 
> one here. Given that Tony_combine is a function wrapping Tony's logic:
> 
>  >>> Tony_combine('This will not work as "more than two words" are 
> quoted')
> ['This', 'will', 'not', 'work', 'as', 'than', 'two', '"more words"', 
> 'are', 'quoted']

Opps.  You're right.  This is probably even uglier (can't be bothered
tidying it up), but should work in the more general case and does combine
them up again:

def Tony_combine2(s):
    combined = []
    b = []
    in_quotes = False
    for a in s.split():
        if '"' in a and in_quotes:
            combined.append(a)
            b.append(" ".join(combined))
            combined = []
            in_quotes = False
            continue
        elif '"' in a and not in_quotes:
            in_quotes = True
        if in_quotes:
            combined.append(a)
        else:
            b.append(a)
    return b

>>> Tony_combine('This will not work as "more than two words" are quoted')
['This', 'will', 'not', 'work', 'as', '"more than two words"', 'are',
'quoted']

Writing your own split or using re is definitely nicer, though.

=Tony.Meyer

From slgeorge at gmail.com  Wed Apr  6 10:36:12 2005
From: slgeorge at gmail.com (Steve George)
Date: Wed Apr  6 10:36:17 2005
Subject: [Tutor] What is the best book to start? - Many Thanks!
In-Reply-To: <20050405013710.97945.qmail@web60007.mail.yahoo.com>
References: <20050405013710.97945.qmail@web60007.mail.yahoo.com>
Message-ID: <3fe17b690504060136138b6d31@mail.gmail.com>

Hi Hoffman,

I'd suggest Dive into Python which you can also find it on-line.  The
printed version is here:
http://www.amazon.com/exec/obidos/ISBN%3D1590593561/002-9100626-6616001

The best book I know is Core Python by Wesley Chun.  But it only
covers 1.6 so quite a few things have changed since then.

http://www.amazon.com/exec/obidos/tg/detail/-/0130260363/qid=1112776154/sr=1-20/ref=sr_1_20/002-9100626-6616001?v=glance&s=books

Best of luck,

Steve

On Apr 5, 2005 2:37 AM, Hoffmann <oasf2004@yahoo.com> wrote:
> Hi John,
> 
> Certainly, I will check it out.
> Many thanks!
> Hoffmann
> 
> --- John Carmona <jeannot18@hotmail.com> wrote:
> > Dear Hoffmann, I am also a Newbie and I am currently
> > going through "A Byte
> > of Python" tutorial from Swaroop C H.
> >
> >
> http://www.byteofpython.info/download?PHPSESSID=c0d52343d90f69f25942f49df9ae7944
> >
> > If you are completely new to programming like me,
> > you will find that this
> > tutorial is excellent.
> > Good luck
> > JC
> >
> >
> >
> 
> __________________________________
> Yahoo! Messenger
> Show us what our next emoticon should look like. Join the fun.
> http://www.advision.webevents.yahoo.com/emoticontest
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From jeannot18 at hotmail.com  Wed Apr  6 13:00:12 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr  6 13:00:15 2005
Subject: [Tutor] Calendar question
In-Reply-To: <005301c53a4d$7d4517a0$155328cf@JSLAPTOP>
Message-ID: <BAY20-F48CA5FBD1C318D13CCEA9B33D0@phx.gbl>

Thanks Jacob, I think that should keep me out of the street for a while!

I will get back to you if I have any question

Regards
JC


From meesters at uni-mainz.de  Wed Apr  6 13:02:51 2005
From: meesters at uni-mainz.de (Christian Meesters)
Date: Wed Apr  6 13:02:55 2005
Subject: [Tutor] one line code
Message-ID: <88d5e314cc04074b2e359573c4b34104@uni-mainz.de>

Hi,

Great! My own solution was more like Wolfram's. But your solution, 
Pierre, really runs under "obfuscating enhanced". I like it. And your 
idea, Andrei, is something I really didn't expect.
Anyway, sorry for my late reply. Guess I learned a lot again.

Thanks,
Christian

From kent37 at tds.net  Wed Apr  6 13:44:48 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr  6 13:44:54 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504052214060.18776-100000@Kuna>
References: <Pine.LNX.4.44.0504052214060.18776-100000@Kuna>
Message-ID: <4253CBB0.8040405@tds.net>

Marilyn Davis wrote:
> Hi Tutors,
> 
> I need a little help with this, if anyone has the time and inclination:
> 
> 
>>>>s = 'Hi "Python Tutors" please help'
>>>>s.split()
> 
> ['Hi', '"Python', 'Tutors"', 'please', 'help']
> 
> 
> I wish it would leave the stuff in quotes in tact:
> 
> ['Hi', '"Python Tutors"', 'please', 'help']

You can do this easily with the csv module. The only complication is that the string has to be 
wrapped in a StringIO to turn it into a file-like object. If your strings are actually coming from a 
file then the wrapping isn't needed, you can pass the file directly to csv.reader().

  >>> import StringIO, csv
  >>> s = 'Hi "Python Tutors" please help'
  >>> input = StringIO.StringIO(s)
  >>> csv.reader(input, delimiter=' ').next()
['Hi', 'Python Tutors', 'please', 'help']

Oops, that isn't actually what you asked for, it strips the quotes. Oh well.

Kent

From jeannot18 at hotmail.com  Wed Apr  6 14:12:39 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr  6 14:12:43 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <1112750153.4253384945d14@www.paradise.net.nz>
Message-ID: <BAY20-F89B0B4E4AD35C922E12ECB33D0@phx.gbl>

Thanks John for your help.

Here is the final script (and it is working)

------------------------------------------------------------------------------------------
import calendar

MonthName = {'January': 1,'February': 2, 'March': 3,'April': 4
         ,'May': 5,'June': 6,'July': 7,'August': 8,
       'September': 9,'October': 10,'November': 11,'December': 12}

calendar.setfirstweekday(0)
              ##setfirstweekday change the day to what you want it be
              ## 0=Monday, 6=Sunday.
year = int(raw_input("Enter a year: "))
monthString = (raw_input("Enter a month: "))
while monthString not in MonthName:
    print "Unknown month!"
    monthString = raw_input('Enter a month: ')
month = MonthName[monthString]


print calendar.prmonth(year,month)

------------------------------------------------------------------------------------------


>##By the way do the number have to be under that format??

I don't understand the question, sorry..

This was a question for me, by that I meant would 01,02,03 etc format work 
as well (And it does). Sorry for the confusion.

Now I have got another question raising from this script. Would it be 
possible for the person doing the input to use either the months name in 
writing and also in number?

Thanks again John

JC


From kristian.zoerhoff at gmail.com  Wed Apr  6 16:23:29 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Wed Apr  6 16:23:32 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <BAY20-F89B0B4E4AD35C922E12ECB33D0@phx.gbl>
References: <1112750153.4253384945d14@www.paradise.net.nz>
	<BAY20-F89B0B4E4AD35C922E12ECB33D0@phx.gbl>
Message-ID: <3511dc7505040607236b72682d@mail.gmail.com>

On Apr 6, 2005 7:12 AM, John Carmona <jeannot18@hotmail.com> wrote:
>
> Now I have got another question raising from this script. Would it be
> possible for the person doing the input to use either the months name in
> writing and also in number?

I can think of 2 ways to accomplish this.

1. Try to convert monthString to an int, use the lookup if that fails.
This might be a good way to learn try/except processing.

2. Just double-up your dictionary to include a second set of keys:

{'1':1, '2':2 ...}

and just use your existing lookup method, unmodified. You wouldn't
have to worry about string->int conversion after raw_input this way,
so it's cleaner to implement.

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From ryan at acceleration.net  Wed Apr  6 16:39:53 2005
From: ryan at acceleration.net (Ryan Davis)
Date: Wed Apr  6 16:39:59 2005
Subject: [Tutor] database access to MSSQL
In-Reply-To: <3511dc7505040607236b72682d@mail.gmail.com>
Message-ID: <20050406143957.A96F91E4004@bag.python.org>

Does anyone know of a decent way to access a SQL Server 2000 database?

I've gotten some versions working using dbi,odbc and defining a DSN on the computer, but I'd like to be able to specify a server,
user, pass, and database in code.  As far as I can tell, I'd have to define a DSN for every database I'd want to use.

I found this via google:
http://www.object-craft.com.au/projects/mssql/
but that has a lot of strong language saying "this isn't ready for use".

Has anyone done this before and come up with a reasonable solution?


Thanks,
Ryan 

From kent37 at tds.net  Wed Apr  6 17:28:34 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr  6 17:28:45 2005
Subject: [Tutor] database access to MSSQL
In-Reply-To: <20050406143957.A96F91E4004@bag.python.org>
References: <20050406143957.A96F91E4004@bag.python.org>
Message-ID: <42540022.5040003@tds.net>

Ryan Davis wrote:
> Does anyone know of a decent way to access a SQL Server 2000 database?

I make heavy use of SQL Server from Jython using Microsoft's JDBC driver. This works great if it is 
an option for you.

Otherwise if your client is on Windows take a look at adodbapi. I have just played around with this 
enough to see that it will connect to SQL Server so I can't vouch for the quality but at least it 
claims to be ready for production use.
http://adodbapi.sourceforge.net/

eGenix sells an ODBC adapter:
http://www.egenix.com/files/python/mxODBC.html

Kent

> 
> I've gotten some versions working using dbi,odbc and defining a DSN on the computer, but I'd like to be able to specify a server,
> user, pass, and database in code.  As far as I can tell, I'd have to define a DSN for every database I'd want to use.
> 
> I found this via google:
> http://www.object-craft.com.au/projects/mssql/
> but that has a lot of strong language saying "this isn't ready for use".
> 
> Has anyone done this before and come up with a reasonable solution?
> 
> 
> Thanks,
> Ryan 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From marilyn at deliberate.com  Wed Apr  6 17:51:58 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Wed Apr  6 17:59:58 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0043@its-xchg4.massey.ac.nz>
Message-ID: <Pine.LNX.4.44.0504060849310.18776-100000@Kuna>

On Wed, 6 Apr 2005, Tony Meyer wrote:

> > >>> s = 'Hi "Python Tutors" please help'
> > >>> s.split()
> > ['Hi', '"Python', 'Tutors"', 'please', 'help']
> > >>> 
> > 
> > I wish it would leave the stuff in quotes in tact:
> > 
> > ['Hi', '"Python Tutors"', 'please', 'help']
> 
> You can do this with a regular expression:
> 
> >>> import re
> >>> re.findall(r'\".*\"|[^ ]+', s)
> ['Hi', '"Python Tutors"', 'please', 'help']
> 
> The regular expression says to find patterns that are either a quote (\")
> then any number of any characters (.*)then a quote (/") or (|) more than one
> of any character except a space ([^ ]).

Yes!  I'll do that.  Thank you, especially, for the explanation.

Thanks folks for all the suggestions.

Python attracts the best people!

Marilyn Davis

> 
> Or you can just join them back up again:
> 
> >>> combined = []
> >>> b = []
> >>> for a in s.split():
> ... 	if '"' in a:
> ... 		if combined:
> ... 			combined.append(a)
> ... 			b.append(" ".join(combined))
> ... 			combined = []
> ... 		else:
> ... 			combined.append(a)
> ... 	else:
> ... 		b.append(a)
> ... 		
> >>> b
> ['Hi', '"Python Tutors"', 'please', 'help']
> 
> (There are probably tidier ways of doing that).
> 
> Or you can do the split yourself:
> 
> def split_no_quotes(s):
>     index_start = 0
>     index_end = 0
>     in_quotes = False
>     result = []
>     while index_end < len(s):
>         if s[index_end] == '"':
>             in_quotes = not in_quotes
>         if s[index_end] == ' ' and not in_quotes:
>             result.append(s[index_start:index_end])
>             index_start = index_end + 1
>         index_end += 1
>     if s[-1] != ' ':
>         result.append(s[index_start:index_end])
>     return result
> 
> >>> print split_no_quotes(s)
> ['Hi', '"Python Tutors"', 'please', 'help']            
> 
> =Tony.Meyer
> 
> 

-- 

From smichr at hotmail.com  Wed Apr  6 18:03:55 2005
From: smichr at hotmail.com (C Smith)
Date: Wed Apr  6 18:05:01 2005
Subject: [Tutor] str.split and quotes
Message-ID: <BAY101-DAV7A5865352288190990FE7C13D0@phx.gbl>


> I wish it would leave the stuff in quotes in tact:
>

If you first split on your delimiter (which must have a matching one) 
you will obtain a list in which every odd position contains a string 
that was quoted. Step through the result and split the ones that are 
not quoted ones but don't do anything to the quoted ones.

###
s='"Hi" there "Python Tutors" please help me'

delim='"'

# check for matching quotes
if s.count(delim)%2<>0:
	print 'Unmatched delimiters in string'
	assert s.count(delim)%2==0

# split it
s=s.split(delim)

# remove elements 1 at a time, putting result to end of list;
# when you're done, the original list has been destroyed and
# the correct list is in its place
for i in range(len(s)):
	si=s.pop(0) #pop off the next one from the list
	if i%2==0:
		s.extend(si.split())
	else:
		s.append(si)
print s
###

OUTPUT: ['Hi', 'there', 'Python Tutors', 'please', 'help', 'me']

/c


From jeannot18 at hotmail.com  Wed Apr  6 18:58:39 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr  6 18:58:42 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <3511dc7505040607236b72682d@mail.gmail.com>
Message-ID: <BAY20-F2C2CE0E9122124EA44A39B33D0@phx.gbl>

Kristian you have said:
---------------------------------------------------------------------------------------------------------
I can think of 2 ways to accomplish this.

1. Try to convert monthString to an int, use the lookup if that fails.
This might be a good way to learn try/except processing.

2. Just double-up your dictionary to include a second set of keys:

{'1':1, '2':2 ...}

and just use your existing lookup method, unmodified. You wouldn't
have to worry about string->int conversion after raw_input this way,
so it's cleaner to implement.
-------------------------------------------------------------------------------------------------------------
When you say to double-up the dictionary do you mean using the following 
method:

Dict = [{1:1,2:4,etc.},
{3:9,4:16, etc}]

Thanks JC


From kristian.zoerhoff at gmail.com  Wed Apr  6 19:07:59 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Wed Apr  6 19:08:03 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <BAY20-F2C2CE0E9122124EA44A39B33D0@phx.gbl>
References: <3511dc7505040607236b72682d@mail.gmail.com>
	<BAY20-F2C2CE0E9122124EA44A39B33D0@phx.gbl>
Message-ID: <3511dc75050406100749b97f8d@mail.gmail.com>

On Apr 6, 2005 11:58 AM, John Carmona <jeannot18@hotmail.com> wrote:
> When you say to double-up the dictionary do you mean using the following
> method:
> 
> Dict = [{1:1,2:4,etc.},
> {3:9,4:16, etc}]

You're close, but a list of dicts is overkill here; stick to one big
dict, and leave the keys as strings, so you can just grab data from
raw_input directly, and do something like this:

Months = {'january':1, '1':1, 'february':2, '2':2, 'march':3, '3':3 .....}

Essentially double the number of keys in the dictionary. It's a bit
redundant, but you'll be able to then just grab

>>>month = raw_input("Enter a month: ")
>>>Months[month]

with no string->int conversion; the dict does it all for you, just as
it does in your code now.

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From jeannot18 at hotmail.com  Wed Apr  6 19:46:06 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr  6 19:46:11 2005
Subject: [Tutor] Re: Calendar question
In-Reply-To: <3511dc75050406100749b97f8d@mail.gmail.com>
Message-ID: <BAY20-F3447539C1B63D7A2D87FBEB33D0@phx.gbl>

Thanks Kristian, it is working fine now. I am learning so much with those 
little exercises, I know they are probably very basics to most of the people 
of this forum but they are great for a beginner like me. Jacob has sent me a 
few exercise to do, some look pretty difficult for my level so surely that 
you will see me back.
JC


From geek_show at dsl.pipex.com  Wed Apr  6 20:17:27 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Wed Apr  6 20:23:40 2005
Subject: [Tutor] comparison function/built-in needed
Message-ID: <425427B7.1010303@dsl.pipex.com>

Greetings

I am attempting to compare the items in two lists across two criteria - 
membership and position. For example:

list_a = [ 0, 4, 3, 6, 8 ]
list_b = [ 1, 8, 4, 6, 2 ]

Membership = There are 3 items that are common to both lists, that is 3 
items in list_a have membership in list_b (viz: 4, 6, 8);
Position = There is 1 item in list_a that is also in the same position 
in both lists (viz: 6).

I have been playing around with for loops and iterations, but feel 
convinced that someone must have tackled this issue previously and who 
knows maybe even wrote a module/built-in that will do the trick.

I'm using Python-2.4.1

Thanks for any insights

/j
From kent37 at tds.net  Wed Apr  6 21:18:59 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr  6 21:18:59 2005
Subject: [Tutor] comparison function/built-in needed
In-Reply-To: <425427B7.1010303@dsl.pipex.com>
References: <425427B7.1010303@dsl.pipex.com>
Message-ID: <42543623.2030600@tds.net>

joe_schmoe wrote:
> Greetings
> 
> I am attempting to compare the items in two lists across two criteria - 
> membership and position. For example:
> 
> list_a = [ 0, 4, 3, 6, 8 ]
> list_b = [ 1, 8, 4, 6, 2 ]
> 
> Membership = There are 3 items that are common to both lists, that is 3 
> items in list_a have membership in list_b (viz: 4, 6, 8);

Use sets:
  >>> list_a = [ 0, 4, 3, 6, 8 ]
  >>> list_b = [ 1, 8, 4, 6, 2 ]
  >>> set(list_a).intersection(list_b)
set([8, 4, 6])

> Position = There is 1 item in list_a that is also in the same position 
> in both lists (viz: 6).

Use zip() to iterate two lists in parallel and a list comprehension to accumulate the results:
  >>> [ a for a, b in zip(list_a, list_b) if a==b ]
[6]

or if you want the position of the item use enumerate() to get the index:
  >>> [ i for i, (a, b) in enumerate(zip(list_a, list_b)) if a==b ]
[3]

Kent

From project5 at redrival.net  Wed Apr  6 21:37:24 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr  6 21:42:37 2005
Subject: [Tutor] Re: Mouseclick
References: <3556.193.216.161.244.1112732327.squirrel@mail.sporck.net>
Message-ID: <loom.20050406T211148-436@post.gmane.org>

?yvind <python <at> kapitalisten.no> writes:

> and would like to click the left mousebutton at that position. Is that
> possible? I have just been able to find ways to click the button on
> buttons that I can name such as:
> def findAButtonCalledOK(hwnd, windowText, windowClass): # Define a
> function to find our button
>     return windowClass == "Button" and windowText == "OK"
> okButton = findControl(optDialog, findAButtonCalledOK)
> click(okButton)

Looking at the implementation of the click() function on the site you 
got that from:

  http://www.brunningonline.net/simon/blog/archives/000664.html ,

a click is a left button down followed by left button up. The docs:

http://www.6URL.com/FED

state that the last parameter (lParam) is the position. This page shows 
how to construct it:

  http://www.geocities.com/practicalvb/vb/windows/messages.html

There's probably something available with ctypes or win32all to build 
the lParam, but if that's not the case, you can do something like:

    lParam = ypos * (2**16) + xpos

(with the positions being relative to the top/left of the control 
the handle of which you use in the SendMessage). If you pass that
parameter in the SendMessage calls, I think the mouse should click
on a certain position (although I haven't tested, as I'm not on 
Windows ATM).

Yours,

Andrei



From geek_show at dsl.pipex.com  Wed Apr  6 21:26:09 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Wed Apr  6 21:51:02 2005
Subject: [Tutor] comparison function/built-in needed
In-Reply-To: <42543623.2030600@tds.net>
References: <425427B7.1010303@dsl.pipex.com> <42543623.2030600@tds.net>
Message-ID: <425437D1.9050206@dsl.pipex.com>

Kent Johnson wrote:
> joe_schmoe wrote:
> 
>> Greetings
>>
>> I am attempting to compare the items in two lists across two criteria 
>> - membership and position. For example:
>>
>> list_a = [ 0, 4, 3, 6, 8 ]
>> list_b = [ 1, 8, 4, 6, 2 ]
>>
>> Membership = There are 3 items that are common to both lists, that is 
>> 3 items in list_a have membership in list_b (viz: 4, 6, 8);
> 
> 
> Use sets:
>  >>> list_a = [ 0, 4, 3, 6, 8 ]
>  >>> list_b = [ 1, 8, 4, 6, 2 ]
>  >>> set(list_a).intersection(list_b)
> set([8, 4, 6])
> 
>> Position = There is 1 item in list_a that is also in the same position 
>> in both lists (viz: 6).
> 
> 
> Use zip() to iterate two lists in parallel and a list comprehension to 
> accumulate the results:
>  >>> [ a for a, b in zip(list_a, list_b) if a==b ]
> [6]
> 
> or if you want the position of the item use enumerate() to get the index:
>  >>> [ i for i, (a, b) in enumerate(zip(list_a, list_b)) if a==b ]
> [3]
> 
> Kent
> 
> 
Excellent Kent - that looks like that will work. I'll get back to you.

Cheers
/j
From alan.gauld at freenet.co.uk  Wed Apr  6 23:49:23 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr  6 23:49:34 2005
Subject: [Tutor] Major Newbie Here
References: <Pine.LNX.4.44.0504051348310.11692-100000@hkn.eecs.berkeley.edu>
	<1112741237.42531575f004e@www.paradise.net.nz>
Message-ID: <003501c53af2$7f56d1a0$46df8751@xp>

> > ######
> > class Spam:
> >  """A meat for combining with other foods
> >  It can be used with other foods to make interesting meals.
> >  It comes with lots of nutrients and can be cooked using many
> >  different techniques"""
> > 
> >  def__init__(self):
> >  ## ... rest of code follows
> > ######

Note that this particular example in the tutor is not intended to be 
typed in! Its only a partial piece of code to illustrate what a doc 
string looks like! Maybe I need to emphasise that a bit more 
clearly in the tutor...

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

From alan.gauld at freenet.co.uk  Thu Apr  7 00:01:49 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr  7 00:02:00 2005
Subject: [Tutor] [HELP]how to test properties of a file
References: <33194d7305040310311b68405f@mail.gmail.com><42502AFF.1020208@cirad.fr>
	<037701c5395f$5c697a60$61cb8751@xp><4251B7A0.3080709@javacat.f2s.com><33194d7305040416346a07de92@mail.gmail.com><4252CBEC.60201@javacat.f2s.com>
	<33194d7305040516035b9f0be2@mail.gmail.com>
Message-ID: <004901c53af4$3c567f20$46df8751@xp>

> Here's where my question.
> The file is already opened by Excel. os.access indicates it's
> writable, but it's actully not.

It is writable, but it is locked by the other program.
There is a difference! :-)

Basically you have two issues, the first is whether the OS will
ever allow anyone or anything to write to the file - its permissions,
the second is whether you can safely do so at this point in time - its
status. If another program has the file open for writing then anything
you tried to write to the file is likely to be overwritten by the
other
program, so you'd lose it! thus the OS refuses to allow more
than one program at a time to open the file in write mode.

[ You can make a guess at whether this is the case by reading the
last access time from the os.stat() result and comparing it to the
current time, but it can only be a guess. However it might enable
a friendlier error message if the program is interactive. ]

So after discovering that the file can be written to, you still
need to use the try/except technique when opening the file to
see if its locked, if it is you can decide to wait and try
again - in case its just a temporary glitch - or to log an
error and exit or move to the next file.

HTH,

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

From amonroe at columbus.rr.com  Thu Apr  7 00:05:38 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu Apr  7 00:06:34 2005
Subject: [Tutor] comparison function/built-in needed
In-Reply-To: <425427B7.1010303@dsl.pipex.com>
References: <425427B7.1010303@dsl.pipex.com>
Message-ID: <831201144244.20050406180538@columbus.rr.com>


> I am attempting to compare the items in two lists across two criteria - 
> membership and position. For example:

> list_a = [ 0, 4, 3, 6, 8 ]
> list_b = [ 1, 8, 4, 6, 2 ]

> Membership = There are 3 items that are common to both lists, that is 3 
> items in list_a have membership in list_b (viz: 4, 6, 8);
> Position = There is 1 item in list_a that is also in the same position 
> in both lists (viz: 6).

Not sure if this will help, but take a look at Levenshtein Distance:
http://www.merriampark.com/ld.htm

Alan

From snoylr at cheqnet.net  Thu Apr  7 04:39:11 2005
From: snoylr at cheqnet.net (Richard Lyons)
Date: Thu Apr  7 04:39:18 2005
Subject: [Tutor] Can't find MSVCR71.dll
Message-ID: <42549D4F.8090805@cheqnet.net>

I tried to install the win32all.exe to work with Python 2.4.1 on a 
Windows XP machine.  Didn't work.  I got the following error message:

This application has failed to start because MSVCR71.dll was not found.

 From what I've found by way of Google, this is a common problem.  What 
is the work around.

After getting the error I installed Python 2.3.5 and win32all.exe for 
2.3 and everything seems to be working fine, but I would really like to 
work with the later version

From keridee at jayco.net  Thu Apr  7 04:58:41 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu Apr  7 04:57:54 2005
Subject: [Tutor] Can't find MSVCR71.dll
References: <42549D4F.8090805@cheqnet.net>
Message-ID: <000301c53b1d$bc51e060$405328cf@JSLAPTOP>

The way I did it was google for "download msvcr71.dll" and found a good 
place to download the file-- < 500K   ---  then I put the dll file in 
C:\windows\system32 folder.  Then it worked and I didn't worry about it 
anymore.

Easy enough, and you don't have to worry about that specific problem ever 
again.

HTH,
Jacob

>I tried to install the win32all.exe to work with Python 2.4.1 on a Windows 
>XP machine.  Didn't work.  I got the following error message:
>
> This application has failed to start because MSVCR71.dll was not found.
>
> From what I've found by way of Google, this is a common problem.  What is 
> the work around.
>
> After getting the error I installed Python 2.3.5 and win32all.exe for 2.3 
> and everything seems to be working fine, but I would really like to work 
> with the later version
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From work at infomaniak.ch  Thu Apr  7 09:34:30 2005
From: work at infomaniak.ch (BRINER Cedric)
Date: Thu Apr  7 09:34:35 2005
Subject: [Tutor] pickle in unicode format
In-Reply-To: <Pine.LNX.4.44.0504051102240.19586-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504051102240.19586-100000@hkn.eecs.berkeley.edu>
Message-ID: <1112859270.20335.22.camel@obslin15.unige.ch>

On Tue, 2005-04-05 at 11:33 -0700, Danny Yoo wrote:
> 
> > > I have this dictionnary :
> > >
> > > a={'partition': u'/export/diskH1/home_evol/ricquebo',
> > >  'rsmFirstname': u'Fran\xe7ois',
> > >  'rsmLastname': u'Ricquebourg',
> > >  'size': u'8161222.0',
> > >  'size_max': '1'}
> > >
> > > and I'd like to *serialize* it with pickle and that the output format
> > > will be of type unicode.
> >
> > I'm not sure what you mean by this. Do you mean that you want the actual
> > pickled data to be a unicode string? Or that you want to be able to
> > pickle something that contains unicode strings?
I mean that the pickled data to be an unicode string

> The first interpretation doesn't make sense to me either: pickled data is
> a 'byte' representation of your data structures.  Why do you need it to be
> treated as a unicode string?

because the idea is to have a database whom keeps email sent
automatically. And I've separated the canevas from the content. So in
the email table I have the column:
-'format' ----eg--> 'hello %(firstname)s %(lastname)s'
-'data'   ----eg--> where I'd like to put my dictionnary (e.g.
{'firstname':u'cedric','lastname':u'briner'}) 

but I cannot push to my database an python dictionnary. So I thought
that I can use pickle to push my dico.

I need the pickled data to be in unicode, because the program talk with
the database with unicode.

> > > unicode(pickle.dumps(a)) doesn't work !
> 
> Can you show us why this doesn't work for you?  I can guess why, but it is
> much better if we don't have to guess what the error message looks like.
> I suspect you're seeing something like this:
> 
> ######
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
> ordinal not in range(128)
> ######
this is it!
> but again, I hate guessing.  *grin*
Sorry for this :(


> Show us exactly what you're seeing as an error message: don't just say it
> doesn't work, because that doesn't give us enough to know if the error or
> bug that we're seeing is the same one that you're seeing.  Problems often
> can have multiple causes, which is why we need to see the one you're
> getting stuck on.
got it, and yes I'll do it.


sorry to take so long to reply, but I get some problems with my emails.

Cedric BRINER

From klappnase at freenet.de  Thu Apr  7 12:35:41 2005
From: klappnase at freenet.de (Michael Lange)
Date: Thu Apr  7 12:32:17 2005
Subject: [Tutor] using the enter key
In-Reply-To: <BAY14-F32867284911164FD6AFF1EE13E0@phx.gbl>
References: <42526125.30705@tds.net>
	<BAY14-F32867284911164FD6AFF1EE13E0@phx.gbl>
Message-ID: <20050407123541.48950ef3.klappnase@freenet.de>

On Thu, 07 Apr 2005 10:06:46 +1000
"Nova Nova" <nova585@hotmail.com> wrote:

>     	def create_widgets(self):
>         	 self.a_lbl=Label(self,text="",fg="Red")
>         	 self.a_lbl.grid(row=0,column=0,columnspan=2,sticky=W)
>         	 self.inst_lbl=Label(self,text="Enter A Number Between 1 and 
> 100.",fg="blue")
>         	 self.inst_lbl.grid(row=1,column=0,columnspan=2,sticky=W)
>         	 self.pw_lbl=Label(self,text="Number: ")
>         	 self.pw_lbl.grid(row=2,column=0,sticky=W)
>         	 self.pw_ent=Entry(self)
>         	 self.pw_ent.grid(row=2,column=1,sticky=W)
>         	 self.submit_bttn=Button(self,text=str(self.g)+" Turns  
> Left",command=self.reveal,fg="red",bg="black")
>         	 self.submit_bttn.grid(row=3,column=0,sticky=W)
>         	 self.win_txt=Text(self,width=35,height=5,wrap=WORD)
>         	 self.win_txt.grid(row=4,column=0,columnspan=2,sticky=W)
> 
> 
> 	def submit(self):
>         	 self.reveal
>         	 entry.bind('<Return>',self.submit)
> 
> this is what im doing and i get an error, IT DOES NOT WORK
> 

The problematic part is your submit() method:

    def submit(self):
        self.reveal    # you forgot the parentheses here to call your reveal() method
                   ^^  
        entry.bind('<Return>',self.submit)

this only binds the event handler to the Entry when the submit button was pressed before;
you better apply this binding in your create_widgets() method immediately after creating the Entry
widget. Please note that if you want to use the submit() method both as button-command and as
event handler for the entry, it needs an optional event instance as argument:

    def submit(self, event=None):
        (...)

because the button's "command" doesn't pass an event to the callback, but the entry's event handler does.

I hope this helps

Michael
From debe at comp.leeds.ac.uk  Thu Apr  7 14:01:39 2005
From: debe at comp.leeds.ac.uk (D Elliott)
Date: Thu Apr  7 14:01:49 2005
Subject: [Tutor] regular expression question
Message-ID: <Pine.LNX.4.60.0504071158310.3513@cslin-gps.csunix.comp.leeds.ac.uk>

I wonder if anyone can help me with an RE. I also wonder if there is an RE 
mailing list anywhere - I haven't managed to find one.

I'm trying to use this regular expression to delete particular strings 
from a file before tokenising it.

I want to delete all strings that have a full stop (period) when it is not 
at the beginning or end of a word, and also when it is not followed by a 
closing bracket. I want to delete file names (eg. fileX.doc), and websites 
(when www/http not given) but not file extensions (eg. this is in .jpg 
format). I also don't want to delete the last word of each sentence just 
because it precedes a fullstop, or if there's a fullstop followed by a 
closing bracket.

fullstopRe = re.compile (r'\S+\.[^)}]]+')

I've also tried 
fullstopRe = re.compile (r'\S+[.][^)}]]+')


I understand this to represent - any character one or more times, a full 
stop (I'm using the backslash, or putting it in a character class to make 
it literal), then any character but not any kind of closing bracket, one 
or more times.

If I forget about the bracket exceptions, the following works:
fullstopRe = re.compile (r'\S+[.]\S+')

But the scripts above are not deleting eg. bbc.co.uk

Can anyone enlighten me?
Thanks
Debbie


-- 
***************************************************
Debbie Elliott
Computer Vision and Language Research Group,
School of Computing,
University of Leeds,
Leeds LS2 9JT
United Kingdom.
Tel: 0113 3437288
Email: debe@comp.leeds.ac.uk
***************************************************
From smichr at hotmail.com  Thu Apr  7 14:00:38 2005
From: smichr at hotmail.com (C Smith)
Date: Thu Apr  7 14:01:50 2005
Subject: [Tutor] flatten
Message-ID: <BAY101-DAV120C9F5179C7A6B95A359CC13E0@phx.gbl>

After posting the suggestion about splitting a string that contained a  
quoted string, I looked back at my (at least I think it?s mine) flatten  
routine and didn?t see anything like it at ASPN. Before I would post it  
there, does anyone see any problems with this non-recursive approach?

I know that there are iterator approaches, but since the list already  
exists is there any problem with flattening the whole thing? Or is part  
of the problem that there may be iterable things that don?t need to be  
completely ?iterated to completion? before being able to yield the next  
element? (Does that make sense?)

After searching for "Tim Peters flatten" I was able to find a similar  
routine at

http://sourceforge.net/project/ 
showfiles.php?group_id=87034&package_id=90541&release_id=288585

(It is in the basictypes folder in the latebind.py script by  Mike C.  
Fletcher.) It's so short, I post it for comparison. I'm not really sure  
why there is a run through all possible indices rather than the ones  
that exist in the given "inlist", though.

### Fletcher's
import sys
def flatten(inlist, type=type, ltype=(list,tuple), maxint= sys.maxint):
	"""Flatten out a list, code developed by myself and modified by Tim  
Peters, then by me again :)"""
	try:
		# for every possible index
		for ind in xrange( maxint):
			# while that index currently holds a list
			while isinstance( inlist[ind], ltype):
				# expand that list into the index (and subsequent indicies)
				inlist[ind:ind+1] = list(inlist[ind])
			#ind = ind+1
	except IndexError:
		pass
	return inlist
###


### mine
def flatten(l):
	???Flattens a list in place.???
	i=0
	while i<len(l):
		while hasattr(l[i],?__iter__?): #used by some ASPN flatteners to  
avoid strings
			l[i:i]=l.pop(i)
		i+=1

###

input: [1, 2, [3, 4, 5, [[6, 7], 8]], ?abc?, 9, [10, 11]]
output:[1, 2, 3, 4, 5, 6, 7, 8, ?abc?, 9, 10, 11]

/c


From bill.mill at gmail.com  Thu Apr  7 19:03:32 2005
From: bill.mill at gmail.com (Bill Mill)
Date: Thu Apr  7 19:03:37 2005
Subject: [Tutor] flatten
In-Reply-To: <BAY101-DAV120C9F5179C7A6B95A359CC13E0@phx.gbl>
References: <BAY101-DAV120C9F5179C7A6B95A359CC13E0@phx.gbl>
Message-ID: <797fe3d4050407100330eb621a@mail.gmail.com>

On Apr 7, 2005 8:00 AM, C Smith <smichr@hotmail.com> wrote:
> After posting the suggestion about splitting a string that contained a
> quoted string, I looked back at my (at least I think it's mine) flatten
> routine and didn't see anything like it at ASPN. Before I would post it
> there, does anyone see any problems with this non-recursive approach?
> 
> I know that there are iterator approaches, but since the list already
> exists is there any problem with flattening the whole thing? Or is part
> of the problem that there may be iterable things that don't need to be
> completely "iterated to completion" before being able to yield the next
> element? (Does that make sense?)
> 
> After searching for "Tim Peters flatten" I was able to find a similar
> routine at
> 
> http://sourceforge.net/project/
> showfiles.php?group_id=87034&package_id=90541&release_id=288585
> 
> (It is in the basictypes folder in the latebind.py script by  Mike C.
> Fletcher.) It's so short, I post it for comparison. I'm not really sure
> why there is a run through all possible indices rather than the ones
> that exist in the given "inlist", though.
> 
<snip code>

1) you should special-case dictionaries:

>>> x = [1, 2, [3, 4, 5, [[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}]
>>> flatten(x)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test']

2) What's different about your flatten than those ASPN entries? Just
that it flattens in-place? I see a general-purpose flattener and a
flattening generator.

Peace
Bill Mill
bill.mill at gmail.com
From python.programming at gmail.com  Thu Apr  7 19:23:04 2005
From: python.programming at gmail.com (Kevin)
Date: Thu Apr  7 19:23:09 2005
Subject: [Tutor] Help with classes
Message-ID: <d082fff805040710236f7251be@mail.gmail.com>

I am fooling around with classes and I was trying to create a very
small one player text adventure. I made a class called commands here
it is:
class Commands:
    def __init__(self):
        pass
    def quiting(self):
        sys.exit()
    def look(self):
        print "\nNot working yet!\n"
    def get(self):
        print "\nNot working yet!\n"
    def take(self):
        print "\nNot working yet!\n"
    def kill(self):
        print "\nNot working yet!\n"
    def drink(self):
        print "\nNot working yet!\n"
    def eat(self):
        print "\nNot working yet!\n"
    def eq(self):
        print "\nNot working yet!\n"
    def helpsys(self,response):
        answer = None
        i = ['look','get','take','kill','drink','eat','eq','help']
        while not answer in i:
            answer = raw_input(response)
            #Help files will go here
            return answer

there is nothing special about it yet. But in the main code wich is:

while 1:
    com = Commands()
    a = ['look',
         'get',
         'take',
         'kill',
         'drink',
         'eat',
         'eq',
         'help',
         'quit']
    commandl = raw_input(">>>: ")
    if commandl not in a:
        print "\nI don't understand that command?\n"

I want to beable to type in a command from the list at the prompt and
have it call one of the functions from the class. I was looking for a
shorter way to write it but the only way I can think of is with an if
statment for each command. Is there a better way or shorter way to do
this?

Thanks
Kevin
From ARobert at MFS.com  Thu Apr  7 20:12:52 2005
From: ARobert at MFS.com (Robert, Andrew)
Date: Thu Apr  7 20:13:10 2005
Subject: [Tutor] Problem installing the Pymqi module
Message-ID: <968452DD78695147AA4A369C3DF9E40A038A7B12@BOSMAILBOX3.corp.mfs.com>

Hi Everyone,


I've tried installing the pymqi Python module on Windows but no luck so
far.

Has anyone had any success in doing this?

Any help you can provide on this would be greatly appreciated.


To install the module under Python v2.4, I did the following steps:

1. Download MinGW Gcc from http://mingw.org

2. Install MinGW GCC

3. Edit path and add GCC area c:\MinGW\bin

4. Verify that GCC is functioning

   c:\ gcc --version

5. Download pexports from
http://starship.python.net/crew/kernr/mingw32/. 

6. Extract pexports to C:\pexports

7. Add C:\pexports\pexports-0.42h\bin to path 

8. Locate the file python2?.dll 

   On windows XP with Python v2.4 installed, it is typically found as 
    C:\WINDOWS\system32\python24.dll

9. Open a command prompt

10. Change your working directory to C:\WINDOWS\system32

11. Extract all of the symbols from the Python library


    C:\WINDOWS\system32\ pexports python24.dll > python24.def 

12. Create a new python library

    C:\WINDOWS\system32\dlltool --dllname python24.dll --def
python24.def --output-lib libpython24.a


The dlltool command is part of the MinGW utilities

13. Copy the newly created python library to its permanent location

	C:\WINDOWS\system32\copy libpython24.a C:\Python24\lib


14. Download pymqi from
http://prdownloads.sourceforge.net/pymqi/pymqi-0.5c.tar.gz?download and
extract to c:\pymqi

15. Edit the file C:\pymqi\pymqi-0.5c\setup.py and change include_dirs
to the following path and save


	C:/Program Files/IBM/WebSphere MQ/Tools/Lib


16. Open command prompt and change working directort to
C:\pymqi\pymqi-0.5c

17. Initiate a client or server build


For a client:

	setup.py build -cmingw32 client

For a server:

	setup.py build -cmingw32 server

In either case, I received the following compile errors.


pymqe.c:78:18: cmqc.h: No such file or directory
pymqe.c:79:19: cmqxc.h: No such file or directory
pymqe.c: In function `pymqe_MQCONN':
pymqe.c:130: `MQHCONN' undeclared (first use in this function)
pymqe.c:130: (Each undeclared identifier is reported only once
pymqe.c:130: for each function it appears in.)
pymqe.c:130: parse error before "handle"
pymqe.c:131: `MQLONG' undeclared (first use in this function)
pymqe.c:137: warning: implicit declaration of function `MQCONN'
pymqe.c:137: `handle' undeclared (first use in this function)
pymqe.c:137: `compCode' undeclared (first use in this function)
pymqe.c:137: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQCONNX':
pymqe.c:162: `MQHCONN' undeclared (first use in this function)
pymqe.c:162: parse error before "handle"
pymqe.c:163: `MQLONG' undeclared (first use in this function)
pymqe.c:166: `MQCNO' undeclared (first use in this function)
pymqe.c:166: parse error before "connectOpts"
pymqe.c:181: `options' undeclared (first use in this function)
pymqe.c:186: `MQCD_CURRENT_LENGTH' undeclared (first use in this
function)
pymqe.c:199: `connectOpts' undeclared (first use in this function)
pymqe.c:199: `MQCNO_VERSION_2' undeclared (first use in this function)
pymqe.c:201: `MQCD' undeclared (first use in this function)
pymqe.c:201: parse error before ')' token
pymqe.c:205: warning: implicit declaration of function `MQCONNX'
pymqe.c:205: `handle' undeclared (first use in this function)
pymqe.c:205: `compCode' undeclared (first use in this function)
pymqe.c:205: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQDISC':
pymqe.c:220: `MQHCONN' undeclared (first use in this function)
pymqe.c:220: parse error before "handle"
pymqe.c:221: `MQLONG' undeclared (first use in this function)
pymqe.c:223: `handle' undeclared (first use in this function)
pymqe.c:227: warning: implicit declaration of function `MQDISC'
pymqe.c:227: `compCode' undeclared (first use in this function)
pymqe.c:227: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQOPEN':
pymqe.c:250: `MQHCONN' undeclared (first use in this function)
pymqe.c:250: parse error before "qmgrHandle"
pymqe.c:251: `MQOD' undeclared (first use in this function)
pymqe.c:251: `qDescP' undeclared (first use in this function)
pymqe.c:254: `MQLONG' undeclared (first use in this function)
pymqe.c:254: parse error before "options"
pymqe.c:255: `MQHOBJ' undeclared (first use in this function)
pymqe.c:258: `qmgrHandle' undeclared (first use in this function)
pymqe.c:259: `options' undeclared (first use in this function)
pymqe.c:262: `MQOD_CURRENT_LENGTH' undeclared (first use in this
function)
pymqe.c:266: parse error before ')' token
pymqe.c:268: warning: implicit declaration of function `MQOPEN'
pymqe.c:268: `qHandle' undeclared (first use in this function)
pymqe.c:268: `compCode' undeclared (first use in this function)
pymqe.c:268: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQCLOSE':
pymqe.c:285: `MQHCONN' undeclared (first use in this function)
pymqe.c:285: parse error before "qmgrHandle"
pymqe.c:286: `MQLONG' undeclared (first use in this function)
pymqe.c:287: `MQHOBJ' undeclared (first use in this function)
pymqe.c:290: `qmgrHandle' undeclared (first use in this function)
pymqe.c:290: `qHandle' undeclared (first use in this function)
pymqe.c:290: `options' undeclared (first use in this function)
pymqe.c:294: warning: implicit declaration of function `MQCLOSE'
pymqe.c:294: `compCode' undeclared (first use in this function)
pymqe.c:294: `compReason' undeclared (first use in this function)
pymqe.c: In function `mqputN':
pymqe.c:305: `MQHCONN' undeclared (first use in this function)
pymqe.c:305: parse error before "qmgrHandle"
pymqe.c:306: `MQHOBJ' undeclared (first use in this function)
pymqe.c:307: `MQLONG' undeclared (first use in this function)
pymqe.c:310: `MQMD' undeclared (first use in this function)
pymqe.c:310: `mDescP' undeclared (first use in this function)
pymqe.c:313: `MQPMO' undeclared (first use in this function)
pymqe.c:313: `pmoP' undeclared (first use in this function)
pymqe.c:318: `MQOD' undeclared (first use in this function)
pymqe.c:318: `qDescP' undeclared (first use in this function)
pymqe.c:322: `qmgrHandle' undeclared (first use in this function)
pymqe.c:322: `qHandle' undeclared (first use in this function)
pymqe.c:338: `MQOD_CURRENT_LENGTH' undeclared (first use in this
function)
pymqe.c:342: parse error before ')' token
pymqe.c:349: parse error before ')' token
pymqe.c:351: `MQPMO_CURRENT_LENGTH' undeclared (first use in this
function)
pymqe.c:355: parse error before ')' token
pymqe.c:358: warning: implicit declaration of function `MQPUT'
pymqe.c:359: `compCode' undeclared (first use in this function)
pymqe.c:359: `compReason' undeclared (first use in this function)
pymqe.c:363: warning: implicit declaration of function `MQPUT1'
pymqe.c: In function `pymqe_MQGET':
pymqe.c:441: `MQHCONN' undeclared (first use in this function)
pymqe.c:441: parse error before "qmgrHandle"
pymqe.c:442: `MQHOBJ' undeclared (first use in this function)
pymqe.c:443: `MQLONG' undeclared (first use in this function)
pymqe.c:446: `MQMD' undeclared (first use in this function)
pymqe.c:446: `mDescP' undeclared (first use in this function)
pymqe.c:449: `MQGMO' undeclared (first use in this function)
pymqe.c:449: `gmoP' undeclared (first use in this function)
pymqe.c:454: `qmgrHandle' undeclared (first use in this function)
pymqe.c:454: `qHandle' undeclared (first use in this function)
pymqe.c:463: parse error before ')' token
pymqe.c:469: parse error before ')' token
pymqe.c:477: warning: implicit declaration of function `MQGET'
pymqe.c:478: `compCode' undeclared (first use in this function)
pymqe.c:478: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQBEGIN':
pymqe.c:510: `MQHCONN' undeclared (first use in this function)
pymqe.c:510: parse error before "handle"
pymqe.c:511: `MQLONG' undeclared (first use in this function)
pymqe.c:512: `MQBO' undeclared (first use in this function)
pymqe.c:514: `handle' undeclared (first use in this function)
pymqe.c:518: warning: implicit declaration of function `MQBEGIN'
pymqe.c:518: `beginOpts' undeclared (first use in this function)
pymqe.c:518: `compCode' undeclared (first use in this function)
pymqe.c:518: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQCMIT':
pymqe.c:533: `MQHCONN' undeclared (first use in this function)
pymqe.c:533: parse error before "handle"
pymqe.c:534: `MQLONG' undeclared (first use in this function)
pymqe.c:536: `handle' undeclared (first use in this function)
pymqe.c:540: warning: implicit declaration of function `MQCMIT'
pymqe.c:540: `compCode' undeclared (first use in this function)
pymqe.c:540: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQBACK':
pymqe.c:554: `MQHCONN' undeclared (first use in this function)
pymqe.c:554: parse error before "handle"
pymqe.c:555: `MQLONG' undeclared (first use in this function)
pymqe.c:557: `handle' undeclared (first use in this function)
pymqe.c:561: warning: implicit declaration of function `MQBACK'
pymqe.c:561: `compCode' undeclared (first use in this function)
pymqe.c:561: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQINQ':
pymqe.c:585: `MQHCONN' undeclared (first use in this function)
pymqe.c:585: parse error before "qmgrHandle"
pymqe.c:586: `MQHOBJ' undeclared (first use in this function)
pymqe.c:587: `MQLONG' undeclared (first use in this function)
pymqe.c:593: `MQCHAR' undeclared (first use in this function)
pymqe.c:596: `qmgrHandle' undeclared (first use in this function)
pymqe.c:596: `objHandle' undeclared (first use in this function)
pymqe.c:596: `selectors' undeclared (first use in this function)
pymqe.c:599: `MQIA_FIRST' undeclared (first use in this function)
pymqe.c:599: `MQIA_LAST' undeclared (first use in this function)
pymqe.c:600: `intAttrCount' undeclared (first use in this function)
pymqe.c:602: `charAttrCount' undeclared (first use in this function)
pymqe.c:602: `charAttrs' undeclared (first use in this function)
pymqe.c:607: warning: implicit declaration of function `MQINQ'
pymqe.c:607: `selectorCount' undeclared (first use in this function)
pymqe.c:608: `intAttrs' undeclared (first use in this function)
pymqe.c:608: `compCode' undeclared (first use in this function)
pymqe.c:608: `compReason' undeclared (first use in this function)
pymqe.c: In function `pymqe_MQSET':
pymqe.c:629: `MQHCONN' undeclared (first use in this function)
pymqe.c:629: parse error before "qmgrHandle"
pymqe.c:630: `MQHOBJ' undeclared (first use in this function)
pymqe.c:631: `MQLONG' undeclared (first use in this function)
pymqe.c:637: `MQCHAR' undeclared (first use in this function)
pymqe.c:640: `qmgrHandle' undeclared (first use in this function)
pymqe.c:640: `objHandle' undeclared (first use in this function)
pymqe.c:640: `selectors' undeclared (first use in this function)
pymqe.c:643: `MQIA_FIRST' undeclared (first use in this function)
pymqe.c:643: `MQIA_LAST' undeclared (first use in this function)
pymqe.c:648: `intAttrs' undeclared (first use in this function)
pymqe.c:649: `intAttrCount' undeclared (first use in this function)
pymqe.c:655: `charAttrs' undeclared (first use in this function)
pymqe.c:656: `charAttrCount' undeclared (first use in this function)
pymqe.c:660: warning: implicit declaration of function `MQSET'
pymqe.c:660: `selectorCount' undeclared (first use in this function)
pymqe.c:661: `compCode' undeclared (first use in this function)
pymqe.c:661: `compReason' undeclared (first use in this function)
error: command 'gcc' failed with exit status 1



Thank you, 
Andrew Robert 
Systems Architect 
Information Technologies
MFS Investment Management
Phone:  617-954-5882 
Pager:   781-945-1742
E-mail:  arobert@mfs.com 
Linux User Number: #201204 



"MFS Relay Service" made the following
 annotations on 04/07/2005 02:20:47 PM
------------------------------------------------------------------------------
This email communication and any attachments may contain proprietary, confidential, or privileged information.  If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited.  The sender does not waive confidentiality or any privilege by mistransmission.  If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments.
==============================================================================

From kent37 at tds.net  Thu Apr  7 20:51:12 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr  7 20:51:14 2005
Subject: [Tutor] regular expression question
In-Reply-To: <Pine.LNX.4.60.0504071158310.3513@cslin-gps.csunix.comp.leeds.ac.uk>
References: <Pine.LNX.4.60.0504071158310.3513@cslin-gps.csunix.comp.leeds.ac.uk>
Message-ID: <42558120.1030802@tds.net>

D Elliott wrote:
> I wonder if anyone can help me with an RE. I also wonder if there is an 
> RE mailing list anywhere - I haven't managed to find one.
> 
> I'm trying to use this regular expression to delete particular strings 
> from a file before tokenising it.
> 
> I want to delete all strings that have a full stop (period) when it is 
> not at the beginning or end of a word, and also when it is not followed 
> by a closing bracket. I want to delete file names (eg. fileX.doc), and 
> websites (when www/http not given) but not file extensions (eg. this is 
> in .jpg format). I also don't want to delete the last word of each 
> sentence just because it precedes a fullstop, or if there's a fullstop 
> followed by a closing bracket.
> 
> fullstopRe = re.compile (r'\S+\.[^)}]]+')

There are two problems with this is:
- The ] inside the [] group must be escaped like this: [^)}\]]
- [^)}\]] matches any whitespace so it will match on the ends of words

It's not clear from your description if the closing bracket must immediately follow the full stop or 
if it can be anywhere after it. If you want it to follow immediately then use
\S+\.[^)}\]\s]\S*

If you want to allow the bracket anywhere after the stop you must force the match to go to a word 
boundary otherwise you will match foo.bar when the word is foo.bar]. I think this works:
(\S+\.[^)}\]\s]+)(\s)

but you have to include the second group in your substitution string.

BTW C:\Python23\pythonw.exe C:\Python24\Tools\Scripts\redemo.py is very helpful with questions like 
this...

Kent

From david at graniteweb.com  Thu Apr  7 20:54:23 2005
From: david at graniteweb.com (David Rock)
Date: Thu Apr  7 20:54:32 2005
Subject: [Tutor] csv module not raising exception properly
Message-ID: <20050407185423.GC32208@wdfs.graniteweb.com>

I am trying to catch an exception from the csv module but it doesn't
seem to be generating a proper exception because I don't seem to be able
to catch it. Here is what I am doing:


for inputline in fileinput.input(args):
	try:
		input = csv.reader([inputline], escapechar='\\')
	except:
		print "ERROR", inputline


This is the traceback:
Traceback (most recent call last):
  File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ?
    for line in input:
_csv.Error: newline inside string


Shouldn't I be able to catch this? The reason I'm doing it this way is
because I have discovered a ctrl-M in the data I am parsing and the csv
module bombs out on it. I needed to check each line individually. I
thought I could do a try block around the csv.reader line and deal with
the rare exception.

Does anyone know why this try block doesn't catch the exception? The
version of Python I am using is 2.3.3

Thanks.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050407/50eb16a9/attachment.pgp
From kent37 at tds.net  Thu Apr  7 20:59:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr  7 20:59:28 2005
Subject: [Tutor] Help with classes
In-Reply-To: <d082fff805040710236f7251be@mail.gmail.com>
References: <d082fff805040710236f7251be@mail.gmail.com>
Message-ID: <4255830D.3090104@tds.net>

Kevin wrote:
> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:
> class Commands:
>     def __init__(self):
>         pass
>     def quiting(self):
>         sys.exit()
>     def look(self):
>         print "\nNot working yet!\n"
<snip more methods>

> while 1:
>     com = Commands()
>     a = ['look',
>          'get',
>          'take',
>          'kill',
>          'drink',
>          'eat',
>          'eq',
>          'help',
>          'quit']
>     commandl = raw_input(">>>: ")
>     if commandl not in a:
>         print "\nI don't understand that command?\n"
> 
> I want to beable to type in a command from the list at the prompt and
> have it call one of the functions from the class. I was looking for a
> shorter way to write it but the only way I can think of is with an if
> statment for each command. Is there a better way or shorter way to do
> this?

You can use introspection to do this:
cmd = getattr(com, commandl)
cmd()

In fact you could use introspection to replace the list a:
while 1:
   com = Commands()
   commandl = raw_input(">>>: ")
   if hasattr(com, commandl) and iscallable(getattr(com, commandl)):
     cmd = getattr(com, commandl)
     cmd()
   else:
     print "\nI don't understand that command?\n"

You can read a bit more about getattr() and hasattr() here:
http://docs.python.org/lib/built-in-funcs.html

Kent

From seansteeg at gmail.com  Thu Apr  7 20:22:36 2005
From: seansteeg at gmail.com (Sean Steeg)
Date: Thu Apr  7 21:14:43 2005
Subject: [Tutor] UselessPython 2.0
Message-ID: <e835145805040711225875506a@mail.gmail.com>

Dear Pythonistas,

USELESSPYTHON (www.uselesspython.com) has finally come of age.

After almost two years of hemming and hawing, we've finally put our
nose to the grindstone and cranked out version 2.0 of everyone's
favorite snippet site.  Our next trick: fill it.  That's where
everyone here comes in.

As UselessPython was originally born from the Tutor list, it seems
fitting to turn to it again for this rebirth.  We're starting things
over, and we have a practically empty site that we'd like to have
swell to epic proportions.  So we're requesting that anyone with
one-offs, snippets, mini-apps, full-fledged apps and the like make a
submission to the new and improved UselessPython.  The code doesn't
have to be pretty, but it does have to work.

We're also looking for ideas for new Python Challenges: ideas for
things that will rouse the creative spirit in visitors.  After all,
without a problem to solve, programming is just a bunch of goofy words
and indentations.

So please, do this list and Python in general a favor and visit (and
support through your code) the new and (hopefully) improved
UselessPython.

Thank you for your time.
Sean
http://www.uselesspython.com
From project5 at redrival.net  Thu Apr  7 21:22:52 2005
From: project5 at redrival.net (Andrei)
Date: Thu Apr  7 21:27:07 2005
Subject: [Tutor] Re: Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com>
Message-ID: <loom.20050407T211337-738@post.gmane.org>

Kevin <python.programming <at> gmail.com> writes:

> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:
> class Commands:
>     def __init__(self):
>         pass
>     def quiting(self):
>         sys.exit()
<snip> 
> I want to beable to type in a command from the list at the prompt and
> have it call one of the functions from the class. I was looking for a
> shorter way to write it but the only way I can think of is with an if
> statment for each command. Is there a better way or shorter way to do
> this?

I don't think you're making proper use of classes. A class is a collection of
data and methods related to that data. The Commands class is merely a collection
of unrelated methods. IMO the natural solution for your problem would be a
dictionary, where a command is mapped to a function. You'd ask the player for a
command, strip + lowercase it and check if you have a key of that name in your
commands dictionary and if that is the case, run the associated function. It's a
shorter solution and easier to maintain than making a class, keeping a list of
commands and inspecting a Commands object to see if something is available.

Possible classes in a text adventure could be a Player class (which could
contain a list of items which the Player carries, life points, etc.), a Room
class (which could contain information and methods related to the room the
player is in plus the connected rooms), an Item class (with subclasses for
different types of items, where different implementations of e.g. PickUp methods
would determine if the player could pick up a pencil or a skyscraper), etc.

Yours,

Andrei

From kent37 at tds.net  Thu Apr  7 21:28:24 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr  7 21:28:27 2005
Subject: [Tutor] csv module not raising exception properly
In-Reply-To: <20050407185423.GC32208@wdfs.graniteweb.com>
References: <20050407185423.GC32208@wdfs.graniteweb.com>
Message-ID: <425589D8.8060106@tds.net>

David Rock wrote:
> I am trying to catch an exception from the csv module but it doesn't
> seem to be generating a proper exception because I don't seem to be able
> to catch it. Here is what I am doing:
> 
> 
> for inputline in fileinput.input(args):
> 	try:
> 		input = csv.reader([inputline], escapechar='\\')
> 	except:
> 		print "ERROR", inputline
> 
> 
> This is the traceback:
> Traceback (most recent call last):
>   File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ?
>     for line in input:
> _csv.Error: newline inside string

I'm suspicious of this - the traceback doesn't match the code you show. Is your program called 
bpdbreport_test.py? What is happening at line 539 of bpdbreport_test.py?

Kent

From david at graniteweb.com  Thu Apr  7 22:00:47 2005
From: david at graniteweb.com (David Rock)
Date: Thu Apr  7 22:00:56 2005
Subject: [Tutor] csv module not raising exception properly
In-Reply-To: <425589D8.8060106@tds.net>
References: <20050407185423.GC32208@wdfs.graniteweb.com>
	<425589D8.8060106@tds.net>
Message-ID: <20050407200046.GA3838@wdfs.graniteweb.com>

* Kent Johnson <kent37@tds.net> [2005-04-07 15:28]:
> David Rock wrote:
> >I am trying to catch an exception from the csv module but it doesn't
> >seem to be generating a proper exception because I don't seem to be able
> >to catch it. Here is what I am doing:
> >
> >
> >for inputline in fileinput.input(args):
> >	try:
> >		input = csv.reader([inputline], escapechar='\\')
> >	except:
> >		print "ERROR", inputline
> >
> >
> >This is the traceback:
> >Traceback (most recent call last):
> >  File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ?
> >    for line in input:
> >_csv.Error: newline inside string
> 
> I'm suspicious of this - the traceback doesn't match the code you show. Is 
> your program called bpdbreport_test.py? What is happening at line 539 of 
> bpdbreport_test.py?

Line 539 is the csv.reader line. I just boiled it down to the place
where things don't make sense. I use try/except blocks all the time and
I even tested this one by putting a "raise" statement inside the block
and it picked it up, so it's not a scope issue or anything weird like
that. I think the csv module doesn't raise an exception properly. Can
someone verify that it works for them?

I am going to continue testing with an extremely watered down version to
see if it _ever_ works right.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050407/f1943cc7/attachment.pgp
From work at infomaniak.ch  Thu Apr  7 21:21:43 2005
From: work at infomaniak.ch (briner)
Date: Thu Apr  7 22:30:41 2005
Subject: [Tutor] OO newbie
Message-ID: <1112901703.4516.55.camel@localhost>

hi,

Hi, I'm having some trouble to understand how to program in OO and to
know what are the possibilities offered by OO programming in python.
This is even more difficult when you -unfortunately- don't know any
other OO languages.

for example I try to improve a dict class whom you can set up a default
value if the key doesn't exist and are able to count how many instance
it have

class SuperDict(dict):
   count = 0
   def __init__(self, *args, **kw):
      self.__class__.count = self.__class__.count+1
      if kw.has_key('default'):
         self.default=kw.pop('default')
      super(C,self).__init__( *args, **kw)
   def __getitem__(self, key):
      try:
         return dict.__getitem__(self, key)
      except KeyError:
         return self.default
   def __del__(self):
      self.__class__.count = self.__class__.count - 1
   def getCount(cls):
      return cls.count

question:

1-
this exemple will also works if you replace the:
super(C,self).__init__( *args, **kw)
by
dict.__init__(self, *args, **kw)

but I do not understand this dict.__init_... call.
Shouldn't you call the super class constructor??

and how can you distinguish the constructor of one superClass to another
in case of polymorhisme
eg:
class A:
   def __init__(self,fooValue):
      self.fooValue=fooValue

and redefine
class SuperDict(dict,A):
so now how do you do to call the constructor of A

2-
what are the differences between
self.__DoubleUnderscore
self._SimpleUnderscore

3-
in the definition of getCount we saw that the parameter is `cls'.
what does that mean???

4-
I just realize when writing this email that SuperDict is also an object.
and 
type(SuperDict)
<type 'type'>
WOW

Cedric BRINER

From bgailer at alum.rpi.edu  Thu Apr  7 22:38:51 2005
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu Apr  7 22:34:22 2005
Subject: [Tutor] Re: Help with classes
In-Reply-To: <loom.20050407T211337-738@post.gmane.org>
References: <d082fff805040710236f7251be@mail.gmail.com>
	<loom.20050407T211337-738@post.gmane.org>
Message-ID: <6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com>

At 12:22 PM 4/7/2005, Andrei wrote:
>Kevin <python.programming <at> gmail.com> writes:
>
> > I am fooling around with classes and I was trying to create a very
> > small one player text adventure. I made a class called commands here
> > it is:
> > class Commands:
> >     def __init__(self):
> >         pass
> >     def quiting(self):
> >         sys.exit()
><snip>
> > I want to beable to type in a command from the list at the prompt and
> > have it call one of the functions from the class. I was looking for a
> > shorter way to write it but the only way I can think of is with an if
> > statment for each command. Is there a better way or shorter way to do
> > this?
>
>I don't think you're making proper use of classes.

IMHO there is no "proper use of classes".

>A class is a collection of data and methods related to that data.

In Python a class is whatever one creates using the class statement. In 
teaching OOP we often use "collection of data and methods related to that 
data" to help learners appreciate the application of classes. But I'd not 
want to limit classes to that explanation.

Understanding the mechanism behind Python classes opens many doors to many 
uses of classes.

Kent's proposal makes IMHO excellent use of the class mechanism. One may 
also access the class __dict__ directly in lieu of using getattr.

>The Commands class is merely a collection of unrelated methods.

But they are related. Each represents a game command; the class is the 
container for the commands. And it might be that as the program expands 
that there would be multiple instances representing players or saved games 
or ??? And class properties would keep track of the player's status.

>MO the natural solution for your problem would be a
>dictionary, where a command is mapped to a function. You'd ask the player 
>for a
>command, strip + lowercase it and check if you have a key of that name in your
>commands dictionary and if that is the case, run the associated function. 
>It's a
>shorter solution and easier to maintain than making a class, keeping a list of
>commands and inspecting a Commands object to see if something is available.
>
>Possible classes in a text adventure could be a Player class (which could
>contain a list of items which the Player carries, life points, etc.), a Room
>class (which could contain information and methods related to the room the
>player is in plus the connected rooms), an Item class (with subclasses for
>different types of items, where different implementations of e.g. PickUp 
>methods
>would determine if the player could pick up a pencil or a skyscraper), etc.
>
>Yours,
>
>Andrei
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

Bob Gailer
mailto:bgailer@alum.rpi.edu
510 558 3275 home
720 938 2625 cell  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050407/e1762a9e/attachment.htm
From spamfilter2 at mupp.net  Thu Apr  7 22:42:06 2005
From: spamfilter2 at mupp.net (j2)
Date: Thu Apr  7 22:43:51 2005
Subject: [Tutor] Talking to mssql?
Message-ID: <20050407204350.399321E4004@bag.python.org>

I need to talk to a MSSQL server from a python script on a Linux box... I
can't seem to find anything useful. 
I found http://adodbapi.sourceforge.net/ but that seem to be made for Python
Scripts on Windows?

From alan.gauld at freenet.co.uk  Thu Apr  7 23:14:23 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr  7 23:14:18 2005
Subject: [Tutor] Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com>
Message-ID: <00be01c53bb6$c62928c0$46df8751@xp>


> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:

OK, recall that a class represents a template from which you
create (one or) many instances. Thus any class that is named in
the plural usually indicates a problem in the design. You
will only have one instance of your class, only one object.

If you use the singlular version, your class will be Command,
and then you can have many instances, one for each command.
But you want each command to do something different - so
you need subclasses of Command, each one responding to a
single command.

Something like:

class Command:
  def doit(self):   # just a placeholder
    print 'Not built yet'

class Quit(Command):
  def doit(self):   # this is polymorphism
     raise SystemExit

class Help(Command):
   def doit(self):
       answer = None
       i = ['look','get','take','kill','drink','eat','eq','help']
       while not answer in i:
          answer = raw_input(response)
          #Help files will go here
          return answer

That of course requires more typing but it does mean you can add
new commands without changing (and maybe breaking) the existing
working commands. Also any common command code can be added to
the Command class and picked up by all the existing command
subclasses. Also you could, for example define a method that
returns a string describing the class. Then your help method
can simply call the appropriate class's describe method. That
way you never need to create separate help files with the
risk of inconsistencies developing or files going missing.

> while 1:
>     com = Commands()

Now instead of instantiating your single instance you can create
a dictionary of command strings and the corresponding command:

     commands = {
          'look'    :    Command()
          'get'     :    Command()
          'take'    :    Command()
          'kill'    :    Command()
          'drink'   :    Command()
          'eat'     :    Command()
          'eq'      :    Command()
          'help'    :    Help()
          'quit'    :    Quit()
          }

And now the user can select from the set of keys

for command in command.keys():
    print command

Now read the choice and call the appropriate command object.

>     command = raw_input(">>>: ")
>     if command not in commands.keys:
>         print "\nI don't understand that command?\n"
      else: commands[command].doit()

> shorter way to write it but the only way I can think of is with an
if
> statment for each command. Is there a better way or shorter way to
do
> this?

The dictionary approach above is extendable and minimises changes
to working code. As you define new Command classes just change the
corresponding dictionary entry.

[There is a more elegant technique yet that involves making the
classes callable and self describing, but this is OK for now...]

HTH,

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

From alan.gauld at freenet.co.uk  Thu Apr  7 23:24:04 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr  7 23:25:07 2005
Subject: [Tutor] OO newbie
References: <1112901703.4516.55.camel@localhost>
Message-ID: <00d401c53bb8$2089cc10$46df8751@xp>

> 1-
> this exemple will also works if you replace the:
> super(C,self).__init__( *args, **kw)
> by
> dict.__init__(self, *args, **kw)
>
> but I do not understand this dict.__init_... call.
> Shouldn't you call the super class constructor??

super is just a convenience feature added to make Python slightly
more like some other OOP languages. It is effectively just a
wrapper around the explicit call to the super class:

Thus super(C,self...) is the same as

dict.__init__(self...)

The second form just explicitly calls the __init__() method
of the dict class.

> and how can you distinguish the constructor of one superClass to
another
> in case of polymorhisme
> eg:
> class A:
>    def __init__(self,fooValue):
>       self.fooValue=fooValue

Thats where super breaks down IMHO and its much easier using the
explicit form. Thus

> and redefine
> class SuperDict(dict,A):
> so now how do you do to call the constructor of A

     def __init__(self,foo):
        dict.__init__(self)
        A.__init__(self.foo)
        # any local initialising here

> 2-
> what are the differences between
> self.__DoubleUnderscore

magic method name used by Python - operator names, init etc


> self._SimpleUnderscore

A name you want to hide from the outside world ('private'
in some other OOP languages)

> 3-
> in the definition of getCount we saw that the parameter is `cls'.
> what does that mean???

Its just a convention like using self for instance methods.
getcount() is a class method because count is a class variable.
Thus using cls instead of self kind of highlights that. In fact
there's no real diffrence in this case.

> I just realize when writing this email that SuperDict is also an
object.

All classes in Python are also objects. This is also the case
in several other OOP languages but by no means all. And indeed
WOW!, it is a very powerful feature. :-)

> type(SuperDict)
> <type 'type'>
> WOW

HTH,

Alan G.

From david at graniteweb.com  Thu Apr  7 23:25:15 2005
From: david at graniteweb.com (David Rock)
Date: Thu Apr  7 23:25:26 2005
Subject: [Tutor] csv module not raising exception properly [SOLVED]
In-Reply-To: <20050407200046.GA3838@wdfs.graniteweb.com>
References: <20050407185423.GC32208@wdfs.graniteweb.com>
	<425589D8.8060106@tds.net>
	<20050407200046.GA3838@wdfs.graniteweb.com>
Message-ID: <20050407212515.GB4463@wdfs.graniteweb.com>

* David Rock <david@graniteweb.com> [2005-04-07 15:00]:
> * Kent Johnson <kent37@tds.net> [2005-04-07 15:28]:
> > David Rock wrote:
> > >I am trying to catch an exception from the csv module but it doesn't
> > >seem to be generating a proper exception because I don't seem to be able
> > >to catch it. Here is what I am doing:
> > >
> > >
> > >for inputline in fileinput.input(args):
> > >	try:
> > >		input = csv.reader([inputline], escapechar='\\')
> > >	except:
> > >		print "ERROR", inputline
> > >
> > >
> > >This is the traceback:
> > >Traceback (most recent call last):
> > >  File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ?
> > >    for line in input:
> > >_csv.Error: newline inside string
> > 
> > I'm suspicious of this - the traceback doesn't match the code you show. Is 
> > your program called bpdbreport_test.py? What is happening at line 539 of 
> > bpdbreport_test.py?
> 
> Line 539 is the csv.reader line. I just boiled it down to the place
> where things don't make sense. I use try/except blocks all the time and
> I even tested this one by putting a "raise" statement inside the block
> and it picked it up, so it's not a scope issue or anything weird like
> that. I think the csv module doesn't raise an exception properly. Can
> someone verify that it works for them?
> 
> I am going to continue testing with an extremely watered down version to
> see if it _ever_ works right.

Turns out the REAL problem is when you try and USE the reader object,
NOT when you create it. The documantation was not clear on which
operation would actually generate an error. The traceback actually
alludes to this, in hindsight (Thanks Kent). The input = csv.reader() is
fine. When you try to iterate over the object, THAT'S when it dies.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050407/3039c3ef/attachment.pgp
From alan.gauld at freenet.co.uk  Thu Apr  7 23:28:10 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr  7 23:28:03 2005
Subject: [Tutor] Re: Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com><loom.20050407T211337-738@post.gmane.org>
	<6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com>
Message-ID: <00e201c53bb8$b2e01ba0$46df8751@xp>

> >I don't think you're making proper use of classes.
>
> IMHO there is no "proper use of classes".

It depends on whether the OP wants to pursue OOP. There are many uses
of classes that are not related to OOP. But if we are talking about
good OOP practie then there are some uses of classes that are
"improper".

> But they are related. Each represents a game command; the class is
the
> container for the commands. And it might be that as the program
expands
> that there would be multiple instances representing players or saved
games
> or ??? And class properties would keep track of the player's status.

But in that case the class would still be badly formed since it should
be called Game or Player as appropriate.

But outside of OOP classes do make useful containers for code -
although
in Python with its modules there is less real need for that.

My 2 cents worth :-)

Alan G.

From luke.jordan at gmail.com  Thu Apr  7 23:45:34 2005
From: luke.jordan at gmail.com (Luke Jordan)
Date: Thu Apr  7 23:45:37 2005
Subject: [Tutor] Associate functinos with Dictionary/Class Usage
Message-ID: <ea0feb800504071445217fe4b9@mail.gmail.com>

Hi! 

My questions arose from reading the "Help with Classes" email that's
been on this list for the past couple of days.

I'm also writing a text game, but mine is puzzle not adventure.
Anyway, someone mentioned that you can key words to a dictionary to
have user input run functions.

I am looking for a little clarification of how exactly this would work.

1. How do I associate a function to a dict key?

2. If I do this, do objects have to be built from classes with
appropriate attributes?

Right now I am using a handful of methods that are called in if statements:

def takeItem(item):
    items.append(item)
    print "You took the", item

action = raw_input(">>> ")
if action == "take":
    what = raw_input("What do you want to take? ")
    takeItem(takeWhat)
elif action == "drink":
    etc.

Thanks!

Luke

-- 
"Scalpel....blood bucket....priest....next patient."
From ryan at acceleration.net  Fri Apr  8 00:07:53 2005
From: ryan at acceleration.net (Ryan Davis)
Date: Fri Apr  8 00:08:23 2005
Subject: [Tutor] Talking to mssql?
In-Reply-To: <20050407204350.399321E4004@bag.python.org>
Message-ID: <20050407220820.26D0F1E4004@bag.python.org>

I had the same question.  The best I found is this:
http://www.object-craft.com.au/projects/mssql/ 
but that has a lot of strong language saying "this isn't ready for use".

I found it perfectly usable for simply running queries, but haven't tried to do anything more complicated with it.  Not sure how
well it works on Linux, but he has binaries that worked for me.

Thanks,
Ryan 

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of j2
Sent: Thursday, April 07, 2005 4:42 PM
To: tutor@python.org
Subject: [Tutor] Talking to mssql?

I need to talk to a MSSQL server from a python script on a Linux box... I
can't seem to find anything useful. 
I found http://adodbapi.sourceforge.net/ but that seem to be made for Python
Scripts on Windows?

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

From john.ertl at fnmoc.navy.mil  Fri Apr  8 00:25:27 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Fri Apr  8 00:22:38 2005
Subject: [Tutor] viewing gif png ?
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C5F7@lanexc107p.fnmoc.navy.mil>

I need to manipulate and view gif and png images.  I have PIL installed so I
can do the manipulation but PIL does not let me view the images, because I
do not have xv.   What is the recommended python module for viewing gif and
png?

Thanks for the recommendation.

John Ertl 
From dyoo at hkn.eecs.berkeley.edu  Fri Apr  8 01:09:46 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 01:09:54 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <4253CBB0.8040405@tds.net>
Message-ID: <Pine.LNX.4.44.0504071600080.28274-100000@hkn.eecs.berkeley.edu>



On Wed, 6 Apr 2005, Kent Johnson wrote:

> >>>>s = 'Hi "Python Tutors" please help'
> >>>>s.split()
> >
> > ['Hi', '"Python', 'Tutors"', 'please', 'help']
> >
> >
> > I wish it would leave the stuff in quotes in tact:
> >
> > ['Hi', '"Python Tutors"', 'please', 'help']
>
> You can do this easily with the csv module. The only complication is
> that the string has to be wrapped in a StringIO to turn it into a
> file-like object.


Hello!

A variation of Kent's approach might be to use the 'tokenize' module:

    http://www.python.org/doc/lib/module-tokenize.html

which takes advantage of Python's tokenizer itself to break lines into
chunks of tokens.  If you intend your input to be broken up just like
Python tokens, the 'tokenize' module might be ok:

######
>>> import tokenize
>>> from StringIO import StringIO
>>> def getListOfTokens(s):
...     results = []
...     for tokenTuple in tokenize.generate_tokens(StringIO(s).readline):
...         results.append(tokenTuple[1])
...     return results
...
>>> getListOfTokens('Hi "Python Tutors" please help')
['Hi', '"Python Tutors"', 'please', 'help', '']
######

(The last token, the empty string, is EOF, which can be filtered out if we
use the token.ISEOF() function.)


I'm not sure if this is appropriate for Marilyn's purposes though, but I
thought I might just toss it out.  *grin*

From dyoo at hkn.eecs.berkeley.edu  Fri Apr  8 01:29:10 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 01:29:15 2005
Subject: [Tutor] regular expression question
In-Reply-To: <Pine.LNX.4.60.0504071158310.3513@cslin-gps.csunix.comp.leeds.ac.uk>
Message-ID: <Pine.LNX.4.44.0504071611500.28274-100000@hkn.eecs.berkeley.edu>



> I wonder if anyone can help me with an RE. I also wonder if there is an
> RE mailing list anywhere - I haven't managed to find one.

Hi Debbie,

I haven't found one either.  There appear to be a lot of good resources
here:

    http://dmoz.org/Computers/Programming/Languages/Regular_Expressions/

> I'm trying to use this regular expression to delete particular strings
> from a file before tokenising it.

Why not tokenize the file first, and then drop the strings with a period?
You may not need to do all your tokenization at once.  Can you do it in
phases?


> I want to delete all strings that have a full stop (period) when it is
> not at the beginning or end of a word, and also when it is not followed
> by a closing bracket.

Let's make sure we're using the same concepts.  By "string", do you mean
"word"?  That is, if we have something like:

     "I went home last Thursday."

do you expect the regular expression to match against the whole thing?

     "I went home last Thursday."

Or do you expect it to match against the specific end word?

     "Thursday."

I'm just trying to make sure we're using the same terms.  How specific
do you want your regular expression to be?



Going back to your question:

> I want to delete all strings that have a full stop (period) when it is
> not at the beginning or end of a word, and also when it is not followed
> by a closing bracket.

from a first glance, I think you're looking for a "lookahead assertion":

http://www.amk.ca/python/howto/regex/regex.html#SECTION000540000000000000000




> I want to delete file names (eg. fileX.doc), and websites (when www/http
> not given) but not file extensions (eg. this is in .jpg format). I also
> don't want to delete the last word of each sentence just because it
> precedes a fullstop, or if there's a fullstop followed by a closing
> bracket.

Does this need to be part of the same regular expression?



There are a lot of requirements here: can we encode this in some kind of
test class, so that we're sure we're hitting all your requirements?

Here's what I think you're looking for so far, written in terms of a unit
test:


######
import unittest

class DebbiesRegularExpressionTest(unittest.TestCase):
    def setUp(self):
        self.fullstopRe = re.compile("... fill me in")

    def testRecognizingEndWord(self):
        self.assertEquals(
            ["Thursday."],
            self.fullstopRe.findall("I went home last Thursday."))

    def testEndWordWithBracket(self):
        self.assertEquals(
            ["bar."],
            self.fullstopRe.findall("[this is foo.] bar. licious"))

if __name__ == '__main__':
    unittest.main()
######

If these tests don't match with what you want, please feel free to edit
and add more to them so that we can be more clear about what you want.



Best of wishes to you!

From dyoo at hkn.eecs.berkeley.edu  Fri Apr  8 01:32:13 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 01:32:20 2005
Subject: [Tutor] UselessPython 2.0
In-Reply-To: <e835145805040711225875506a@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504071631200.28274-100000@hkn.eecs.berkeley.edu>



On Thu, 7 Apr 2005, Sean Steeg wrote:

> So please, do this list and Python in general a favor and visit (and
> support through your code) the new and (hopefully) improved
> UselessPython.
>
> Thank you for your time.
> Sean
> http://www.uselesspython.com

It looks great; I'll try submitting some stuff on it later!

From dyoo at hkn.eecs.berkeley.edu  Fri Apr  8 01:40:51 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 01:40:54 2005
Subject: [Tutor] Associate functinos with Dictionary/Class Usage
In-Reply-To: <ea0feb800504071445217fe4b9@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504071633490.28274-100000@hkn.eecs.berkeley.edu>



On Thu, 7 Apr 2005, Luke Jordan wrote:

> I am looking for a little clarification of how exactly this would work.
>
> 1. How do I associate a function to a dict key?


Hi Luke,


We're probably already familiar of values like numbers and strings, and
how to give them names with variables:

######
>>> number = 42
>>> name = "luke"
>>> number
42
>>> name
'luke'
######

'number' is a name that refers to the value 42, and 'name' is a name (Doh!
I must use a better variable name next time...) that refers to the value
"luke".



And we also already know how to make functions and to call them:

######
>>> def square(x):
...     return x * x
...
>>> square(42)
1764
######


But what happens if we just say "square" at the interpreter?

######
>>> square
<function square at 0x40300b1c>
######

The value of 'square' is a function value.


And just like any other value, we can assign it to another name:

######
>>> anotherNameForSquare = square
>>> anotherNameForSquare(16)
256
######


And just like any other value, we can use it as a dictionary value:

######
>>> operators = {'^2': square}
>>> operators['^2']
<function square at 0x40300b1c>
>>> operators['^2'](4)
16
######


Does this make sense so far?  Please feel free to ask more questions about
this.  Best of wishes!

From marilyn at deliberate.com  Fri Apr  8 02:36:32 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Fri Apr  8 02:44:42 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504071600080.28274-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504071730320.18776-100000@Kuna>

On Thu, 7 Apr 2005, Danny Yoo wrote:

> 
> 
> On Wed, 6 Apr 2005, Kent Johnson wrote:
> 
> > >>>>s = 'Hi "Python Tutors" please help'
> > >>>>s.split()
> > >
> > > ['Hi', '"Python', 'Tutors"', 'please', 'help']
> > >
> > >
> > > I wish it would leave the stuff in quotes in tact:
> > >
> > > ['Hi', '"Python Tutors"', 'please', 'help']
> >
> > You can do this easily with the csv module. The only complication is
> > that the string has to be wrapped in a StringIO to turn it into a
> > file-like object.
> 
> 
> Hello!
> 
> A variation of Kent's approach might be to use the 'tokenize' module:
> 
>     http://www.python.org/doc/lib/module-tokenize.html
> 
> which takes advantage of Python's tokenizer itself to break lines into
> chunks of tokens.  If you intend your input to be broken up just like
> Python tokens, the 'tokenize' module might be ok:
> 
> ######
> >>> import tokenize
> >>> from StringIO import StringIO
> >>> def getListOfTokens(s):
> ...     results = []
> ...     for tokenTuple in tokenize.generate_tokens(StringIO(s).readline):
> ...         results.append(tokenTuple[1])
> ...     return results
> ...
> >>> getListOfTokens('Hi "Python Tutors" please help')
> ['Hi', '"Python Tutors"', 'please', 'help', '']
> ######
> 
> (The last token, the empty string, is EOF, which can be filtered out if we
> use the token.ISEOF() function.)
> 

In my context, I expect exactly 8 tokens so the extra '' wouldn't be
noticed.

> 
> I'm not sure if this is appropriate for Marilyn's purposes though, but I
> thought I might just toss it out.  *grin*

Thank you Danny.  Very interesting.  Both approaches are perfect for
me.

Is there a reason to prefer one over the other?  Is one faster?  I
compiled my regular expression to make it quicker.

What a rich language!  So many choices.

Marilyn

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

-- 

From keridee at jayco.net  Fri Apr  8 03:18:44 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr  8 03:18:11 2005
Subject: [Tutor] OO newbie
References: <1112901703.4516.55.camel@localhost>
Message-ID: <002901c53bd8$fb3079c0$3a5428cf@JSLAPTOP>

> 2-
> what are the differences between
> self.__DoubleUnderscore
> self._SimpleUnderscore

Double Underscores are way cooler!
Here's why.
Single underscores are just subtle clues to the user of the class that you 
aren't specifically supposed to call that function of the class. IOW, its 
used internally but not supposed to be used externally.

Double underscores are much neater.
For example --  in the python docs it should say that

int([x]) calls the __int__ method of x
float([x])  calls the __float__ method of x

And all of the other functions similar.  str, repr, etc.
Yet even cooler---

a + b  is the same as  a.__add__(b)
a - b  is the same as a.__sub__(b)
a * b is the same as a.__mul__(b)
a / b is the same as a.__div__(b)  when from __future__ import division is 
not imported

This means that you can control how the operands affect your object!
Even cooler...
Say the first argument is not your object

a + b  is the same as  b.__radd__(a)  where b is your object

This allows you to affect how other objects treat your object.

a += b  is the same as a.__iadd__(b)

It says in the docs that you should make the __i...__ series try to modify 
the object, whereas the normal ones return a new object.

etcetera, etcetera, etcetera.

To find the full series in the docs -- 

http://docs.python.org/lib/module-operator.html

HTH,
Jacob 

From dyoo at hkn.eecs.berkeley.edu  Fri Apr  8 03:32:53 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 03:33:04 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504071730320.18776-100000@Kuna>
Message-ID: <Pine.LNX.4.44.0504071829440.28274-100000@hkn.eecs.berkeley.edu>

> > I'm not sure if this is appropriate for Marilyn's purposes though, but
> > I thought I might just toss it out.  *grin*
>
> Thank you Danny.  Very interesting.  Both approaches are perfect for
> me.
>
> Is there a reason to prefer one over the other?  Is one faster?  I
> compiled my regular expression to make it quicker.

Hi Marilyn,

I think that Kent's approach is better because it's simpler.  Unlike the
'tokenize' module approach, the 'csv' module is conceptually not closely
coupled to Python.  The 'tokenize' module, on the other hand, uses
Python's rules for tokenization, and they might not fit your purposes as
well.

From dmalle at bankbii.com  Fri Apr  8 03:50:15 2005
From: dmalle at bankbii.com (Dionysius Malle)
Date: Fri Apr  8 03:49:54 2005
Subject: [Tutor] How to create multi disks zip file
Message-ID: <B95417754EC0D811B2C3000D88CC68D50278B766@UP3EXCG1P>

Hi,

 

I'm a newbie. My friend asked me for a help. He wanted to backup his files
into multi disks zip file. Is there any possibilities for me to help him by
using python?

 

TIA,

Ony

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/04afbee7/attachment.html
From tameyer at ihug.co.nz  Fri Apr  8 03:53:50 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Fri Apr  8 03:55:01 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8028DBF78@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0056@its-xchg4.massey.ac.nz>

> Is there a reason to prefer one over the other?  Is one
> faster?  I compiled my regular expression to make it quicker.

With Python 2.4 I get these results (all imports are factored out, all give
the same result except for CSV which strips the "s) with timeit.py:

Own split:   26.8668364275
Tokenize:    78.8295112926
Rejoin:      11.237671827
Re:          13.9386123097
Re compiled:  8.19355839918
CSV:         23.3710904598

Of course, speed isn't everything (or you wouldn't be using Python).
Readability is probably the most important factor - I'd say that a re
(particularly a verbose re) would be the most readable, followed by using
the CSV module, followed by writing your own split function.  Since re is
also the fastest of the methods suggested so far, it seems like a good
choice.

> What a rich language!  So many choices.

Somewhat ironically, one of the tenets of Python is "there should be one--
and preferably only one --obvious way to do it." (type "import this" at an
interactive prompt).

=Tony.Meyer
-------------- next part --------------
import re
import csv
import tokenize
from StringIO import StringIO

def split_with_csv(s):
    input = StringIO(s)
    return csv.reader(input, delimiter=' ').next()

r = re.compile(r'\".*\"|[^ ]+')
def split_with_re_compiled(s):
    return r.findall(s)

def split_with_re(s):
    return re.findall(r'\".*\"|[^ ]+', s)

def split_with_tokenize(s):
    results = [tokenTuple[1] for tokenTuple in tokenize.generate_tokens(StringIO(s).readline)]
    return results[:-1]
    
def split_and_rejoin(s):
    combined = []
    b = []
    in_quotes = False
    for a in s.split():
        if '"' in a and in_quotes:
            combined.append(a)
            b.append(" ".join(combined))
            combined = []
            in_quotes = False
            continue
        elif '"' in a and not in_quotes:
            in_quotes = True
        if in_quotes:
            combined.append(a)
        else:
            b.append(a)
    return b

def split_no_quotes(s):
    index_start = 0
    index_end = 0
    in_quotes = False
    result = []
    while index_end < len(s):
        if s[index_end] == '"':
            in_quotes = not in_quotes
        if s[index_end] == ' ' and not in_quotes:
            result.append(s[index_start:index_end])
            index_start = index_end + 1
        index_end += 1
    if s[-1] != ' ':
        result.append(s[index_start:index_end])
    return result

if __name__ == "__main__":
    import timeit

    t = timeit.Timer("temp3.split_no_quotes('Hi \"Python Tutors\" please help')", "import temp3")
    print "No quotes", t.timeit()
    t = timeit.Timer("temp3.split_with_tokenize('Hi \"Python Tutors\" please help')", "import temp3")
    print "Tokenize", t.timeit()
    t = timeit.Timer("temp3.split_and_rejoin('Hi \"Python Tutors\" please help')", "import temp3")
    print "Rejoin", t.timeit()
    t = timeit.Timer("temp3.split_with_re('Hi \"Python Tutors\" please help')", "import temp3")
    print "Re", t.timeit()
    t = timeit.Timer("temp3.split_with_re_compiled('Hi \"Python Tutors\" please help')", "import temp3")
    print "Re compiled", t.timeit()
    t = timeit.Timer("temp3.split_with_csv('Hi \"Python Tutors\" please help')", "import temp3")
    print "CSV", t.timeit()

    t = timeit.Timer("temp3.split_no_quotes('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "No quotes", t.timeit()
    t = timeit.Timer("temp3.split_with_tokenize('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "Tokenize", t.timeit()
    t = timeit.Timer("temp3.split_and_rejoin('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "Rejoin", t.timeit()
    t = timeit.Timer("temp3.split_with_re('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "Re", t.timeit()
    t = timeit.Timer("temp3.split_with_re_compiled('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "Re compiled", t.timeit()
    t = timeit.Timer("temp3.split_with_csv('This will not work as \"more than two words\" are quoted')", "import temp3")
    print "CSV", t.timeit()
From cyresse at gmail.com  Fri Apr  8 04:12:19 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Fri Apr  8 04:12:22 2005
Subject: [Tutor] How to create multi disks zip file
In-Reply-To: <B95417754EC0D811B2C3000D88CC68D50278B766@UP3EXCG1P>
References: <B95417754EC0D811B2C3000D88CC68D50278B766@UP3EXCG1P>
Message-ID: <f2ff2d05040719126871ceea@mail.gmail.com>

Err... you probably could, but why reinvent the wheel? WinZip?



On Apr 8, 2005 1:50 PM, Dionysius Malle <dmalle@bankbii.com> wrote:
>  
>  
> 
> Hi, 
> 
>   
> 
> I'm a newbie. My friend asked me for a help. He wanted to backup his files
> into multi disks zip file. Is there any possibilities for me to help him by
> using python? 
> 
>   
> 
> TIA, 
> 
> Ony 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
From marilyn at deliberate.com  Fri Apr  8 04:33:48 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Fri Apr  8 04:41:58 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0056@its-xchg4.massey.ac.nz>
Message-ID: <Pine.LNX.4.44.0504071919180.18776-100000@Kuna>

On Fri, 8 Apr 2005, Tony Meyer wrote:

> > Is there a reason to prefer one over the other?  Is one
> > faster?  I compiled my regular expression to make it quicker.
> 
> With Python 2.4 I get these results (all imports are factored out, all give
> the same result except for CSV which strips the "s) with timeit.py:
> 
> Own split:   26.8668364275
> Tokenize:    78.8295112926
> Rejoin:      11.237671827
> Re:          13.9386123097
> Re compiled:  8.19355839918
> CSV:         23.3710904598

Wow Tony.  That is so generous of you to do this experiment.  It must
be a great re engine.

I wondered if tokenize was resource-hungry.  It goes so far around the
bush.  But I'm glad to know about it.  Thank you again, Danny.

> 
> Of course, speed isn't everything (or you wouldn't be using Python).
> Readability is probably the most important factor - I'd say that a re
> (particularly a verbose re) would be the most readable, followed by using
> the CSV module, followed by writing your own split function.  Since re is
> also the fastest of the methods suggested so far, it seems like a good
> choice.

Yes!  To everything you say.

And there's the added feature that I don't have to go back and change
that code now!  And so little typing in the first place.

> 
> > What a rich language!  So many choices.
> 
> Somewhat ironically, one of the tenets of Python is "there should be one--
> and preferably only one --obvious way to do it." (type "import this" at an

In this case, there is: regular expressions.  :^)

"Obvious" doesn't mean we can, necessarily, all see it immediately, or
that even any one of us can see it without study, thought and
inspiration, but, it means we can all see it once it's pointed out.

Or maybe I'm wrong.  

Thank you, you guys.

Marilyn

> interactive prompt).
> 
> =Tony.Meyer
> 

-- 

From tim.peters at gmail.com  Fri Apr  8 04:53:01 2005
From: tim.peters at gmail.com (Tim Peters)
Date: Fri Apr  8 04:53:03 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504071919180.18776-100000@Kuna>
References: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0056@its-xchg4.massey.ac.nz>
	<Pine.LNX.4.44.0504071919180.18776-100000@Kuna>
Message-ID: <1f7befae05040719532b0742a@mail.gmail.com>

[Tony Meyer]
...
>> Somewhat ironically, one of the tenets of Python is "there should be one--
>> and preferably only one --obvious way to do it." (type "import this" at an

[Marilyn Davis]
> In this case, there is: regular expressions.  :^)
>
> "Obvious" doesn't mean we can, necessarily, all see it immediately, or
> that even any one of us can see it without study, thought and
> inspiration, but, it means we can all see it once it's pointed out.
>
> Or maybe I'm wrong.

Nope, that's exactly right!  That's what "import this" means when it
says immediately after:

    Although that way may not be obvious at first unless you're Dutch.

I'm not sure even the Dutch understand regexps at first, though. 
Sometimes we slightly undersell the true difficulty of things <wink>.
From tameyer at ihug.co.nz  Fri Apr  8 05:08:16 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Fri Apr  8 05:08:57 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8028DC00B@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0059@its-xchg4.massey.ac.nz>

> Wow Tony.  That is so generous of you to do this experiment.  
> It must be a great re engine.

It really wasn't much effort - just copying & pasting it all together and
throwing in a few timeit statements.  The timeit module is another great
thing about Python :)

> "Obvious" doesn't mean we can, necessarily, all see it 
> immediately, or that even any one of us can see it without 
> study, thought and inspiration, but, it means we can all see 
> it once it's pointed out.

Nicely said :)

=Tony.Meyer

From rdm at rcblue.com  Fri Apr  8 05:50:59 2005
From: rdm at rcblue.com (Dick Moores)
Date: Fri Apr  8 05:51:10 2005
Subject: [Tutor] What is the best book to start? - Many Thanks!
In-Reply-To: <3fe17b690504060136138b6d31@mail.gmail.com>
References: <20050405013710.97945.qmail@web60007.mail.yahoo.com>
	<3fe17b690504060136138b6d31@mail.gmail.com>
Message-ID: <6.2.1.2.2.20050407204350.044578f0@rcblue.com>

Steve George wrote at 01:36 4/6/2005:
>The best book I know is Core Python by Wesley Chun.  But it only
>covers 1.6 so quite a few things have changed since then.

The first page (p. ixx?) of the Preface to my copy says "At the time of 
publication (2001), Python 2.0 was just released, so you will definitely 
have the latest and greatest."

Dick Moores
rdm@rcblue.com


From bvande at po-box.mcgill.ca  Fri Apr  8 06:00:40 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Fri Apr  8 06:01:11 2005
Subject: [Tutor] OO newbie
In-Reply-To: <002901c53bd8$fb3079c0$3a5428cf@JSLAPTOP>
References: <1112901703.4516.55.camel@localhost>
	<002901c53bd8$fb3079c0$3a5428cf@JSLAPTOP>
Message-ID: <425601E8.50006@po-box.mcgill.ca>

Jacob S. said unto the world upon 2005-04-07 21:18:
>> 2-
>> what are the differences between
>> self.__DoubleUnderscore
>> self._SimpleUnderscore
> 
> 
> Double Underscores are way cooler!
> Here's why.
> Single underscores are just subtle clues to the user of the class that 
> you aren't specifically supposed to call that function of the class. 
> IOW, its used internally but not supposed to be used externally.
> 
> Double underscores are much neater.
> For example --  in the python docs it should say that
> 
> int([x]) calls the __int__ method of x
> float([x])  calls the __float__ method of x

<SNIP>

Hi Cedric, Jacob, and all,

Jacob's answer focused on special methods -- those with both leading 
*and* trailing underscores. They're pretty cool, but methods with 
leading double underscores *only* are cool in a different way. They 
approximate `private' methods from other languages, only rather than 
being fully private, they are just really `shy'.

 >>> class A:
... 	def __init__(self):
... 		print 42
... 		
 >>> a = A()
42
 >>> a.__init__()
42
 >>>

So A.__init__ can be called like any other A method (if A had other 
methods, that is).

Contrast that with this example where there is a `shy' method with one 
leading underscore and a mangled method with 2:

 >>> class Shy:
     '''My silly example'''
     def _shy_method(self):
	'''I am a shy docstring'''
         print "I'm a shy method"
     def public_method(self):
	'''I am a public docstring'''
         print "I'm a public method"
     def __mangled_method(self):
	'''I'm a very shy docstring'''
         print "I'm quite shy and a bit of a challenge to call as"
         print "I've been mangled!"


 >>> help(Shy)
Help on class Shy in module __main__:

class Shy
  |  My silly example
  |
  |  Methods defined here:
  |
  |  public_method(self)
  |      I am a public docstring


So, either 1 or 2 leading underscores hides a method from pydoc. We 
can still get to them though:


 >>> help(Shy._shy_method)
Help on method _shy_method in module __main__:

_shy_method(self) unbound __main__.Shy method
     I am a shy docstring

 >>> help(Shy.__mangled_method)

Traceback (most recent call last):
   File "<pyshell#22>", line 1, in -toplevel-
     help(Shy.__mangled_method)
AttributeError: class Shy has no attribute '__mangled_method'
 >>> help(Shy._Shy__mangled_method)
Help on method __mangled_method in module __main__:

__mangled_method(self) unbound __main__.Shy method
     I'm a very shy docstring

The double underscore in a method name leads to so called "name 
mangling". As the example shows, we have to preface the method with 
_ClassName in order to access it.

This works the same for method calls:

 >>> shy.public_method()
I'm a public method
 >>> shy._shy_method()
I'm a shy method
 >>> shy.__mangled_method()

Traceback (most recent call last):
   File "<pyshell#26>", line 1, in -toplevel-
     shy.__mangled_method()
AttributeError: Shy instance has no attribute '__mangled_method'
 >>> shy._Shy.__mangled_method()

Traceback (most recent call last):
   File "<pyshell#27>", line 1, in -toplevel-
     shy._Shy.__mangled_method()
AttributeError: Shy instance has no attribute '_Shy'
 >>> shy._Shy__mangled_method()
I'm quite shy and a bit of a challenge to call as
I've been mangled!
 >>>

So, the idea of single and double underscores is to convey in strong, 
or really strong, terms that the method probably ought not be called 
outside the class. One is mere convention, the other is convention 
plus a barrier in your way. But, if you want to eschew convention you 
can -- "we are all adults here."


Best,

Brian vdB


From bvande at po-box.mcgill.ca  Fri Apr  8 06:07:23 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Fri Apr  8 06:07:34 2005
Subject: [Tutor] OO newbie
In-Reply-To: <425601E8.50006@po-box.mcgill.ca>
References: <1112901703.4516.55.camel@localhost>
	<002901c53bd8$fb3079c0$3a5428cf@JSLAPTOP>
	<425601E8.50006@po-box.mcgill.ca>
Message-ID: <4256037B.9010706@po-box.mcgill.ca>

Brian van den Broek said unto the world upon 2005-04-08 00:00:

<SNIP>

>  >>> class Shy:
>     '''My silly example'''
>     def _shy_method(self):
>     '''I am a shy docstring'''
>         print "I'm a shy method"
>     def public_method(self):
>     '''I am a public docstring'''
>         print "I'm a public method"
>     def __mangled_method(self):
>     '''I'm a very shy docstring'''
>         print "I'm quite shy and a bit of a challenge to call as"
>         print "I've been mangled!"

<SNIP>

Something went goofy with the indentation -- that should have the the 
method doscstrings indented to align with the print statements.

Sorry about that,

Brian vdB

From bvande at po-box.mcgill.ca  Fri Apr  8 06:57:36 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Fri Apr  8 07:00:42 2005
Subject: [Tutor] How to create multi disks zip file
In-Reply-To: <B95417754EC0D811B2C3000D88CC68D50278B766@UP3EXCG1P>
References: <B95417754EC0D811B2C3000D88CC68D50278B766@UP3EXCG1P>
Message-ID: <42560F40.4030504@po-box.mcgill.ca>

Dionysius Malle said unto the world upon 2005-04-07 21:50:
> Hi,
> 
> I'm a newbie. My friend asked me for a help. He wanted to backup his files
> into multi disks zip file. Is there any possibilities for me to help him by
> using python?
> 
> TIA,
> 
> Ony

Hi,

I'd separate the zip and split steps.

Chapter 4 of the second edition of Programming Python has a thorough 
discussion of 2 scripts, one for splitting a large file, the other for 
joining the parts. It is a fairly advanced book, but the code is 
pretty clear. You can get the code from the book's website 
<http://www.oreilly.com/catalog/python2/>. It might help get you started.

Best,

Brian vdB


From project5 at redrival.net  Fri Apr  8 09:01:39 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr  8 09:04:50 2005
Subject: [Tutor] Re: Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com>
	<loom.20050407T211337-738@post.gmane.org>
	<6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com>
Message-ID: <loom.20050408T081423-533@post.gmane.org>

Bob Gailer <bgailer <at> alum.rpi.edu> writes:

> At 12:22 PM 4/7/2005, Andrei wrote:
> >Kevin <python.programming <at> gmail.com> writes:
> >
> > > I am fooling around with classes and I was trying to create a very
> > > small one player text adventure. I made a class called commands here
<snip>
> >I don't think you're making proper use of classes.
>
> IMHO there is no "proper use of classes".

Perhaps I didn't phrase that quite the way I intended. What I meant is that
there are places where classes are obviously beneficial and there are places
where a different solution is the easier one. Python is fortunately flexible
enough to allow all kinds of approaches.

> In Python a class is whatever one creates using the class statement. In 

As it is in all languages. Which is not to say that any class the language
allows you to make is actually useful or the best way to do the job. Python has
with its tuples, lists, dicts and sets a whole bunch of collection types readily
available, which look like collections and are instantly recognized by any
programmer as collections (unlike a class, which I for one would expect to be
used as more than a collection when reading code).

<snip>
> Kent's proposal makes IMHO excellent use of the class mechanism. One may 
> also access the class __dict__ directly in lieu of using getattr.

Yep, hence my statement that a class in this use case is just a confusing way of
using a dict :). I read (perhaps misread) Kevin's post as a question from
someone who is new to OOP and wants to learn about it, rather than a request on
info regarding the manipulation of class internals. 

> >The Commands class is merely a collection of unrelated methods.
> 
> But they are related. Each represents a game command; the class is the 
> container for the commands. And it might be that as the program expands 
> that there would be multiple instances representing players or saved games 
> or ??? And class properties would keep track of the player's status.

Guessing at Kevin's intentions is quite difficult by other means than reading
the posted code. A class called "Commands" that only contains methods
implementing actions as results to commands given by the human player, can't
reasonably be interpreted as something that will at some point hold a
character's status.

Yours,

Andrei

From python.programming at gmail.com  Fri Apr  8 10:08:18 2005
From: python.programming at gmail.com (Kevin)
Date: Fri Apr  8 10:08:25 2005
Subject: [Tutor] Re: Help with classes
In-Reply-To: <loom.20050408T081423-533@post.gmane.org>
References: <d082fff805040710236f7251be@mail.gmail.com>
	<loom.20050407T211337-738@post.gmane.org>
	<6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com>
	<loom.20050408T081423-533@post.gmane.org>
Message-ID: <d082fff8050408010810a955e@mail.gmail.com>

Well this OOP stuff is realy hard for me as I have never even
programmed it took me a while just to understand defs. However I am
determined to learn how to do it. My biggest problem is with __init__
I still don't understand how to use it. Though I did try somthing
different with my code rather then having the dict of commands in the
main part of the code, I put it in th __init__ of class Comands like
so:

class Command:
    def __init__(self):
        self.command_list = {}
        self.command_list['get'] = 'get'
        self.command_list['look'] = 'look'
        self.command_list['kill'] = 'kill'
        
    def UserCMD_get(self):
        print "Not in yet"

    def UserCMD_look(self):
        print "Not in yet"

    def UserCMD_kill(self):
        print "Not in yet"

test = Command()
while 1:
    prompt = raw_input(">>>: ")
    if prompt not in test.command_list:
        print "That is not a command"
    if prompt in test.command_list:
        exec 'test.UserCMD_' + prompt + '()'
        
though doing it like this to me the only real difference is the dict
of commands is in the __init__ of class. But why do I feel that this
is still the wrong way to do this. I was trying to look at other
examples but they are hard to fallow with no comments of any kind.
what my ultimate goal for right now is make it so that at the prompt
wich is >>>:
When a player type is "get sword" it will add a sword to there
inventory. Wich I'm not sure if I am going about this the right way.

thanks

Kevin



On Apr 8, 2005 3:01 AM, Andrei <project5@redrival.net> wrote:
> Bob Gailer <bgailer <at> alum.rpi.edu> writes:
> 
> > At 12:22 PM 4/7/2005, Andrei wrote:
> > >Kevin <python.programming <at> gmail.com> writes:
> > >
> > > > I am fooling around with classes and I was trying to create a very
> > > > small one player text adventure. I made a class called commands here
> <snip>
> > >I don't think you're making proper use of classes.
> >
> > IMHO there is no "proper use of classes".
> 
> Perhaps I didn't phrase that quite the way I intended. What I meant is that
> there are places where classes are obviously beneficial and there are places
> where a different solution is the easier one. Python is fortunately flexible
> enough to allow all kinds of approaches.
> 
> > In Python a class is whatever one creates using the class statement. In
> 
> As it is in all languages. Which is not to say that any class the language
> allows you to make is actually useful or the best way to do the job. Python has
> with its tuples, lists, dicts and sets a whole bunch of collection types readily
> available, which look like collections and are instantly recognized by any
> programmer as collections (unlike a class, which I for one would expect to be
> used as more than a collection when reading code).
> 
> <snip>
> > Kent's proposal makes IMHO excellent use of the class mechanism. One may
> > also access the class __dict__ directly in lieu of using getattr.
> 
> Yep, hence my statement that a class in this use case is just a confusing way of
> using a dict :). I read (perhaps misread) Kevin's post as a question from
> someone who is new to OOP and wants to learn about it, rather than a request on
> info regarding the manipulation of class internals.
> 
> > >The Commands class is merely a collection of unrelated methods.
> >
> > But they are related. Each represents a game command; the class is the
> > container for the commands. And it might be that as the program expands
> > that there would be multiple instances representing players or saved games
> > or ??? And class properties would keep track of the player's status.
> 
> Guessing at Kevin's intentions is quite difficult by other means than reading
> the posted code. A class called "Commands" that only contains methods
> implementing actions as results to commands given by the human player, can't
> reasonably be interpreted as something that will at some point hold a
> character's status.
> 
> Yours,
> 
> Andrei
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From work at infomaniak.ch  Fri Apr  8 10:55:11 2005
From: work at infomaniak.ch (BRINER Cedric)
Date: Fri Apr  8 10:55:23 2005
Subject: [Tutor] OO newbie
In-Reply-To: <00d401c53bb8$2089cc10$46df8751@xp>
References: <1112901703.4516.55.camel@localhost>
	<00d401c53bb8$2089cc10$46df8751@xp>
Message-ID: <1112950511.20335.67.camel@obslin15.unige.ch>

> > 1-
> > this exemple will also works if you replace the:
> > super(C,self).__init__( *args, **kw)
> > by
> > dict.__init__(self, *args, **kw)
> >
> > but I do not understand this dict.__init_... call.
> > Shouldn't you call the super class constructor??
> 
> super is just a convenience feature added to make Python slightly
> more like some other OOP languages. It is effectively just a
> wrapper around the explicit call to the super class:
> 
> Thus super(C,self...) is the same as
> 
> dict.__init__(self...)
after you telling me that dict.__init__(self...) should in your opinion
the way to do it.
I was not really happy because I did not understand at all this line.
I start looking at this line for a while before understanding it (2
hours maybe)...  :B

type(dict)
<type 'type'>
so dict is a class


dict.__init__ is the function to initialize a dictionnary
so
dict.__init__(self...) initialize the dictionnary `self'. Which work
because self derive from a dictionnary...

I got it !
I was really lost because I was not clearly making a difference between
the class: ``dict'' and an instance of it: ``dict()''

and thanks for your time.

Cedric BRINER

From debe at comp.leeds.ac.uk  Fri Apr  8 11:20:32 2005
From: debe at comp.leeds.ac.uk (D Elliott)
Date: Fri Apr  8 11:20:34 2005
Subject: [Tutor] Thanks for Regex help
Message-ID: <Pine.LNX.4.60.0504081006050.25747@cslin-gps.csunix.comp.leeds.ac.uk>

Thanks to Matt, Kent and Danny for helping me with my regex question. I 
will try your suggestions this morning.

In response to Danny's question about tokenising first, there are reasons 
why I don't want to do this - the initial problem was that filenames in my 
test data were being tokenised as separate words. EG. 
DataMarchAccounts.txt would be tokenised as two words, neither of which 
are real words that can be found in an English dictionary. (Often, 
filenames are not proper words, which is why I needed to delete the whole 
string - and by 'string' I mean any consecutive string of non-whitespace 
characters.) Because I don't want to subsequently analyse any 'non-words', 
only real words that will then be automatically checked against a lexicon.

Well - my code is all done now, apart from the tweaking of this one RE. 
BTW - I am new to Python and had never done any programming before that, 
so you may see some more questions from me in the future...

Cheers again,
Debbie
-- 
***************************************************
Debbie Elliott
Computer Vision and Language Research Group,
School of Computing,
University of Leeds,
Leeds LS2 9JT
United Kingdom.
Tel: 0113 3437288
Email: debe@comp.leeds.ac.uk
***************************************************
From alan.gauld at freenet.co.uk  Fri Apr  8 11:33:08 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  8 11:32:49 2005
Subject: [Tutor] Re: Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com><loom.20050407T211337-738@post.gmane.org><6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com><loom.20050408T081423-533@post.gmane.org>
	<d082fff8050408010810a955e@mail.gmail.com>
Message-ID: <012d01c53c1d$fa498ed0$46df8751@xp>

> Well this OOP stuff is realy hard for me as I have never even
> programmed it took me a while just to understand defs.

That's OK, OOP is quite a strange concept for many folks. Its
actually easier to learn as a beginner than for folks who
have been programming without OOP for a long time!

> determined to learn how to do it. My biggest problem is with
__init__
> I still don't understand how to use it.

init is simply where you initialise the data attributes of your class.

It could be defined as a normal method and you call it explicitly:

class Message:
  def init(self, txt = 'Hello world'):
     self.text = txt
  def sayIt(self):
     print self.text

And every time you create a message object you explicitly call it:

m = Message()
m.init('Hiya fred!')
m.sayIt()


The __init__ style is simply a way for Python to do some of the work
by calling the init method immediately after it creates the new,
blank object. So

class Message:
  def __init__(self, txt = 'Hello world'):
     self.text = txt
  def sayIt(self):
     print self.text

Does exactly the same as the first version except that we no longer
call init explicitly abnd instead pass the message text into the
instantiation call:

m = Message('hiya fred!')
m.sayIt()

But there is nothing mysterious, its just a way to initialise the
internal data at the time you create an instance of the class.

> different with my code rather then having the dict of commands in
the
> main part of the code, I put it in th __init__ of class Comands like
> so:
>
> class Command:
>     def __init__(self):
>         self.command_list = {}
>         self.command_list['get'] = 'get'

You are not actually storing your methods(function objects) here, you
are simply storing the name(a string) which is the same as the key.

>     def UserCMD_get(self):
>         print "Not in yet"

So you need to do:

       self.command_list['get'] = self.UserCMD_get   # no parens!

To store a reference to the actual function UserCMD_get in your
dictionary.
However, as Kents mail pointed out this isn't necessary since Python
already uses a dictionary of its own to store these things so you can
use get_attr() etc to do the same job. And as Andrei said you can do
it
even more simply without a class at all, just using functions. If you
really want to use classes then having one per command is a better
approach. The commands are all individual objects that you can use.

> test = Command()
> while 1:
>     prompt = raw_input(">>>: ")
>     if prompt not in test.command_list:
>         print "That is not a command"
>     if prompt in test.command_list:
>         exec 'test.UserCMD_' + prompt + '()'

And you don't need to use exec, all you need to do is call
the function object in the dictionary directly:

      test.command_list[prompt]()

test.command_list['prompt'] will fetch the function object from
the dictionary and the parens () at the end calls the function.

> what my ultimate goal for right now is make it so that at the prompt
> wich is >>>:
> When a player type is "get sword" it will add a sword to there
> inventory. Wich I'm not sure if I am going about this the right way.

Its probably easier to use a non OOP style for the menu and commands
and use the OOP stuff for the objects within the game - like Player,
Character, Sword etc. But you have to start thinking about the objects
not the functions. The objects are "alive" and communicating with each
other via messages. Each message is a call to a method of a class.

Its worth trying to sketch out how these objects would be related to
one another in a diagram, nothing fancy just some boxes and lines.
Maybe use arrows to show what direction messages flow in - ie which
object sends which message to which other object. Also an adventure
game is quite a duifficult starting point for OOP.

Maybe trying something simpler first like a shopping list creator
say. There each item you might want to buy can be an object that
knows how to print itself and its price. The ShoppingList itself
is just a collection of such objects and when you print it it asks
each object to print itself and return the price...
The ShoppingList completes the list by printing the total price.

Many of the concepts are similar to what you are doing here but
the overall program is much simpler in concept.

Good luck!

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

From kent37 at tds.net  Fri Apr  8 12:00:03 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  8 12:00:08 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <Pine.LNX.4.44.0504071730320.18776-100000@Kuna>
References: <Pine.LNX.4.44.0504071730320.18776-100000@Kuna>
Message-ID: <42565623.8000607@tds.net>

Marilyn Davis wrote:
> Is there a reason to prefer one over the other?  Is one faster?  I
> compiled my regular expression to make it quicker.

The only way to know which is faster is to time them both. The timeit module makes it pretty easy to 
do this.

Here is a simple example of using timeit for a different problem; you can adapt it to your own needs:

d = dict( ((i,i,i), i) for i in range(1000))

def withItems(d):
     for k,v in d.iteritems():
         pass


def withKeys(d):
     for k in d:
         d[k]


from timeit import Timer

for fn in [withItems, withKeys]:
     name = fn.__name__
     timer = Timer('%s(d)' % name, 'from __main__ import d, %s' % name)
     print name, timer.timeit(1000)


Kent

From alan.gauld at freenet.co.uk  Fri Apr  8 12:18:47 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr  8 12:21:03 2005
Subject: [Tutor] OO newbie
References: <1112901703.4516.55.camel@localhost><00d401c53bb8$2089cc10$46df8751@xp>
	<1112950511.20335.67.camel@obslin15.unige.ch>
Message-ID: <013e01c53c24$5d3598d0$46df8751@xp>

> > super is just a convenience feature added to make Python slightly
> > more like some other OOP languages. It is effectively just a
> > wrapper around the explicit call to the super class:
> >
> > Thus super(C,self...) is the same as
> >
> > dict.__init__(self...)
> after you telling me that dict.__init__(self...) should in your
opinion
> the way to do it.

That's not quite what I said. super has some advantages - it means
you don't need to change code so much if you change the class
heirarchy
and so on. Unfortunately the way super is implemented in Python it
does seem to be less effective in that way than I'd like...

The bottom line is that I *personally* prefer to use explicit calls,
but there is nothing wrong with using super if you find it more
readable.

> type(dict)
> <type 'type'>
> so dict is a class
>
>
> dict.__init__ is the function to initialize a dictionnary
> so
> dict.__init__(self...) initialize the dictionnary `self'. Which work
> because self derive from a dictionnary...
>
> I got it !

Well done. Sometimes you just have to churn the ideas around for
a while until the light comes on.

> I was really lost because I was not clearly making a difference
between
> the class: ``dict'' and an instance of it: ``dict()''

Yes, it might help if Python had used the capitalised name convention
for types, but that was settled a long time before the builtin types
became classes (in v2.2?) so we have to live with the confusion...

Alan G.

From dmalle at bankbii.com  Fri Apr  8 13:09:22 2005
From: dmalle at bankbii.com (Dionysius Malle)
Date: Fri Apr  8 13:08:59 2005
Subject: [Tutor] How to create multi disks zip file
Message-ID: <B95417754EC0D811B2C3000D88CC68D50278B837@UP3EXCG1P>

Hi Brian,

Thanks for the help. I'll get the code.

Ony.

-----Original Message-----
From: Brian van den Broek [mailto:bvande@po-box.mcgill.ca] 
Sent: Friday, April 08, 2005 12:58 PM
To: Dionysius Malle
Cc: tutor@python.org
Subject: Re: [Tutor] How to create multi disks zip file

***********************
Your mail has been scanned by InterScan.
***********-***********


Dionysius Malle said unto the world upon 2005-04-07 21:50:
> Hi,
> 
> I'm a newbie. My friend asked me for a help. He wanted to backup his files
> into multi disks zip file. Is there any possibilities for me to help him
by
> using python?
> 
> TIA,
> 
> Ony

Hi,

I'd separate the zip and split steps.

Chapter 4 of the second edition of Programming Python has a thorough 
discussion of 2 scripts, one for splitting a large file, the other for 
joining the parts. It is a fairly advanced book, but the code is 
pretty clear. You can get the code from the book's website 
<http://www.oreilly.com/catalog/python2/>. It might help get you started.

Best,

Brian vdB
From python at kapitalisten.no  Fri Apr  8 13:11:34 2005
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Fri Apr  8 13:11:33 2005
Subject: [Tutor] GUI-trouble
Message-ID: <27786.193.71.38.142.1112958694.squirrel@mail.sporck.net>

Hello.

I am trying to make a little gui. It has a button and a checkbox. If I
push the button, it is supposed to print the value of the checkbox. But, I
can not seem to get it right. How should I define the variable? Where
should I put it? I have tried every way possible, and gotten lots of
different errormessages.

Thanks in advance
?yvind



from Tkinter import *
import Tix, sys


def vp_start_gui():
    global w
    global root
    root = Tix.Tk()
    root.title('New_Toplevel_1')
    root.geometry('200x205+1157+142')
    w = New_Toplevel_1 (root)
    init()
    root.mainloop()


def message():
    print New_Toplevel_1.v.get()
#   print self.v.get()      This doesn't seem to work either


class New_Toplevel_1:
    def __init__(self, master=None):
        pass

        self.but26 = Button (master)
        self.but26.place(in_=master,x=60,y=30)
        self.but26.configure(command=message)
        self.but26.configure(text="button")

        self.che27 = Checkbutton (master)
        self.che27.place(in_=master,x=50,y=120)
        self.che27.configure(text="check")
        v = IntVar()
        self.che27.configure(variable=v)



if __name__ == '__main__':
    vp_start_gui()


-- 
This email has been scanned for viruses & spam by Decna as - www.decna.no
Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no

From work at infomaniak.ch  Fri Apr  8 13:29:16 2005
From: work at infomaniak.ch (BRINER Cedric)
Date: Fri Apr  8 13:29:23 2005
Subject: [Tutor] dictionary2unicode and unicode2dictionnary
Message-ID: <1112959756.20335.85.camel@obslin15.unige.ch>

hi,

sorry to relaunch this topie but I really need this to work. (o.o)'

how can I have an unicode pickled data ???

e.g.

a={'partition': u'/export/diskH1/home_evol/ricquebo',
'rsmFirstname': u'Fran\xe7ois',
'rsmLastname': u'Ricquebourg',
'size': u'8161222.0',
'size_max': '1'}

<(hint: rsmFirstname = fran?ois)>

import pickle

q=pickle.dumps(a)
>>> type(q)
<type 'str'>
so this is a string

>>> unicode(q)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 64:
ordinal not in range(128)

at position 64
>>> q[:64]
"(dp0\nS'rsmLastname'\np1\nVRicquebourg\np2\nsS'rsmFirstname'\np3
\nVFran"
there is the ? : it's the a special 'c'

In fact, what I really need is the ability to push a dictionary (which
can contain unicode) in a postgres database.

and the sql command given are in unicode. Thus I need to transform a
dictionnary--to-->unicode and then, do the inverse operation
unicode--to-->dictionnary


Cedric BRINER

From kent37 at tds.net  Fri Apr  8 14:08:49 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  8 14:08:52 2005
Subject: [Tutor] OO newbie
In-Reply-To: <00d401c53bb8$2089cc10$46df8751@xp>
References: <1112901703.4516.55.camel@localhost>
	<00d401c53bb8$2089cc10$46df8751@xp>
Message-ID: <42567451.5030605@tds.net>

Alan Gauld wrote:
>>this exemple will also works if you replace the:
>>super(C,self).__init__( *args, **kw)
>>by
>>dict.__init__(self, *args, **kw)
>>
>>but I do not understand this dict.__init_... call.
>>Shouldn't you call the super class constructor??
> 
> 
> super is just a convenience feature added to make Python slightly
> more like some other OOP languages. It is effectively just a
> wrapper around the explicit call to the super class:
> 
> Thus super(C,self...) is the same as
> 
> dict.__init__(self...)


No, super() is much smarter than that and was created to address deficiencies in direct superclass 
calling. super(C, self) actually finds the class that follows C in the method resolution order of 
the class of self. This can be very different from just calling the base class method; in the case 
of multiple inheritance super(C, self) may not ever refer to a base class of C.

For example this program:

class A(object):
     def __init__(self, *args, **kwds):
         print 'A.__init__()'
         super(A, self).__init__(*args, **kwds)

class B(object):
     def __init__(self, *args, **kwds):
         print 'B.__init__()'
         super(B, self).__init__(*args, **kwds)

class C(A, B):
     def __init__(self, *args, **kwds):
         print 'C.__init__()'
         super(C, self).__init__(*args, **kwds)
C()

prints:
C.__init__()
A.__init__()
B.__init__()


For the original question (class SuperDict(dict,A)) this will not help because dict doesn't seem to 
call super(dict, self).__init__(). But if dict is listed as the last base class it works:

class mydict(A, dict):
     def __init__(self, *args, **kwds):
         print 'mydict.__init__()'
         super(mydict, self).__init__(*args, **kwds)

d=mydict(a=1, b=2)
print d

prints:
mydict.__init__()
A.__init__()
{'a': 1, 'b': 2}

so you can see both A.__init__() and dict.__init__() have been called.

For a fairly clear explanation see http://www.python.org/2.2/descrintro.html#cooperation

Kent

From python at venix.com  Fri Apr  8 14:26:24 2005
From: python at venix.com (Lloyd Kvam)
Date: Fri Apr  8 14:26:30 2005
Subject: [Tutor] Talking to mssql
Message-ID: <1112963184.22565.5.camel@laptop.venix.com>

The freetds project talks to Sybase and mssql
http://www.freetds.org/

http://mail.python.org/pipermail/db-sig/2005-April/004403.html
A new sybase module has been released.  Note the instructions for
installing with freetds.


-- 
Lloyd Kvam
Venix Corp

From project5 at redrival.net  Fri Apr  8 14:27:46 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr  8 14:31:49 2005
Subject: [Tutor] Re: Help with classes
References: <d082fff805040710236f7251be@mail.gmail.com>
	<loom.20050407T211337-738@post.gmane.org>
	<6.1.2.0.0.20050407132519.03c3a150@pop.sbcglobal.yahoo.com>
	<loom.20050408T081423-533@post.gmane.org>
	<d082fff8050408010810a955e@mail.gmail.com>
Message-ID: <loom.20050408T140712-699@post.gmane.org>

Kevin <python.programming <at> gmail.com> writes:

> Well this OOP stuff is realy hard for me as I have never even
> programmed it took me a while just to understand defs. However I am
> determined to learn how to do it. My biggest problem is with __init__
> I still don't understand how to use it. Though I did try somthing
> different with my code rather then having the dict of commands in the
> main part of the code, I put it in th __init__ of class Comands like
> so:

__init__ is called when a new instance of that class (an object) is created.
It's particularly useful when used with certain arguments in order to initialize
certain properties of an object. Let's say you have a number of enemies and each
enemy has a certain name and strength. You can then define a class like this:

class Enemy:
    def __init__(self, name, strength):
        self.name = name
        self.strength

and create any number of enemies like this:

enemy1 = Enemy('Gargoyle', 10) # calls __init__
enemy2 = Enemy('Soldier', 3)

If you then ask enemy1 about its name, it wall answer:

>>> print enemy1.name
'Gargoyle'

> When a player type is "get sword" it will add a sword to there
> inventory. Wich I'm not sure if I am going about this the right way.

That part about the sword in the inventory sounds right. Let's do a quick dummy
implementation:

class Player:
    def __init__(self, name, strength):
        self.name = name
        self.inventory = [] # player always starts with empty inventory
        self.strength = strength
    def PickUp(self, item):
        # the player can only cary the amount of stuff around
        # that is allowed by his strength
        if len(self.inventory)==self.strength:
            print "You are not strong enough to pick that up!"
        else:
            self.inventory.append(item)
            print "You've picked up a %s" % item.name

class Item:
    def __init__(self, name):
        self.name = name

conan = Player('Conan the Barbarian', 3)
excalibur = Item('sword')
bottle = Item('bottle of water')
ball = Item('crystal ball')
scroll = Item('ancient scroll')

conan.PickUp(excalibur)
conan.PickUp(ball)
conan.PickUp(scroll)
conan.PickUp(bottle) # will fail

donan = Player('Donan the Civilized', 2) # different player!
donan.PickUp(bottle) # can pick it up, because donan != conan



(The implementation above has some obvious problems, like not being able to drop
anything, a sword demanding just as much strength as a bottle and most
importantly the fact that donan will be able to pick up excalibur even though
conan already has it.) 
You can see that conan and donan are both players (Player objects), but each of
them has his own name, inventory and strength. Even if conan's inventory is
full, donan can still pick up new things.

Yours,

Andrei

From kristian.zoerhoff at gmail.com  Fri Apr  8 14:47:31 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Fri Apr  8 14:47:34 2005
Subject: [Tutor] dictionary2unicode and unicode2dictionnary
In-Reply-To: <1112959756.20335.85.camel@obslin15.unige.ch>
References: <1112959756.20335.85.camel@obslin15.unige.ch>
Message-ID: <3511dc7505040805473ad5843b@mail.gmail.com>

On Apr 8, 2005 6:29 AM, BRINER Cedric <work@infomaniak.ch> wrote:
> 
> <(hint: rsmFirstname = fran?ois)>
> 
> import pickle
> 
> q=pickle.dumps(a)
> >>> type(q)
> <type 'str'>
> so this is a string
> 
> >>> unicode(q)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 64:
> ordinal not in range(128)

Call unicode() with an encoding that can handle the character in question:

>>>unicode(q, 'latin-1')

and it should work just fine (I just tested this in pythonwin).

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From albertito_g at hotmail.com  Fri Apr  8 16:35:58 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr  8 16:36:03 2005
Subject: [Tutor] Support
Message-ID: <BAY106-F184E80FF733B120689AE22893F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/11207e38/attachment.htm
From bvande at po-box.mcgill.ca  Fri Apr  8 17:03:39 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Fri Apr  8 17:05:38 2005
Subject: [Tutor] Support
In-Reply-To: <BAY106-F184E80FF733B120689AE22893F0@phx.gbl>
References: <BAY106-F184E80FF733B120689AE22893F0@phx.gbl>
Message-ID: <42569D4B.5010203@po-box.mcgill.ca>

Alberto Troiano said unto the world upon 2005-04-08 10:35:
> I am trying to make an application with Python 2.3.4, PIL 1.1.5 and
> I want to convert an image file to binary so I can store it in a
> MySQL database and then retrieve it and show it from binary to
> Image again so I can show the image
> 
> Please help
> 
> Thanks
> 
> Alberto

Hi Alberto,

It will be much easier for people to help if you describe what you
have tried and where you are having problems. Ideally, show the list
some of what you have done -- that will give those responding
something from which to start.

Best,

Brian vdB

From albertito_g at hotmail.com  Fri Apr  8 17:31:42 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr  8 17:31:47 2005
Subject: [Tutor] Support
In-Reply-To: <42569D4B.5010203@po-box.mcgill.ca>
Message-ID: <BAY106-F2060EA6AEC136651471C05893F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/42201ce3/attachment.html
From geek_show at dsl.pipex.com  Fri Apr  8 17:55:26 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Fri Apr  8 17:54:10 2005
Subject: [Tutor] Recursive list checking
Message-ID: <4256A96E.7000408@dsl.pipex.com>

Dear Pythonites

I am looking for a more elegant solution to a piece of code that is too 
unwieldy and reptitive. The purpose of the code is for a new addition to 
a list to check whether it is a duplicate of a list element already a 
member of that list, and if so to regenerate itself randomly and to 
perform the same check again until such time as it is unique.
For example, this is what I am currently doing:

=============code block ========================

    # generate unique numbers and append to list
    nmbr01 = random.randrange( 1, 20 )
    nmbr_list.append( nmbr01 )

    nmbr02 = random.randrange( 1, 20 )
    # check for duplicates and re-generate a number if needed
    while nmbr02 in nmbr_list:
        nmbr02 = random.randrange( 1, 20 )
    nmbr_list.append( nmbr02 )

    nmbr03 = random.randrange( 1, 20 )
    while nmbr03 in nmbr_list:
        nmbr03 = random.randrange( 1, 20 )
    nmbr.append( nmbr03 )

================================================

This method works, but increasing the numbers to be appended makes the 
code excessively long. I can't see anything in list methods that seems 
to do the trick, so anybody want to make a suggestion please?

TIA
/j
From kent37 at tds.net  Fri Apr  8 17:59:24 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  8 17:59:29 2005
Subject: [Tutor] Support
In-Reply-To: <BAY106-F2060EA6AEC136651471C05893F0@phx.gbl>
References: <BAY106-F2060EA6AEC136651471C05893F0@phx.gbl>
Message-ID: <4256AA5C.9060300@tds.net>

Alberto Troiano wrote:
> I tried the code below but the image gets messed up:
> 
> import Image
> 
> im=Image.open("auto.jpg")
> 
> im.show() ###This is to show the image so you can see it
> 
> m=im.tostring()
> 
> ima=Image.fromstring("RGB",im.size,m)###I tried also with F,RGBA 
> and L mode instead of RGB

maybe ima=Image.fromstring(im.mode,im.size,m) will work...

Kent

From geek_show at dsl.pipex.com  Fri Apr  8 18:10:29 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Fri Apr  8 18:09:14 2005
Subject: [Tutor] comparison function/built-in needed
In-Reply-To: <42543623.2030600@tds.net>
References: <425427B7.1010303@dsl.pipex.com> <42543623.2030600@tds.net>
Message-ID: <4256ACF5.8000603@dsl.pipex.com>

Kent Johnson wrote:
> joe_schmoe wrote:
> 
>> Greetings
>>
>> I am attempting to compare the items in two lists across two criteria 
>> - membership and position. For example:
>>
>> list_a = [ 0, 4, 3, 6, 8 ]
>> list_b = [ 1, 8, 4, 6, 2 ]
>>
>> Membership = There are 3 items that are common to both lists, that is 
>> 3 items in list_a have membership in list_b (viz: 4, 6, 8);
> 
> 
> Use sets:
>  >>> list_a = [ 0, 4, 3, 6, 8 ]
>  >>> list_b = [ 1, 8, 4, 6, 2 ]
>  >>> set(list_a).intersection(list_b)
> set([8, 4, 6])
> 
>> Position = There is 1 item in list_a that is also in the same position 
>> in both lists (viz: 6).
> 
> 
> Use zip() to iterate two lists in parallel and a list comprehension to 
> accumulate the results:
>  >>> [ a for a, b in zip(list_a, list_b) if a==b ]
> [6]
> 
> or if you want the position of the item use enumerate() to get the index:
>  >>> [ i for i, (a, b) in enumerate(zip(list_a, list_b)) if a==b ]
> [3]
> 
> Kent
> 
> 
Hi Kent

Just to confirm: this works just great - thanks!! :)

/j
From maitj at vianet.ca  Fri Apr  8 18:11:38 2005
From: maitj at vianet.ca (Jeffrey Maitland)
Date: Fri Apr  8 18:11:41 2005
Subject: [Tutor] Re: Recursive list checking
In-Reply-To: <4256A96E.7000408@dsl.pipex.com>
References: <4256A96E.7000408@dsl.pipex.com>
Message-ID: <20050408161138.16866.qmail@mail.vianet.ca>

joe_schmoe writes: 

> Dear Pythonites 
> 
> I am looking for a more elegant solution to a piece of code that is too 
> unwieldy and reptitive. The purpose of the code is for a new addition to a 
> list to check whether it is a duplicate of a list element already a member 
> of that list, and if so to regenerate itself randomly and to perform the 
> same check again until such time as it is unique.
> For example, this is what I am currently doing: 
> 
> =============code block ======================== 
> 
>    # generate unique numbers and append to list
>    nmbr01 = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 ) 
> 
>    nmbr02 = random.randrange( 1, 20 )
>    # check for duplicates and re-generate a number if needed
>    while nmbr02 in nmbr_list:
>        nmbr02 = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr02 ) 
> 
>    nmbr03 = random.randrange( 1, 20 )
>    while nmbr03 in nmbr_list:
>        nmbr03 = random.randrange( 1, 20 )
>    nmbr.append( nmbr03 ) 
> 
> ================================================ 
> 
> This method works, but increasing the numbers to be appended makes the 
> code excessively long. I can't see anything in list methods that seems to 
> do the trick, so anybody want to make a suggestion please? 
> 
> TIA
> /j
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Well I would start by doing something like. 

nmbr_list = []
value = int(raw_input("Input the number of items you wish to generate")) 

for i in range(value):
  if i == 0:
    nmbr = random.randrange( 1, 20 )
    nmbr_list.append( nmbr01 )
  else:
     nmbr = random.randrange( 1, 20 )
     # check for duplicates and re-generate a number if needed
     while nmbr in nmbr_list:
        nmbr = random.randrange( 1, 20 )
     nmbr_list.append( nmbr ) 

I hope that helps. or gives you an idea.
Jeff 

From maitj at vianet.ca  Fri Apr  8 18:17:40 2005
From: maitj at vianet.ca (Jeffrey Maitland)
Date: Fri Apr  8 18:17:43 2005
Subject: [Tutor] Re: Recursive list checking
In-Reply-To: <20050408161138.16866.qmail@mail.vianet.ca>
References: <4256A96E.7000408@dsl.pipex.com>
	<20050408161138.16866.qmail@mail.vianet.ca>
Message-ID: <20050408161740.31381.qmail@mail.vianet.ca>

Jeffrey Maitland writes: 

> joe_schmoe writes:  
> 
>> Dear Pythonites  
>> 
>> I am looking for a more elegant solution to a piece of code that is too 
>> unwieldy and reptitive. The purpose of the code is for a new addition to 
>> a list to check whether it is a duplicate of a list element already a 
>> member of that list, and if so to regenerate itself randomly and to 
>> perform the same check again until such time as it is unique.
>> For example, this is what I am currently doing:  
>> 
>> =============code block ========================  
>> 
>>    # generate unique numbers and append to list
>>    nmbr01 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr01 )  
>> 
>>    nmbr02 = random.randrange( 1, 20 )
>>    # check for duplicates and re-generate a number if needed
>>    while nmbr02 in nmbr_list:
>>        nmbr02 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr02 )  
>> 
>>    nmbr03 = random.randrange( 1, 20 )
>>    while nmbr03 in nmbr_list:
>>        nmbr03 = random.randrange( 1, 20 )
>>    nmbr.append( nmbr03 )  
>> 
>> ================================================  
>> 
>> This method works, but increasing the numbers to be appended makes the 
>> code excessively long. I can't see anything in list methods that seems to 
>> do the trick, so anybody want to make a suggestion please?  
>> 
>> TIA
>> /j
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
> 
> Well I would start by doing something like.  
> 
> nmbr_list = []
> value = int(raw_input("Input the number of items you wish to generate"))  
> 
> for i in range(value):
>  if i == 0:
>    nmbr = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 )
>  else:
>     nmbr = random.randrange( 1, 20 )
>     # check for duplicates and re-generate a number if needed
>     while nmbr in nmbr_list:
>        nmbr = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr )  
> 
> I hope that helps. or gives you an idea.
> Jeff  
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Err just noted that I screwed up on my idea.. here.. is a better party same 
idea edited some. 

nmbr_list = []
value = int(raw_input("Input the number of items you wish to generate")) 

# so this loops the value specified times, as this will add that number to 
list too.  so a range of 1 - 20 in random order if 20 is the sepcified 
number.
for i in range(value):
if i == 0:
  nmbr = random.randrange( 1, value )
  nmbr_list.append( nmbr )
else:
   nmbr = random.randrange( 1, value )
   # check for duplicates and re-generate a number if needed
   while nmbr in nmbr_list:
      nmbr = random.randrange( 1, value )
   nmbr_list.append( nmbr ) 


Jeff 

also feel free to ask me more speicifc questions via email if you think they 
won't help the cominity at all. 

From marilyn at deliberate.com  Fri Apr  8 18:16:30 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Fri Apr  8 18:24:36 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <42565623.8000607@tds.net>
Message-ID: <Pine.LNX.4.44.0504080915410.18776-100000@Kuna>

On Fri, 8 Apr 2005, Kent Johnson wrote:

> Marilyn Davis wrote:
> > Is there a reason to prefer one over the other?  Is one faster?  I
> > compiled my regular expression to make it quicker.
> 
> The only way to know which is faster is to time them both. The timeit module makes it pretty easy to 
> do this.
> 
> Here is a simple example of using timeit for a different problem; you can adapt it to your own needs:

Thank you so much again.

This will be handy.

Marilyn

> 
> d = dict( ((i,i,i), i) for i in range(1000))
> 
> def withItems(d):
>      for k,v in d.iteritems():
>          pass
> 
> 
> def withKeys(d):
>      for k in d:
>          d[k]
> 
> 
> from timeit import Timer
> 
> for fn in [withItems, withKeys]:
>      name = fn.__name__
>      timer = Timer('%s(d)' % name, 'from __main__ import d, %s' % name)
>      print name, timer.timeit(1000)
> 
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 

From kent37 at tds.net  Fri Apr  8 19:26:30 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  8 19:26:33 2005
Subject: [Tutor] Re: Recursive list checking
In-Reply-To: <20050408161138.16866.qmail@mail.vianet.ca>
References: <4256A96E.7000408@dsl.pipex.com>
	<20050408161138.16866.qmail@mail.vianet.ca>
Message-ID: <4256BEC6.7010906@tds.net>

Jeffrey Maitland wrote:
> joe_schmoe writes:
> 
>> Dear Pythonites
>> I am looking for a more elegant solution to a piece of code that is 
>> too unwieldy and reptitive. The purpose of the code is for a new 
>> addition to a list to check whether it is a duplicate of a list 
>> element already a member of that list, and if so to regenerate itself 
>> randomly and to perform the same check again until such time as it is 
>> unique.
>> For example, this is what I am currently doing:
>> =============code block ========================
>>    # generate unique numbers and append to list
>>    nmbr01 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr01 )
>>    nmbr02 = random.randrange( 1, 20 )
>>    # check for duplicates and re-generate a number if needed
>>    while nmbr02 in nmbr_list:
>>        nmbr02 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr02 )
>>    nmbr03 = random.randrange( 1, 20 )
>>    while nmbr03 in nmbr_list:
>>        nmbr03 = random.randrange( 1, 20 )
>>    nmbr.append( nmbr03 )
>> ================================================
>> This method works, but increasing the numbers to be appended makes the 
>> code excessively long. I can't see anything in list methods that seems 
>> to do the trick, so anybody want to make a suggestion please?
>> TIA
>> /j
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> Well I would start by doing something like.
> nmbr_list = []
> value = int(raw_input("Input the number of items you wish to generate"))
> for i in range(value):
>  if i == 0:
>    nmbr = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 )
>  else:
>     nmbr = random.randrange( 1, 20 )
>     # check for duplicates and re-generate a number if needed
>     while nmbr in nmbr_list:
>        nmbr = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr )
> I hope that helps. or gives you an idea.

The special case for i==0 is not needed, in this case the test for nmbr in nmbr_list will fail and 
nmbr will be added to the list.

But if you are trying to get n random elements from range(m) you are probably better off using 
random.sample(), I think it does exactly what you want:
  >>> random.sample(xrange(10000000), 10)
[274075, 2925710, 7715591, 8236811, 1161108, 5804222, 2385884, 9236087, 5603149, 8473299]

If you actually want *all* elements of the range in random order, use random.shuffle():
  >>> l=range(20)
  >>> random.shuffle(l)
  >>> l
[13, 7, 6, 9, 3, 10, 1, 8, 4, 0, 18, 12, 11, 17, 19, 5, 16, 15, 2, 14]

You might also want to look at random.choice()...

Kent

From luke.jordan at gmail.com  Fri Apr  8 19:37:29 2005
From: luke.jordan at gmail.com (Luke Jordan)
Date: Fri Apr  8 19:37:34 2005
Subject: [Tutor] Associate functinos with Dictionary/Class Usage
In-Reply-To: <Pine.LNX.4.44.0504071633490.28274-100000@hkn.eecs.berkeley.edu>
References: <ea0feb800504071445217fe4b9@mail.gmail.com>
	<Pine.LNX.4.44.0504071633490.28274-100000@hkn.eecs.berkeley.edu>
Message-ID: <ea0feb80050408103762540e70@mail.gmail.com>

Yes, Danny - that makes sense. I was getting hung up how to handle the
parens in this part

dict['some'](thing)

all clear now.

:-)

On Apr 7, 2005 4:40 PM, Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
> On Thu, 7 Apr 2005, Luke Jordan wrote:
> 
> > I am looking for a little clarification of how exactly this would work.
> >
> > 1. How do I associate a function to a dict key?
> 
> Hi Luke,
> 
> We're probably already familiar of values like numbers and strings, and
> how to give them names with variables:
> 
> ######
> >>> number = 42
> >>> name = "luke"
> >>> number
> 42
> >>> name
> 'luke'
> ######
> 
> 'number' is a name that refers to the value 42, and 'name' is a name (Doh!
> I must use a better variable name next time...) that refers to the value
> "luke".
> 
> And we also already know how to make functions and to call them:
> 
> ######
> >>> def square(x):
> ...     return x * x
> ...
> >>> square(42)
> 1764
> ######
> 
> But what happens if we just say "square" at the interpreter?
> 
> ######
> >>> square
> <function square at 0x40300b1c>
> ######
> 
> The value of 'square' is a function value.
> 
> And just like any other value, we can assign it to another name:
> 
> ######
> >>> anotherNameForSquare = square
> >>> anotherNameForSquare(16)
> 256
> ######
> 
> And just like any other value, we can use it as a dictionary value:
> 
> ######
> >>> operators = {'^2': square}
> >>> operators['^2']
> <function square at 0x40300b1c>
> >>> operators['^2'](4)
> 16
> ######
> 
> Does this make sense so far?  Please feel free to ask more questions about
> this.  Best of wishes!
> 
> 


-- 
"Scalpel....blood bucket....priest....next patient."
From jsoares at Safe-mail.net  Fri Apr  8 20:49:50 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Fri Apr  8 20:49:57 2005
Subject: [Tutor] Re: IDLE crashing suddenly
Message-ID: <N1-OlnVGfdL@Safe-mail.net>

I've noticed that after 20 or 30 compile/link/execute runs, IDLE crashes. This seems to happen pretty consistently. At the time, I'm not doing anything that might cause it to crash. Does this happen to anyone else? What causes it? Is it just a bug? I have IDLE version 1.1.1 which came with Python 2.4. Thanks. John Soares jsoares@safe-mail.net 

-------- Original Message --------
From: tutor-request@python.org
Apparently from: tutor-bounces@python.org
To: tutor@python.org
Subject: Tutor Digest, Vol 14, Issue 25
Date: Fri,  8 Apr 2005 19:37:37 +0200 (CEST)

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: Support (Alberto Troiano)
2. Recursive list checking (joe_schmoe)
3. Re: Support (Kent Johnson)
4. Re: comparison function/built-in needed (joe_schmoe)
5. Re: Recursive list checking (Jeffrey Maitland)
6. Re: Recursive list checking (Jeffrey Maitland)
7. Re: str.split and quotes (Marilyn Davis)
8. Re: Re: Recursive list checking (Kent Johnson)
9. Re: Associate functinos with Dictionary/Class Usage (Luke Jordan)


----------------------------------------------------------------------

Message: 1
Date: Fri, 08 Apr 2005 15:31:42 +0000
From: "Alberto Troiano" 
Subject: Re: [Tutor] Support
To: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset="us-ascii"

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/42201ce3/attachment-0001.html

------------------------------

Message: 2
Date: Fri, 08 Apr 2005 16:55:26 +0100
From: joe_schmoe 
Subject: [Tutor] Recursive list checking
To: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Dear Pythonites

I am looking for a more elegant solution to a piece of code that is too 
unwieldy and reptitive. The purpose of the code is for a new addition to 
a list to check whether it is a duplicate of a list element already a 
member of that list, and if so to regenerate itself randomly and to 
perform the same check again until such time as it is unique.
For example, this is what I am currently doing:

=============code block ========================

# generate unique numbers and append to list
nmbr01 = random.randrange( 1, 20 )
nmbr_list.append( nmbr01 )

nmbr02 = random.randrange( 1, 20 )
# check for duplicates and re-generate a number if needed
while nmbr02 in nmbr_list:
nmbr02 = random.randrange( 1, 20 )
nmbr_list.append( nmbr02 )

nmbr03 = random.randrange( 1, 20 )
while nmbr03 in nmbr_list:
nmbr03 = random.randrange( 1, 20 )
nmbr.append( nmbr03 )

================================================

This method works, but increasing the numbers to be appended makes the 
code excessively long. I can't see anything in list methods that seems 
to do the trick, so anybody want to make a suggestion please?

TIA
/j


------------------------------

Message: 3
Date: Fri, 08 Apr 2005 11:59:24 -0400
From: Kent Johnson 
Subject: Re: [Tutor] Support
Cc: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Alberto Troiano wrote:
> I tried the code below but the image gets messed up:
> 
> import Image
> 
> im=Image.open("auto.jpg")
> 
> im.show() ###This is to show the image so you can see it
> 
> m=im.tostring()
> 
> ima=Image.fromstring("RGB",im.size,m)###I tried also with F,RGBA 
> and L mode instead of RGB

maybe ima=Image.fromstring(im.mode,im.size,m) will work...

Kent



------------------------------

Message: 4
Date: Fri, 08 Apr 2005 17:10:29 +0100
From: joe_schmoe 
Subject: Re: [Tutor] comparison function/built-in needed
To: Kent Johnson 
Cc: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Kent Johnson wrote:
> joe_schmoe wrote:
> 
>> Greetings
>>
>> I am attempting to compare the items in two lists across two criteria 
>> - membership and position. For example:
>>
>> list_a = [ 0, 4, 3, 6, 8 ]
>> list_b = [ 1, 8, 4, 6, 2 ]
>>
>> Membership = There are 3 items that are common to both lists, that is 
>> 3 items in list_a have membership in list_b (viz: 4, 6, 8);
> 
> 
> Use sets:
>  >>> list_a = [ 0, 4, 3, 6, 8 ]
>  >>> list_b = [ 1, 8, 4, 6, 2 ]
>  >>> set(list_a).intersection(list_b)
> set([8, 4, 6])
> 
>> Position = There is 1 item in list_a that is also in the same position 
>> in both lists (viz: 6).
> 
> 
> Use zip() to iterate two lists in parallel and a list comprehension to 
> accumulate the results:
>  >>> [ a for a, b in zip(list_a, list_b) if a==b ]
> [6]
> 
> or if you want the position of the item use enumerate() to get the index:
>  >>> [ i for i, (a, b) in enumerate(zip(list_a, list_b)) if a==b ]
> [3]
> 
> Kent
> 
> 
Hi Kent

Just to confirm: this works just great - thanks!! :)

/j


------------------------------

Message: 5
Date: Fri, 08 Apr 2005 12:11:38 -0400
From: "Jeffrey Maitland" 
Subject: [Tutor] Re: Recursive list checking
To: tutor@python.org
Message-ID: 
Content-Type: text/plain; format=flowed; charset="iso-8859-1"

joe_schmoe writes: 

> Dear Pythonites 
> 
> I am looking for a more elegant solution to a piece of code that is too 
> unwieldy and reptitive. The purpose of the code is for a new addition to a 
> list to check whether it is a duplicate of a list element already a member 
> of that list, and if so to regenerate itself randomly and to perform the 
> same check again until such time as it is unique.
> For example, this is what I am currently doing: 
> 
> =============code block ======================== 
> 
>    # generate unique numbers and append to list
>    nmbr01 = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 ) 
> 
>    nmbr02 = random.randrange( 1, 20 )
>    # check for duplicates and re-generate a number if needed
>    while nmbr02 in nmbr_list:
>        nmbr02 = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr02 ) 
> 
>    nmbr03 = random.randrange( 1, 20 )
>    while nmbr03 in nmbr_list:
>        nmbr03 = random.randrange( 1, 20 )
>    nmbr.append( nmbr03 ) 
> 
> ================================================ 
> 
> This method works, but increasing the numbers to be appended makes the 
> code excessively long. I can't see anything in list methods that seems to 
> do the trick, so anybody want to make a suggestion please? 
> 
> TIA
> /j
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Well I would start by doing something like. 

nmbr_list = []
value = int(raw_input("Input the number of items you wish to generate")) 

for i in range(value):
if i == 0:
nmbr = random.randrange( 1, 20 )
nmbr_list.append( nmbr01 )
else:
nmbr = random.randrange( 1, 20 )
# check for duplicates and re-generate a number if needed
while nmbr in nmbr_list:
nmbr = random.randrange( 1, 20 )
nmbr_list.append( nmbr ) 

I hope that helps. or gives you an idea.
Jeff 



------------------------------

Message: 6
Date: Fri, 08 Apr 2005 12:17:40 -0400
From: "Jeffrey Maitland" 
Subject: [Tutor] Re: Recursive list checking
To: "Jeffrey Maitland" 
Cc: tutor@python.org
Message-ID: 
Content-Type: text/plain; format=flowed; charset="iso-8859-1"

Jeffrey Maitland writes: 

> joe_schmoe writes:  
> 
>> Dear Pythonites  
>> 
>> I am looking for a more elegant solution to a piece of code that is too 
>> unwieldy and reptitive. The purpose of the code is for a new addition to 
>> a list to check whether it is a duplicate of a list element already a 
>> member of that list, and if so to regenerate itself randomly and to 
>> perform the same check again until such time as it is unique.
>> For example, this is what I am currently doing:  
>> 
>> =============code block ========================  
>> 
>>    # generate unique numbers and append to list
>>    nmbr01 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr01 )  
>> 
>>    nmbr02 = random.randrange( 1, 20 )
>>    # check for duplicates and re-generate a number if needed
>>    while nmbr02 in nmbr_list:
>>        nmbr02 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr02 )  
>> 
>>    nmbr03 = random.randrange( 1, 20 )
>>    while nmbr03 in nmbr_list:
>>        nmbr03 = random.randrange( 1, 20 )
>>    nmbr.append( nmbr03 )  
>> 
>> ================================================  
>> 
>> This method works, but increasing the numbers to be appended makes the 
>> code excessively long. I can't see anything in list methods that seems to 
>> do the trick, so anybody want to make a suggestion please?  
>> 
>> TIA
>> /j
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
> 
> Well I would start by doing something like.  
> 
> nmbr_list = []
> value = int(raw_input("Input the number of items you wish to generate"))  
> 
> for i in range(value):
>  if i == 0:
>    nmbr = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 )
>  else:
>     nmbr = random.randrange( 1, 20 )
>     # check for duplicates and re-generate a number if needed
>     while nmbr in nmbr_list:
>        nmbr = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr )  
> 
> I hope that helps. or gives you an idea.
> Jeff  
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Err just noted that I screwed up on my idea.. here.. is a better party same 
idea edited some. 

nmbr_list = []
value = int(raw_input("Input the number of items you wish to generate")) 

# so this loops the value specified times, as this will add that number to 
list too.  so a range of 1 - 20 in random order if 20 is the sepcified 
number.
for i in range(value):
if i == 0:
nmbr = random.randrange( 1, value )
nmbr_list.append( nmbr )
else:
nmbr = random.randrange( 1, value )
# check for duplicates and re-generate a number if needed
while nmbr in nmbr_list:
nmbr = random.randrange( 1, value )
nmbr_list.append( nmbr ) 


Jeff 

also feel free to ask me more speicifc questions via email if you think they 
won't help the cominity at all. 



------------------------------

Message: 7
Date: Fri, 8 Apr 2005 09:16:30 -0700 (PDT)
From: Marilyn Davis 
Subject: Re: [Tutor] str.split and quotes
To: Kent Johnson 
Cc: tutor@python.org
Message-ID: 
Content-Type: TEXT/PLAIN; charset=US-ASCII

On Fri, 8 Apr 2005, Kent Johnson wrote:

> Marilyn Davis wrote:
> > Is there a reason to prefer one over the other?  Is one faster?  I
> > compiled my regular expression to make it quicker.
> 
> The only way to know which is faster is to time them both. The timeit module makes it pretty easy to 
> do this.
> 
> Here is a simple example of using timeit for a different problem; you can adapt it to your own needs:

Thank you so much again.

This will be handy.

Marilyn

> 
> d = dict( ((i,i,i), i) for i in range(1000))
> 
> def withItems(d):
>      for k,v in d.iteritems():
>          pass
> 
> 
> def withKeys(d):
>      for k in d:
>          d[k]
> 
> 
> from timeit import Timer
> 
> for fn in [withItems, withKeys]:
>      name = fn.__name__
>      timer = Timer('%s(d)' % name, 'from __main__ import d, %s' % name)
>      print name, timer.timeit(1000)
> 
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 



------------------------------

Message: 8
Date: Fri, 08 Apr 2005 13:26:30 -0400
From: Kent Johnson 
Subject: Re: [Tutor] Re: Recursive list checking
Cc: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Jeffrey Maitland wrote:
> joe_schmoe writes:
> 
>> Dear Pythonites
>> I am looking for a more elegant solution to a piece of code that is 
>> too unwieldy and reptitive. The purpose of the code is for a new 
>> addition to a list to check whether it is a duplicate of a list 
>> element already a member of that list, and if so to regenerate itself 
>> randomly and to perform the same check again until such time as it is 
>> unique.
>> For example, this is what I am currently doing:
>> =============code block ========================
>>    # generate unique numbers and append to list
>>    nmbr01 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr01 )
>>    nmbr02 = random.randrange( 1, 20 )
>>    # check for duplicates and re-generate a number if needed
>>    while nmbr02 in nmbr_list:
>>        nmbr02 = random.randrange( 1, 20 )
>>    nmbr_list.append( nmbr02 )
>>    nmbr03 = random.randrange( 1, 20 )
>>    while nmbr03 in nmbr_list:
>>        nmbr03 = random.randrange( 1, 20 )
>>    nmbr.append( nmbr03 )
>> ================================================
>> This method works, but increasing the numbers to be appended makes the 
>> code excessively long. I can't see anything in list methods that seems 
>> to do the trick, so anybody want to make a suggestion please?
>> TIA
>> /j
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> Well I would start by doing something like.
> nmbr_list = []
> value = int(raw_input("Input the number of items you wish to generate"))
> for i in range(value):
>  if i == 0:
>    nmbr = random.randrange( 1, 20 )
>    nmbr_list.append( nmbr01 )
>  else:
>     nmbr = random.randrange( 1, 20 )
>     # check for duplicates and re-generate a number if needed
>     while nmbr in nmbr_list:
>        nmbr = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr )
> I hope that helps. or gives you an idea.

The special case for i==0 is not needed, in this case the test for nmbr in nmbr_list will fail and 
nmbr will be added to the list.

But if you are trying to get n random elements from range(m) you are probably better off using 
random.sample(), I think it does exactly what you want:
>>> random.sample(xrange(10000000), 10)
[274075, 2925710, 7715591, 8236811, 1161108, 5804222, 2385884, 9236087, 5603149, 8473299]

If you actually want *all* elements of the range in random order, use random.shuffle():
>>> l=range(20)
>>> random.shuffle(l)
>>> l
[13, 7, 6, 9, 3, 10, 1, 8, 4, 0, 18, 12, 11, 17, 19, 5, 16, 15, 2, 14]

You might also want to look at random.choice()...

Kent



------------------------------

Message: 9
Date: Fri, 8 Apr 2005 10:37:29 -0700
From: Luke Jordan 
Subject: Re: [Tutor] Associate functinos with Dictionary/Class Usage
To: Danny Yoo 
Cc: tutor@python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1

Yes, Danny - that makes sense. I was getting hung up how to handle the
parens in this part

dict['some'](thing)

all clear now.

:-)

On Apr 7, 2005 4:40 PM, Danny Yoo  wrote:
> 
> 
> On Thu, 7 Apr 2005, Luke Jordan wrote:
> 
> > I am looking for a little clarification of how exactly this would work.
> >
> > 1. How do I associate a function to a dict key?
> 
> Hi Luke,
> 
> We're probably already familiar of values like numbers and strings, and
> how to give them names with variables:
> 
> ######
> >>> number = 42
> >>> name = "luke"
> >>> number
> 42
> >>> name
> 'luke'
> ######
> 
> 'number' is a name that refers to the value 42, and 'name' is a name (Doh!
> I must use a better variable name next time...) that refers to the value
> "luke".
> 
> And we also already know how to make functions and to call them:
> 
> ######
> >>> def square(x):
> ...     return x * x
> ...
> >>> square(42)
> 1764
> ######
> 
> But what happens if we just say "square" at the interpreter?
> 
> ######
> >>> square
> 
> ######
> 
> The value of 'square' is a function value.
> 
> And just like any other value, we can assign it to another name:
> 
> ######
> >>> anotherNameForSquare = square
> >>> anotherNameForSquare(16)
> 256
> ######
> 
> And just like any other value, we can use it as a dictionary value:
> 
> ######
> >>> operators = {'^2': square}
> >>> operators['^2']
> 
> >>> operators['^2'](4)
> 16
> ######
> 
> Does this make sense so far?  Please feel free to ask more questions about
> this.  Best of wishes!
> 
> 


-- 
"Scalpel....blood bucket....priest....next patient."


------------------------------

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


End of Tutor Digest, Vol 14, Issue 25
*************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/4e9a3581/attachment-0001.htm
From albertito_g at hotmail.com  Fri Apr  8 20:56:29 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr  8 20:56:32 2005
Subject: [Tutor] Support
In-Reply-To: <4256AA5C.9060300@tds.net>
Message-ID: <BAY106-F2803A73EE9DD7946B3CA78893F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/555bd4aa/attachment.html
From rmuller at sandia.gov  Fri Apr  8 20:54:15 2005
From: rmuller at sandia.gov (Rick Muller)
Date: Fri Apr  8 20:58:26 2005
Subject: [Tutor] Recursive list checking
In-Reply-To: <20050408173738.392F01E400A@bag.python.org>
References: <20050408173738.392F01E400A@bag.python.org>
Message-ID: <9A8A15A8-A85F-11D9-83E2-000A95823962@sandia.gov>


On Apr 8, 2005, at 11:37 AM, tutor-request@python.org wrote:
> From: joe_schmoe <geek_show@dsl.pipex.com>
> For example, this is what I am currently doing:
>
> =============code block ========================
>
>     # generate unique numbers and append to list
>     nmbr01 = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr01 )
>
>     nmbr02 = random.randrange( 1, 20 )
>     # check for duplicates and re-generate a number if needed
>     while nmbr02 in nmbr_list:
>         nmbr02 = random.randrange( 1, 20 )
>     nmbr_list.append( nmbr02 )
>
>     nmbr03 = random.randrange( 1, 20 )
>     while nmbr03 in nmbr_list:
>         nmbr03 = random.randrange( 1, 20 )
>     nmbr.append( nmbr03 )
>
> ================================================
>

Since you want unique entries, couldn't you just do something like

def unique_entries(n,start=1,stop=20):
     "Generate n unique entries in range(1,20)"
     from random import shuffle
     l = range(start,stop)
     shuffle(l)
     return l[:n]


From maitj at vianet.ca  Fri Apr  8 21:00:19 2005
From: maitj at vianet.ca (Jeffrey Maitland)
Date: Fri Apr  8 21:00:24 2005
Subject: [Tutor] Re: Support
In-Reply-To: <BAY106-F2803A73EE9DD7946B3CA78893F0@phx.gbl>
References: <BAY106-F2803A73EE9DD7946B3CA78893F0@phx.gbl>
Message-ID: <20050408190019.25731.qmail@mail.vianet.ca>

Alberto Troiano writes: 

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

I would personally use a blob.  That is why they are there. To store that 
binary data.  I am sure you could use a longtext but this way space should 
not be an issue to fit images in there. 

Jeff 


From kent37 at tds.net  Fri Apr  8 21:04:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr  8 21:04:46 2005
Subject: [Tutor] Support
In-Reply-To: <BAY106-F2803A73EE9DD7946B3CA78893F0@phx.gbl>
References: <BAY106-F2803A73EE9DD7946B3CA78893F0@phx.gbl>
Message-ID: <4256D5CA.8090605@tds.net>

Alberto Troiano wrote:
> Thanks
> 
> Apparently it worked but one question do
> 
> What kind of data is the return of the function tostring()????

It's a string
> 
> Can i put it in a blob type of a database????or maybe in a longtext??

I would try longtext.

Kent

From 3dbernard at gmail.com  Fri Apr  8 21:05:13 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri Apr  8 21:05:16 2005
Subject: [Tutor] Class - superclass
Message-ID: <61d0e2b4050408120579512e29@mail.gmail.com>

Hello,

I'm experimenting with basic inheritance concepts, and something that
I would assume to work returns an error.


>>> class A:
...     def __init__( self ):
...             self.a = 13
...
>>> class B( A ): # create sub-class of class A
...     def __init__( self ):
...             self.b = 14
...
>>>
>>>
>>>
>>> b = B() # create instance of class B
>>> b.a # here I would expect the class A's a attibute to be accessible...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: B instance has no attribute 'a'



Anyone can shed any light on this? Using Python 2.3.4.


Thanks
Bernard
From albertito_g at hotmail.com  Fri Apr  8 21:07:00 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr  8 21:07:04 2005
Subject: [Tutor] Re: Support
In-Reply-To: <20050408190019.25731.qmail@mail.vianet.ca>
Message-ID: <BAY106-F7FC1C4A57E6B0AF6DFFAD893F0@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/e8655a87/attachment.htm
From project5 at redrival.net  Fri Apr  8 21:48:04 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr  8 21:50:21 2005
Subject: [Tutor] Re: Class - superclass
References: <61d0e2b4050408120579512e29@mail.gmail.com>
Message-ID: <74zrmw46rgns$.1w95nxzewehhf$.dlg@40tude.net>

Bernard Lebel wrote on Fri, 8 Apr 2005 15:05:13 -0400:

> I'm experimenting with basic inheritance concepts, and something that
> I would assume to work returns an error.
> 
>>>> class A:
> ...     def __init__( self ):
> ...             self.a = 13
> ...
>>>> class B( A ): # create sub-class of class A
> ...     def __init__( self ):
> ...             self.b = 14

Call the __init__ of the ancestor explicitly:

>>> class B(A):
...     def __init__(self):
...         A.__init__(self)
...         self.b = 14
>>> b = B()
>>> b.a, b.b
(13, 14)

B inherits everything from A, but by defining B.__init__, the __init__
inherited from A is replaced, so you'll need to call it explicitly. Python
has no way of knowing that you still want to use the original __init__ too
unless you tell it so. To demonstrate the fact that __init__ is indeed
inherited:

>>> class C(A):
...     pass
>>> c = C() # inherited __init__ (A.__init__) is called
>>> c.a
13

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. 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  Fri Apr  8 23:33:18 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr  8 23:36:38 2005
Subject: [Tutor] Re: IDLE crashing suddenly
In-Reply-To: <N1-OlnVGfdL@Safe-mail.net>
Message-ID: <Pine.LNX.4.44.0504081427410.6776-100000@hkn.eecs.berkeley.edu>



On Fri, 8 Apr 2005 jsoares@Safe-mail.net wrote:

> I've noticed that after 20 or 30 compile/link/execute runs, IDLE
> crashes. This seems to happen pretty consistently. At the time, I'm not
> doing anything that might cause it to crash. Does this happen to anyone
> else? What causes it? Is it just a bug? I have IDLE version 1.1.1 which
> came with Python 2.4. Thanks. John Soares jsoares@safe-mail.net

Hi John,

[Note: when you send messages to the list, try to snip out the rest of the
digest out.  Otherwise, it looks like you're trying to reply to the whole
digest message, which looks weird.  *grin*]

What you're running to in IDLE doesn't sound right at all.  Try checking
this up with the IDLE folks at:

    http://mail.python.org/mailman/listinfo/idle-dev

But before you contact them, try to make the error report more specific.
What do you mean by "crash"?  Does IDLE just not respond, or does it look
like it's waiting for something?  Do you have other software running like
a firewall?


It'll help if you can open up Python's interactive interpreter and try
this from your console window:

#####
>>> from idlelib.PyShell import main
>>> main()
#####

This runs IDLE, and also allows you to see any debugging messages or error
tracebacks that come out of IDLE.  Try doing those 20-30 executes, and
check the console window to see if you see something funky there.  If you
do see some output in your console window, copy and paste it along with
your error report.

Best of wishes to you!

From geek_show at dsl.pipex.com  Sat Apr  9 00:52:05 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Sat Apr  9 00:50:52 2005
Subject: [Tutor] Recursive list checking
In-Reply-To: <9A8A15A8-A85F-11D9-83E2-000A95823962@sandia.gov>
References: <20050408173738.392F01E400A@bag.python.org>
	<9A8A15A8-A85F-11D9-83E2-000A95823962@sandia.gov>
Message-ID: <42570B15.9050206@dsl.pipex.com>

Rick Muller wrote:
> 
> On Apr 8, 2005, at 11:37 AM, tutor-request@python.org wrote:
> 
>> From: joe_schmoe <geek_show@dsl.pipex.com>
>> For example, this is what I am currently doing:
>>
>> =============code block ========================
>>
>>     # generate unique numbers and append to list
>>     nmbr01 = random.randrange( 1, 20 )
>>     nmbr_list.append( nmbr01 )
>>
>>     nmbr02 = random.randrange( 1, 20 )
>>     # check for duplicates and re-generate a number if needed
>>     while nmbr02 in nmbr_list:
>>         nmbr02 = random.randrange( 1, 20 )
>>     nmbr_list.append( nmbr02 )
>>
>>     nmbr03 = random.randrange( 1, 20 )
>>     while nmbr03 in nmbr_list:
>>         nmbr03 = random.randrange( 1, 20 )
>>     nmbr.append( nmbr03 )
>>
>> ================================================
>>
> 
> Since you want unique entries, couldn't you just do something like
> 
> def unique_entries(n,start=1,stop=20):
>     "Generate n unique entries in range(1,20)"
>     from random import shuffle
>     l = range(start,stop)
>     shuffle(l)
>     return l[:n]
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
Rick, Kent, Bernard, and Jeff

Thanks for your comments: that is so cool - ask a question and 5 
different ways to do the same thing!! Thanks guys :)

As it so happens, I settled for Jeff's suggestion for 2 reasons:
1. because it was the first response and it worked when tested
2. it is straight forward enough for me to mentally follow what's happening

I thought some of the suggestions were really cool, but admittedly a 
little over my head at this point in time.

The solution was worked into a small "Master-Mind" like program I was 
fooling around with. I don't know what the protocol is on this list, but 
if you want to see it I'm happy to post here or off-list.

Anyway, just to give feedback on your helpful comments. Thanks.

/j
From spamfilter2 at mupp.net  Sat Apr  9 00:51:06 2005
From: spamfilter2 at mupp.net (j2)
Date: Sat Apr  9 00:52:49 2005
Subject: [Tutor] Talking to mssql?
In-Reply-To: <20050407220820.26D0F1E4004@bag.python.org>
Message-ID: <20050408225246.14A141E4005@bag.python.org>

>I had the same question.  The best I found is this:
>http://www.object-craft.com.au/projects/mssql/ 
>but that has a lot of strong language saying "this isn't ready for use".
>
>I found it perfectly usable for simply running queries, but haven't tried
>to do anything more complicated with it.  Not sure how
>well it works on Linux, but he has binaries that worked for me.

Well, doesn't fly for me, because I can't install it. Can you offer any help
on the below?


I am trying to install http://www.object-craft.com.au/projects/mssql/ on my
Debian system, but when i try to build, i end up with the below. Also, my
package list is at the bottom.

hooch:~/Download/Asterisk/MSSQL-0.09# python setup.py install
running install
running build
running build_py
not copying MSSQL.py (output up-to-date)
running build_ext
building 'mssqldb' extension
creating build/temp.linux-i686-2.2
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c mssqldb.c -o
build/temp.linux-i686-2.2/mssqldb.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c loginrec.c -o
build/temp.linux-i686-2.2/loginrec.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c dbproc.c -o
build/temp.linux-i686-2.2/dbproc.o
dbproc.c:199: warning: `wrap_DbProcIntFunc_bool' defined but not used
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c databuf.c -o
build/temp.linux-i686-2.2/databuf.o
databuf.c: In function `get_buff_value':
databuf.c:86: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:86: error: (Each undeclared identifier is reported only once
databuf.c:86: error: for each function it appears in.)
databuf.c:86: error: parse error before ')' token
databuf.c:87: error: parse error before ')' token
databuf.c:90: error: `DBBIT' undeclared (first use in this function)
databuf.c:90: error: parse error before ')' token
databuf.c: In function `DataBuf_set':
databuf.c:155: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:155: error: parse error before ')' token
databuf.c:160: error: parse error before ')' token
databuf.c:161: error: parse error before ')' token
databuf.c:169: error: `DBBIT' undeclared (first use in this function)
databuf.c:169: error: parse error before ')' token
databuf.c: In function `DataBuf__init__':
databuf.c:270: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:273: error: `DBBIT' undeclared (first use in this function)
error: command 'gcc' failed with exit status 1
hooch:~/Download/Asterisk/MSSQL-0.09#

From jsoares at Safe-mail.net  Sat Apr  9 01:39:56 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Sat Apr  9 01:40:01 2005
Subject: [Tutor] Re: Notepad++ support for Python
Message-ID: <N1-cFMV7LYJ@Safe-mail.net>



I need a backup editor for IDLE, so I'm trying Notepad++. It looks nice, but there is no direct support for running Python.



What you have to do is click the "Run" menu item and then you type the command line for the Python interpreter. This should be simple; there are only to .exe files: python and pythonw.



The python.exe file brings up the shell, while the pythonw.exe brings up a black screen that very quickly goes away.



What do I do?



I would think: python(w).exe %filename%



or something like that. Is there a .bat file somewhere that starts everything off?



Thanks.



=================================
John Soares, Webmaster
Family Safe Surfinghttp://www.family-safe-surfing.net
jsoares@family-safe-surfing.net
jsoares@safe-mail.net

"Your best bet for online family-friendly resources"
=================================



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/ce6646f2/attachment.html
From dyoo at hkn.eecs.berkeley.edu  Sat Apr  9 02:47:11 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Apr  9 02:47:19 2005
Subject: [Tutor] Talking to mssql?
In-Reply-To: <20050408225246.14A141E4005@bag.python.org>
Message-ID: <Pine.LNX.4.44.0504081702160.16110-100000@hkn.eecs.berkeley.edu>


On Sat, 9 Apr 2005, j2 wrote:

> Well, doesn't fly for me, because I can't install it. Can you offer any
> help on the below?

Hi J2,

This is a slightly specialized question for tutor; you might be able to
get some better help by asking on the db-sig mailing list:

    http://mail.python.org/mailman/listinfo/db-sig

You may want to look at:

    http://pymssql.sourceforge.net/

too, which may work better with FreeTDS.  I'm guessing that you are using
FreeTDS, the Sybase library implementation, from the GCC output that you
included earlier.


>From a first glance, I think that the compilation errors are trying to say
that the C compiler can't find certain symbols that it expects to see.
These include:

    DBVARYCHAR
    DBBIT


According to:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dblibc/dbc_pdcapb_6vvm.asp

those types are valid in SQL Server 2000.  So everything should be fine.


Wait.  Ok, got it.  You are using the FreeTDS libraries!  If so, that's
probably the problem: I don't see the type definitions for those two types
in sybdb.h from the FreeTDS libraries:

    http://www.freetds.org/reference/a00265.html

So I think this is the problem: there are holes in the FreeTDS
implementation of Sybase that make it incompatible with David Cole's MSSQL
Python library.


... Ok, I found some more information on this.  It appears that some folks
have written a workaround by editing the mssqldb.h in the MSSQL Python
module.  I don't speak Russian, but from:

    http://itconnection.ru/pipermail/zopyrus/2003-September/070093.html

it looks like MSSQL needs to be modified slightly to support FreeTDS
better.  The message above defines a customized definition of DBBIT and
DBVARYCHAR.


Add the following to the mssqldb.h file in the MSSQL Python module:

######
#ifdef HAVE_FREETDS
typedef unsigned char DBBIT;
#define PRNUMERIC MAXPRECISION
#define DB_MAX_PREC MAXPRECISION
#define DB_MAX_SCALE MAXPRECISION
typedef struct dbvarychar
{
        DBSMALLINT  len;
        DBCHAR      str[DBMAXCHAR];
} DBVARYCHAR;
#endif
######

and then try recompiling.


I do not know if this is really the right thing to do: you really should
follow up by talking with David Cole, the developer of MSSQL, to see his
thoughts on this.  Can you follow up on this?  Here's a link to the
mailing list:

    https://object-craft.com.au/cgi-bin/mailman/listinfo/python-sybase


Anyway, hope this helps!

From missive at hotmail.com  Sat Apr  9 04:35:10 2005
From: missive at hotmail.com (Lee Harr)
Date: Sat Apr  9 04:35:15 2005
Subject: [Tutor] Re: How to create multi disks zip file
Message-ID: <BAY2-F260E278281C0AA4318AFE7B1300@phx.gbl>

>>I'm a newbie. My friend asked me for a help. He wanted to backup his files
>>into multi disks zip file. Is there any possibilities for me to help him 
>>by
>>using python?
>>
>Err... you probably could, but why reinvent the wheel? WinZip?


winzip is not free, and I always found it terribly annoying.

Info-ZIP is free and zipsplit (included) works quite well:
http://www.info-zip.org/pub/infozip/

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

From cyresse at gmail.com  Sat Apr  9 05:29:52 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sat Apr  9 05:29:59 2005
Subject: [Tutor] GUI-trouble
In-Reply-To: <27786.193.71.38.142.1112958694.squirrel@mail.sporck.net>
References: <27786.193.71.38.142.1112958694.squirrel@mail.sporck.net>
Message-ID: <f2ff2d05040820296e1f27a5@mail.gmail.com>

Hi ?yvind, 

A few errors in this here function - 

> def message():
> print New_Toplevel_1.v.get()
> # print self.v.get() This doesn't seem to work either

Your class New_Toplevel_1 is not instantiated as New_Toplevel_1 - you 
created an instance of it as 

>w = New_Toplevel_1 (root)

So def message() should have this line - 

>print w.v.get()

That wouldn't work either, however, and I'll explain why shortly. 
I just wanted to point out for the moment that 
>#print self.v.get()

will never work. You can only call self.attributes within a class i.e. 

>>> class Foo:
... def __init__(self):
... self.name <http://self.name> = "Bob"
...
... def changeName(self):
... self.name <http://self.name> = "Dave"
...
... def getThenChangeName(self):
... print self.name <http://self.name>
... self.changeName()
... print 'Name changed to', self.name <http://self.name>
... 
>>> h = Foo()
>>> h.getThenChangeName()

Bob
Name changed to Dave

Whereas, trying to use self in a function will always result in an error. 

>>> def trySelfInAFunction():
... self.bob = 20
... print 'Did it work?'
... print self.bob
... 
>>> trySelfInAFunction()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 2, in trySelfInAFunction
NameError: global name 'self' is not defined


Ok... so you need your function message to be inside your class....

I've made your code work, I'll paste it up and highlight the important bits. 


from Tkinter import *
import Tix, sys

def vp_start_gui():
global w
global root
root = Tix.Tk()
root.title('New_Toplevel_1')
#root.geometry('200x205+1157+142')
w = New_Toplevel_1 (root)
#init()
root.mainloop()



class New_Toplevel_1:
def __init__(self, master=None):

self.but26 = Button (master)
self.but26.place(in_=master,x=60,y=30)
self.but26.configure(command=self.message)
self.but26.configure(text="button")
self.but26.pack()

self.che27 = Checkbutton(master)
self.che27.place(in_=master,x=50,y=120)
self.che27.configure(text="check")
self.v = IntVar()
self.che27.configure(variable=self.v)
self.che27.pack()

def message(self):
#print New_Toplevel_1.v.get()
print self.v.get() # This doesn't seem to work either

if __name__ == '__main__':
vp_start_gui()


Here are the main changes - 

Line 9 - root.geometry('200x205+1157+142') 

I had to comment this out to get your window to show. Having poked at 
root.geometry, I must say I think that that one was implemented funny. 
Passing a string for window parameters.... try passing root.geometry('200 x 
205 + 1157 + 142') and see the errors you get from that. Highly unpythonic, 
in my arrogant opinion.

So, anyway, for the time being, comment out that line.

line 21 - self.but26.configure(command=message) changed to 
self.but26.configure(command = self.message)

As you'll be calling a class method, you need to explicitly call self.method
.

line 23 - inserted self.but26.pack()

AFAIK, you need to do this to display your widget.

line 28 v = IntVar() changed to self.v = IntVar()

Within a class, if you want a variable to act as a global, you need to make 
it global. 

class Foo():

def __init__(self):
x = "Hi"

def getX(self):
print x

>>>w = Foo()
>>> print w.x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: Foo instance has no attribute 'x'

Would need to be - 

class Foo:

def __init__(self):
self.x = 'Hi'

def getX(self):
print self.x


line 29 self.che27.configure(variable=v) changed to self.che27.configure
(variable=self.v)

line 30 self.che27.pack() added

line 33 - 34 - Following method added to class - 

def message(self):
print self.v.get() 

Remember, you are calling class methods from within your class, not external 
functions.


You aren't having GUI trouble, quite frankly, you're having object trouble, 
classes are quite an integral part of GUI toolkits, so you need to learn a 
bit more about class methods, attributes etc. 

I recommend http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm, 

Alan Gauld's wonderful programming tutorial.

Good luck.

Liam Clarke

On Apr 8, 2005 11:11 PM, ?yvind <python@kapitalisten.no> wrote:
> Hello.
> 
> I am trying to make a little gui. It has a button and a checkbox. If I
> push the button, it is supposed to print the value of the checkbox. But, I
> can not seem to get it right. How should I define the variable? Where
> should I put it? I have tried every way possible, and gotten lots of
> different errormessages.
> 
> Thanks in advance
> ?yvind
> 
> from Tkinter import *
> import Tix, sys
> 
> def vp_start_gui():
> global w
> global root
> root = Tix.Tk()
> root.title('New_Toplevel_1')
> root.geometry('200x205+1157+142')
> w = New_Toplevel_1 (root)
> init()
> root.mainloop()
> 
> def message():
> print New_Toplevel_1.v.get()
> # print self.v.get() This doesn't seem to work either
> 
> class New_Toplevel_1:
> def __init__(self, master=None):
> pass
> 
> self.but26 = Button (master)
> self.but26.place(in_=master,x=60,y=30)
> self.but26.configure(command=message)
> self.but26.configure(text="button")
> 
> self.che27 = Checkbutton (master)
> self.che27.place(in_=master,x=50,y=120)
> self.che27.configure(text="check")
> v = IntVar()
> self.che27.configure(variable=v)
> 
> if __name__ == '__main__':
> vp_start_gui()
> 
> --
> This email has been scanned for viruses & spam by Decna as - www.decna.no<http://www.decna.no>
> Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no<http://www.decna.no>
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050409/4f6b06ee/attachment.htm
From cyresse at gmail.com  Sat Apr  9 05:36:19 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sat Apr  9 05:36:24 2005
Subject: [Tutor] Re: How to create multi disks zip file
In-Reply-To: <BAY2-F260E278281C0AA4318AFE7B1300@phx.gbl>
References: <BAY2-F260E278281C0AA4318AFE7B1300@phx.gbl>
Message-ID: <f2ff2d05040820361c655b4a@mail.gmail.com>

Personally, I tend to winRar. Paying for software isn't a bad thing. Open 
source != free.


On Apr 9, 2005 2:35 PM, Lee Harr <missive@hotmail.com> wrote:
> 
> >>I'm a newbie. My friend asked me for a help. He wanted to backup his 
> files
> >>into multi disks zip file. Is there any possibilities for me to help him
> >>by
> >>using python?
> >>
> >Err... you probably could, but why reinvent the wheel? WinZip?
> 
> winzip is not free, and I always found it terribly annoying.
> 
> Info-ZIP is free and zipsplit (included) works quite well:
> http://www.info-zip.org/pub/infozip/
> 
> _________________________________________________________________
> Express yourself instantly with MSN Messenger! Download today it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050409/b4278c3d/attachment-0001.html
From smichr at hotmail.com  Sat Apr  9 07:08:53 2005
From: smichr at hotmail.com (C Smith)
Date: Sat Apr  9 07:08:56 2005
Subject: [Tutor] str.split and quotes
Message-ID: <20050409050853.4677.qmail@gem-wbe06.prod.mesa1.secureserver.net>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/fdbd2fab/attachment.htm
From marilyn at deliberate.com  Sat Apr  9 07:18:28 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Sat Apr  9 07:26:37 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <20050409050853.4677.qmail@gem-wbe06.prod.mesa1.secureserver.net>
Message-ID: <Pine.LNX.4.44.0504082216490.18776-100000@Kuna>

On Fri, 8 Apr 2005, C Smith wrote:

> Tony wrote:
>       With Python 2.4 I get these results (all imports are factored
>       out, all give
>       the same result except for CSV which strips the "s) with
>       timeit.py:
> 
> Just a note here in terms of results.? Although the results are all the
> same and they work for the case where there is single quoted phrase with
> more than one word in it, the split_and_rejoin has problems for the case
> where there is only a single word in quotes (since the trailing quote
> that you are assuming is in another word occurs in the same word and thus
> is never found). e.g. 'I said "wow" when I saw the result' will give it
> problems.
> ?
> The re expression has a problem if there is more than one quoted string
> in the string (e.g. 'if "this" and "that" are quoted'). The reason is
> that the expression is "greedy" and matches the longest string of
> characters between quote marks: in '"this" and "that"' the entire string
> will be matched rather than the first "this". The fix is to use the
> non-greedy pattern:
> ?
> re.compile(r'\".*?\"|[^ ]+')

Yes, thank you.  I did discover it to be too greedy and added the ?

Thank you for giving it another thought.  This will be the best
snippet of code in my whole application.

Marilyn

> ?
> Note the ? after the *
> ?
> /c
> ?
> ?
> 
> 

-- 

From dyoo at hkn.eecs.berkeley.edu  Sat Apr  9 10:36:41 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Apr  9 10:36:44 2005
Subject: [Tutor] newb problem running the translator (fwd)
Message-ID: <Pine.LNX.4.44.0504090136380.17924-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Fri, 8 Apr 2005 22:03:58 EDT
From: Drumming4NOTA@aol.com
To: tutor-owner@python.org
Subject: newb problem running the translator

    I will try to make this quick. I am a newb to python, and programming at
that, but i am realy interested. I have been looking at simple programs to be
run through the shell but i cannot figure out the translator. When i save
program i have tried to tell it to opoen it in the translator. I have been looking
through several websites and looked through the documents my python
installation came with. On one computer i am running Windows Xp and on another win98SE.
If you could explain to me how to open a program through the translator i
would appreciate it alot.


Thanx

From smiles at saysomething.com  Sat Apr  9 06:45:21 2005
From: smiles at saysomething.com (smiles@saysomething.com)
Date: Sat Apr  9 10:38:38 2005
Subject: [Tutor] str.split and quotes
Message-ID: <20050409044521.26246.qmail@webmail10.mesa1.secureserver.net>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050408/15c4eddf/attachment.html
From spamfilter2 at mupp.net  Sat Apr  9 00:03:19 2005
From: spamfilter2 at mupp.net (j2)
Date: Sat Apr  9 10:39:18 2005
Subject: [Tutor] Talking to mssql?
In-Reply-To: <20050407220820.26D0F1E4004@bag.python.org>
Message-ID: <20050408222406.B96041E4003@bag.python.org>

>I had the same question.  The best I found is this:
>http://www.object-craft.com.au/projects/mssql/ 
>but that has a lot of strong language saying "this isn't ready for use".
>
>I found it perfectly usable for simply running queries, but haven't tried
>to do anything more complicated with it.  Not sure how
>well it works on Linux, but he has binaries that worked for me.

Well, doesn't fly for me, because I can't install it. Can you offer any help
on the below?


I am trying to install http://www.object-craft.com.au/projects/mssql/ on my
Debian system, but when i try to build, i end up with the below. Also, my
package list is at the bottom.

hooch:~/Download/Asterisk/MSSQL-0.09# python setup.py install
running install
running build
running build_py
not copying MSSQL.py (output up-to-date)
running build_ext
building 'mssqldb' extension
creating build/temp.linux-i686-2.2
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c mssqldb.c -o
build/temp.linux-i686-2.2/mssqldb.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c loginrec.c -o
build/temp.linux-i686-2.2/loginrec.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c dbproc.c -o
build/temp.linux-i686-2.2/dbproc.o
dbproc.c:199: warning: `wrap_DbProcIntFunc_bool' defined but not used
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c databuf.c -o
build/temp.linux-i686-2.2/databuf.o
databuf.c: In function `get_buff_value':
databuf.c:86: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:86: error: (Each undeclared identifier is reported only once
databuf.c:86: error: for each function it appears in.)
databuf.c:86: error: parse error before ')' token
databuf.c:87: error: parse error before ')' token
databuf.c:90: error: `DBBIT' undeclared (first use in this function)
databuf.c:90: error: parse error before ')' token
databuf.c: In function `DataBuf_set':
databuf.c:155: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:155: error: parse error before ')' token
databuf.c:160: error: parse error before ')' token
databuf.c:161: error: parse error before ')' token
databuf.c:169: error: `DBBIT' undeclared (first use in this function)
databuf.c:169: error: parse error before ')' token
databuf.c: In function `DataBuf__init__':
databuf.c:270: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:273: error: `DBBIT' undeclared (first use in this function)
error: command 'gcc' failed with exit status 1
hooch:~/Download/Asterisk/MSSQL-0.09#


+++-==================-==================-==================================
==================
ii  adduser            3.51               Add and remove users and groups
ii  apache             1.3.29.0.1-3       Versatile, high-performance HTTP
server
ii  apache-common      1.3.29.0.1-3       Support files for all Apache
webservers
ii  apache-utils       1.3.29.0.1-3       Utility programs for webservers
ii  apt                0.5.4              Advanced front-end for dpkg
ii  apt-utils          0.5.4              APT utility programs
ii  arping             1.05-1             sends IP and/or ARP pings (to the
MAC address)
ii  asterisk           1.0.7.dfsg.1-2     open source Private Branch
Exchange (PBX)
ii  asterisk-config    1.0.7.dfsg.1-2     config files for asterisk
ii  asterisk-prompt-se 0.8-2              Swedish voice prompts for Asterisk
ii  asterisk-sounds-ma 1.0.7.dfsg.1-2     sound files for asterisk
ii  at                 3.1.8-11           Delayed job execution and batch
processing
ii  atftpd             0.6.2              Advanced TFTP server.
ii  aub                2.1.3-1            Assembles binary files from USENET
ii  autoconf           2.57-10            automatic configure script builder
ii  autoconf2.13       2.13-48            automatic configure script builder
(obsolete version
ii  automake           1.4-p4-1.1         A tool for generating GNU
Standards-compliant Makefi
ii  autoproject        0.17-1             create a skeleton source package
for a new program
ii  autotools-dev      20030717.1         Update infrastructure for
config.{guess,sub} files
ii  backup2l           1.1-gk.1.1         low-maintenance backup/restore
tool for mountable me
ii  base-config        1.72               Debian base configuration package
ii  base-files         3.0.10             Debian base system miscellaneous
files
ii  base-passwd        3.5.4              Debian base system master password
and group files
ii  bash               2.05b-8.1          The GNU Bourne Again SHell
ii  bc                 1.06-11            The GNU bc arbitrary precision
calculator language
ii  biff               0.17.pre20000412-1 a mail notification tool
ii  bin86              0.16.3-2           16-bit assembler and loader
ii  bind9-host         9.2.2-2            Version of 'host' bundled with
BIND 9.X
ii  binutils           2.15-5             The GNU assembler, linker and
binary utilities
ii  bison              1.875a-1           A parser generator that is
compatible with YACC.
ii  blt                2.4z-2             shared libraries for BLT
ii  blt-common         2.4z-2             common run-time parts to the BLT
libraries
ii  bonobo             1.0.22-2.1         The GNOME Bonobo System.
ii  bsdmainutils       5.20030320-1       collection of more utilities from
FreeBSD
ii  bsdutils           2.11z-1            Basic utilities from 4.4BSD-Lite.
ii  c2man              2.41-16            Graham Stoney's mechanized man
page generator.
ii  cacti              0.8.5a-3           Frontend to rrdtool for monitoring
systems and servi
ii  cflow              2.0-17             C function call hierarchy analyzer
ii  console-common     0.7.25             Basic infrastructure for text
console configuration
ii  console-data       2002.12.04dbs-16   Keymaps, fonts, charset maps,
fallback tables for co
ii  console-tools      0.2.3dbs-39        Linux console and font utilities
rc  console-tools-libs 0.2.3dbs-32        Shared libraries for Linux console
and font manipula
ii  coreutils          5.0-5              The GNU core utilities
ii  courier-authdaemon 0.42.2-5           Courier Mail Server authentication
daemon
ii  courier-base       0.42.2-5           Courier Mail Server Base System
ii  courier-imap       1.7.3-5            IMAP daemon with PAM and Maildir
support
ii  courier-imap-ssl   1.7.3-5            IMAP daemon with SSL, PAM and
Maildir support
ii  courier-pop        0.42.2-5           POP3 daemon with PAM and Maildir
support
ii  courier-pop-ssl    0.42.2-5           POP3 daemon with SSL, PAM and
Maildir support
ii  courier-ssl        0.42.2-5           Courier Mail Server SSL Package
ii  cpio               2.5-1.1            GNU cpio -- a program to manage
archives of files.
ii  cpp                3.3-1              The GNU C preprocessor.
ii  cpp-2.95           2.95.4-17          The GNU C preprocessor.
ii  cpp-3.0            3.0.4-7            The GNU C preprocessor.
ii  cpp-3.3            3.3.5-8            The GNU C preprocessor
ii  cron               3.0pl1-74          management of regular background
processing
ii  cutils             1.6-2              C source code utilities
ii  cvs                1.12.1-4           Concurrent Versions System
ii  cxref              1.5d-7             Generates latex and HTML
documentation for C program
ii  dc                 1.06-11            The GNU dc arbitrary precision
reverse-polish calcul
ii  ddd                3.3.7-1            The Data Display Debugger, a
graphical debugger fron
ii  debconf            1.3.8              Debian configuration management
system
ii  debconf-i18n       1.3.8              full internationalization support
for debconf
ii  debianutils        2.5.4              Miscellaneous utilities specific
to Debian
ii  defoma             0.11.4             Debian Font Manager -- automatic
font configuration
ii  dhcp-client        2.0pl5-16          DHCP Client
ii  dialog             0.9b-20030720-1    Displays user-friendly dialog
boxes from shell scrip
ii  dictionaries-commo 0.10.3             Common utilities for spelling
dictionary tools
ii  diff               2.8.1-2            File comparison utilities
ii  dnsutils           9.2.2-2            Clients provided with BIND
ii  doc-debian         3.0.2              Debian Project documentation,
Debian FAQ and other d
ii  doc-linux-text     2003.07-1          Linux HOWTOs and FAQs in ASCII
format
ii  dpkg               1.10.10            Package maintenance system for
Debian
ii  dpkg-dev           1.10.10            Package building tools for Debian
ii  dselect            1.10.10            a user tool to manage Debian
packages
ii  e2fsprogs          1.33+1.34-WIP-2003 The EXT2 file system utilities and
libraries
ii  ed                 0.2-20             The classic unix line editor
ii  elinks             0.9.1-1            Character mode WWW/FTP browser
ii  emacs20            20.7-13.1          The GNU Emacs editor.
ii  emacsen-common     1.4.15             Common facilities for all emacsen.
ii  enscript           1.6.3-5            Converts ASCII text to Postscript,
HTML, RTF or Pret
ii  esound-clients     0.2.29-1           Enlightened Sound Daemon - clients
ii  esound-common      0.2.29-1           Enlightened Sound Daemon - Common
files
ii  ettercap           0.6.b-2            Multipurpose
sniffer/interceptor/logger for switched
ii  ettercap-common    0.6.b-2            Common support files and plugins
for ettercap
hi  exim               3.35-1             An MTA (Mail Transport Agent)
ii  expect             5.42.1-1.2         A program that "talks" to other
programs
ii  fdutils            5.4-20030718-1     Linux floppy utilities
rc  fetchmail          5.9.11-6.1         POP3, APOP, IMAP mail
gatherer/forwarder (crypto-cri
rc  fetchmail-common   5.9.11-6.1         POP3, APOP, IMAP mail
gatherer/forwarder (common fil
ii  file               4.02-4             Determines file type using "magic"
numbers
ii  fileutils          5.0-5              The GNU file management utilities
(transitional pack
ii  findutils          4.1.20-1           utilities for finding files--find,
xargs, and locate
ii  finger             0.17-6             User information lookup program.
ii  flex               2.5.31-14          A fast lexical analyzer generator.
ii  fmirror            0.8.4-12           memory efficient ftp mirror
program
ii  fontconfig         2.2.1-1            generic font configuration library
ii  fping              2.4b2-to-ipv6-7    Send ICMP ECHO_REQUEST packets to
network hosts.
ii  freetds-dev        0.61-6.1           MS SQL and Sybase client library
(static libs and he
ii  ftp                0.17-11            The FTP client.
rc  ftpmirror          1.2l-8             Mirroring directory hierarchy with
FTP
ii  g++                3.3-1              The GNU C++ compiler.
ii  g++-2.95           2.95.4-17          The GNU C++ compiler.
ii  g++-3.3            3.3.5-8            The GNU C++ compiler
ii  gadfly             1.0.0-3            Server and interactive shell for
Gadfly SQL database
ii  gcc                3.3-1              The GNU C compiler.
ii  gcc-2.95           2.95.4-17          The GNU C compiler.
ii  gcc-3.0            3.0.4-7            The GNU C compiler.
ii  gcc-3.0-base       3.0.4-7            The GNU Compiler Collection (base
package).
ii  gcc-3.3            3.3.5-8            The GNU C compiler
ii  gcc-3.3-base       3.3.5-8            The GNU Compiler Collection (base
package)
ii  gconf              1.0.9-2.1          GNOME configuration database
system. (daemon and too
ii  gdb                5.3-2              The GNU Debugger
ii  gdk-imlib1         1.9.14-13          imaging library for use with gtk
(using libpng2)
ii  gettext            0.12.1-3           GNU Internationalization utilities
ii  gettext-base       0.12.1-3           GNU Internationalization utilities
for the base syst
ii  gettext-el         0.12.1-3           Emacs po-mode for editing .po
files.
ii  gimp-python        1.2-4              Write plugins for Gimp in Python
ii  gimpprint-locales  4.2.5-3            Locale data files for gimp-print
ii  gnome-bin          1.4.2-14           Miscellaneous binaries used by
GNOME
ii  gnome-libs-data    1.4.2-14           Data for GNOME libraries
ii  gnupg              1.2.3-1            GNU privacy guard - a free PGP
replacement
ii  gnupg-doc          2003.04.06-2       GNU Privacy Guard documentation
ii  grep               2.5.1-6            GNU grep, egrep and fgrep
ii  groff-base         1.18.1-9           GNU troff text-formatting system
(base system compon
ii  gs                 7.07-1             The Ghostscript Postscript
interpreter
ii  gs-common          0.3.3.1            Common files for different
Ghostscript releases
ii  gsfonts            6.0-2.1            Fonts for the ghostscript
interpreter
ii  gsfonts-x11        0.17               Make Ghostscript fonts available
to X11
ii  gzip               1.3.5-7            The GNU compression utility
ii  hdparm             5.4-2              Tune hard disk parameters for high
performance
ii  hostname           2.10               A utility to set/show the host
name or domain name
ii  htmlgen            2.2.2-9            Dummy package to facilitate
HTMLgen upgrades
ii  hylafax-client     4.1.1-1            Flexible client/server fax
software - client utiliti
ii  hylafax-server     4.1.1-1            Flexible client/server fax
software - server daemons
ii  iamerican          3.1.20.0-3         An American English dictionary for
ispell
ii  ibritish           3.1.20.0-3         A British English dictionary for
ispell
ii  iconx              9.4.0-2.1          Executor for Icon, a high-level
programming language
ii  ifupdown           0.6.4-4.6          High level tools to configure
network interfaces
ii  imagemagick        5.5.7.9-1          Image manipulation programs
ii  imlib-base         1.9.14-13          Common files needed by the
Imlib/Gdk-Imlib packages
ii  indent             2.2.9-2            C language source code formatting
program
ii  info               4.6-1              Standalone GNU Info documentation
browser
ii  initscripts        2.85-7             Standard scripts needed for
booting and shutting dow
ii  ipchains           1.3.10-15          Network firewalling for Linux
2.2.x
ii  ipmasqadm          0.4.2-2            Utility for configuring extra
masquerading functiona
ii  iptables           1.2.8-4            IP packet filter administration
tools for 2.4.4+ ker
ii  iptraf             2.7.0-4            Interactive Colorful IP LAN
Monitor
ii  iputils-ping       20020927-2         Tools to test the reachability of
network hosts
ii  ispell             3.1.20.0-3         International Ispell (an
interactive spelling correc
pc  jffnms             0.7.5-1            Web-based Network Management Sytem
(NMS) for IP netw
rc  klogd              1.4.1-10           Kernel Logging Daemon
ii  less               381-2              A file pager program, similar to
more(1)
ii  lesstif1           0.93.44-2          OSF/Motif 1.2 implementation
released under LGPL.
ii  lesstif2           0.93.44-2          OSF/Motif 2.1 implementation
released under LGPL.
ii  libacl1            2.2.15-1           Access control list shared library
ii  libart2            1.4.2-14           The GNOME canvas widget - runtime
files
ii  libasound2         1.0.8-3            ALSA library
ii  libatk1.0-0        1.2.4-1            The ATK accessibility toolkit
ii  libattr1           2.4.8-1            Extended attribute shared library
ii  libaudiofile0      0.2.3-4            The Audiofile Library
ii  libauthen-pam-perl 0.14-1             This module provides a Perl
interface to the PAM lib
ii  libber0            0.2.4              A Basic Encoding Rules (ITU X.690)
implementation
ii  libblkid1          1.33+1.34-WIP-2003 Block device id library
ii  libbonobo2         1.0.22-2.1         The GNOME Bonobo library.
ii  libbz2-1.0         1.0.2-1            A high-quality block-sorting file
compressor library
ii  libc6              2.3.2.ds1-20       GNU C Library: Shared libraries
and Timezone data
ii  libc6-dev          2.3.2.ds1-20       GNU C Library: Development
Libraries and Header File
ii  libcap1            1.10-12            support for getting/setting
POSIX.1e capabilities
ii  libcapplet0        1.4.0.5-3          Library for Gnome Control Center
applets
ii  libcdb-file-perl   0.84-2.1           Perl interface to Dan Berstein's
cdb package.
ii  libcgi-perl        2.76-22            modules for perl5, for use in
writing CGI scripts.
ii  libcomerr2         1.37-1             common error description library
ii  libconfig-inifiles 2.38-2             A module for reading .ini-style
configuration files
ii  libconsole         0.2.3dbs-39        Shared libraries for Linux console
and font manipula
ii  libct1             0.61-6.1           libraries for connecting to MS SQL
and Sybase SQL se
ii  libcupsys2         1.1.19final-1      Common UNIX Printing System(tm) -
libs
ii  libdb1-compat      2.1.3-7            The Berkeley database routines
[glibc 2.0/2.1 compat
ii  libdb2             2.7.7.0-8          The Berkeley database routines
(run-time files).
ii  libdb2-dev         2.7.7.0-8          The Berkeley database routines
(development files).
ii  libdb2-util        2.7.7.0-8          The Berkeley database routines
(development files).
ii  libdb3             3.2.9-19           Berkeley v3 Database Libraries
[runtime]
ii  libdb4.0           4.0.14-1.2         Berkeley v4.0 Database Libraries
[runtime]
ii  libdb4.1           4.1.25-6           Berkeley v4.1 Database Libraries
[runtime]
ii  libdb4.2           4.2.52-16          Berkeley v4.2 Database Libraries
[runtime]
ii  libdbd-mysql-perl  2.1027-1           A Perl5 database interface to the
MySQL database
ii  libdbi-perl        1.35-1             The Perl5 Database Interface by
Tim Bunce
ii  libdebug0          0.2.3              Memory leak detection system and
logging library
ii  libdigest-hmac-per 1.01-1             create standard message integrity
checks
ii  libdigest-sha1-per 2.01-0.1           NIST SHA-1 message digest
algorithm
ii  libdns5            9.2.1-2.woody.1    DNS Shared Library used by BIND
ii  libdns8            9.2.2-2            DNS Shared Library used by BIND
ii  libefs1            1.0.22-2.1         Embedded File System library.
ii  libesd0            0.2.29-1           Enlightened Sound Daemon - Shared
libraries
ii  libevent-perl      0.87-1             Generic Perl event loop
ii  libexif8           0.5.9-4            The EXIF library allows you to
parse an EXIF file
ii  libexpat1          1.95.8-1           XML parsing C library - runtime
library
ii  libfam0c102        2.6.10-1           client library to control the FAM
daemon
ii  libfontconfig1     2.2.1-1            generic font configuration library
(shared library)
ii  libfreetype6       2.1.7-2.1          FreeType 2 font engine, shared
library files
ii  libgal-data        0.24-1.3           G App Libs (data files)
ii  libgal19           0.19.2-2           G App Libs (run time library)
ii  libgal23           0.24-1.3           G App Libs (run time library)
ii  libgcc1            3.4.3-12           GCC support library
ii  libgconf11         1.0.9-2.1          GNOME configuration database
system libraries
ii  libgcrypt1         1.1.12-3           LGPL Crypto library - runtime
library
ii  libgcrypt7         1.1.90-9           LGPL Crypto library - runtime
library
ii  libgd-gif1         1.3-4              GD Graphics Library with gif
support
ii  libgd2             2.0.15-1           GD Graphics Library version 2
ii  libgd2-xpm         2.0.23-2           GD Graphics Library version 2
ii  libgdbm3           1.8.3-1            GNU dbm database routines (runtime
version)
ii  libgdbmg1          1.7.3-28           GNU dbm database routines (runtime
version)
ii  libgdk-pixbuf-gnom 0.22.0-2.0.1       The GNOME1 Canvas pixbuf library
ii  libgdk-pixbuf2     0.22.0-2.0.1       The GdkPixBuf image library, gtk+
1.2 version
ii  libgimp1.2         1.2.3-2.4          Libraries necessary to run the
GIMP, version 1.2
ii  libgimpprint1      4.2.5-3            Gimp-Print printer drivers - core
library
ii  libglade-gnome0    0.17-2.7           Library to load .glade files at
runtime (Gnome widge
ii  libglade0          0.17-2.7           Library to load .glade files at
runtime.
ii  libglib1.2         1.2.10-9           The GLib library of C routines
ii  libglib2.0-0       2.2.2-1            The GLib library of C routines
ii  libgnome32         1.4.2-14           The GNOME libraries
ii  libgnomeprint-bin  0.37-3             The GNOME Print architecture -
binary files
ii  libgnomeprint-data 0.37-3             The GNOME Print architecture -
data files
ii  libgnomeprint15    0.37-3             The GNOME Print architecture -
runtime library
ii  libgnomesupport0   1.4.2-14           The GNOME libraries (Support
libraries)
ii  libgnomeui32       1.4.2-14           The GNOME libraries (User
Interface)
ii  libgnorba27        1.4.2-14           GNOME CORBA services
ii  libgnorbagtk0      1.4.2-14           GNOME CORBA services (Gtk
bindings)
ii  libgnutls10        1.0.4-3            GNU TLS library - runtime library
ii  libgnutls5         0.8.8-2            GNU TLS library - runtime library
ii  libgnutls7         0.8.9-2            GNU TLS library - runtime library
ii  libgpg-error0      1.0-1              library for common error values
and messages in GnuP
ii  libgphoto2-2       2.1.1-9            The gphoto2 digital camera library
ii  libgphoto2-port0   2.1.1-9            The gphoto2 digital camera port
library
ii  libgpmg1           1.19.6-12.1        General Purpose Mouse Library
[libc6]
ii  libgsm1            1.0.10-13          Shared libraries for GSM speech
compressor
ii  libgtk-perl        0.7008-1.8         Perl module for the gtk+ library
ii  libgtk-pixbuf-perl 0.7008-1.8         Perl module for the gdkpixbuf
library
ii  libgtk1.2          1.2.10-16          The GIMP Toolkit set of widgets
for X
ii  libgtk1.2-common   1.2.10-16          Common files for the GTK+ library
ii  libgtk2.0-0        2.2.1-6            The GTK+ graphical user interface
library
ii  libgtk2.0-common   2.2.1-6            Common files for the GTK+
graphical user interface l
ii  libgtkhtml20       1.0.4-5.1          HTML rendering/editing library -
runtime files.
ii  libgtkxmhtml1      1.4.2-14           The GNOME gtkxmhtml (HTML) widget
ii  libhtml-parser-per 3.28-3             A collection of modules that parse
HTML text documen
ii  libhtml-tagset-per 3.03-2             Data tables pertaining to HTML
ii  libhtml-tree-perl  3.17-1             represent and create HTML syntax
trees
ii  libident           0.22-2.2           simple RFC1413 client library -
runtime
ii  libidn9            0.1.14-2           GNU libidn library, implementation
of IETF IDN speci
ii  libieee1284-3      0.2.8-1            Cross-platform library for
parallel port access
ii  libiodbc2          3.0.6-4            iODBC Driver Manager
ii  libisc4            9.2.2-2            ISC Shared Library used by BIND
ii  libjpeg62          6b-8               The Independent JPEG Group's JPEG
runtime library
ii  libkeynote0        2.3-10             Decentralized Trust-Management
system, shared librar
ii  libkrb53           1.3.6-2            MIT Kerberos runtime libraries
ii  liblcms1           1.10-1             Color management library
ii  libldap2           2.1.22-1           OpenLDAP libraries
rc  libldap2-tls       2.0.27-4           OpenLDAP libraries (with TLS
support).
ii  liblocale-gettext- 1.01-17            Using libc functions for
internationalization in Per
ii  liblockfile-simple 0.2.5-4            Simple advisory file locking
ii  liblockfile1       1.05               NFS-safe locking library, includes
dotlockfile progr
ii  libltdl3           1.5.6-6            A system independent dlopen
wrapper for GNU libtool
ii  libltdl3-dev       1.5.6-6            A system independent dlopen
wrapper for GNU libtool
ii  liblua50           5.0.2-3            Main interpreter library for the
Lua 5.0 programming
ii  liblualib50        5.0.2-3            Extension library for the Lua 5.0
programming langua
ii  liblwres1          9.2.2-2            Lightweight Resolver Library used
by BIND
ii  liblzo1            1.08-1             A real-time data compression
library
ii  libmagic1          4.02-4             File type determination library
using "magic" number
ii  libmagick5.5.7     5.5.7.9-1          Image manipulation library (free
version)
ii  libmail-sendmail-p 0.79-1             Send email from a perl script
ii  libmm11            1.1.3-6.1          Shared memory library
ii  libmm13            1.3.0-1            Shared memory library - runtime
ii  libmysqlclient10   3.23.56-2          LGPL-licensed client library for
MySQL databases
ii  libmysqlclient10-d 3.23.56-2          LGPL-licensed client development
files for MySQL dat
ii  libmysqlclient12   4.0.13-3           mysql database client library
ii  libncurses5        5.4-4              Shared libraries for terminal
handling
ii  libncurses5-dev    5.4-4              Developer's libraries and docs for
ncurses
ii  libnet-dns-perl    0.46-2             Perform DNS queries from a Perl
script
ii  libnet-perl        1.18-4             Implementation of Internet
protocols for Perl
ii  libnet-rawip-perl  0.10-1             Perl interface to lowlevel TCP/IP
ii  libnet-snmp-perl   4.0.3-1            Script SNMP connections
ii  libnet-ssleay-perl 1.25-1             Perl module for Secure Sockets
Layer (SSL)
ii  libnewt0           0.50.17-9.6        Not Erik's Windowing Toolkit -
text mode windowing w
ii  libnewt0.51        0.51.4-14          Not Erik's Windowing Toolkit -
text mode windowing w
rc  libnss-db          2.2-6              DB Name Service Module
ii  liboaf0            0.6.10-3           The GNOME Object Activation
Framework.
ii  libopencdk4        0.4.2-3            Open Crypto Development Kit
(OpenCDK) (runtime)
ii  libopencdk8        0.5.5-8            Open Crypto Development Kit
(OpenCDK) (runtime)
ii  liborbit0          0.5.17-9           Libraries for ORBit - a CORBA ORB
ii  libpam-modules     0.76-13            Pluggable Authentication Modules
for PAM
ii  libpam-pwgen       0.1-2              a password generator
ii  libpam-runtime     0.76-22            Runtime support for the PAM
library
ii  libpam0g           0.76-13            Pluggable Authentication Modules
library
ii  libpanel-applet0   1.4.2-1            Library for GNOME Panel applets
ii  libpango1.0-0      1.2.3-1            Layout and rendering of
internationalized text
ii  libpango1.0-common 1.2.3-1            Modules and configuration files
for the Pango
ii  libpaper-utils     1.1.13             Library for handling paper
characteristics (utilitie
ii  libpaper1          1.1.13             Library for handling paper
characteristics
ii  libpaperg          1.1.13             Library for handling paper
characteristics (dummy pa
ii  libpcap0           0.6.2-2            System interface for user-level
packet capture.
ii  libpcap0.7         0.7.2-1            System interface for user-level
packet capture.
ii  libpcre3           4.5-1.1            Perl 5 Compatible Regular
Expression Library - runti
ii  libperl-dev        5.8.3-3            Perl library: development files.
ii  libperl5.6         5.6.1-8.2          Shared Perl library.
ii  libperl5.8         5.8.3-3            Shared Perl library.
ii  libpgsql2          7.2.1-2            Shared library libpq.so.2 for
PostgreSQL
ii  libphp-adodb       4.21-1             The 'adodb' database abstraction
layer for php
ii  libpng10-0         1.0.15-4           PNG library, older version -
runtime
ii  libpng12-0         1.2.5.0-4          PNG library - runtime
ii  libpng2            1.0.15-4           PNG library, older version -
runtime
ii  libpng3            1.2.5.0-4          PNG library - runtime
ii  libpopt0           1.7-2              lib for parsing cmdline parameters
ii  libpq3             7.4.7-3            PostgreSQL C client library
ii  libpri1            1.0.7-1            Primary Rate ISDN specification
library
ii  libreadline4       4.3-5              GNU readline and history
libraries, run-time librari
ii  libregexp-common-p 2.113-1            Provide commonly requested regular
expressions
ii  librrd0            1.0.42-2           Time-series data storage and
display system (runtime
ii  librsync-dev       0.9.5.1-3          Binary diff library based on the
rsync algorithm
ii  librsync1          0.9.5.1-3          Binary diff library based on the
rsync algorithm
ii  librudiments0c102  0.27-3             C++ class library providing base
classes
ii  libsane            1.0.12-5           API library for scanners
ii  libsasl2           2.1.12-1           Authentication abstraction library
ii  libsasl7           1.5.27-3.5         Authentication abstraction
library.
ii  libsensors3        2.9.0-9            library to read
temperature/voltage/fan sensors
ii  libslp1            1.0.11-2           OpenSLP libraries
ii  libsnmp-base       5.1.1-2            NET SNMP (Simple Network
Management Protocol) MIBs a
ii  libsnmp-perl       5.1.1-2            NET SNMP (Simple Network
Management Protocol) Perl5
ii  libsnmp4.2         4.2.5-3.3          NET SNMP (Simple Network
Management Protocol) Librar
ii  libsnmp4.2-dev     4.2.5-3.3          NET SNMP (Simple Network
Management Protocol) Develo
ii  libsnmp5           5.1.1-2            NET SNMP (Simple Network
Management Protocol) Librar
ii  libspeex1          1.1.6-2            The Speex Speech Codec
ii  libsqlite0         2.8.16-1           SQLite shared library
ii  libssl-dev         0.9.7b-2           SSL development libraries, header
files and document
ii  libssl0.9.6        0.9.6j-1           SSL shared libraries (old version)
ii  libssl0.9.7        0.9.7b-2           SSL shared libraries
ii  libstdc++2.10-dev  2.95.4-17          The GNU stdc++ library
(development files)
ii  libstdc++2.10-glib 2.95.4-17          The GNU stdc++ library
ii  libstdc++3         3.0.4-7            The GNU stdc++ library version 3
ii  libstdc++5         3.3.5-8            The GNU Standard C++ Library v3
ii  libstdc++5-3.3-dev 3.3.5-8            The GNU Standard C++ Library v3
(development files)
ii  libsybdb3          0.61-6.1           libraries for connecting to MS SQL
and Sybase SQL se
ii  libtasn1-0         0.1.2-1            Manage ASN.1 structures (runtime)
ii  libtasn1-2         0.2.10-3           Manage ASN.1 structures (runtime)
ii  libtext-charwidth- 0.04-1             get display widths of characters
on the terminal
ii  libtext-iconv-perl 1.2-2              Convert between character sets in
Perl
ii  libtext-wrapi18n-p 0.06-1             internationalized substitute of
Text::Wrap
ii  libtiff-tools      3.5.7-2            TIFF manipulation and conversion
tools
ii  libtiff3g          3.5.7-2            Tag Image File Format library
ii  libtime-modules-pe 2003.0211-1        Various Perl modules for time/date
manipulation
ii  libtonezone1       1.0.7-3            tonezone library (runtime)
ii  libtool            1.4.3-10           Generic library support script
ii  libungif4g         4.1.0b1-5          shared library for GIF images
(runtime lib)
ii  libunix-syslog-per 0.100-2            Perl interface to the UNIX
syslog(3) calls
ii  liburi-perl        1.23-1             Manipulates and accesses URI
strings
ii  libusb-0.1-4       0.1.7-2            Userspace USB programming library
ii  libwmf0.2-7        0.2.8-1            Windows metafile conversion
library
ii  libwrap0           7.6-ipv6.1-3       Wietse Venema's TCP wrappers
library
ii  libwww-perl        5.69-3             WWW client/server library for Perl
(aka LWP)
ii  libxaw7            4.2.1-6            X Athena widget set library
ii  libxft2            2.1.1-2            advanced font drawing library for
X
ii  libxml1            1.8.17-2           GNOME XML library
ii  libxml2            2.6.16-4           GNOME XML library
ii  libxml2-utils      2.6.16-4           XML utilities
ii  libzvt2            1.4.2-14           The GNOME zvt (zterm) widget
ii  lilo               22.5.7.2-1         LInux LOader - The Classic OS
loader can load Linux
ii  links              0.99-1.2           Character mode WWW browser
ii  links-ssl          0.99-1.2           Dummy package for transition to
elinks
ii  linux-kernel-heade 2.5.999-test7-bk-1 Linux Kernel Headers for
development
ii  liwc               1.20-2             Tools for manipulating C source
code
ii  lm-sensors         2.9.0-9            utilities to read
temperature/voltage/fan sensors
ii  locales            2.3.2.ds1-20       GNU C Library: National Language
(locale) data [supp
ii  login              4.0.3-8            System login tools
ii  logrotate          3.6.5-2            Log rotation utility
ii  lpr                2000.05.07-4.20    BSD lpr/lpd line printer spooling
system
ii  lrzsz              0.12.21-4          Tools for zmodem/xmodem/ymodem
file transfer
ii  lsof               4.64-1             List open files.
ii  ltrace             0.3.31             Tracks runtime library calls in
dynamically linked p
ii  lynx               2.8.4.1b-5         Text-mode WWW Browser
ii  m4                 1.4-16             a macro processing language
ii  magicfilter        1.2-55             automatic printer filter
ii  mailx              8.1.2-0.20030521cv A simple mail user agent
ii  make               3.80-2             The GNU version of the "make"
utility.
ii  makedev            2.3.1-63           Creates device files in /dev
ii  man-db             2.4.1-13           The on-line manual pager
ii  manpages           1.60-2             Manual pages about using a
GNU/Linux system
ii  manpages-dev       1.60-2             Manual pages about using GNU/Linux
for development
ii  mantis             0.17.5-8           A php/MySQL/web based bug tracking
system
ii  mawk               1.3.3-11           a pattern scanning and text
processing language
ii  mbr                1.1.5-1            Master Boot Record for IBM-PC
compatible computers.
ii  mc                 4.5.55-1.2         Midnight Commander - A powerful
file manager. - norm
ii  mc-common          4.5.55-1.2         Common files for mc and gmc
ii  mime-support       3.23-1             MIME files 'mime.types' &
'mailcap', and support pro
ii  mimedecode         1.9-2              Decodes transfer encoded text type
mime messages.
ii  minicom            2.1-6              friendly menu driven serial
communication program
ii  modconf            0.2.44             Device Driver Configuration
ii  modutils           2.4.21-3           Linux module utilities
ii  mount              2.11z-1            Tools for mounting and
manipulating filesystems.
ii  mpack              1.6-1              tools for encoding/decoding MIME
messages
ii  mtools             3.9.9-1            Tools for manipulating MSDOS files
ii  mtr-tiny           0.54-1             Full screen ncurses traceroute
tool
ii  mutt               1.5.4-1            Text-based mailreader supporting
MIME, GPG, PGP and
ii  mysql-client       4.0.13-3           mysql database client binaries
ii  mysql-common       4.0.13-3           mysql database common files (e.g.
/etc/mysql/my.cnf)
ii  mysql-server       4.0.13-3           mysql database server binaries
ii  nagios-text        1.1-1              A host/service/network monitoring
and management sys
ii  nano               1.2.2-1            free Pico clone with some new
features
ii  ncftp              3.1.8-1            A user-friendly and well-featured
FTP client
ii  ncurses-base       5.3.20030719-1     Descriptions of common terminal
types
ii  ncurses-bin        5.3.20030719-1     Terminal-related programs and man
pages
ii  ncurses-term       5.3.20030719-1     Additional terminal type
definitions
ii  net-tools          1.60-8             The NET-3 networking toolkit
ii  netbase            4.13               Basic TCP/IP networking system
ii  netcdfg3           3.5.0-7            An interface for scientific data
access.
ii  netkit-inetd       0.10-9             The Internet Superserver
ii  netsaint-plugins   1.2.9.4-18.1       Plugins for NetSaint
ii  netsaint-plugins-e 1.2.9.4-18.1       Extra plugins for NetSaint (dummy
package with depen
ii  netsaint-plugins-f 1.2.9.4-18.1       check_fping plugin for NetSaint
ii  netsaint-plugins-g 1.2.9.4-18.1       check_game plugin for NetSaint
ii  netsaint-plugins-l 1.2.9.4-18.1       check_ldap plugin for NetSaint
ii  netsaint-plugins-m 1.2.9.4-18.1       check_mysql plugin for NetSaint
ii  netsaint-plugins-p 1.2.9.4-18.1       check_pgsql plugin for NetSaint
ii  netsaint-plugins-r 1.2.9.4-18.1       check_radius plugin for NetSaint
ii  netsaint-plugins-s 1.2.9.4-18.1       check_snmp and check_hpjd plugins
for NetSaint
ii  nfs-common         1.0.5-3            NFS support files common to client
and server
ii  nmap               3.27-1             The Network Mapper
ii  nowebm             2.10c-2            A WEB-like literate-programming
tool
ii  ntp                4.2.0a-11          Network Time Protocol: network
utilities
ii  ntp-server         4.2.0a-11          Network Time Protocol: common
server tools
ii  ntp-simple         4.2.0a-11          Network Time Protocol: daemon for
simple systems
ii  nvi                1.79-21            4.4BSD re-implementation of vi
ii  oaf                0.6.10-3           The GNOME Object Activation
Framework.
ii  odbcinst1          2.2.4-11           Support library and helper program
for accessing odb
rc  opennms            1.1.1-1            A network management system.
ii  openssl            0.9.7b-2           Secure Socket Layer (SSL) binary
and related cryptog
ii  otp                970425-6           Generator for One Time Passwords
ii  passwd             4.0.3-8            Change and administer password and
group data.
ii  patch              2.5.9-1            Apply a diff file to an original
ii  pciutils           2.1.11-2           Linux PCI Utilities (for
2.[12345].x kernels)
ii  perl               5.8.3-3            Larry Wall's Practical Extraction
and Report Languag
ii  perl-base          5.8.3-3            The Pathologically Eclectic
Rubbish Lister.
ii  perl-modules       5.8.3-3            Core Perl modules.
ii  php4               4.3.3-4            A server-side, HTML-embedded
scripting language
ii  php4-cgi           4.3.4-4            A server-side, HTML-embedded
scripting language
ii  php4-gd2           4.3.2+rc3-2        GD module (with GD2) for php4
ii  php4-ldap          4.3.4-4            LDAP module for php4
ii  php4-mysql         4.3.4-4            MySQL module for php4
ii  php4-snmp          4.3.4-4            SNMP module for php4
ii  phpmyadmin         2.5.7-pl1-1        A set of PHP-scripts to
administrate MySQL over the
ii  pidentd            3.0.16-3           TCP/IP IDENT protocol server with
DES support.
ii  portmap            5-2                The RPC portmapper
ii  ppp                2.4.1.uus-5        Point-to-Point Protocol (PPP)
daemon.
ii  pppconfig          2.2.0              A text menu based utility for
configuring ppp
ii  pppoe              3.5-1              PPP over Ethernet driver
ii  pppoeconf          0.9.10.10          configures PPPoE/ADSL connections
ii  procmail           3.22-7             Versatile e-mail processor.
ii  procps             3.1.9-1            The /proc file system utilities
ii  psfontmgr          0.11.4             PostScript font manager -- part of
Defoma, Debian Fo
ii  psmisc             21.3-1             Utilities that use the proc
filesystem
ii  python             2.2.3-3            An interactive high-level
object-oriented language (
ii  python-egenix-mxda 2.0.4-1            Date and time handling routines
for Python [dummy pa
ii  python-extclass    1.2.0zope-2.5.1-1. Improves integration between
Python and C++ classes
ii  python-gadfly      1.0.0-3            SQL database and parser generator
for Python [dummy
ii  python-gdk-imlib   0.6.11-8           GTK gdk_imlib support module for
Python.
ii  python-gendoc      0.73-9             Documentation generation from
Python source files.
ii  python-glade       0.6.11-8           Put a bit of python code behind
interfaces built wit
ii  python-gnome       1.4.4-8            PyGNOME -- Python bindings for
GNOME.
ii  python-gtk         0.6.11-8           GTK support module for Python.
ii  python-htmlgen     2.2.2-9            Python library for the generation
of HTML
ii  python-imaging     1.1.4-1            The Python Imaging Library
ii  python-imaging-san 1.1.4-1            The Python Imaging Library SANE
interface
ii  python-imaging-tk  1.1.4-1            The Python Imaging Library (Module
with Tk support)
ii  python-kjbuckets   1.0.0-3            Set and graph data types for
Python [dummy package]
ii  python-netcdf      2.4.3-2            A netCDF interface for Python
ii  python-newt        0.51.4-14          A NEWT module for Python
ii  python-numeric     23.0-5             Numerical (matrix-oriented)
Mathematics for Python
ii  python-numeric-tut 23.0-5             Tutorial for the Numerical Python
Library
ii  python-pmw         0.8.5-6.1          Pmw -- Python MegaWidgets
ii  python-tk          2.2.3-3            Tkinter - Writing Tk applications
with Python (defau
ii  python-xml         0.8.2-3            XML tools for Python [dummy
package]
ii  python2.1          2.1.3-20           An interactive high-level
object-oriented language (
ii  python2.1-egenix-m 2.0.4-1            Date and time handling routines
for Python 2.1
ii  python2.1-egenix-m 2.0.4-1            A collection of new builtins for
Python 2.1
ii  python2.1-imaging  1.1.4-1            The Python Imaging Library
ii  python2.1-imaging- 1.1.4-1            The Python Imaging Library SANE
interface
ii  python2.1-imaging- 1.1.4-1            The Python Imaging Library (Module
with Tk support)
ii  python2.1-kjbucket 1.0.0-3            Set and graph data types for
Python 2.1
ii  python2.1-numeric  23.0-5             Numerical (matrix-oriented)
Mathematics for Python
ii  python2.1-tk       2.1.3-20           Tkinter - Writing Tk applications
with Python (v2.1)
ii  python2.1-xml      0.8.2-3            XML tools for Python (2.1.x)
ii  python2.1-xmlbase  2.1.3-20           XML support included in Python
(v2.1)
ii  python2.2          2.2.3dfsg-1        An interactive high-level
object-oriented language (
ii  python2.2-dev      2.2.3dfsg-1        Header files and a static library
for Python (v2.2)
ii  python2.2-egenix-m 2.0.4-1            Date and time handling routines
for Python 2.2
ii  python2.2-egenix-m 2.0.4-1            A collection of new builtins for
Python 2.2
ii  python2.2-extclass 1.2.0zope-2.5.1-1. Improves integration between
Python and C++ classes
ii  python2.2-gadfly   1.0.0-3            SQL database and parser generator
for Python 2.2
ii  python2.2-htmlgen  2.2.2-9            Generation of HTML documents with
Python scripts
ii  python2.2-imaging  1.1.4-1            The Python Imaging Library
ii  python2.2-imaging- 1.1.4-1            The Python Imaging Library SANE
interface
ii  python2.2-imaging- 1.1.4-1            The Python Imaging Library (Module
with Tk support)
ii  python2.2-kjbucket 1.0.0-3            Set and graph data types for
Python 2.2
ii  python2.2-numeric  23.0-5             Numerical (matrix-oriented)
Mathematics for Python
ii  python2.2-optik    1.4.1-1            advanced command-line parsing
library for Python 2.2
ii  python2.2-tk       2.2.3dfsg-1        Tkinter - Writing Tk applications
with Python (v2.2)
ii  python2.2-xml      0.8.2-3            XML tools for Python (2.2.x)
ii  python2.2-xmlbase  2.2.3dfsg-1        XML support included in Python
(v2.2)
ii  qstat              2.5c-1             Command-line tool for querying
quake (and other) ser
ii  rancid-cgi         2.3.1-1            CGI for rancid
ii  rancid-core        2.3.1-1            rancid -- Really Awesome New Cisco
confIg Differ
ii  rancid-util        2.3.1-1            Utilities for rancid
ii  rcs                5.7-13.1           The GNU Revision Control System
ii  rdate              1.4-4              Set the system's date from a
remote host.
ii  reportbug          2.20               Reports bugs in the Debian
distribution
ii  rrdtool            1.0.42-2           Time-series data storage and
display system (program
ii  samba              3.0.0beta2-1       a LanManager-like file and printer
server for Unix
ii  samba-common       3.0.0beta2-1       Samba common files used by both
the server and the c
ii  sed                4.0.7-1            The GNU sed stream editor
ii  setserial          2.17-33            Controls configuration of serial
ports
ii  sharutils          4.2.1-10           shar, unshar, uuencode, uudecode
ii  shellutils         5.0-5              The GNU shell programming
utilities (transitional pa
ii  slang1             1.4.5-2.1          The S-Lang programming library -
runtime version.
ii  slang1a-utf8       1.4.5-2.1          The S-Lang programming library
with utf8 support
ii  slapd              2.1.22-1           OpenLDAP server (slapd)
ii  smartsuite         2.1-1              SMART suite - SMART utility suite
for Linux
ii  snmp               5.1.1-2            NET SNMP (Simple Network
Management Protocol) Apps
ii  snmpd              5.1.1-2            NET SNMP (Simple Network
Management Protocol) Agents
ii  sqlrelay           0.35-6.1           Database connection pooling,
proxying and load balan
ii  sqlrelay-freetds   0.35-6.1           SQL Relay FreeTDS (Sybase and MS
SQL Server) connect
ii  squid              2.5.3-8            Internet Object Cache (WWW proxy
cache)
ii  squid-cgi          2.5.3-8            Squid cache manager CGI program
ii  squidguard         1.2.0-5            filter, redirector and access
controller plug for Sq
ii  ssh                3.6.1p2-3          Secure rlogin/rsh/rcp replacement
(OpenSSH)
ii  stl-manual         3.30-4             C++-STL documentation in HTML
ii  strace             4.4.99-1           A system call tracer
rc  sysklogd           1.4.1-10           System Logging Daemon
ii  syslinux           2.04-1             Bootloader for Linux/i386 using
MS-DOS floppies
ii  syslog-ng          1.6.0rc1+20030310- Next generation logging daemon
ii  sysv-rc            2.85-7             Standard boot mechanism using
symlinks in /etc/rc?.d
ii  sysvinit           2.86.ds1-1         System-V like init
ii  t1lib1             1.3.1-1            Type 1 font rasterizer library -
runtime
ii  tar                1.13.25-5          GNU tar
ii  tasksel            1.25               Tool for selecting tasks for
installation on Debian
ii  tcl8.0             8.0.5-7            The Tool Command Language (TCL)
v8.0 - Run-Time File
ii  tcl8.3             8.3.5-3            Tcl (the Tool Command Language)
v8.3 - run-time file
ii  tcl8.4             8.4.9-1            Tcl (the Tool Command Language)
v8.4 - run-time file
ii  tcpd               7.6-ipv6.1-3       Wietse Venema's TCP wrapper
utilities
ii  tcpdump            3.7.2-1            A powerful tool for network
monitoring and data acqu
ii  tcsh               6.12.00-4          TENEX C Shell, an enhanced version
of Berkeley csh
ii  telnet             0.17-20            The telnet client.
ii  texinfo            4.6-1              Documentation system for on-line
information and pri
ii  textutils          5.0-5              The GNU text file processing
utilities (transitional
ii  time               1.7-16             The GNU time command.
ii  tinysnmp-tools     0.4.4.1            TinySNMP Utilities
ii  tix41              4.1.0.7-4.1        The Tix library for Tk, version
4.1 -- runtime packa
ii  tix8.1             8.1.4-1            The Tix library for Tk, version
8.1 -- runtime packa
ii  tk8.3              8.3.5-3            Tk toolkit for Tcl and X11, v8.3 -
run-time files
ii  tk8.4              8.4.9-1            Tk toolkit for Tcl and X11, v8.4 -
run-time files
ii  traceroute         1.4a12-12          Traces the route taken by packets
over a TCP/IP netw
ii  ucf                1.07               Update Configuration File:
preserves user changes to
ii  unixodbc           2.2.4-11           ODBC tools libraries
ii  unzip              5.50-3             De-archiver for .zip files
ii  util-linux         2.11z-1            Miscellaneous system utilities.
ii  util-linux-locales 2.11z-1            Locales files for util-linux
ii  uudeview           0.5.19+beta2003041 Smart multi-file multi-part
decoder (command line)
ii  vacation           3.3.0              email autoresponder
rc  video-dvdrip       0.50.14-woody0.1   Perl front end for transcode
ii  wamerican          5-3                American English dictionary words
for /usr/share/dic
ii  webmin             1.150-2            Web-based administration toolkit
ii  wenglish           5-3                American English dictionary words
for /usr/share/dic
ii  wget               1.8.2-11           retrieves files from the web
ii  whiptail           0.51.4-14          Displays user-friendly dialog
boxes from shell scrip
ii  whois              4.6.7              The GNU whois client
ii  wwwconfig-common   0.0.30             Debian web auto configuration
ii  xfree86-common     4.2.1-6            X Window System (XFree86)
infrastructure
ii  xlibs              4.2.1-6            X Window System client libraries
ii  xpdf               2.02pl1-1          Portable Document Format (PDF)
suite
ii  xpdf-common        2.02pl1-1          Portable Document Format (PDF)
suite -- common files
ii  xpdf-reader        2.02pl1-1          Portable Document Format (PDF)
suite -- viewer for X
ii  xpdf-utils         2.02pl1-1          Portable Document Format (PDF)
suite -- utilities
ii  xutils             4.2.1-6            X Window System utility programs
ii  zlib1g             1.2.1.1-3          compression library - runtime
ii  zlib1g-dev         1.2.1.1-3          compression library - development
hooch:~/Download/Asterisk/MSSQL-0.09#

From maxnoel_fr at yahoo.fr  Sat Apr  9 10:47:01 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr  9 10:47:04 2005
Subject: [Tutor] newb problem running the translator (fwd)
In-Reply-To: <Pine.LNX.4.44.0504090136380.17924-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504090136380.17924-100000@hkn.eecs.berkeley.edu>
Message-ID: <0269f1f62c7fa5e80627e86673c0ad98@yahoo.fr>


On Apr 9, 2005, at 10:36, Danny Yoo wrote:

>
>
> ---------- Forwarded message ----------
> Date: Fri, 8 Apr 2005 22:03:58 EDT
> From: Drumming4NOTA@aol.com
> To: tutor-owner@python.org
> Subject: newb problem running the translator
>
>     I will try to make this quick. I am a newb to python, and 
> programming at
> that, but i am realy interested. I have been looking at simple 
> programs to be
> run through the shell but i cannot figure out the translator. When i 
> save
> program i have tried to tell it to opoen it in the translator. I have 
> been looking
> through several websites and looked through the documents my python
> installation came with. On one computer i am running Windows Xp and on 
> another win98SE.
> If you could explain to me how to open a program through the 
> translator i
> would appreciate it alot.

	What exactly do you call the "translator"?
	If you mean the compiler, it's normal that you can't find it: there is 
none. Python is an interpreted language (well, bytecode, but let's not 
get into that, shall we?). To run your Python programs, you call the 
Python interpreter on them: "python foo.py", for example, runs the 
foo.py program.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From kent37 at tds.net  Sat Apr  9 13:45:27 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 13:45:55 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <20050409044521.26246.qmail@webmail10.mesa1.secureserver.net>
References: <20050409044521.26246.qmail@webmail10.mesa1.secureserver.net>
Message-ID: <4257C057.6070507@tds.net>

smiles@saysomething.com wrote:
> I was glad to see your post showing how to run a list of functions 
> through the timer.  That's a nice way to do it!  You better slip some 
> square brackets into your definition of d though:
> 
>  
> 
>     d = dict( [((i,i,i), i) for i in range(1000)])

In Python 2.4 they are not needed. For earlier versions, you are right. (((i,i,i), i) for i in 
range(1000)) is a generator expression. It's value is a generator object that supports the iterator 
protocol.

  >>> g=(((i,i,i), i) for i in range(1000))
  >>> g
<generator object at 0x008D7198>
  >>> g.next()
((0, 0, 0), 0)
  >>> g.next()
((1, 1, 1), 1)

In general, if you replace the [] of a list comprehensions with () you will get a generator 
comprehension. The () are required but syntactically they can be part of the function call syntax - 
you don't have to add another () if one is present.

BTW a note about timing for optimization - it is important to do your timing on the same Python 
version that you will deploy with; there have been significant speedups in portions of Python 2.4 
and 2.3. For example list comprehension has gotten much faster.

Kent

From cyresse at gmail.com  Sat Apr  9 14:09:36 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sat Apr  9 14:09:39 2005
Subject: [Tutor] chr() and extended ASCII?
Message-ID: <f2ff2d05040905096138d665@mail.gmail.com>

Hi all, 

Just working on some validators for text fields, and I started getting 
unusual errors - 

File "C:\Python23\lib\site-packages\PythonCard\components\textfield.py", 
line 338, in _dispatch
widget.Widget._dispatch(self, aWxEvent)
File "C:\Python23\lib\site-packages\PythonCard\widget.py", line 402, in 
_dispatch
handler(background, aWxEvent)
File "C:\Python23\SEDB\generic.py", line 53, in on_keyPress
elif len(eventSourceWidget.text) >=
self.restrictions[eventSourceWidget.name<http://eventSourceWidget.name>]['length']
or not self.isOK(eventSourceWidget.name <http://eventSourceWidget.name>, 
event.keyCode):
File "C:\Python23\SEDB\generic.py", line 69, in isOK
xR = self.integerRE.search(chr(keyCode))
ValueError: chr() arg not in range(256)

(And yes, I know wxPython has validators already, I was 90% through mine 
when I found them, and so I'll finish off the last 10% out of stubborn 
pride.)

For the life of me, I couldn't figure out what was happening, so I stuck in 
a try clause. 

*******
Oops
keyCode = 333
Widget = dateBooked
*******

*******
Oops
keyCode = 332
Widget = dateBooked
*******

I was entering numeric data, and as I do a lot of data entry at work, by 
default I use the numeric keypad, so I guess I just found that extended 
ASCII stuff. Is there a easy way around this with chr()?

Or is it a case of making my own keycode to character dictionary? I'm 
feeling lazy at the moment.

Regards, 


Liam Clarke

-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050410/a1e89358/attachment.htm
From albertito_g at hotmail.com  Sat Apr  9 14:41:22 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr  9 14:41:25 2005
Subject: [Tutor] Support
In-Reply-To: <4256D5CA.8090605@tds.net>
Message-ID: <BAY106-F3556DAB56CB079C3DF19C789300@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050409/0cb5f32f/attachment.htm
From albertito_g at hotmail.com  Sat Apr  9 14:49:29 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr  9 14:49:33 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <4257C057.6070507@tds.net>
Message-ID: <BAY106-F38CB1AE3BB7AA3B1CA500F89300@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050409/d3eeb5fe/attachment.htm
From jeannot18 at hotmail.com  Sat Apr  9 16:21:25 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Sat Apr  9 16:21:30 2005
Subject: [Tutor] How can I suspend...
Message-ID: <BAY20-F175F07CA5CA089D5323480B3300@phx.gbl>

I am off to sunny Spain for the next 2 weeks and I would like to suspend the 
emailing from Python.tutor for that period. Could someone put me in the 
right direction on how to do that, thanks.

Regards
JC


From cpu.crazy at gmail.com  Sat Apr  9 00:46:33 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat Apr  9 16:34:37 2005
Subject: [Tutor] Re: Help with classes (Joseph Q.)
In-Reply-To: <20050408100115.BB4721E40A3@bag.python.org>
References: <20050408100115.BB4721E40A3@bag.python.org>
Message-ID: <6.1.0.6.2.20050408163818.01eeb628@pop.gmail.com>

class Message:
   def init(self, p = 'Hello world'):
      self.text = p
   def sayIt(self):
      print self.text

m = Message()
m.init()
m.sayIt()
m.init('Hiya fred!')
m.sayIt()



> > Well this OOP stuff is realy hard for me as I have never even
> > programmed it took me a while just to understand defs.
>
>That's OK, OOP is quite a strange concept for many folks. Its
>actually easier to learn as a beginner than for folks who
>have been programming without OOP for a long time!
>
> > determined to learn how to do it. My biggest problem is with
>__init__
> > I still don't understand how to use it.
>
>init is simply where you initialise the data attributes of your class.
>
>It could be defined as a normal method and you call it explicitly:
>
>class Message:
>   def init(self, txt = 'Hello world'):
>      self.text = txt
>   def sayIt(self):
>      print self.text
>
>And every time you create a message object you explicitly call it:
>
>m = Message()
>m.init('Hiya fred!')
>m.sayIt()

I was having problems with the __init__ too.

class Message:
   def init(self, txt = 'Hello world'):
      self.text = txt
   def sayIt(self):
      print self.text

And every time you create a message object you explicitly call it:

m = Message()
m.init()
m.sayIt()
m.init("Hello World is so overdone. It hard to break tradition though :->")
m.sayIt()

Why did you put 'Hiya fred!' in place of having m.init print "Hello World"?

Now what are dictionaries and the __name__ really used for? A byte of 
python never got that through my thick skull.

From cpu.crazy at gmail.com  Sat Apr  9 00:58:37 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat Apr  9 16:34:39 2005
Subject: [Tutor] import.... (Joseph Q.)
Message-ID: <6.1.0.6.2.20050408165605.01e87ca8@pop.gmail.com>

I don't think I have said it already, but I'll say it again just incase 
:-), I'm new to python. I started Feb. this year.

import is handy. But my questions are:
is there a type of unimport or something to unload a module? Foo: What's it 
good for?

From albertito_g at hotmail.com  Sat Apr  9 16:40:44 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr  9 16:40:47 2005
Subject: [Tutor] import.... (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050408165605.01e87ca8@pop.gmail.com>
Message-ID: <BAY106-F176F8064944EBD1A41C08389300@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050409/2e0d4a72/attachment.htm
From kent37 at tds.net  Sat Apr  9 17:17:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 17:17:46 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <BAY106-F38CB1AE3BB7AA3B1CA500F89300@phx.gbl>
References: <BAY106-F38CB1AE3BB7AA3B1CA500F89300@phx.gbl>
Message-ID: <4257F215.5030302@tds.net>

Alberto Troiano wrote:
> Sorry to bother you that much. I know I have a lot to learn yet but I 
> hope you can teach me.
> 
> I see that someone posted something about running functions with a 
> timer. How can I do this???

You can use the timeit module, see my recent post for an example.

You can also use time.time() directly like this:
import time
start = time.time()
# do something that you want to time...
elapsed = time.time() - start

now elapsed is the elapsed time in seconds as a floating point number.

Kent

From kent37 at tds.net  Sat Apr  9 17:21:10 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 17:21:14 2005
Subject: [Tutor] How can I suspend...
In-Reply-To: <BAY20-F175F07CA5CA089D5323480B3300@phx.gbl>
References: <BAY20-F175F07CA5CA089D5323480B3300@phx.gbl>
Message-ID: <4257F2E6.1050905@tds.net>

Go to the address at the bottom of this email. Unsubscribe. When you return, re-subscribe.

Kent

John Carmona wrote:
> I am off to sunny Spain for the next 2 weeks and I would like to suspend 
> the emailing from Python.tutor for that period. Could someone put me in 
> the right direction on how to do that, thanks.
> 
> Regards
> JC
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Sat Apr  9 17:23:34 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 17:23:39 2005
Subject: [Tutor] import.... (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050408165605.01e87ca8@pop.gmail.com>
References: <6.1.0.6.2.20050408165605.01e87ca8@pop.gmail.com>
Message-ID: <4257F376.3090104@tds.net>

Joseph Quigley wrote:
> I don't think I have said it already, but I'll say it again just incase 
> :-), I'm new to python. I started Feb. this year.
> 
> import is handy. But my questions are:
> is there a type of unimport or something to unload a module? 

This is not normally needed.

Foo: What's
> it good for?

Foo and Bar are popular names used in examples. They don't mean anything. For example to show how to 
define a function I might write

def foo():
   print 'Hello'

I just use foo to avoid having to think of a meaningful name.

Kent

From python.programming at gmail.com  Sat Apr  9 17:51:41 2005
From: python.programming at gmail.com (Kevin)
Date: Sat Apr  9 17:51:45 2005
Subject: [Tutor] re: IDLE
Message-ID: <d082fff805040908516c45869e@mail.gmail.com>

Is there a way to get line numbers to show in python IDLE? I looked at
all the preferances but nothing?

Thanks

Kevin
From python at venix.com  Sat Apr  9 17:59:21 2005
From: python at venix.com (Lloyd Kvam)
Date: Sat Apr  9 18:00:13 2005
Subject: [Tutor] Talking to mssql?
Message-ID: <4257FBD9.5070103@venix.com>

I replied earlier from a digest entry (which starts a new thread) so you might have missed that reply.
I included a URL for the mssql package which included the compile instructions for using freetds.
Here is the link.  Just follow the instructions and you should be able to compile cleanly.

http://mail.python.org/pipermail/db-sig/2005-April/004403.html
A new sybase module has been released.  Note the instructions for
installing with freetds.



From geek_show at dsl.pipex.com  Sat Apr  9 18:01:28 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Sat Apr  9 18:01:34 2005
Subject: [Tutor] re: IDLE
In-Reply-To: <d082fff805040908516c45869e@mail.gmail.com>
References: <d082fff805040908516c45869e@mail.gmail.com>
Message-ID: <4257FC58.8080804@dsl.pipex.com>

Kevin wrote:
> Is there a way to get line numbers to show in python IDLE? I looked at
> all the preferances but nothing?
> 
> Thanks
> 
> Kevin
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
Not that I am aware of, although when you have the cursor over the 
lines, the line and column numbers are displayed in the bottom left hand 
corner of the window frame.
/j
From project5 at redrival.net  Sat Apr  9 20:36:31 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr  9 20:36:57 2005
Subject: [Tutor] Re: Help with classes (Joseph Q.)
References: <20050408100115.BB4721E40A3@bag.python.org>
	<6.1.0.6.2.20050408163818.01eeb628@pop.gmail.com>
Message-ID: <1nfaa8pqia0qz.1jslnx4mp2jev$.dlg@40tude.net>

Joseph Quigley wrote on Fri, 08 Apr 2005 16:46:33 -0600:

> Now what are dictionaries and the __name__ really used for? A byte of 
> python never got that through my thick skull.

Dictionaries associate a value with a certain key, sort of like a real
world dictionary where you can take a word and look up its
meaning/translation (except that real world dictionaries are alphabetically
sorted and only contain words, while Python dictionaries are not sorted and
can contain lots of things, including numbers and tuples). 

It's possible to get by without using them directly (other languages don't
even have something resembling a dictionary and they still manage to work
somehow :)), but you might end up building functionality to emulate their
behaviour with for example lists. Let's say you build an application which
allows the user to attach comments to their pictures: you could use a
dictionary for it, mapping a string to each file name:

comments = {}
while True:
    photo = raw_input("Picture name: ")
    if photo = '':
        break
    comment = raw_input("Comment: ")
    comments[photo] = comment
print comments

You could also think of an address book (where you use names as keys and
addresses as values), a menu system (where certain user input is mapped to
a certain function), a cache system (where results of certain
time-consuming operations are saved in case the user asks for the same
operation again) and there are many, many other uses.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. 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  Sat Apr  9 20:44:35 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr  9 20:45:24 2005
Subject: [Tutor] Re: import.... (Joseph Q.)
References: <6.1.0.6.2.20050408165605.01e87ca8@pop.gmail.com>
Message-ID: <6gn12rh7a3ab$.1oo6jmw1z74v9$.dlg@40tude.net>

Joseph Quigley wrote on Fri, 08 Apr 2005 16:58:37 -0600:

> import is handy. But my questions are:
> is there a type of unimport or something to unload a module? 

Things which are not used are cleaned up automatically at some point. What
would you like to do do that this mechanism doesn't provide?

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From logesh at iafrica.com  Sat Apr  9 20:58:49 2005
From: logesh at iafrica.com (Logesh Pillay)
Date: Sat Apr  9 20:59:05 2005
Subject: [Tutor] quicksort using list comprehension
Message-ID: <opsoza0br1reljbd@laptop>

I'm trying to program quicksort using list comprehension.
The following gives me a type mismatch error for "+".

def qsort (t):
     if len (t) > 1:
         return qsort([x for x in t[1:] if x <= t[0]]) + [t[0]] + qsort([x  
for x in t[1:] if x > t[0]])

I know this sounds strange but I have and idea it (or something similar)  
worked when I last tried Python a yr or so ago. An earlier version of  
Python?

Logesh Pillay
From shanel at gmail.com  Sat Apr  9 21:38:54 2005
From: shanel at gmail.com (Shane Liebling)
Date: Sat Apr  9 21:38:57 2005
Subject: [Tutor] Associate functinos with Dictionary/Class Usage
In-Reply-To: <Pine.LNX.4.44.0504071633490.28274-100000@hkn.eecs.berkeley.edu>
References: <ea0feb800504071445217fe4b9@mail.gmail.com>
	<Pine.LNX.4.44.0504071633490.28274-100000@hkn.eecs.berkeley.edu>
Message-ID: <79c85c1a0504091238258637ef@mail.gmail.com>

Although I was not the questioner, I must admit this was a brief but
efficient answer.  Reminds me to try something like the last part out
some time...

-Shane

On Apr 7, 2005 4:40 PM, Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
> On Thu, 7 Apr 2005, Luke Jordan wrote:
> 
> > I am looking for a little clarification of how exactly this would work.
> >
> > 1. How do I associate a function to a dict key?
> 
> Hi Luke,
> 
> We're probably already familiar of values like numbers and strings, and
> how to give them names with variables:
> 
> ######
> >>> number = 42
> >>> name = "luke"
> >>> number
> 42
> >>> name
> 'luke'
> ######
> 
> 'number' is a name that refers to the value 42, and 'name' is a name (Doh!
> I must use a better variable name next time...) that refers to the value
> "luke".
> 
> And we also already know how to make functions and to call them:
> 
> ######
> >>> def square(x):
> ...     return x * x
> ...
> >>> square(42)
> 1764
> ######
> 
> But what happens if we just say "square" at the interpreter?
> 
> ######
> >>> square
> <function square at 0x40300b1c>
> ######
> 
> The value of 'square' is a function value.
> 
> And just like any other value, we can assign it to another name:
> 
> ######
> >>> anotherNameForSquare = square
> >>> anotherNameForSquare(16)
> 256
> ######
> 
> And just like any other value, we can use it as a dictionary value:
> 
> ######
> >>> operators = {'^2': square}
> >>> operators['^2']
> <function square at 0x40300b1c>
> >>> operators['^2'](4)
> 16
> ######
> 
> Does this make sense so far?  Please feel free to ask more questions about
> this.  Best of wishes!
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Shane Liebling
Systems Administrator and SAGE Member
From germanator at gmx.de  Sat Apr  9 21:47:43 2005
From: germanator at gmx.de (Carsten Bohnens)
Date: Sat Apr  9 21:48:07 2005
Subject: [Tutor] how useful is __del__()
Message-ID: <4258315F.1060608@gmx.de>

hey,
I wrote a small class that does some ftp work for me:

#myftpclass.py
class myftp:
    def __init__(self, ...):
       ...
    def connect_and_login(self):
       ...
    def do_foo(self):
       ...
    def do_bar(self):
       ...
    #here comes the interesting part for me
    def goodbye(self):
       self.currenthost.quit()
       print 'Disconnected.'

my actual scripts then look like that:

#movesomedata.py

from myftpclass import myftp
ftp = myftp(--host, username, etc...--)
ftp.connect_and_login()
ftp.do_foo()
ftp.do_bar()
ftp.do_foo()
ftp.goodbye()


I am wondering if there is a way to get the disconnect without calling 
the funcion goodbye or doing ftp.currenthost.quit() by youself and if 
that could be done by defining a __del__() funcion in myftpclass. like, 
the end of the script is reached, or an exception is raised somewhere, 
disconnect.
or should I do something like this instead:

#movesomedata2.py
from myftpclass import myftp
try:
    ftp = myftp([host, username, etc...])
    ftp.connect_and_login()
    ftp.do_foo()
    ftp.do_bar()
    ftp.do_foo()
finally:
    ftp.goodbye()

thanks for all answers

Carsten

germanator at gmx dot de
From kent37 at tds.net  Sat Apr  9 21:50:20 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 21:50:26 2005
Subject: [Tutor] quicksort using list comprehension
In-Reply-To: <opsoza0br1reljbd@laptop>
References: <opsoza0br1reljbd@laptop>
Message-ID: <425831FC.9030806@tds.net>

I think you have to return a value when len(t) <= 1. You don't return anything which means you 
return None which can't be added to a list.

Kent

Logesh Pillay wrote:
> I'm trying to program quicksort using list comprehension.
> The following gives me a type mismatch error for "+".
> 
> def qsort (t):
>     if len (t) > 1:
>         return qsort([x for x in t[1:] if x <= t[0]]) + [t[0]] + 
> qsort([x  for x in t[1:] if x > t[0]])
> 
> I know this sounds strange but I have and idea it (or something 
> similar)  worked when I last tried Python a yr or so ago. An earlier 
> version of  Python?
> 
> Logesh Pillay
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Sat Apr  9 21:54:01 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 21:54:07 2005
Subject: [Tutor] Re: Help with classes (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050408163818.01eeb628@pop.gmail.com>
References: <20050408100115.BB4721E40A3@bag.python.org>
	<6.1.0.6.2.20050408163818.01eeb628@pop.gmail.com>
Message-ID: <425832D9.7010704@tds.net>

Joseph Quigley wrote:
> class Message:
>   def init(self, p = 'Hello world'):
>      self.text = p
>   def sayIt(self):
>      print self.text
> 
> m = Message()
> m.init()
> m.sayIt()
> m.init('Hiya fred!')
> m.sayIt()

This is OK but a more conventional usage is to write an __init__() method. This is sometimes called 
a constructor and it is called automatically when you make a new class instance. Using __init__() 
your example would look like this:

class Message:
   def __init__(self, p = 'Hello world'):
      self.text = p
   def sayIt(self):
      print self.text

m = Message()
m.sayIt()
m = Message('Hiya fred!')
m.sayIt()

though this is nemantically a little different than yours because I create a new Message with the 
new string while you reuse the old one.

Kent

From kent37 at tds.net  Sat Apr  9 21:59:21 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr  9 21:59:25 2005
Subject: [Tutor] Support
In-Reply-To: <BAY106-F3556DAB56CB079C3DF19C789300@phx.gbl>
References: <BAY106-F3556DAB56CB079C3DF19C789300@phx.gbl>
Message-ID: <42583419.6060505@tds.net>

Alberto Troiano wrote:
> Hey dudes
> 
> This code worked fine
> 
> The one you gave me worked as well but when I wanteed to store it in the 
> database it says that the packet was too large
> 
> Whit this code it doesn't complain but now I don't know  how to retrieve 
> the image
> I retrieve it like this:
> 
> db=MySQLdb.connect(connection string)
> 
> cursor=db.cursor()
> 
> cursor.execute("select * from image")
> 
> res=cursor.fetchall()
> 
> Now I have the binary string in res[1] but when I try to open it it 
> gives me an error (I'm sorry I'm not in the machine that has the 
> database and I forgot to copy the error :/)

I think res is going to be a sequence of sequences. So I think the first image will be at res[0][1]. 
Otherwise the error message will be helpful.

Kent

From maxnoel_fr at yahoo.fr  Sat Apr  9 22:20:54 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr  9 22:20:59 2005
Subject: [Tutor] quicksort using list comprehension
In-Reply-To: <425831FC.9030806@tds.net>
References: <opsoza0br1reljbd@laptop> <425831FC.9030806@tds.net>
Message-ID: <2fcab0f2d90712faebd2bbc27bde18f9@yahoo.fr>


On Apr 9, 2005, at 21:50, Kent Johnson wrote:

> I think you have to return a value when len(t) <= 1. You don't return 
> anything which means you return None which can't be added to a list.
>
> Kent

	Yup. Here's a quicksort I did, adapting an example from the Wikipedia 
article on Haskell:


def qsort(toSort):
     if toSort == []:
         return []
     else:
         x = toSort[0]
         elts_lt_x = [y for y in toSort if y < x]
         elts_gt_x = [y for y in toSort if y > x]
     return qsort(elts_lt_x) + [x] + qsort(elts_gt_x)



	It is, of course, nowhere near as optimal as a "real" quicksort 
algorithm (like the one the list.sort method implements).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From rmuller at sandia.gov  Sat Apr  9 22:29:25 2005
From: rmuller at sandia.gov (Rick Muller)
Date: Sat Apr  9 22:33:42 2005
Subject: [Tutor] Re: Tutor Digest, Vol 14, Issue 32
In-Reply-To: <20050409195408.1C6651E400F@bag.python.org>
References: <20050409195408.1C6651E400F@bag.python.org>
Message-ID: <10787D15-A936-11D9-89DE-000A95823962@sandia.gov>


On Apr 9, 2005, at 1:54 PM, tutor-request@python.org wrote:
>
> Message: 8
> Date: Sat, 09 Apr 2005 20:58:49 +0200
> From: "Logesh Pillay" <logesh@iafrica.com>
> Subject: [Tutor] quicksort using list comprehension
> To: "Discussion for learning programming with Python"
> 	<tutor@python.org>
> Message-ID: <opsoza0br1reljbd@laptop>
> Content-Type: text/plain; format=flowed; delsp=yes;
> 	charset=iso-8859-15
>
> I'm trying to program quicksort using list comprehension.
> The following gives me a type mismatch error for "+".
>
> def qsort (t):
>      if len (t) > 1:
>          return qsort([x for x in t[1:] if x <= t[0]]) + [t[0]] + 
> qsort([x
> for x in t[1:] if x > t[0]])
>
> I know this sounds strange but I have and idea it (or something 
> similar)
> worked when I last tried Python a yr or so ago. An earlier version of
> Python?
>
> Logesh Pillay
>

I think the following recipe is what you want:

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

Rick


From dyoo at hkn.eecs.berkeley.edu  Sat Apr  9 23:17:39 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Apr  9 23:17:42 2005
Subject: [Tutor] What is "foo"?
In-Reply-To: <4257F376.3090104@tds.net>
Message-ID: <Pine.LNX.4.44.0504091408120.15958-100000@hkn.eecs.berkeley.edu>

> > Foo: What's it good for?
>
> Foo and Bar are popular names used in examples. They don't mean
> anything. For example to show how to define a function I might write
>
> def foo():
>    print 'Hello'
>
> I just use foo to avoid having to think of a meaningful name.


Hi Joseph,

I sometimes get lazy and use 'foo' in my own code examples too.  But I
find that it's usually a lax idea, precisely because it has no meaning.

Because that "foo" nonsense word confuses beginners quite a bit, I'm
trying to be more conscious to make good variable names, even for
throwaway code, although I sometimes slip.

There's a nice article in the wikipedia that explains Foo:

    http://en.wikipedia.org/wiki/Foo

From bvande at po-box.mcgill.ca  Sun Apr 10 03:45:48 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 03:53:22 2005
Subject: [Tutor] problems with doctest: apparent interferance between tests
	(LONG)
Message-ID: <4258854C.9050709@po-box.mcgill.ca>

Hi all,

I must apologize for the length of the post. I have explained my 
problem as tersely as able, and have done my level-best to produce the 
minimum code snippet illustrative of my difficulties. But, as (I hope) 
will become clear, any substantial attempts to further cull it made 
the problem go away. (For what it is worth, this is the product of 
several hours of investigating and attempting to cull.)


The quick story:
I have apparent interference between doctests embedded in the 
docstrings of different methods, and this interference also appears to 
be influenced by seemingly irrelevant things such as whether the 
module has a (non-doctest-containing) docstring or not. I'm flummoxed 
as to why there is this apparent interference. The long code snippet 
below is the minimal snippet I was able to make which still exhibited 
the problems; it is commented with indications of the dependencies of 
the tests.



Background:
(Perhaps the the reader could skip this `Background' and jump down to 
`The Problem', returning here if need be.) I have cut enough of the 
original code that the point of what remains may be obscure. (The 
original code includes complete documentation, more methods, etc.) A 
bit of explanation is perhaps needed to give the context of my problem.

I've been writing a module to allow convenient wall clock timings and 
generate a report of same on demand. The idea is to import it, make an 
instance of the Wall_clock class, and then call Wall_clock methods at 
places of interest in the code, so as to add _check_point's and start 
and stop _intervals. (Never mind if this isn't too useful or 
duplicates functionality available elsewhere--it is largely a learning 
exercise to explore various Python features, many of which are not 
reflected in the snippet below.)

All the timings are relative to the creation of the Wall_clock 
instance. To prevent confusion in the reports, my original design idea 
was to make the Wall_clock class `Singleton-like' in that there could 
only be one instance alive at a time, and any attempt to create 
another concurrent instance would raise an exception. (I've since 
decided to opt for using the Borg pattern 
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531>, with 
a class attribute storing the time of first instantiation, but my 
issues depend on the first approach I explored.)

I made my `Singleton-like' class by having a class attribute 
is_instanced, set to True by the class __init__ method, and False by 
its __del__. The __init__ method raises an error if the attribute is 
True, thus preventing concurrent instances. (See the final code 
snippet for a working model with tests that pass as expected.)

So far, so good.



The Problem:
doctest is one of the aspects of Python that I've been trying to learn 
with this project. I have 2 problems using doctest on my module:

1) There is a test neat the start of Wall_clock.check_point's 
docstring that attempts to instantiate the Wall_clock class. It fails, 
in the manner an attempt to create a *second* concurrent instance of 
Wall_clock should fail. But, since the relevant test is not preceded 
in the docstring by any tests which create a Wall_clock instance, I 
don't understand how this could be happening. I had theorized that 
perhaps there was interference in that previously run tests might 
leave Wall_clock.is_instanced == True. The first test in 
Wall_clock.check_point appears to bare this out. Yet this doesn't make 
sense either. And it won't explain:

2) In my attempts to produce the minimal working sample that 
illustrated my problem, I found that removing any of:

     a) the Wall_clock class docstring (which contains no tests),

     b) the entire Wall_clock.stop_interval method (this method
        is not called anywhere in the code in the snippet, nor
        does it contain any tests), or

     c) a portion of the Wall_clock.interval method's doctests
        (this portion does not do anything to affect affect the
        Wall_clock.is_instanced class attribute)

all caused the failing test to pass. (These are all identified by 
comments in the code.) I cannot understand why these things, not in 
Wall_clock.check_point's doctest, should affect whether its tests pass 
or fail. I am utterly perplexed. I *am* sure there is a bug, but also 
think it much more likely to be mine than Tim Peters' :-)

In addition to the culled-code where I originally observed this 
problem, I have produced a similar bit of skeleton code which works as 
expected. I don't understand why they operate differently. First, my 
culled code, then the skeleton that works.



The Culled Code:
When I run this, the Wall_clock.interval method is tested first, then 
the Wall_clock.check_point method. (Assessed by the commented out 
tests that were intentional failures.) It is the 
Wall_clock.check_point docstring that is the locus of the problem. 
(The heavy edit on the code has robbed the tests and much of the code 
of their sense and relevance; please ignore that.)

<culled code>

import time

class Wall_clockInstanceError(Exception):
     def __init__(self):
         Exception.__init__(self)

class Interval_name_conflictError(Exception):
     def __init__(self):
         Exception.__init__(self)

class Wall_clock(object):
     '''A class for making wall clock timings.'''
     # If I remove the docstring above, the test passes. WHY?

     is_instanced = False

     def __init__(self):

         if self.__class__.is_instanced:
             raise Wall_clockInstanceError
         else:
             self.__class__.is_instanced = True
         self.intervals = []
         self.data = []
         self.check_point_names = set()
         self.interval_names = set()
         self.start_time = time.time()
         _Check_point.offset = _Interval.offset = self.start_time
         _Check_point.count = _Interval.count = 0

     def __del__(self):
         self.__class__.is_instanced = False

     def check_point(self, check_point_name = None):
         '''Creates a new _Check_point instance; appends it to .data.

         >>> # print "Testing check_point (intentional fail)."
         >>> print Wall_clock.is_instanced
         True
         >>> # Why should it be True at this point?
         >>> # Note, too, that any of the commented changes
         >>> # make the most recent test fail!
         >>> wclock = Wall_clock()      # Failing test WHY?
         >>> del(wclock)
         >>> new_wclock = Wall_clock()  # This passes
         '''
         # The test commented WHY? in this docstring fails unless
         # I make any of the changes elsewhere commented. I don't
         # understand why it fails in the present code, nor why the
         # elsewhere commented changes make it pass.
         # Since the marked test (and the subsequent del() test
         # fail, I don't understand why the final test passes.
         pass

     def interval(self, interval_name = None):
         '''
         >>> # print "Testing interval (intentional fail)."
         >>> wc = Wall_clock()
         >>> del(wc)
         >>> wclock = Wall_clock()
         >>> # If I omit the rest of the tests here, no failure
         >>> # of the test of interest in Wall_clock.check_point
         >>> an_interval = wclock.interval('F')
         >>> same_name = wclock.interval('F')
         Traceback (most recent call last):
             ...
         Interval_name_conflictError
         '''
         # The last few lines are key! (See comments in tests.) WHY?

         if interval_name:
             if type(interval_name) == int:
                 interval_name = str(interval_name)

             if not interval_name.startswith(_Interval.name_form %''):
                 interval_name = _Interval.name_form %interval_name

             if interval_name in self.interval_names:
                 raise Interval_name_conflictError

         new_interval = _Interval(interval_name)
         self.intervals.append(new_interval)
         self.data.append(new_interval)
         self.interval_names.add(str(new_interval.name))
         return new_interval

     # None of the code in the snippet references the method below.
     # But, if I remove the method, the test of interest in
     # Wall_clock.check_point passes. WTF!?!?!
     def stop_interval(self, interval=None):

         try:
             if None == interval:
                 interval = self.intervals.pop()
                 interval.stop()

             else:
                 self.intervals.remove(interval)
                 interval.stop()

         except IndexError, ValueError:
             raise "A custom error class my orig. code defined"

class _Check_point(object):

     count = None    # Wall_clock.__init__ will set these 2.
     offset = None   # Assignments here to make the existence of
                     # the attributes obvious.
     name_form = 'Check point %s'

     def __init__(self, name = None):

         _Check_point.count += 1
         if not name:
             name = _Check_point.name_form % _Check_point.count
         self.name = name
         self.data = time.time() - _Check_point.offset


class _Interval(object):

     count = None    # Wall_clock.__init__ will set these 2.
     offset = None   # Assignments here to make the existence of
                     # the attributes obvious.
     name_form = 'Interval %s'

     def __init__(self, name = None):

         _Interval.count += 1
         self.running = True
         if not name:
             name = _Interval.name_form % _Interval.count
         self.name = name

def _test():
     import doctest, sys
     doctest.testmod(sys.modules[__name__], report = True,
                            optionflags = doctest.ELLIPSIS)

if __name__ == '__main__':
     _test()
     print "\nIf you got this far in my post, my sincerest thanks!"


</culled code>



The Skeleton Code:

All tests pass in this, and it is, as far as I can tell, employing the 
same broad structure as my problematic code above, save that there are 
no `interfering' elements akin the the class docstring, etc.

<skeleton code>

'''
 >>> an_instance = Singleton_like()
 >>> another_instance = Singleton_like()
Traceback (most recent call last):
     ...
NameError: global name 'Concurrent_instancesError' is not defined
 >>> del(an_instance)
 >>> another_instance = Singleton_like()
'''

class Singleton_like(object):

     is_instanced = False

     def __init__(self):
         if self.__class__.is_instanced:
             raise Concurrent_instancesError
         self.__class__.is_instanced = True

     def __del__(self):
         self.__class__.is_instanced = False

     def a_method(self):
         '''>>> an_instance = Singleton_like()'''
         pass

     def another_method(self):
         '''>>> another_instance = Singleton_like()'''
         pass

if __name__ == '__main__':
     import doctest, sys
     doctest.testmod(sys.modules[__name__])

</skeleton code>

I, and what hair I've not yet torn out, would be most grateful for any 
suggestions.

Best to

From rdm at rcblue.com  Sun Apr 10 07:18:09 2005
From: rdm at rcblue.com (Dick Moores)
Date: Sun Apr 10 07:20:37 2005
Subject: [Tutor] UselessPython 2.0
In-Reply-To: <e835145805040711225875506a@mail.gmail.com>
References: <e835145805040711225875506a@mail.gmail.com>
Message-ID: <6.2.1.2.2.20050409221002.02817750@rcblue.com>

Sean Steeg wrote at 11:22 4/7/2005:
>So we're requesting that anyone with
>one-offs, snippets, mini-apps, full-fledged apps and the like make a
>submission to the new and improved UselessPython.  The code doesn't
>have to be pretty, but it does have to work.

I'm a newbie, but would this qualify as a contribution to UselessPython 2.0?

====================================
#isPalindrome.py

# revision of http://www.uselesspython.com/glpalindrome.py to handle 
palindromes
#   such as "Radar" and "A man, a plan, a canal, Panama!"

# http://www.palindromelist.com/ has many palindromes

# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'


import string

def isPalindrome(w):
     return w == '' or (w[0]==w[-1]) and isPalindrome(w[1:-1]) # recursive

def makeStringAllLowercaseAlpha(s):
     """
     Take any string, convert all uppercase alphabetic characters to 
lower case,
     then strip all non-alphabetic characters
     """
     s1 = string.lower(userstring)
     s2 = ""
     for index in range(len(s1)):
         if s1[index] in string.ascii_lowercase:
             s2 += s1[index]
     return s2

userstring = raw_input('Enter a word or sentence to test: ')
userstringRevised = makeStringAllLowercaseAlpha(userstring)

if isPalindrome(userstringRevised):
     print userstring, "is a palindrome."
else:
     print userstring, "is not a palindrome."
====================================

Dick Moores
rdm@rcblue.com






From rdm at rcblue.com  Sun Apr 10 09:38:14 2005
From: rdm at rcblue.com (Dick Moores)
Date: Sun Apr 10 09:38:19 2005
Subject: [Tutor] Trying to write a string formatting demo
Message-ID: <6.2.1.2.2.20050410001351.042b2880@rcblue.com>

I'm trying to write a string formatting demo, just for things like 
%.4f,  %.3e, and %.3g.

Here's what I have, but of course it doesn't work. What should the print 
statement be?

========================
x = raw_input("enter a float: ")
if x == "":
     print "x will be the default 1234.56789"
     x = 1234.56789
else:
     x = float(x)

s = raw_input("enter a float format string such as '.4f' or '.3e': ")

print "%f formatted with '%s' is %s" % (x,s,x)
==========================

Thanks,

Dick Moores
rdm@rcblue.com

From bvande at po-box.mcgill.ca  Sun Apr 10 09:58:51 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 10:02:45 2005
Subject: [Tutor] Trying to write a string formatting demo
In-Reply-To: <6.2.1.2.2.20050410001351.042b2880@rcblue.com>
References: <6.2.1.2.2.20050410001351.042b2880@rcblue.com>
Message-ID: <4258DCBB.3070208@po-box.mcgill.ca>

Dick Moores said unto the world upon 2005-04-10 03:38:
> I'm trying to write a string formatting demo, just for things like 
> %.4f,  %.3e, and %.3g.
> 
> Here's what I have, but of course it doesn't work. What should the print 
> statement be?
> 
> ========================
> x = raw_input("enter a float: ")
> if x == "":
>     print "x will be the default 1234.56789"
>     x = 1234.56789
> else:
>     x = float(x)
> 
> s = raw_input("enter a float format string such as '.4f' or '.3e': ")
> 
> print "%f formatted with '%s' is %s" % (x,s,x)
> ==========================
> 
> Thanks,
> 
> Dick Moores
> rdm@rcblue.com

Hi Dick,

why not replace th last line with the following 2:

print_value = ('%' + s ) %x
print "%f formatted with '%s' is %s" %(x, s, print_value)

HTH,

Brian vdB

From dianahawks at optusnet.com.au  Sun Apr 10 10:07:48 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Sun Apr 10 10:10:10 2005
Subject: [Tutor] Entry widgets
Message-ID: <001a01c53da4$6e349d80$4808a4cb@dianahawks>

Hello list,

Is it possible to change the width of an Entry widget - or not?  I am using Tkinter, GUI - and have an Entry widget that accepts a number. I just don't want it to extend the width of the column.  I have tried width =  - but get an error.

Maybe a text widget would be preferable?

Also - how do I set the insertion symbol there already, so I don't need to click there to enter the number?

TIA. Diana
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050410/4bd78448/attachment.htm
From bvande at po-box.mcgill.ca  Sun Apr 10 10:09:48 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 10:10:22 2005
Subject: [Tutor] Trying to write a string formatting demo
In-Reply-To: <4258DCBB.3070208@po-box.mcgill.ca>
References: <6.2.1.2.2.20050410001351.042b2880@rcblue.com>
	<4258DCBB.3070208@po-box.mcgill.ca>
Message-ID: <4258DF4C.3020108@po-box.mcgill.ca>

Brian van den Broek said unto the world upon 2005-04-10 03:58:
> Dick Moores said unto the world upon 2005-04-10 03:38:
> 
>> I'm trying to write a string formatting demo, just for things like 
>> %.4f,  %.3e, and %.3g.
>>
>> Here's what I have, but of course it doesn't work. What should the 
>> print statement be?
>>
>> ========================
>> x = raw_input("enter a float: ")
>> if x == "":
>>     print "x will be the default 1234.56789"
>>     x = 1234.56789
>> else:
>>     x = float(x)
>>
>> s = raw_input("enter a float format string such as '.4f' or '.3e': ")
>>
>> print "%f formatted with '%s' is %s" % (x,s,x)
>> ==========================
>>
>> Thanks,
>>
>> Dick Moores
>> rdm@rcblue.com
> 
> 
> Hi Dick,
> 
> why not replace th last line with the following 2:
> 
> print_value = ('%' + s ) %x
> print "%f formatted with '%s' is %s" %(x, s, print_value)
> 
> HTH,
> 
> Brian vdB

Sorry, half asleep: I should also have said that I don't think it is 
wise to call your user input string governing the formating of the 
float `s'. Much better to choose a meaningful name, or, failing that, 
at least not a letter that is itself a string formatting code :-)

Best,

Brian

From rdm at rcblue.com  Sun Apr 10 11:10:03 2005
From: rdm at rcblue.com (Dick Moores)
Date: Sun Apr 10 11:10:07 2005
Subject: [Tutor] Trying to write a string formatting demo
In-Reply-To: <4258DF4C.3020108@po-box.mcgill.ca>
References: <6.2.1.2.2.20050410001351.042b2880@rcblue.com>
	<4258DCBB.3070208@po-box.mcgill.ca>
	<4258DF4C.3020108@po-box.mcgill.ca>
Message-ID: <6.2.1.2.2.20050410013734.05867240@rcblue.com>

Brian van den Broek wrote at 01:09 4/10/2005:
>>Hi Dick,
>>why not replace th last line with the following 2:
>>print_value = ('%' + s ) %x
>>print "%f formatted with '%s' is %s" %(x, s, print_value)
>>HTH,
>>Brian vdB
>
>Sorry, half asleep: I should also have said that I don't think it is 
>wise to call your user input string governing the formating of the float 
>`s'. Much better to choose a meaningful name, or, failing that, at least 
>not a letter that is itself a string formatting code :-)

Thanks very much, Brian. Here's what I have now, and it works.
==============================
# formatDemo.py
while True:
     print "enter a float, 'q' to quit, or nothing to accept default 
float of 1234.56789"
     x = raw_input()
     if x == "":
         print "x will be the default 1234.56789"
         x = 1234.56789
     elif x in "qQ":
         break
     else:
         x = float(x)

     floatFormatString = raw_input("enter a float format string such as 
'.4f' or '.3e': ")

     printValue = ('%' + floatFormatString ) %x
     print "%f formatted with '%s' is %s" %(x, floatFormatString, printValue)
     print
======================================

Dick


From ojokimu at yahoo.co.uk  Sun Apr 10 16:05:45 2005
From: ojokimu at yahoo.co.uk (John Ridley)
Date: Sun Apr 10 16:05:47 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
Message-ID: <20050410140545.26541.qmail@web26804.mail.ukl.yahoo.com>

Hello Brian

I think the source of your problem is that the second instance of
Wall_clock doesn't get deleted in the interval doctest. This is
critical, because the is_instanced attribute is reset by __del__.

>   def interval(self, interval_name = None):
>       '''
>       >>> # print "Testing interval (intentional fail)."
>       >>> wc = Wall_clock()
>       >>> del(wc)
>       >>> wclock = Wall_clock()

As a quick hack, try adding the following line here:

?       >>> wclock.__del__()

HTH

John Ridley

Send instant messages to your online friends http://uk.messenger.yahoo.com 
From cpu.crazy at gmail.com  Sun Apr 10 03:36:41 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sun Apr 10 16:14:58 2005
Subject: [Tutor] Re: import.... (Joseph Q.)
In-Reply-To: <20050409195407.B30C71E400E@bag.python.org>
References: <20050409195407.B30C71E400E@bag.python.org>
Message-ID: <6.1.0.6.2.20050409193318.01eeca28@pop.gmail.com>


>
>Joseph Quigley wrote on Fri, 08 Apr 2005 16:58:37 -0600:
>
> > import is handy. But my questions are:
> > is there a type of unimport or something to unload a module?
>
>Things which are not used are cleaned up automatically at some point. What
>would you like to do do that this mechanism doesn't provide?
>
>--
>Yours,
>
>Andrei

Well, I'm importing a custom module, and I can't loop back to the module I 
imported (the modules are different modes of the program. Someone suggested 
classes, but I have no idea how to use them. 

From missive at hotmail.com  Sun Apr 10 16:21:27 2005
From: missive at hotmail.com (Lee Harr)
Date: Sun Apr 10 16:21:31 2005
Subject: [Tutor] Re: problems with doctest: apparent interferance between
	tests (LONG)
Message-ID: <BAY2-F4E681297D6C1BAC978450B1310@phx.gbl>

>I have apparent interference between doctests embedded in the
>docstrings of different methods, and this interference also appears to
>be influenced by seemingly irrelevant things such as whether the
>module has a (non-doctest-containing) docstring or not.

>
>I, and what hair I've not yet torn out, would be most grateful for any
>suggestions.


I did not see if you have read the doctest.py docstrings... It looks
(unsurprisingly ;o) to be quite well documented.

It might be a place to start, anyhow.

_________________________________________________________________
FREE pop-up blocking with the new MSN Toolbar - get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/

From bvande at po-box.mcgill.ca  Sun Apr 10 17:26:02 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 17:30:32 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
In-Reply-To: <20050410140545.26541.qmail@web26804.mail.ukl.yahoo.com>
References: <20050410140545.26541.qmail@web26804.mail.ukl.yahoo.com>
Message-ID: <4259458A.9070101@po-box.mcgill.ca>

John Ridley said unto the world upon 2005-04-10 10:05:
> Hello Brian
> 
> I think the source of your problem is that the second instance of
> Wall_clock doesn't get deleted in the interval doctest. This is
> critical, because the is_instanced attribute is reset by __del__.
> 
> 
>>  def interval(self, interval_name = None):
>>      '''
>>      >>> # print "Testing interval (intentional fail)."
>>      >>> wc = Wall_clock()
>>      >>> del(wc)
>>      >>> wclock = Wall_clock()
> 
> 
> As a quick hack, try adding the following line here:
> 
>         >>> wclock.__del__()
> 
> HTH
> 
> John Ridley

Hi John,

thanks *very* much for making it through my long post :-)

Your suggestion of
     >>> wclock.__del__()
does indeed work. Thanks.

But it leaves me with some of the same puzzles as before and adds a 
new one.

The new:
 >>> wclock.__del__() works whereas:
     >>> del(wclock)
does not. But del(foo) calls foo's __del__ method if defined (as it is 
in this case). So, I don't understand why the two ought be different.

The old:
Your addition does make it work in the code as I posted. But 1) I 
thought doctests embedded in different methods' docstrings were 
supposed to be independent, and 2) none of that explains why the 
presence or absence of the various things outside of the docstring at 
issue and mentioned in my original post make a difference.

So, your suggestion leaves me able to test my code; for that I am most 
appreciative. But I still have an uncomfortable sensation that 
something is truly amiss.

Thanks again and best,

Brian vdB

From klappnase at freenet.de  Sun Apr 10 17:49:39 2005
From: klappnase at freenet.de (Michael Lange)
Date: Sun Apr 10 17:46:09 2005
Subject: [Tutor] Entry widgets
In-Reply-To: <001a01c53da4$6e349d80$4808a4cb@dianahawks>
References: <001a01c53da4$6e349d80$4808a4cb@dianahawks>
Message-ID: <20050410174939.00110019.klappnase@freenet.de>

On Sun, 10 Apr 2005 18:07:48 +1000
"Diana Hawksworth" <dianahawks@optusnet.com.au> wrote:

> Hello list,
> 
> Is it possible to change the width of an Entry widget - or not?  I am using Tkinter, GUI - and have an Entry widget that accepts a number. I just don't want it to extend the width of the column.  I have tried width =  - but get an error.
> 

You should be able to use the width option as for any other widget:

    e = Entry(parent, width=5)
or
    e.configure(width=5)

What exactly did you write, and what was the error? 


> Maybe a text widget would be preferable?
> 

If you just want one line to enter a number, I don't think so.

> Also - how do I set the insertion symbol there already, so I don't need to click there to enter the number?
> 

You can use focus_set():

    e = Entry(parent)
    e.focus_set()

> TIA. Diana

I hope this helps

Michael

From bvande at po-box.mcgill.ca  Sun Apr 10 18:46:10 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 18:46:54 2005
Subject: [Tutor] Re: problems with doctest: apparent interferance between
	tests (LONG)
In-Reply-To: <BAY2-F4E681297D6C1BAC978450B1310@phx.gbl>
References: <BAY2-F4E681297D6C1BAC978450B1310@phx.gbl>
Message-ID: <42595852.1030000@po-box.mcgill.ca>

Lee Harr said unto the world upon 2005-04-10 10:21:
>> I have apparent interference between doctests embedded in the
>> docstrings of different methods, and this interference also appears to
>> be influenced by seemingly irrelevant things such as whether the
>> module has a (non-doctest-containing) docstring or not.
> 
> 
>>
>> I, and what hair I've not yet torn out, would be most grateful for any
>> suggestions.
> 
> 
> 
> I did not see if you have read the doctest.py docstrings... It looks
> (unsurprisingly ;o) to be quite well documented.
> 
> It might be a place to start, anyhow.
> 

Thanks for the suggestion, Lee. :-)

I was working mostly off of the library reference, rather than the 
code itself. (2600+ l.o.c. is a bit past my level of experience.) But, 
there's no way to learn but by trying, so I've plunged in.

It is more code than I can currently form a mental model for, but one 
line does make me think I cannot understand the observed behaviour.
class DocTest.__init__ takes, among its args, globs, where globs is 
documented as:

> globs: The namespace (aka globals) that the examples should
>         be run in.

The relevant line of the __init__ method says:

>         self.globs = globs.copy()

Thus, if I understand it aright (a shaky bet at best) there should not 
be interference between individual doctests. (It seems like each 
docstring is parsed to create a DocTest object, and each such object 
has its own copy of the appropriate namespace.

So, no joy (yet) :-(  Will dig more. Thanks for the push :-)

Best,

Brian vdB




From kent37 at tds.net  Sun Apr 10 20:13:14 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 10 20:13:18 2005
Subject: [Tutor] Re: import.... (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050409193318.01eeca28@pop.gmail.com>
References: <20050409195407.B30C71E400E@bag.python.org>
	<6.1.0.6.2.20050409193318.01eeca28@pop.gmail.com>
Message-ID: <42596CBA.1000702@tds.net>

Joseph Quigley wrote:
  > Well, I'm importing a custom module, and I can't loop back to the module
> I imported (the modules are different modes of the program. Someone 
> suggested classes, but I have no idea how to use them.

I'm not sure I understand you, but it sounds like you have two versions of a module and you would 
like to alternate between them? You could do something like this:

import mymodule_initial as mymodule

mymodule.dosomething()  # calls mymodule_initial .dosomething()

# switch to the other version of mymodule
import mymodule_alternate as mymodule

mymodule.dosomething()  # calls mymodule_alternate.dosomething()

A couple of notes:
- If the import is in a function, declare mymodule as global (I'm not sure this will work, actually; 
try it and see)
- I would always use qualified names to access mymodule, e.g. mymodule.dosomething(). Don't use
from mymodule_initial import dosomething
there's too much chance for confusion.

You could use a class to do this too but I'm not sure there is an advantage; the module and the 
class are both serving as namespaces.

Kent

From kent37 at tds.net  Sun Apr 10 21:11:12 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 10 21:11:18 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
In-Reply-To: <4258854C.9050709@po-box.mcgill.ca>
References: <4258854C.9050709@po-box.mcgill.ca>
Message-ID: <42597A50.6070405@tds.net>

As John Ridley suggests, you have to balance creation and deletion of Wall_clock instances. But 
unfortunately del wc does not necessarily call Wall_clock.__del__() immediately.

See below for more...

Brian van den Broek wrote:
>     def check_point(self, check_point_name = None):
>         '''Creates a new _Check_point instance; appends it to .data.
> 
>         >>> # print "Testing check_point (intentional fail)."
>         >>> print Wall_clock.is_instanced
>         True
>         >>> # Why should it be True at this point?
>         >>> # Note, too, that any of the commented changes
>         >>> # make the most recent test fail!
>         >>> wclock = Wall_clock()      # Failing test WHY?
>         >>> del(wclock)
>         >>> new_wclock = Wall_clock()  # This passes

You need a matching del new_wclock() here.

>         '''

>     def interval(self, interval_name = None):
>         '''
>         >>> # print "Testing interval (intentional fail)."
>         >>> wc = Wall_clock()
>         >>> del(wc)
>         >>> wclock = Wall_clock()
>         >>> # If I omit the rest of the tests here, no failure
>         >>> # of the test of interest in Wall_clock.check_point
>         >>> an_interval = wclock.interval('F')
>         >>> same_name = wclock.interval('F')
>         Traceback (most recent call last):
>             ...
>         Interval_name_conflictError

You need a matching del wclock here. BUT it still doesn't work because __del__() doesn't get called.

If you read the Note under the description of __del__() on this page
http://docs.python.org/ref/customization.html
it says that in the case of an exception, references are retained in the stack track object. I tried 
the workarounds suggested with no luck. but taking out the line that causes the exception (and 
adding the missing del) does in fact make the test work.

As far as doctests being independent, each doctest has it's own copy globals(). But your class has 
its own internal state, this is not affected by globals(). Basically there are side-effects to the 
use of your class; doctest can't account for them.

Personally I don't see any compelling reason why Wall_clock() should be a singleton. It could easily 
be a module with global functions and global state, or you could allow clients to have multiple 
instances to time different things.

Kent

From bvande at po-box.mcgill.ca  Sun Apr 10 22:18:33 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 10 22:19:06 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
In-Reply-To: <42597A50.6070405@tds.net>
References: <4258854C.9050709@po-box.mcgill.ca> <42597A50.6070405@tds.net>
Message-ID: <42598A19.9060304@po-box.mcgill.ca>

Kent Johnson said unto the world upon 2005-04-10 15:11:
> As John Ridley suggests, you have to balance creation and deletion of 
> Wall_clock instances. But unfortunately del wc does not necessarily call 
> Wall_clock.__del__() immediately.


Hi Kent and all,

OK, the delay between the statement del(wc) and the call of
Wall_clock.__del__() helps explain a good deal. Thanks for pointing
that out!

> See below for more...
> 
> Brian van den Broek wrote:
> 
>>     def check_point(self, check_point_name = None):
>>         '''Creates a new _Check_point instance; appends it to .data.

<SNIP>

>>         >>> new_wclock = Wall_clock()  # This passes
> 
> 
> You need a matching del new_wclock() here.
> 
>>         '''
>
>>     def interval(self, interval_name = None):
>>         '''
<SNIP>
>>         >>> same_name = wclock.interval('F')
>>         Traceback (most recent call last):
>>             ...
>>         Interval_name_conflictError
> 
> 
> You need a matching del wclock here. BUT it still doesn't work because 
> __del__() doesn't get called.
> 
> If you read the Note under the description of __del__() on this page
> http://docs.python.org/ref/customization.html
> it says that in the case of an exception, references are retained in the 
> stack track object. I tried the workarounds suggested with no luck. but 
> taking out the line that causes the exception (and adding the missing 
> del) does in fact make the test work.


OK, that's helpful; thanks. Making the changes you suggest does indeed
fix the failure problem. :-)

But: it still leaves me wondering why removing either a) the one-line
no-doctest-containing docstring of the Wall_clock class or b) the
unreferenced Wall_clock.stop_interval method made my original test
code pass without needing to effect the changes you suggest. That
seems really odd to me.

> As far as doctests being independent, each doctest has it's own copy 
> globals(). But your class has its own internal state, this is not 
> affected by globals(). Basically there are side-effects to the use of 
> your class; doctest can't account for them.

I've not fully grokked the doctest code (which I delved into after Lee
Harr suggested I do so), but I would have thought that each doctest
had its own copy of the Wall_clock class from copying globals. But
here, I surely have more work to do myself :-)


> Personally I don't see any compelling reason why Wall_clock() should be 
> a singleton. It could easily be a module with global functions and 
> global state, or you could allow clients to have multiple instances to 
> time different things.

I'm not sure I see a reason anymore, either. :-)

The code that I removed before posting allows for multiple things to
be timed, but all timings are relative to the first instantiation of
the Wall_clock class. _Check_points, on creation, store how many
seconds have elapsed since the Wall_clock instance was created,
_Intervals how long between their start and stop signals, as well as
how long from Wall_clock instance creation their start signal was
sent. The thought was that the results would be easier to interpret
were all timings relative to a single initiation point, rather than
having timings of instance 1 relative to instance 1's initiation, and
instance 2's relative to its.

 From a usability standpoint, I think I have settled on a Borg, where
the first instances start time is the one to which all timings will be
relative.

But, in a way, which route is best is something of a side issue
(though I do appreciate the input). I took this up to primarily to
explore various possible structures just for learning about them.

So, apart from the open questions (about why the unreferenced method
and the no-doctest class docstring made a difference), I think I can
count my original problem solved. I know how to make my tests work as
excepted, and that is the main thing.

Sincere thanks to everyone who worked their way through my mammoth
original post; I very much appreciate the contributions!

Best to all,

Brian vdB


From ojokimu at yahoo.co.uk  Mon Apr 11 01:19:02 2005
From: ojokimu at yahoo.co.uk (John Ridley)
Date: Mon Apr 11 01:19:04 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests (LONG)
In-Reply-To: <42598A19.9060304@po-box.mcgill.ca>
Message-ID: <20050410231902.11827.qmail@web26809.mail.ukl.yahoo.com>


 --- Brian van den Broek <bvande@po-box.mcgill.ca> wrote: 
> But: it still leaves me wondering why removing either a) the one-line
> no-doctest-containing docstring of the Wall_clock class or b) the
> unreferenced Wall_clock.stop_interval method made my original test
> code pass without needing to effect the changes you suggest. That
> seems really odd to me.

Hello again, Brian

Thought I'd better follow up on my previous post even though Kent has
already done a much better job than me of explaining things.

I believe your two remaining puzzles can be solved by trying this
little experiment. Using your original <culled code> example, add the
extra line that I suggested and then run the script with the -v
commandline option (i.e. python test.py -v).

What you should see is that the interval doctest is run first. But if
you comment out the 'no-doctest-containing docstring' and re-run the
script, the check_point doctest is run first! Needless to say, this
rather awkward side-effect is going to make it hard to ensure objects
are created and deleted at the right times ;-)

Now, I am not familiar enough with the doctest module to explain
exactly why this change in the 'running-order' should occur. But maybe
once you've begun to 'grok' doctest a little more you'll be able to
shed some light on it for us!

Regards

John Ridley

Send instant messages to your online friends http://uk.messenger.yahoo.com 
From bvande at po-box.mcgill.ca  Mon Apr 11 02:29:00 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Mon Apr 11 02:29:47 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests (LONG)
In-Reply-To: <20050410231902.11827.qmail@web26809.mail.ukl.yahoo.com>
References: <20050410231902.11827.qmail@web26809.mail.ukl.yahoo.com>
Message-ID: <4259C4CC.3050504@po-box.mcgill.ca>

John Ridley said unto the world upon 2005-04-10 19:19:
>  --- Brian van den Broek <bvande@po-box.mcgill.ca> wrote: 
> 
>>But: it still leaves me wondering why removing either a) the one-line
>>no-doctest-containing docstring of the Wall_clock class or b) the
>>unreferenced Wall_clock.stop_interval method made my original test
>>code pass without needing to effect the changes you suggest. That
>>seems really odd to me.
> 
> 
> Hello again, Brian
> 
> Thought I'd better follow up on my previous post even though Kent has
> already done a much better job than me of explaining things.
> 
> I believe your two remaining puzzles can be solved by trying this
> little experiment. Using your original <culled code> example, add the
> extra line that I suggested and then run the script with the -v
> commandline option (i.e. python test.py -v).
> 
> What you should see is that the interval doctest is run first. But if
> you comment out the 'no-doctest-containing docstring' and re-run the
> script, the check_point doctest is run first! Needless to say, this
> rather awkward side-effect is going to make it hard to ensure objects
> are created and deleted at the right times ;-)
> 
> Now, I am not familiar enough with the doctest module to explain
> exactly why this change in the 'running-order' should occur. But maybe
> once you've begun to 'grok' doctest a little more you'll be able to
> shed some light on it for us!
> 
> Regards
> 
> John Ridley
> 
> Send instant messages to your online friends http://uk.messenger.yahoo.com 


Hi John and all,

Well, I think that has pointed the way to a solution! :-)

I had two methods in my culled code which included tests. I'd been 
puzzled as to why the presence or absence of apparently unrelated 
things made a difference to the passing or failing of my tests. You've 
just pointed out that only is the pass-state of the tests sensitive to 
the presence or absence of those elements but so is the order in which 
the two methods in my culled tests are run. (Indeed, that explains why 
the presence or absence matters, as the tests fail when ran in one 
ordering, while passing if ran in the other. Embarrassingly, I'd given 
myself some intentionally failing tests to confirm the order in which 
things were tested. So, the data was there, if only I'd had eyes to 
see :-[ .)

This suggests to me quite strongly that order in which the tests are 
run is determined at one or more points by dictionary access. (I 
suspect that one or both of the module objects to be examined and the 
docstrings in module objects are at some point stored in a 
dictionary.[*]) Since dictionary access is random, any fetching of a 
list of items to feed to the DocTest class could have the order of 
testing of two items altered by the presence of other items.

I've rarely read other people's code longer than 500 or so lines, so 
it is going to take me a while to understand doctest.py well enough to 
be certain of this hypothesis. But given the centrality of the 
dictionary to Python and how nicely the hypothesis matches the 
observed behaviour, it seems pretty well, though not conclusively, 
supported. I do indeed hope I can understand doctest.py well enough in 
the near future to confirm. But, for the moment, this has calmed the 
voices in my head. :-)

[*] "one or both" because one of objects whose presence mattered was a 
method without docstrings, the other a class docstring. So, I don't 
think it can simply be that there is a single dictionary involved. It 
would seem to be something more like one for objects to examine, 
another for docstrings of those objects. But now the armchair 
philosophy is well in front of the supporting evidence :-)

If (no, *when*!) I work it out, I will be certain to report back briefly.

Thanks again to all for the very useful help and observations!

Best,

Brian vdB

From rmkrauter at yahoo.com  Mon Apr 11 02:53:05 2005
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Mon Apr 11 02:53:55 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
In-Reply-To: <4258854C.9050709@po-box.mcgill.ca>
References: <4258854C.9050709@po-box.mcgill.ca>
Message-ID: <4259CA71.5020607@yahoo.com>

Brian van den Broek wrote:
[text and code snipped]

FWIW, I ran your code using python 2.3.4 on linux with the following 
modifications, and it worked fine (no failing tests out of 9):

1- added 'from sets import Set as set' since set() isn't built in in 2.3
2- changed True back to False in the following test:

>         '''Creates a new _Check_point instance; appends it to .data.
> 
>         >>> # print "Testing check_point (intentional fail)."
>         >>> print Wall_clock.is_instanced
>         True


3- omitted the optionflags=doctest.ELLIPSIS argument from the following 
code, since it's not available in python 2.3's doctest:

> def _test():
>     import doctest, sys
>     doctest.testmod(sys.modules[__name__], report = True,
>                            optionflags = doctest.ELLIPSIS)

Running the same code with 2.4 gave 3 failures out of 9 tests.

Rich



From kent37 at tds.net  Mon Apr 11 03:30:02 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 11 03:30:06 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests (LONG)
In-Reply-To: <4259C4CC.3050504@po-box.mcgill.ca>
References: <20050410231902.11827.qmail@web26809.mail.ukl.yahoo.com>
	<4259C4CC.3050504@po-box.mcgill.ca>
Message-ID: <4259D31A.2060901@tds.net>

Brian van den Broek wrote:
> I've not fully grokked the doctest code (which I delved into after Lee
> Harr suggested I do so), but I would have thought that each doctest
> had its own copy of the Wall_clock class from copying globals. But
> here, I surely have more work to do myself :-)

doctest makes a shallow copy of the globals (see 
http://docs.python.org/lib/doctest-execution-context.html)
So all the tests have references to the same Wall_clock class.

Copying the globals protects each test from depending on objects created or destroyed by other 
tests, but it doesn't isolate tests from changes to mutable objects in the global namespace.

> This suggests to me quite strongly that order in which the tests are run 
> is determined at one or more points by dictionary access. (I suspect 
> that one or both of the module objects to be examined and the docstrings 
> in module objects are at some point stored in a dictionary.[*]) Since 
> dictionary access is random, any fetching of a list of items to feed to 
> the DocTest class could have the order of testing of two items altered 
> by the presence of other items.

doctest finds classes, functions and methods by inspecting the __dict__ attributes of modules and 
classes; see lines 901 and 932 of doctest.py (in Python2.4). So this sounds like a good theory to 
explain at least why adding a new method changes the order of the tests.

Kent

From kenny.li at gmail.com  Mon Apr 11 04:59:14 2005
From: kenny.li at gmail.com (Kenny Li)
Date: Mon Apr 11 04:59:17 2005
Subject: [Tutor] Looking for a number adding script
Message-ID: <2c48519d05041019591a715c56@mail.gmail.com>

Hi all,

A little while ago, when I tried to pick up Python, I ran into an
article that has a script to add up all numbers in a text file (email
message, for example). I want to use that script now, but I could not
find (recalled) the URL to the article. If you have a point, please
let me know. Appreciate it.

Example text: XXX, today's restaurant bill looks like this: coffee
$9.43, bread $91.44, food $141.43

I like to use a python script to automatically, add 9.43, 91.44 and
141.43 and give me a total.

Thanks,

Kenny
From jfouhy at paradise.net.nz  Mon Apr 11 05:25:30 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Mon Apr 11 05:25:39 2005
Subject: [Tutor] Looking for a number adding script
In-Reply-To: <2c48519d05041019591a715c56@mail.gmail.com>
References: <2c48519d05041019591a715c56@mail.gmail.com>
Message-ID: <1113189930.4259ee2aeec78@www.paradise.net.nz>

Quoting Kenny Li <kenny.li@gmail.com>:

> A little while ago, when I tried to pick up Python, I ran into an
> article that has a script to add up all numbers in a text file (email
> message, for example). I want to use that script now, but I could not
> find (recalled) the URL to the article. If you have a point, please
> let me know. Appreciate it.

I don't have the original one you saw ...

But this is a problem very well suited to regular expressions.  Python's re
module has good documentation on regular expression syntax.

example:

------------------------- sumFile.py ---------------------------
import sys, re

if len(sys.argv) < 2:
    print 'Syntax: python sumFile.py <filename>'
    sys.exit(1)
filename = sys.argv[1]

numexp = re.compile(r'\d+(?:\.\d+)?')  # Match one or more digits, optionaly
followed
                                       # by (a ., followed by one or more digits).
                                       # Note that ".18" will be treated as
"18", not
                                       # "0.18" (unless it really is "0.18" in
the text).

print 'Sum: ', sum(map(float, numexp.findall(file(filename).read())))

-- 
John.
From project5 at redrival.net  Mon Apr 11 08:33:22 2005
From: project5 at redrival.net (Andrei)
Date: Mon Apr 11 08:36:53 2005
Subject: [Tutor] Re: import.... (Joseph Q.)
References: <20050409195407.B30C71E400E@bag.python.org>
	<6.1.0.6.2.20050409193318.01eeca28@pop.gmail.com>
Message-ID: <loom.20050411T082629-678@post.gmane.org>

Joseph Quigley <cpu.crazy <at> gmail.com> writes:

> Well, I'm importing a custom module, and I can't loop back to the module I 
> imported (the modules are different modes of the program. Someone suggested 
> classes, but I have no idea how to use them. 

So you have two modules which implement the same functions in different ways,
depending on the mode of the program? If this is the case, just import the
modules by name and use the dot-notation (see post before mine). There's no need
to unload anything. Whether classes are useful in this case: it's possible, but
without a more detailed description it's hard to determine. I would say it's
perpahs a bit unusual if you do indeed have two modules with the same interface
but different behavior.

Yours,

Andrei

From dianahawks at optusnet.com.au  Mon Apr 11 08:50:02 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr 11 08:51:43 2005
Subject: [Tutor] Entry widgets
References: <001a01c53da4$6e349d80$4808a4cb@dianahawks>
	<20050410174939.00110019.klappnase@freenet.de>
Message-ID: <000301c53e62$b13b5560$98c41dd3@dianahawks>

Thanks Michael. Your suggestions did the trick!  I did mean to include my
code - but obviously did not do that. Appreciate your help. Diana

----- Original Message ----- 
From: "Michael Lange" <klappnase@freenet.de>
To: <tutor@python.org>
Sent: Monday, April 11, 2005 1:49 AM
Subject: Re: [Tutor] Entry widgets


> On Sun, 10 Apr 2005 18:07:48 +1000
> "Diana Hawksworth" <dianahawks@optusnet.com.au> wrote:
>
> > Hello list,
> >
> > Is it possible to change the width of an Entry widget - or not?  I am
using Tkinter, GUI - and have an Entry widget that accepts a number. I just
don't want it to extend the width of the column.  I have tried width =  -
but get an error.
> >
>
> You should be able to use the width option as for any other widget:
>
>     e = Entry(parent, width=5)
> or
>     e.configure(width=5)
>
> What exactly did you write, and what was the error?
>
>
> > Maybe a text widget would be preferable?
> >
>
> If you just want one line to enter a number, I don't think so.
>
> > Also - how do I set the insertion symbol there already, so I don't need
to click there to enter the number?
> >
>
> You can use focus_set():
>
>     e = Entry(parent)
>     e.focus_set()
>
> > TIA. Diana
>
> I hope this helps
>
> Michael
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From smichr at hotmail.com  Mon Apr 11 11:12:30 2005
From: smichr at hotmail.com (C Smith)
Date: Mon Apr 11 11:13:30 2005
Subject: [Tutor] Flatten
Message-ID: <D5254A52-AA69-11D9-8E90-000393C0D100@hotmail.com>

Sorry for the delay in answering.

Bill Mill wrote:
[cut]
> 1) you should special-case dictionaries: > >> x = [1, 2, [3, 4, 5, 
> [[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}] > >> flatten(x) > >> x 
> [1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test']
>
OK, now it only handles lists and tuples
> 2) What's different about your flatten than those ASPN entries? Just
> that it flattens in-place? I see a general-purpose flattener and a
> flattening generator.

The flatten procedure by Ganel does excessive work, it appears, by 
doing one level of flattening per pass through the entire list. Initial 
non-iterable items are rechecked as long as any iterables remain in the 
list. It is also not an "in-place" routine.

The one by Rodrigues and the one by Rol is recursive (and the one by 
Yoo is admittedly complicated).

The one I presented is essentially the same as Fletcher's.  Fletcher's 
does not actually run through all indices as I thought: as soon as it 
steps on an out-of-range index it exits. Fletcher's routine is a 
non-recursive version that runs in place that can be recommended if 
recursion is a problem.

I'll add a note to the ASPN pages.

/c

From ryan at acceleration.net  Mon Apr 11 14:47:49 2005
From: ryan at acceleration.net (Ryan Davis)
Date: Mon Apr 11 14:47:53 2005
Subject: [Tutor] Talking to mssql?
In-Reply-To: <20050408225246.14A141E4005@bag.python.org>
Message-ID: <20050411124751.125BE1E4005@bag.python.org>

I couldn't compile it either, but got it working by copying the MSSQL.py and bin/python2.3/mssqldb.pyd from the archive to my
site-packages directory.

He scarcely mentions that option at the bottom of the install page:
http://www.object-craft.com.au/projects/mssql/install.html.

Not sure if the binary would work on Linux, though.

Thanks,
Ryan 

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of j2
Sent: Friday, April 08, 2005 6:51 PM
To: tutor@python.org
Subject: RE: [Tutor] Talking to mssql?

>I had the same question.  The best I found is this:
>http://www.object-craft.com.au/projects/mssql/ 
>but that has a lot of strong language saying "this isn't ready for use".
>
>I found it perfectly usable for simply running queries, but haven't tried
>to do anything more complicated with it.  Not sure how
>well it works on Linux, but he has binaries that worked for me.

Well, doesn't fly for me, because I can't install it. Can you offer any help
on the below?


I am trying to install http://www.object-craft.com.au/projects/mssql/ on my
Debian system, but when i try to build, i end up with the below. Also, my
package list is at the bottom.

hooch:~/Download/Asterisk/MSSQL-0.09# python setup.py install
running install
running build
running build_py
not copying MSSQL.py (output up-to-date)
running build_ext
building 'mssqldb' extension
creating build/temp.linux-i686-2.2
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c mssqldb.c -o
build/temp.linux-i686-2.2/mssqldb.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c loginrec.c -o
build/temp.linux-i686-2.2/loginrec.o
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c dbproc.c -o
build/temp.linux-i686-2.2/dbproc.o
dbproc.c:199: warning: `wrap_DbProcIntFunc_bool' defined but not used
gcc -DNDEBUG -g -O3 -fno-strict-aliasing -Wall -Wstrict-prototypes -fPIC
-DHAVE_FREETDS -DHAVE_DBALTBIND -DHAVE_DBCLROPT -DHAVE_DBCURCMD
-DHAVE_DBCURROW -DHAVE_DBISOPT -DHAVE_DBNUMCOMPUTE -DHAVE_DBRETTYPE
-I/usr/include -I/usr/include/python2.2 -c databuf.c -o
build/temp.linux-i686-2.2/databuf.o
databuf.c: In function `get_buff_value':
databuf.c:86: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:86: error: (Each undeclared identifier is reported only once
databuf.c:86: error: for each function it appears in.)
databuf.c:86: error: parse error before ')' token
databuf.c:87: error: parse error before ')' token
databuf.c:90: error: `DBBIT' undeclared (first use in this function)
databuf.c:90: error: parse error before ')' token
databuf.c: In function `DataBuf_set':
databuf.c:155: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:155: error: parse error before ')' token
databuf.c:160: error: parse error before ')' token
databuf.c:161: error: parse error before ')' token
databuf.c:169: error: `DBBIT' undeclared (first use in this function)
databuf.c:169: error: parse error before ')' token
databuf.c: In function `DataBuf__init__':
databuf.c:270: error: `DBVARYCHAR' undeclared (first use in this function)
databuf.c:273: error: `DBBIT' undeclared (first use in this function)
error: command 'gcc' failed with exit status 1
hooch:~/Download/Asterisk/MSSQL-0.09#

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

From 3dbernard at gmail.com  Mon Apr 11 15:11:28 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon Apr 11 15:11:32 2005
Subject: [Tutor] Re: Class - superclass
In-Reply-To: <74zrmw46rgns$.1w95nxzewehhf$.dlg@40tude.net>
References: <61d0e2b4050408120579512e29@mail.gmail.com>
	<74zrmw46rgns$.1w95nxzewehhf$.dlg@40tude.net>
Message-ID: <61d0e2b4050411061140963cfd@mail.gmail.com>

Thanks a lot, now it's clear.


Bernard


On Apr 8, 2005 3:48 PM, Andrei <project5@redrival.net> wrote:
> Bernard Lebel wrote on Fri, 8 Apr 2005 15:05:13 -0400:
> 
> > I'm experimenting with basic inheritance concepts, and something that
> > I would assume to work returns an error.
> >
> >>>> class A:
> > ...     def __init__( self ):
> > ...             self.a = 13
> > ...
> >>>> class B( A ): # create sub-class of class A
> > ...     def __init__( self ):
> > ...             self.b = 14
> 
> Call the __init__ of the ancestor explicitly:
> 
> >>> class B(A):
> ...     def __init__(self):
> ...         A.__init__(self)
> ...         self.b = 14
> >>> b = B()
> >>> b.a, b.b
> (13, 14)
> 
> B inherits everything from A, but by defining B.__init__, the __init__
> inherited from A is replaced, so you'll need to call it explicitly. Python
> has no way of knowing that you still want to use the original __init__ too
> unless you tell it so. To demonstrate the fact that __init__ is indeed
> inherited:
> 
> >>> class C(A):
> ...     pass
> >>> c = C() # inherited __init__ (A.__init__) is called
> >>> c.a
> 13
> 
> --
> Yours,
> 
> Andrei
> 
> =====
> Real contact info (decode with rot13):
> cebwrpg5@jnanqbb.ay. 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 albertito_g at hotmail.com  Mon Apr 11 17:34:42 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 17:34:47 2005
Subject: [Tutor] Re: [Python-Help] Support with Image
In-Reply-To: <Pine.LNX.4.44.0504091428390.15958-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-F122CAAB6774881A5690DCA89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/90d277da/attachment.html
From albertito_g at hotmail.com  Mon Apr 11 17:49:29 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 17:49:36 2005
Subject: [Tutor] Re: [Python-Help] Support with Image
In-Reply-To: <1113071863.31.1843@mint-julep.mondoinfo.com>
Message-ID: <BAY106-F369F33EFAC52C118D1BAAE89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/b9cfd82f/attachment.html
From albertito_g at hotmail.com  Mon Apr 11 18:00:03 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 18:00:07 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <4257F6D4.1050006@tds.net>
Message-ID: <BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/17ddc5c2/attachment.htm
From kristian.zoerhoff at gmail.com  Mon Apr 11 18:03:13 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Mon Apr 11 18:03:18 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>
References: <4257F6D4.1050006@tds.net>
	<BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>
Message-ID: <3511dc75050411090334e39686@mail.gmail.com>

On Apr 11, 2005 11:00 AM, Alberto Troiano <albertito_g@hotmail.com> wrote:
> 
> To give you a graphic example how can make this function to run every 5
> seconds 
> 
> def foo(): 
> 
>     print "Hello world!" 
> 

I'm not Kent, but I play him on TV ;-)

import time

def foo():
    print "Hello world!"

while true:
    foo()
    time.sleep(5)

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From klas.martelleur at telia.com  Mon Apr 11 18:06:10 2005
From: klas.martelleur at telia.com (Klas Marteleur)
Date: Mon Apr 11 18:06:15 2005
Subject: [Tutor] Sorting of files based on filesize
Message-ID: <200504111806.10765.klas.martelleur@telia.com>

Hi
Some of my harddrives are getting full and i would like to burn the files to 
some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 

Ofcourse i would like to optimize the size of each DVD to be as close to 4.7Gb 
as possible (to save this cheep media :) ).

There are plenty of software that are able to index my DVD's so sorting 
between disks is not a problem. Just size.

What i would like to do is write a Python program that could sort my files 
(based on size) into chunks as close to a given storage size (DVD 4.7Gb, CD 
650Mb...), and minimize the use of disks. Does anyone know of if something 
like this is done before in Python, that i could look at?

With a couple of hundred files it should be a lot of possible combinations. So 
I am not lookng for something absolute, just something that could help me get 
a little closer to the truth :)

Its the "sorting function" that i am looking for, getting filesizes and do the 
actual sorting of files on disk i will worry about later.

Kind regards
Klas

From kristian.zoerhoff at gmail.com  Mon Apr 11 18:06:01 2005
From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff)
Date: Mon Apr 11 18:08:03 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <3511dc75050411090334e39686@mail.gmail.com>
References: <4257F6D4.1050006@tds.net>
	<BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>
	<3511dc75050411090334e39686@mail.gmail.com>
Message-ID: <3511dc750504110906d1f6149@mail.gmail.com>

On Apr 11, 2005 11:03 AM, Kristian Zoerhoff <kristian.zoerhoff@gmail.com> wrote:
> while true:
>     foo()
>     time.sleep(5)

Err, make that

while True:

Note to self: test before posting.

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
From bvande at po-box.mcgill.ca  Mon Apr 11 18:37:18 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Mon Apr 11 19:03:38 2005
Subject: [Tutor] problems with doctest: apparent interferance between
	tests	(LONG)
In-Reply-To: <4259CA71.5020607@yahoo.com>
References: <4258854C.9050709@po-box.mcgill.ca> <4259CA71.5020607@yahoo.com>
Message-ID: <425AA7BE.9020107@po-box.mcgill.ca>

Rich Krauter said unto the world upon 2005-04-10 20:53:
> Brian van den Broek wrote:
> [text and code snipped]
> 
> FWIW, I ran your code using python 2.3.4 on linux with the following 
> modifications, and it worked fine (no failing tests out of 9):

<SNIP>

Hi Rich, Kent, and all,

thanks for these additional datapoints, Rich. And thanks too, Kent for 
  the additional pointers in your most recent post.

But for the list's help, I don't know if I would have emerged from the 
weekend still retaining what sanity I have left :-)

Best to all,

Brian vdB

From kent37 at tds.net  Mon Apr 11 19:17:59 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 11 19:18:23 2005
Subject: [Tutor] Sorting of files based on filesize
In-Reply-To: <200504111806.10765.klas.martelleur@telia.com>
References: <200504111806.10765.klas.martelleur@telia.com>
Message-ID: <425AB147.6020600@tds.net>

This is a hard problem. It is a version of the "0-1 knapsack problem" - googling for that might give 
you some ideas.

Kent

Klas Marteleur wrote:
> Hi
> Some of my harddrives are getting full and i would like to burn the files to 
> some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 
> 
> Ofcourse i would like to optimize the size of each DVD to be as close to 4.7Gb 
> as possible (to save this cheep media :) ).
> 
> There are plenty of software that are able to index my DVD's so sorting 
> between disks is not a problem. Just size.
> 
> What i would like to do is write a Python program that could sort my files 
> (based on size) into chunks as close to a given storage size (DVD 4.7Gb, CD 
> 650Mb...), and minimize the use of disks. Does anyone know of if something 
> like this is done before in Python, that i could look at?
> 
> With a couple of hundred files it should be a lot of possible combinations. So 
> I am not lookng for something absolute, just something that could help me get 
> a little closer to the truth :)
> 
> Its the "sorting function" that i am looking for, getting filesizes and do the 
> actual sorting of files on disk i will worry about later.
> 
> Kind regards
> Klas
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From mi.janssen at gmail.com  Mon Apr 11 19:30:46 2005
From: mi.janssen at gmail.com (Michael Janssen)
Date: Mon Apr 11 19:31:20 2005
Subject: [Tutor] UselessPython 2.0
In-Reply-To: <6.2.1.2.2.20050409221002.02817750@rcblue.com>
References: <e835145805040711225875506a@mail.gmail.com>
	<6.2.1.2.2.20050409221002.02817750@rcblue.com>
Message-ID: <1ff2dfbf05041110305a2218f0@mail.gmail.com>

On Apr 10, 2005 7:18 AM, Dick Moores <rdm@rcblue.com> wrote:

> I'm a newbie, but would this qualify as a contribution to UselessPython 2.0?

Hello Dick,

don't be shy, or do you suspect it might be too usefull? ;-) I found
it funny, so it must be good enough.

here my remarks:

> def makeStringAllLowercaseAlpha(s):
>     """
>     Take any string, convert all uppercase alphabetic characters to
> lower case,
>     then strip all non-alphabetic characters

[what's bad about non-alphabetic characters?]

>     """
>     s1 = string.lower(userstring)

oops: this function gets an argument s, here you're using the global
variable userstring. I know, it works, but there will be functions
were mistakes like this weren't just ugly but buggy.

>     s2 = ""
>     for index in range(len(s1)):
>         if s1[index] in string.ascii_lowercase:
>             s2 += s1[index]

or easier (much more readable, helps understanding the programm):

for char in s1:
     if char in string.ascii_lowercase:
           s2 += char

regards
Michael
From mi.janssen at gmail.com  Mon Apr 11 19:34:57 2005
From: mi.janssen at gmail.com (Michael Janssen)
Date: Mon Apr 11 19:35:00 2005
Subject: [Tutor] UselessPython 2.0
In-Reply-To: <1ff2dfbf05041110305a2218f0@mail.gmail.com>
References: <e835145805040711225875506a@mail.gmail.com>
	<6.2.1.2.2.20050409221002.02817750@rcblue.com>
	<1ff2dfbf05041110305a2218f0@mail.gmail.com>
Message-ID: <1ff2dfbf05041110345f42d31f@mail.gmail.com>

On Apr 11, 2005 7:30 PM, Michael Janssen <mi.janssen@gmail.com> wrote:

> [what's bad about non-alphabetic characters?]

I found it out for myself. To quote from Dick's post:
"A man, a plan, a canal, Panama!" 

Seems like palindromes are allowed not to reflect whitespace and
punctuation (an how could this be?).

cheers
Michael
From andre.wayne.thompson at gmail.com  Mon Apr 11 19:42:40 2005
From: andre.wayne.thompson at gmail.com (Andre Thompson)
Date: Mon Apr 11 19:42:43 2005
Subject: [Tutor] Using python with MS Excel (Newbie)
Message-ID: <9405eb91050411104213ab3566@mail.gmail.com>

Hi All,

I am trying to create a couple of python programs that creates and
modifies MS Excel docs.

I have been searching the web and have found some interesting pieces
of information and programs but i need something more complete. Is the
any documentation available explaning all the options available
programming with win32com.

I thank you in advance for the help.

Regards,
Andre
From glaevsky at ECE.NEU.EDU  Mon Apr 11 20:54:37 2005
From: glaevsky at ECE.NEU.EDU (glaevsky@ECE.NEU.EDU)
Date: Mon Apr 11 20:54:37 2005
Subject: [Tutor] Cell Bio Newbie Here
Message-ID: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>

Hey all,

Sorry for the bother, thanks for the help.

I'm trying to write a password guessing program to keep track of
how many times the user has entered the password wrong.
If it is more than 3 times, print ``That must have been complicated.''

Following is what I got.  If I type "unicorn" it goes straight to "welcome 
in." Great.  But after my third mistake, it just loops in "That must have 
been complicated."

I'd like for someone to tell me "why" i screwed up.  Not to just fix it.

Thank you so much in advance.  And to give you a little smile for a Monday, 
I've been working on this for days....argh



#first of all, why does this have to be here?
password="foobar"

count=3
current_count=0

while password !="unicorn":
     if current_count<count:
         password=raw_input("Password:")
         current_count=current_count+1
     else:
         print "That must have been complicated"


print "Welcome in"
Best,

Gary



Gary Laevsky, Ph.D.
Keck Facility Manager, CenSSIS
Northeastern University
302 Stearns
360 Huntington Ave.
Boston, MA 02115
voice(617) 373 - 2589<br>
fax(617) 373 - 7783<br><br>

http://www.censsis.neu.edu

http://www.ece.neu.edu/groups/osl

http://www.keck3dfm.neu.edu

From ryan at acceleration.net  Mon Apr 11 22:00:54 2005
From: ryan at acceleration.net (Ryan Davis)
Date: Mon Apr 11 22:00:31 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <20050411200029.C02841E4005@bag.python.org>

Make a flowchart, by hand, on paper of what this program does.  That should help explain the why.

Basically, after 3 attempts, your "while" loop becomes an infinte loop.  Once you are over the count, the user is never prompted for
another password, so the password remains not equal to "unicorn" until the end of time.

Thanks,
Ryan 

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of glaevsky@ECE.NEU.EDU
Sent: Monday, April 11, 2005 2:55 PM
To: tutor@python.org
Subject: [Tutor] Cell Bio Newbie Here

Hey all,

Sorry for the bother, thanks for the help.

I'm trying to write a password guessing program to keep track of
how many times the user has entered the password wrong.
If it is more than 3 times, print ``That must have been complicated.''

Following is what I got.  If I type "unicorn" it goes straight to "welcome 
in." Great.  But after my third mistake, it just loops in "That must have 
been complicated."

I'd like for someone to tell me "why" i screwed up.  Not to just fix it.

Thank you so much in advance.  And to give you a little smile for a Monday, 
I've been working on this for days....argh



#first of all, why does this have to be here?
password="foobar"

count=3
current_count=0

while password !="unicorn":
     if current_count<count:
         password=raw_input("Password:")
         current_count=current_count+1
     else:
         print "That must have been complicated"


print "Welcome in"
Best,

Gary



Gary Laevsky, Ph.D.
Keck Facility Manager, CenSSIS
Northeastern University
302 Stearns
360 Huntington Ave.
Boston, MA 02115
voice(617) 373 - 2589<br>
fax(617) 373 - 7783<br><br>

http://www.censsis.neu.edu

http://www.ece.neu.edu/groups/osl

http://www.keck3dfm.neu.edu

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

From cyresse at gmail.com  Mon Apr 11 22:00:32 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Mon Apr 11 22:00:36 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <f2ff2d05041113001715820a@mail.gmail.com>

Hi Gary, 

In a while loop, you could looping until the while condition is no longer 
true.
So your one - 


while password != "unicorn"

So while password isn't unicorn, your condition is True, so your while loop 
will keep looping until the password equals 'unicorn'

After your 3rd mistake, the if current_count<count condition is no longer 
True, so you can't change the password, so the while loop will go infinite. 

Python goes 

Is password unicorn? Nope.
Is current_count < count? Nope.
better print "That must have been complicated"
Is password unicorn? Nope.
Is current_count < count? Nope.
better print"That must have been complicated"
Is password unicorn? Nope.
Is current_count < count? Nope.
better print "That must have been complicated"

if you get the drift. 

If you want it to be

Is password unicorn? Nope.
Is current_count < count? Yup.
Get password....
Is password unicorn? Nope.
Is current_count < count? Yup.
Get password....
Is password unicorn? Nope.
Is current_count < count? Yup.
Get password....
Is password unicorn? Nope.
Is current_count < count? Nope.
Get password....
better print "That must have been complicated"
Now exit the loop

you need is to check out the break command in a while loop - 


while 1 == 1:
x = raw_input('Secret? ')
if x == 'foo':
print 'broke'
break
else:
print 'loopy, loopy'.

print 'ended loop'


Regards, 

Liam Clarke


On Apr 12, 2005 6:54 AM, glaevsky@ece.neu.edu <glaevsky@ece.neu.edu> wrote:
> 
> Hey all,
> 
> Sorry for the bother, thanks for the help.
> 
> I'm trying to write a password guessing program to keep track of
> how many times the user has entered the password wrong.
> If it is more than 3 times, print ``That must have been complicated.''
> 
> Following is what I got. If I type "unicorn" it goes straight to "welcome
> in." Great. But after my third mistake, it just loops in "That must have
> been complicated."
> 
> I'd like for someone to tell me "why" i screwed up. Not to just fix it.
> 
> Thank you so much in advance. And to give you a little smile for a Monday,
> I've been working on this for days....argh
> 
> #first of all, why does this have to be here?
> password="foobar"
> 
> count=3
> current_count=0
> 
> while password !="unicorn":
> if current_count<count:
> password=raw_input("Password:")
> current_count=current_count+1
> else:
> print "That must have been complicated"
> 
> print "Welcome in"
> Best,
> 
> Gary
> 
> Gary Laevsky, Ph.D.
> Keck Facility Manager, CenSSIS
> Northeastern University
> 302 Stearns
> 360 Huntington Ave.
> Boston, MA 02115
> voice(617) 373 - 2589<br>
> fax(617) 373 - 7783<br><br>
> 
> http://www.censsis.neu.edu
> 
> http://www.ece.neu.edu/groups/osl
> 
> http://www.keck3dfm.neu.edu
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/16e86676/attachment.htm
From bvande at po-box.mcgill.ca  Mon Apr 11 22:01:35 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Mon Apr 11 22:02:08 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <425AD79F.20300@po-box.mcgill.ca>

glaevsky@ECE.NEU.EDU said unto the world upon 2005-04-11 14:54:
> Hey all,
> 
> Sorry for the bother, thanks for the help.
> 
> I'm trying to write a password guessing program to keep track of
> how many times the user has entered the password wrong.
> If it is more than 3 times, print ``That must have been complicated.''
> 
> Following is what I got.  If I type "unicorn" it goes straight to 
> "welcome in." Great.  But after my third mistake, it just loops in "That 
> must have been complicated."
> 
> I'd like for someone to tell me "why" i screwed up.  Not to just fix it.
> 
> Thank you so much in advance.  And to give you a little smile for a 
> Monday, I've been working on this for days....argh


Hi Gary,


> #first of all, why does this have to be here?
> password="foobar"

Given that you've structured things with a while loop that checks 
whether password is not equal to something else, you need to have a 
value for password, else you cannot check if the value of password is 
<whatever>. (If I asked you "Is graffleb less than 4?" you reasonably 
would reply "How can I answer that? You've not told me to what 
`graffleb' refers!")

That said, I'd use
 >>> password = None
instead.


> count=3
> current_count=0
> 
> while password !="unicorn":
>     if current_count<count:
>         password=raw_input("Password:")
>         current_count=current_count+1
>     else:
>         print "That must have been complicated"
> 
> 
> print "Welcome in"

You'd like the loop to exit after your third mistake, right? Well, the 
loop hasn't been told to do that :-)  The word you are looking for is 
`break'. If that doesn't get you to where you can make it behave as 
desired, post again.

HTH,

Brian vdB


From albertito_g at hotmail.com  Mon Apr 11 22:09:19 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 22:09:23 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <BAY106-F285199D200F80A77AF29EF89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/edc9943c/attachment.html
From project5 at redrival.net  Mon Apr 11 22:09:32 2005
From: project5 at redrival.net (Andrei)
Date: Mon Apr 11 22:13:55 2005
Subject: [Tutor] Re: Sorting of files based on filesize
References: <200504111806.10765.klas.martelleur@telia.com>
Message-ID: <loom.20050411T214327-700@post.gmane.org>

Klas Marteleur <klas.martelleur <at> telia.com> writes:

> Some of my harddrives are getting full and i would like to burn the files to 
> some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 
> 
> Ofcourse i would like to optimize the size of each DVD to be as close to 4.7Gb 
> as possible (to save this cheep media :) ).
> 
> There are plenty of software that are able to index my DVD's so sorting 
> between disks is not a problem. Just size.
> 
> What i would like to do is write a Python program that could sort my files 
> (based on size) into chunks as close to a given storage size (DVD 4.7Gb, CD 
> 650Mb...), and minimize the use of disks. Does anyone know of if something 
> like this is done before in Python, that i could look at?

Depends on how optimal you want things done. The easiest way is probably to sort
them by size, start with the largest and then keep adding smaller ones to the
compilation until it's full. Then start with the largest that's left and repeat
the process until you're left with (part of) a DVD with all kinds of small
files. I have some doubts about how optimal this will turn out to be. 

So instead, I went and implemented a fun 100-line script which uses a simple
genetic algorithm to generate disc layouts. Lacking real files, the script
listed below first generates 500 files with normally distributed sizes with an
average of 200 MB and a standard deviation of 200MB (with some sanity checks to
prevent files with negative size and files larger than 650MB) and tries to cram
those in 650MB CD's. 

Here's the link: http://ww3.6URL.com/FOK

It does this by first shuffling the list of files in a random manner several
times and determining the best fit of those (the solution that fills up the
discs as much as possible). This is the initial parent. Then it randomly
shuffles parts of this parent several times and determines the best fit of those
combinations. Then it uses that best fit to generate new children, etc. 

The siblings variable determines how many shuffles are performed before a best
fit in that group is selected. The generations variable determines how many
times the process of selecting the best is repeated.

The algorithm seems to work reasonably well (I get 190-ish CD's for files which
would cover 180-ish CD's if those CD's could be filled perfectly, even though
initial random file distributions give 240+ discs), but I haven't checked the
results very thoroughly. It might be doing something really stupid. It's also
reasonably fast (1000 generations of 1000 individuals each is feasible for
example, but not necessarily very useful). There's also no guarantee that the
result is the absolute best you can get.

Yours,

Andrei

From albertito_g at hotmail.com  Mon Apr 11 22:25:53 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 22:25:57 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <3511dc75050411090334e39686@mail.gmail.com>
Message-ID: <BAY106-F84870374784289B575F5189320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/687896ff/attachment.htm
From bvande at po-box.mcgill.ca  Mon Apr 11 22:45:55 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Mon Apr 11 22:51:04 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <BAY106-F285199D200F80A77AF29EF89320@phx.gbl>
References: <BAY106-F285199D200F80A77AF29EF89320@phx.gbl>
Message-ID: <425AE203.6060508@po-box.mcgill.ca>

Alberto Troiano said unto the world upon 2005-04-11 16:09:
> Hey Gary
> 
> password="foobar"
> 
> #######
> 
> the variable password has to be here because you are referiencing before the 
> assignment inside the while sentence. You can also set it to password="" and 
> still will work because you have to tell (in this example) that password is a 
> reserved word(variable)

Hi Alberto, Gary, and all,

Alberto, if I may, I think there are some problems in what you posted. 
(But, if you want to see some *really* troubled postings, just find 
some of my earliest attempts to answer on the tutor list!)

I think it is important to keep the distinction between variables and
reserved words clear.

>>> if = "Won't work as 'if' is a reserved word"
Traceback (  File "<interactive input>", line 1
     if = "Won't work as 'if' is a reserved word"
        ^
SyntaxError: invalid syntax
>>>

"Reserved words" or "keywords" are the fixed words of the Python
language itself. See Section 2.3.1 Keywords of the Language Reference.

> ########
> 
> count=3
> current_count=0
> 
> #######
> 
> Here you have two options:
> 
> Option 1:
> 
> 
> while password !="unicorn":
>     if current_count<count:
>         password=raw_input("Password:")
>         current_count=current_count+1
>     else:  
>         current_count=2  
>         print "That must have been complicated" 
> 
> print "Welcome in"
> 
> Add this line inside the "else" clause: current_count=2 ####This will make you 
> have more chances and if you fail it will complain.

That isn't going to solve the infinite looping problem in the case
that password never is equal to 'unicorn'

> The problem is that current_count doesn't decrement in the loop, so let's say 
> you fail 3 times the current_count will keep looping because its value is 3 and 
> it won't change in your code. Also I think that if you're making an application 
> to restrict the error to 3 times you may want to finish the app to start over so 
> in that case you may want to try option 2. 
> 
> #######                
> 
> Option 2:
> 
> while password !="unicorn" and current_count <= count:
>     if current_count<count:
>         password=raw_input("Password:")
>         current_count=current_count+1
>     else: 
>         current_count=current_count+1
>         print "That must have been complicated" 
> if password="unicorn":  
>         print "Try again Later"
>     else: 
>         print "Welcome in"         
> 
> Here you will lock your prog when the user fails 3 times and will print your 
> line once and then will jump to Try Again later and it will finish

I'm pretty sure there are some crossed wires here. :-) Maybe you
intended the last two print statements to be swapped? But, either way, 
since Option 2 will never exit the while loop unless password does
equal 'unicorn', the final else clause will never be reached. Or, so
it seems to me.

Last, I don't see why the first else block increments current_count.

Best,

Brian vdB


From python at jayloden.com  Mon Apr 11 21:45:45 2005
From: python at jayloden.com (Jay Loden)
Date: Mon Apr 11 22:53:05 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <200504112045.46618.python@jayloden.com>

Ok, it's a logic error in the while loop.  Starting at the beginning: you 
can't compare the value of "password" until the user inputs the value, which 
is why it's requiring you to put password = "foobar" at the top.  Otherwise, 
password has no value, and as far as the interpreter is concerned, it doesn't 
exist yet. 

The rest of it is a logic error because your while loop is executing as long 
as "unicorn" != "foobar" and therefore it's continuously looping.  Each time 
it loops, it asks for the password again, and sets a LOCAL variable called 
password to the new raw_input.  Then, when you get to the third time, it does 
the "if current_count<count:", realizes it doesn't match, and skips the rest 
of the if statement, moving to the else.  When it gets to the else, it prints 
out your error messge, then loops all over again.  

You have to provide it a way to break out of the loop and correctly compare 
the value of the user input to "unicorn" 

You'd be better off with something more like 

while raw_input("Password: ") != "unicorn:

or maybe reworking the whole thing to work in a for loop, since I'm assuming 
you only want it to give them three chances? Generally, if you know how many 
times you want something to happen, it's best to use a for loop rather than a 
while. 

-Jay
 

On Monday 11 April 2005 07:54 pm, glaevsky@ECE.NEU.EDU wrote:
> Following is what I got.  If I type "unicorn" it goes straight to "welcome
> in." Great.  But after my third mistake, it just loops in "That must have
> been complicated."
>
> I'd like for someone to tell me "why" i screwed up.  Not to just fix it.

> #first of all, why does this have to be here?
> password="foobar"
>
> count=3
> current_count=0
>
> while password !="unicorn":
>      if current_count<count:
>          password=raw_input("Password:")
>          current_count=current_count+1
>      else:
>          print "That must have been complicated"
>
>
> print "Welcome in"
> Best,
>
> Gary
>
>
>
> Gary Laevsky, Ph.D.
> Keck Facility Manager, CenSSIS
> Northeastern University
> 302 Stearns
> 360 Huntington Ave.
> Boston, MA 02115
> voice(617) 373 - 2589<br>
> fax(617) 373 - 7783<br><br>
>
> http://www.censsis.neu.edu
>
> http://www.ece.neu.edu/groups/osl
>
> http://www.keck3dfm.neu.edu
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From kent37 at tds.net  Mon Apr 11 22:55:22 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 11 22:55:25 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>
References: <BAY106-F18D6CA097731F18CA2C09389320@phx.gbl>
Message-ID: <425AE43A.1060700@tds.net>

Alberto Troiano wrote:
> Thanks Kent but now I need you to explain me the code :(

That code won't work for you. It is for timing how long it takes to do something, not for generating 
repeated events.

> 
> To give you a graphic example how can make this function to run every 5 
> seconds
> 
> def foo():
> 
>     print "Hello world!"

Here is a Tkinter program that updates the text of a label every second. It uses the root.after() 
method to schedule a callback. Since it is a one-time callback, the callback reschedules itself each 
time it is called.

This is not a great example of code structure but it is simple and demonstrates the concept.

from Tkinter import *

count = 0

def update():
     ''' Callback method updates the label '''
     global count
     count += 1
     label.configure(text=str(count))

     # Schedule another callback
     root.after(1000, update)


root=Tk()
label=Label(root,text="0")
label.pack()

b=Button(root,text="Bye",command='exit')
b.pack()

# Schedule the initial callback
root.after(1000, update)

root.mainloop()


Kent

From albertito_g at hotmail.com  Mon Apr 11 23:31:06 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 23:31:11 2005
Subject: [Tutor] str.split and quotes
In-Reply-To: <425AE43A.1060700@tds.net>
Message-ID: <BAY106-F1884697C143117BEE1866C89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/7854a318/attachment-0001.html
From albertito_g at hotmail.com  Mon Apr 11 23:43:22 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 23:43:26 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <425AE203.6060508@po-box.mcgill.ca>
Message-ID: <BAY106-F16F009566157931801577E89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/7578c444/attachment.htm
From albertito_g at hotmail.com  Mon Apr 11 23:46:05 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 11 23:46:08 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <425AE203.6060508@po-box.mcgill.ca>
Message-ID: <BAY106-F42BF8FA09D0E1379FCDE6E89320@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/7374c5cf/attachment.html
From jfouhy at paradise.net.nz  Tue Apr 12 00:25:30 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Tue Apr 12 00:25:35 2005
Subject: [Tutor] Sorting of files based on filesize
In-Reply-To: <425AB147.6020600@tds.net>
References: <200504111806.10765.klas.martelleur@telia.com>
	<425AB147.6020600@tds.net>
Message-ID: <1113258330.425af95a601ad@www.paradise.net.nz>

Quoting Kent Johnson <kent37@tds.net>:

> This is a hard problem. It is a version of the "0-1 knapsack problem" -
> googling for that might give 
> you some ideas.
> > Hi
> > Some of my harddrives are getting full and i would like to burn the files to 
> > some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 
> > Ofcourse i would like to optimize the size of each DVD to be as close to 4.7Gb 
> > as possible (to save this cheep media :) ).

Hmm, I would have called it an example of bin packing...

http://en.wikipedia.org/wiki/Bin_packing_problem

-- 
John.
From bvande at po-box.mcgill.ca  Tue Apr 12 01:11:50 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 12 01:12:18 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <BAY106-F16F009566157931801577E89320@phx.gbl>
References: <BAY106-F16F009566157931801577E89320@phx.gbl>
Message-ID: <425B0436.1020309@po-box.mcgill.ca>

Alberto Troiano said unto the world upon 2005-04-11 17:43:
> Hi Brian
> 
> Thanks for correcting me about the variable and reserved word differences (just 
> for the record the problem is that my english is not so good, you see I'm from 
> Bolivia so pardon my franc?is :P)


Hi Alberto,


I wouldn't have known you felt you had difficulties in English had you
not said so. :-)

> About the code I posted let me stand for it because it sure works like a charm.
> 
> I tested and the Option 1 gives the message of "That has been difficult" stuff 
> when you pass the 3 errors and still ask you for password.
> 
> The option 2 loops 3 times unless you put unicorn or whatever is the password 
> and at the third time it gives the message and then increment the current_count 
> once more to take you out of the while loop
> 
> Test it and let me know how it went, and also if I have a few problems with my 
> writing please let me know as I will try to correct them

You are absolutely right that your `Option 2' code does exit the loop.
I somehow missed that the while condition had an `and' in it :-[  My
apologies.

Your second post said you intended the final if clause to be:
if password=="unicorn":
     # etc

I've changed it to
if password != "unicorn":
     # etc

and get what I would think is correct behaviour.

So, it now reads:

password = None      # necessary pre-setting of names
current_count = 0
count = 3

while password != "unicorn" and current_count <= count:
     if current_count < count:
         password=raw_input("Password:")
         current_count=current_count+1
     else:
         current_count=current_count+1
         print "That must have been complicated"
if password!="unicorn":
     print "Try again Later"
else:
     print "Welcome in"


I would suggest that it be done like this, though:

# pre-sets as before go here

while password != "unicorn":
     if current_count < count:
         password = raw_input("Password:")
         if password=='unicorn':
             print 'Welcome in'
     else:
         print "That must have been complicated"
	print "Try again Later"
         break
     current_count += 1

This pushes all of the actions consequent on the password into the
password fetching loop and uses just a single incrementing line.


Anyway, once again, sorry for misreading and mis-correcting you.

Best,

Brian vdB


From cyresse at gmail.com  Tue Apr 12 01:42:12 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Tue Apr 12 01:42:15 2005
Subject: [Tutor] Using python with MS Excel (Newbie)
In-Reply-To: <9405eb91050411104213ab3566@mail.gmail.com>
References: <9405eb91050411104213ab3566@mail.gmail.com>
Message-ID: <f2ff2d05041116422434b4b3@mail.gmail.com>

Hi Andre, 

The gent responsible for win32com Mark Hammond wrote a book about it, but 
there's quite a useful help file included with the Win32all package. 

http://www.oreilly.com/catalog/pythonwin32/

I do recommend the book, however.

Also I recommend The Quick Python book, it has a nice run-down on creating 
COM objects to interact with MS software.


Regards, 

Liam Clarke
On Apr 12, 2005 5:42 AM, Andre Thompson <andre.wayne.thompson@gmail.com> 
wrote:
> 
> Hi All,
> 
> I am trying to create a couple of python programs that creates and
> modifies MS Excel docs.
> 
> I have been searching the web and have found some interesting pieces
> of information and programs but i need something more complete. Is the
> any documentation available explaning all the options available
> programming with win32com.
> 
> I thank you in advance for the help.
> 
> Regards,
> Andre
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/c4e20b37/attachment.html
From cyresse at gmail.com  Tue Apr 12 01:43:38 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Tue Apr 12 01:43:44 2005
Subject: [Tutor] Using python with MS Excel (Newbie)
In-Reply-To: <f2ff2d05041116422434b4b3@mail.gmail.com>
References: <9405eb91050411104213ab3566@mail.gmail.com>
	<f2ff2d05041116422434b4b3@mail.gmail.com>
Message-ID: <f2ff2d050411164341822d18@mail.gmail.com>

PS 

Check out the sample chapter 
http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html

On Apr 12, 2005 11:42 AM, Liam Clarke <cyresse@gmail.com> wrote:
> 
> Hi Andre, 
> 
> The gent responsible for win32com Mark Hammond wrote a book about it, but 
> there's quite a useful help file included with the Win32all package. 
> 
> http://www.oreilly.com/catalog/pythonwin32/
> 
> I do recommend the book, however.
> 
> Also I recommend The Quick Python book, it has a nice run-down on creating 
> COM objects to interact with MS software.
> 
> 
> Regards, 
> 
> Liam Clarke
> On Apr 12, 2005 5:42 AM, Andre Thompson <andre.wayne.thompson@gmail.com> 
> wrote:
> > 
> > Hi All,
> > 
> > I am trying to create a couple of python programs that creates and
> > modifies MS Excel docs.
> > 
> > I have been searching the web and have found some interesting pieces
> > of information and programs but i need something more complete. Is the
> > any documentation available explaning all the options available
> > programming with win32com.
> > 
> > I thank you in advance for the help.
> > 
> > Regards,
> > Andre
> > _______________________________________________
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> 
> 
> -- 
> 'There is only one basic human right, and that is to do as you damn well 
> please.
> And with it comes the only basic human duty, to take the consequences.' 




-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/0a49ed4c/attachment.htm
From keridee at jayco.net  Tue Apr 12 04:48:04 2005
From: keridee at jayco.net (Jacob S.)
Date: Tue Apr 12 04:47:05 2005
Subject: [Tutor] Cell Bio Newbie Here
References: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
	<200504112045.46618.python@jayloden.com>
Message-ID: <006f01c53f0a$129a1d80$155428cf@JSLAPTOP>

> Ok, it's a logic error in the while loop.  Starting at the beginning: you
> can't compare the value of "password" until the user inputs the value, 
> which
> is why it's requiring you to put password = "foobar" at the top. 
> Otherwise,
> password has no value, and as far as the interpreter is concerned, it 
> doesn't
> exist yet.

Looks good.

> The rest of it is a logic error because your while loop is executing as 
> long
> as "unicorn" != "foobar" and therefore it's continuously looping.  Each 
> time
> it loops, it asks for the password again, and sets a LOCAL variable called
> password to the new raw_input.

So you're telling us that --- 

x = 5
while x != 5:
    print "Not equal"
    x = x+1
print "Equal"

will result in an infinite loop because stating x = x+1 sets a Local 
variable? I don't think so.
Maybe what you're saying is the condition stated with the while loop is only 
executed once?
That's not the case.


Oh by the way Gary -- summing up the answers.

password = raw_input("What's the password? ")
count = 0
good = True
while password != 'unicorn':
    if count > 2:
        print "That must be hard work."
        good = False
        break
    print "That's not it."
    count = count+1
    password = raw_input("What's the password? ")

if good:
    print "Welcome in. "
else:
    print "I'm gonna kick you out. "


Execution is as follows.

We start off by asking the password.
Count is zero.
We assume that password is good  # good = True
We check with while loop condition.
If good, skip loop and print "Welcome in " because good == True
If bad, check if count greater than three. In this case no.
print "That's not it" because whatever the password is, it's not unicorn, or 
we wouldn't be in the loop.
Increment count
Ask another password.
Check to see if password is unicorn.
If it is, good == True, so "Welcome in. " is printed.
If not, check to see if count > 2 i.e. this is the third time. In this case 
it's not, so print "That's not it. "
Increment count
Ask another password.
Check to see if password is unicorn.
If it is, good still equals True, so print "Welcome in."
If not, which it isn't yet, check to see if count > 2.
In this case, it is, so print "This must be hard work."
Set good = False
break out of loop
good != True
so print "I'm gonna kick you out."

HTH,
Jacob 

From smichr at hotmail.com  Tue Apr 12 08:40:43 2005
From: smichr at hotmail.com (C Smith)
Date: Tue Apr 12 08:41:39 2005
Subject: [Tutor] Sorting of files based on filesize
Message-ID: <CB5CB3D0-AB1D-11D9-B1ED-000393C0D100@hotmail.com>

--request for a method of sorting disk files based on size so as to 
fill backup disks--

You may want to check out the karp.py routine posted at
http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/749797

Right now it is coded to split N numbers into 2 groups that have sums 
as nearly identical as possible. The set of numbers it is coded to test 
are are the first 50 square roots of integers; you would replace these 
with a list of N file sizes that are close to 2X a single disk capacity 
and it would tell you how to split up the group into two 
nearly-identically sized groups.  It's "very, very, very clever, and 
runs in an eyeblink" says Tim Peters. You might even want to use Tim's 
greedy "knapsack filler" approach that he initially proposed as part of 
the thread above which will try random selections from a list of values 
and keep track of the one that came closest to a target value. Your 
target value would be 2X the storage limit and then you could use the 
karp routine to split it nicely. Tim's greedy approach is at
http://mail.python.org/pipermail/tutor/2001-August/008075.html


An alternative to breaking your list of file sizes into sublists that 
are close to 2X your disk capacity would be to generalize the algorithm 
to break the numbers into M groups rather than 2 groups...but I'm not 
sure how easy that will be.

You're going to love using the karp for this problem :-)

/c

From rdm at rcblue.com  Tue Apr 12 12:08:48 2005
From: rdm at rcblue.com (Dick Moores)
Date: Tue Apr 12 12:10:36 2005
Subject: [Tutor] UselessPython 2.0
In-Reply-To: <1ff2dfbf05041110305a2218f0@mail.gmail.com>
References: <e835145805040711225875506a@mail.gmail.com>
	<6.2.1.2.2.20050409221002.02817750@rcblue.com>
	<1ff2dfbf05041110305a2218f0@mail.gmail.com>
Message-ID: <6.2.1.2.2.20050412030332.0428ada0@rcblue.com>

Michael Janssen wrote at 10:30 4/11/2005:
>On Apr 10, 2005 7:18 AM, Dick Moores <rdm@rcblue.com> wrote:
>
> > I'm a newbie, but would this qualify as a contribution to 
> UselessPython 2.0?
>
>Hello Dick,
>
>don't be shy, or do you suspect it might be too usefull? ;-) I found
>it funny, so it must be good enough.
>
>here my remarks:
>
> > def makeStringAllLowercaseAlpha(s):
> >     """
> >     Take any string, convert all uppercase alphabetic characters to
> > lower case,
> >     then strip all non-alphabetic characters
>
>[what's bad about non-alphabetic characters?]
>
> >     """
> >     s1 = string.lower(userstring)
>
>oops: this function gets an argument s, here you're using the global
>variable userstring. I know, it works, but there will be functions
>were mistakes like this weren't just ugly but buggy.
>
> >     s2 = ""
> >     for index in range(len(s1)):
> >         if s1[index] in string.ascii_lowercase:
> >             s2 += s1[index]
>
>or easier (much more readable, helps understanding the programm):
>
>for char in s1:
>      if char in string.ascii_lowercase:
>            s2 += char
>
>regards
>Michael

Thanks very much, Michael. Here's the revision.
=====================================
# isPalindrome.py

# revision of http://www.uselesspython.com/glpalindrome.py to handle 
palindromes
#   such as "Radar" and "A man, a plan, a canal, Panama!"

# http://www.palindromelist.com/ has many palindromes

# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'

import string

def isPalindrome(w):
     return w == '' or (w[0]==w[-1]) and isPalindrome(w[1:-1]) # recursive

def makeStringAllLowercaseAlpha(s):
     """
     Take any string, convert all uppercase alphabetic characters to 
lower case,
     then strip all non-alphabetic characters
     """
     s1 = string.lower(s)
     s2 = ""
     for char in s1:
         if char in string.ascii_lowercase:
             s2 += char
     return s2

userstring = raw_input('Enter a word or sentence to test: ')
userstringRevised = makeStringAllLowercaseAlpha(userstring)
====================================

Dick


From marcosm at gmail.com  Tue Apr 12 13:20:34 2005
From: marcosm at gmail.com (=?ISO-8859-1?Q?Marcos_Mendon=E7a?=)
Date: Tue Apr 12 13:20:38 2005
Subject: [Tutor] Using python with MS Excel (Newbie)
In-Reply-To: <f2ff2d050411164341822d18@mail.gmail.com>
References: <9405eb91050411104213ab3566@mail.gmail.com>
	<f2ff2d05041116422434b4b3@mail.gmail.com>
	<f2ff2d050411164341822d18@mail.gmail.com>
Message-ID: <2b46c715050412042064cdb5a1@mail.gmail.com>

Also you should try the MSDN documentation on Excel, since most
methods you are going to use are Excel related more than Python
related, that is, win32all is and wrapper for Excel methods. Hope I?m
not mistaken on this one :-)



On Apr 11, 2005 8:43 PM, Liam Clarke <cyresse@gmail.com> wrote:
> PS 
>  
>  Check out the sample chapter
> http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html
> 
> 
> On Apr 12, 2005 11:42 AM, Liam Clarke <cyresse@gmail.com> wrote:
> > Hi Andre, 
> > 
> > The gent responsible for win32com Mark Hammond wrote a book about it, but
> there's quite a useful help file included with the Win32all package. 
> > 
> > http://www.oreilly.com/catalog/pythonwin32/
> > 
> > I do recommend the book, however.
> > 
> > Also I recommend The Quick Python book, it has a nice run-down on creating
> COM objects to interact with MS software.
> > 
> > 
> > Regards, 
> > 
> > Liam Clarke
> > 
> > 
> > On Apr 12, 2005 5:42 AM, Andre Thompson <andre.wayne.thompson@gmail.com>
> wrote:
> > > Hi All,
> > > 
> > > I am trying to create a couple of python programs that creates and
> > > modifies MS Excel docs.
> > > 
> > > I have been searching the web and have found some interesting pieces
> > > of information and programs but i need something more complete. Is the
> > > any documentation available explaning all the options available
> > > programming with win32com.
> > > 
> > > I thank you in advance for the help.
> > > 
> > > Regards,
> > > Andre
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > > 
> > 
> > 
> > 
> > -- 
> > 'There is only one basic human right, and that is to do as you damn well
> please.
> > And with it comes the only basic human duty, to take the consequences.' 
> 
> 
> 
> -- 
> 'There is only one basic human right, and that is to do as you damn well
> please.
> And with it comes the only basic human duty, to take the consequences.' 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>
From rdm at rcblue.com  Tue Apr 12 14:05:53 2005
From: rdm at rcblue.com (Dick Moores)
Date: Tue Apr 12 14:07:59 2005
Subject: [Tutor] How to calculate pi with another formula?
In-Reply-To: <41828B7F.1060608@aon.at>
References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com>
	<41828B7F.1060608@aon.at>
Message-ID: <6.2.1.2.2.20050412032247.0552f3e0@rcblue.com>

Gregor Lingl wrote at 11:27 10/29/2004:
>Hi Dick!
>
>Accidentally I just was tinkering around with the new
>decimal module of Python2.4. (By the way: it also works
>with Python 2.3 - just copy it into /Python23/Lib)
>
>The attached program uses a very elementary (and inefficient)
>formula to calculate pi, namely as the area of a 6*2**n-sided
>polygon (starting with n=0), inscribed into a circle of radius 1.
>(Going back to Archimedes, if I'm right ...)
>
>Nevertheless it calculates pi with a precision of (nearly)
>100 digits, and the precision can be  arbitrarily enlarged.
>In the output of this program only the last digit is not correct.
>
>import decimal
>
>decimal.getcontext().prec = 100
>
>def calcpi():
>    s = decimal.Decimal(1)
>    h = decimal.Decimal(3).sqrt()/2
>    n = 6
>    for i in range(170):
>        A = n*h*s/2  # A ... area of polygon
>        print i,":",A
>        s2 = ((1-h)**2+s**2/4)
>        s = s2.sqrt()
>        h = (1-s2/4).sqrt()
>        n = 2*n
>
>calcpi()
>
>Just for fun ...
>
>Gregor

This works great, and if I change the precision to, say, 2000, and the 
range to 2000, I get pi accurate to the 1,205th digit (this took 66 
minutes, with psyco employed), when I compare with the pi pages on the web.

Now to my new question. I have an artist friend who knows an artist who 
needs pi expressed in base 12. I don't know how many digits he needs, but 
I think he'll take what he can get. Is there a way to use math.log(x, 
base) with the decimal module to accomplish this? Or is there another 
way? Or is there no way?

Thanks,

Dick Moores
rdm@rcblue.com

From albertito_g at hotmail.com  Tue Apr 12 14:42:49 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 12 14:42:53 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <425B0436.1020309@po-box.mcgill.ca>
Message-ID: <BAY106-F19CCCC71B8AE3ADD111E4589330@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/b4f2c836/attachment.htm
From cpu.crazy at gmail.com  Mon Apr 11 22:20:42 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue Apr 12 15:20:16 2005
Subject: [Tutor] Tk code problem (Joseph Q.)
In-Reply-To: <20050411170341.402A61E4014@bag.python.org>
References: <20050411170341.402A61E4014@bag.python.org>
Message-ID: <6.1.0.6.2.20050411141339.01eedb80@pop.gmail.com>

Hi,
It seems that whenever I click the QUIT button the TK windows freezes, then 
I have to CTRL-ALT-DEL to be able to shut it down. Here's the code (its not 
mine though):



from Tkinter import *

class App:

     def __init__(self, master):

         frame = Frame(master)
         frame.pack()

         self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
         self.button.pack(side=LEFT)

         self.hi_there = Button(frame, text="Hello", command=self.say_hi)
         self.hi_there.pack(side=LEFT)

     def say_hi(self):
         print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()


It's probably the
command=frame.quit

Is there another command to close the Tk program? (like raise  SystemExit 
and sys.exit()  for the text based programs)

Also could I do something like root and tk = Tk()?

Thanks,
         Joseph.

P.S  I'm currently looking for an dedicated python IDE (or IDLE, i never 
can tell the difference between the two)
for Linux. I know about emacs and vi (or vim) (but they're not dedicated). 
I was wondering if any of you know of any.  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/fea77691/attachment.html
From cpu.crazy at gmail.com  Tue Apr 12 02:23:19 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue Apr 12 15:20:18 2005
Subject: [Tutor] Defining a function (Joseph Q.)
Message-ID: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>

Well, now I've learned what def is good for. But what could I put in the 
parenthesis of  def foo():?
Of course self is always available, but what would maybe def foo(number1): 
do? An error right? So I now repeat my self, what else besides self could I 
put in there?

Thanks,
         Joseph 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050411/04158928/attachment.htm
From cyresse at gmail.com  Tue Apr 12 15:27:32 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Tue Apr 12 15:27:36 2005
Subject: [Tutor] Defining a function (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>
References: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>
Message-ID: <f2ff2d050412062714bbf7e3@mail.gmail.com>

>>> def foo(x):
... print x
... 
>>> foo('hi')
hi

What goes in the brackets is simply the arguments that foo() works with. 

>>>def foo(a,b):
... return a + b
>>> sum = foo(5,10)
>>>print sum
15
>>> conjun = foo("Hi ", "Dave")
>>>print conjun
Hi Dave


Good luck, 

Liam Clarke

On Apr 12, 2005 12:23 PM, Joseph Quigley <cpu.crazy@gmail.com> wrote:
> 
> Well, now I've learned what def is good for. But what could I put in the 
> parenthesis of def foo():? 
> Of course self is always available, but what would maybe def foo(number1):do? An error right? So I now repeat my self, what else besides self could I 
> put in there?
> 
> Thanks,
> Joseph 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/aceec993/attachment.html
From albertito_g at hotmail.com  Tue Apr 12 16:21:54 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 12 16:22:00 2005
Subject: [Tutor] Question about Frames and Scrollbars
Message-ID: <BAY106-F180D1AA0B10F958875CB0F89330@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/1aa8f74a/attachment.htm
From kent37 at tds.net  Tue Apr 12 16:24:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 12 16:24:33 2005
Subject: [Tutor] Tk code problem (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050411141339.01eedb80@pop.gmail.com>
References: <20050411170341.402A61E4014@bag.python.org>
	<6.1.0.6.2.20050411141339.01eedb80@pop.gmail.com>
Message-ID: <425BDA1D.6030305@tds.net>

Joseph Quigley wrote:
> Hi,
> It seems that whenever I click the QUIT button the TK windows freezes, 
> then I have to CTRL-ALT-DEL to be able to shut it down. Here's the code 
> (its not mine though):

It works if you run from the command line instead of inside IDLE. I thought IDLE was supposed to be 
able to run Tkinter programs since Python 2.3 but it doesn't seem to work?
> 
> P.S  I'm currently looking for an dedicated python IDE (or IDLE, i never 
> can tell the difference between the two)
> for Linux. I know about emacs and vi (or vim) (but they're not 
> dedicated). I was wondering if any of you know of any.

AFAIK IDLE runs on Linux. There are many other possibilities listed here:
http://www.python.org/moin/IntegratedDevelopmentEnvironments

eric is popular...

Kent

From John.Gooch at echostar.com  Tue Apr 12 16:49:47 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Tue Apr 12 16:49:55 2005
Subject: [Tutor] sorting a list of dictionaries
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>

I am working on a dictionary sorting problem just like the one in the email
thread at the bottom of this message. My question about their solution is:
In these lines:
	lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
	where field is either 'name' or 'size'.

What is "n:" and what is "lambda m" ? 


Thank You, 

John A. Gooch

-----Original Message-----
From: sigurd@12move.de [mailto:sigurd@12move.de] 
Sent: Thursday, December 09, 2004 12:19 PM
To: tutor@python.org
Subject: Re: [Tutor] sorting a list of dictionaries


On  9 Dez 2004, ljholish@speakeasy.net wrote:

> I have a list of dictionaries, each representing info about a file, 
> something like:
>
> [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
>
> I want to present a sorted list of all the files' data, sorting on the 
> keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) 
> across all the dictionaries. Can someone point me towards an efficient 
> solution for accomplishing the sort? (The list has 1000s of files).

That's easy to achieve, since sort takes a custom sort function as optional
argument.  Now you need only a function which takes the values of the fileds
and compares them.

E.g.

lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
where field is either 'name' or 'size'.

As a function:

def sort_it (lst, field):
    lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))


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

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From bvande at po-box.mcgill.ca  Tue Apr 12 18:08:02 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 12 18:09:01 2005
Subject: [Tutor] Defining a function (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>
References: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>
Message-ID: <425BF262.2010005@po-box.mcgill.ca>

Joseph Quigley said unto the world upon 2005-04-11 20:23:
> Well, now I've learned what def is good for. But what could I put in the 
> parenthesis of  def foo():?
> Of course self is always available, but what would maybe def 
> foo(number1): do? An error right? So I now repeat my self, what else 
> besides self could I put in there?
> 
> Thanks,
>         Joseph

Hi Joseph,

as Liam explained, you put the arguments (if any) to the function in
the parenthesis.

But, I want to address the bit where you said "Of course self is
always available". *Any* valid Python identifier (or name) can be used
("is always available"):

>>> def silly(a_name_I_picked_at_random):   # well, not quite
... 	print a_name_I_picked_at_random     # at random ;-)
... 	
>>> silly(42)
42

The name a_name_I_picked_at_random is like a "placeholder" inside the
function for whatever input we gave to the function. And *that* can be
any object:

>>> silly(silly)
<function silly at 0x01298070>
>>>

Some functions require certain sorts of inputs in virtue of what they
try to do with them, but we can still pass any sort of object in.  For
instance, Liam had:

>>> def foo(a, b):
... 	return a + b
...

Now, try this:

>>> foo(42, '42')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 2, in foo
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

That's not a problem with Liam's function; it's a problem that I
caused by sending it inappropriate inputs.


At any rate, you are correct that you can always name an argument
"self". But "self" is, by *very* strong convention, used only within
classes.  Simplifying[*] a bit, a method is a function defined
internal to a class. If you define a method in a class, you call the
first argument of the method definition "self", and it is
automatically interpreted as a reference to the `active' instance of
the class on which the method is called.

So, don't use "self" outside of method definitions. You can ("we are
all adults here"), but doing so will only confuse things given the
strength of the convention.

[*] The simplification comes in that not all methods in a class need
to be bound to an instance, so not all methods employ "self". But, my
guess is that is something you shouldn't be worrying about just yet.

Best,

Brian vdB


From klas.martelleur at telia.com  Tue Apr 12 18:09:38 2005
From: klas.martelleur at telia.com (Klas Marteleur)
Date: Tue Apr 12 18:09:41 2005
Subject: [Tutor] Sorting of files based on filesize
In-Reply-To: <CB5CB3D0-AB1D-11D9-B1ED-000393C0D100@hotmail.com>
References: <CB5CB3D0-AB1D-11D9-B1ED-000393C0D100@hotmail.com>
Message-ID: <200504121809.38219.klas.martelleur@telia.com>

Thanks C, John, Kent and Andrei.

I knew that someone had thought about this problem before :). But i couldnt 
relize that the problem was this widespread and had so many names.

Thanks for pointing me in the right direction. The problem is a bit over my 
head but its fun with some brain exercise :)  

Kind Regards
Klas
From John.Gooch at echostar.com  Tue Apr 12 18:20:47 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Tue Apr 12 18:20:54 2005
Subject: [Tutor] Pass By Reference
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0C0@riv-excha5.echostar.com>

I have a class named 'Dir' that I want to be put into another class
'DirList' ( essential a linked list of Dir objects ) using the 'insert()'
method. The syntax is 'DirList.insert( Dir )' which works, but then I try to
access the 'getSize()' function of the 'Dir' class from *inside* of the
DirList class, it gives me this -> 
    'I added a node for dir d:/ with size <bound method Dir.getSize of
<__main__.Dir instance at 0x00E18CD8>>'
 
Any ideas on what I am doing wrong? 
 
Thank You, 
 
John A. Gooch 
Systems Administrator 
IT - Tools 
EchoStar Satellite L.L.C. 
9601 S. Meridian Blvd. 
Englewood, CO  80112 
Desk: 720-514-5708 

 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/253d7b20/attachment.html
From maitj at vianet.ca  Tue Apr 12 18:54:57 2005
From: maitj at vianet.ca (Jeffrey Maitland)
Date: Tue Apr 12 18:55:12 2005
Subject: [Tutor] Re: Defining a function (Joseph Q.)
In-Reply-To: <425BF262.2010005@po-box.mcgill.ca>
References: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com>
	<425BF262.2010005@po-box.mcgill.ca>
Message-ID: <20050412165457.31157.qmail@mail.vianet.ca>

Brian van den Broek writes: 

> Joseph Quigley said unto the world upon 2005-04-11 20:23:
>> Well, now I've learned what def is good for. But what could I put in the 
>> parenthesis of  def foo():?
>> Of course self is always available, but what would maybe def 
>> foo(number1): do? An error right? So I now repeat my self, what else 
>> besides self could I put in there? 
>> 
>> Thanks,
>>         Joseph
> 
> Hi Joseph, 
> 
> as Liam explained, you put the arguments (if any) to the function in
> the parenthesis. 
> 
> But, I want to address the bit where you said "Of course self is
> always available". *Any* valid Python identifier (or name) can be used
> ("is always available"): 
> 
>>>> def silly(a_name_I_picked_at_random):   # well, not quite
> ... 	print a_name_I_picked_at_random     # at random ;-)
> ... 	
>>>> silly(42)
> 42 
> 
> The name a_name_I_picked_at_random is like a "placeholder" inside the
> function for whatever input we gave to the function. And *that* can be
> any object: 
> 
>>>> silly(silly)
> <function silly at 0x01298070>
>>>> 
> 
> Some functions require certain sorts of inputs in virtue of what they
> try to do with them, but we can still pass any sort of object in.  For
> instance, Liam had: 
> 
>>>> def foo(a, b):
> ... 	return a + b
> ... 
> 
> Now, try this: 
> 
>>>> foo(42, '42')
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 2, in foo
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>> 
> 
> That's not a problem with Liam's function; it's a problem that I
> caused by sending it inappropriate inputs. 
> 
> 
> At any rate, you are correct that you can always name an argument
> "self". But "self" is, by *very* strong convention, used only within
> classes.  Simplifying[*] a bit, a method is a function defined
> internal to a class. If you define a method in a class, you call the
> first argument of the method definition "self", and it is
> automatically interpreted as a reference to the `active' instance of
> the class on which the method is called. 
> 
> So, don't use "self" outside of method definitions. You can ("we are
> all adults here"), but doing so will only confuse things given the
> strength of the convention. 
> 
> [*] The simplification comes in that not all methods in a class need
> to be bound to an instance, so not all methods employ "self". But, my
> guess is that is something you shouldn't be worrying about just yet. 
> 
> Best, 
> 
> Brian vdB 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Brian is correct. 

Also I would like to point out that
def foo(*args): #this allows for any number of arguments to be passed.

The *args is powerful when used correctly. *args is a list of any length of 
arguments being passed to the function and/or class, and the arguments 
passed can be any type/object you want to pass . 

So you might do something like.
def foo(*args):
  print len(args)
# this prints the length of the list of the arguements passed 

# so using that function you would see something like. in the example I only 
used basic types but you can pass objects as well.
>>foo(1, 2, 3, "cat", "mouse", ['bee', 'honey', 'stinger'])
6 

Notice that the length that is returned is only 6 but there are 8 items so 
it appears to have been passed to the function.   In actuallity it is only 6 
items.  There is 3 integers, then 2 strings, then 1 list that is 3 items 
long. Thus the length of the list args is 6 items long. I wouldn't recomend 
passing mixed types like this to a function using args because it can get 
very confusing. I hope this helps you out and doesn't confuse you. I know 
from first hand experience the first time I saw the *args in some code I was 
lost. 

If you know the type of variables that are to be passed to the function and 
the number of them then it is easier to specify them, and use names. such 
as. 

def bar(num1, num2): #this is not catching invalid data types and such.
  return num1 + num2 #returns the sum of num1 + num2 

>> bar(1, 2)
3 

Also if you want to have default values passed incase the call is issued 
without any arguments passed.
#This will take 2 arguments and add them together and return the sum
# but the default values will fill in the remaining (missing) arguments.
def my_foo(num1 = 0.0, num2 = 1.0):
  return num1 + num2 

>> my_foo()
1.0
>> my_foo(6.7)
7.7
>> my_foo(2, 2)
4 

The reason that my_foo() returns 1.0 is that no arguments were given so the 
default values were used and the 2nd argument default value is 1.0 and was 
added to the 1st argument's default value of 0.0. Thus 0.0 + 1.0 

The reason that in the my_foo(6.7) example 7.7 is returned is that the 
default value of the 2nd argument is used since no 2nd argument was given 
was given. so it was 6.7 + 1.0 

And Finally both arguments were specified my_foo(2, 2) the function takes 
both values and adds them giving you 4. 

I hope this helps, and does not make any more confusing. I try to be consise 
when giving information however I like to be thorough in my explanations. 

Jeff
From benmarkwell at gmail.com  Tue Apr 12 18:56:25 2005
From: benmarkwell at gmail.com (Ben Markwell)
Date: Tue Apr 12 18:56:48 2005
Subject: [Tutor] New to programming question
Message-ID: <b930511705041209564b3f9255@mail.gmail.com>

This is an exercise from "How to think like a Computer Scientist."


The following example shows how to use concatenation and a for loop to 
generate an abecedarian series. "Abecedarian" refers to a series or list in 
which the elements appear in alphabetical order. For example, in Robert 
McCloskey's book *Make Way for Ducklings*, the names of the ducklings are 
Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs 
these names in order: 

prefixes = "JKLMNOPQ" 
suffix = "ack" 

for letter in prefixes: 
print letter + suffix 

The output of this program is: 

Jack 
Kack 
Lack 
Mack 
Nack 
Oack 
Pack 
Qack 

Of course, that's not quite right because "Ouack" and "Quack" are 
misspelled.*
*

*As an exercise, modify the program to fix this error.
*

==================================================
 
In trying to solve the problem I have come up with the following:
 
prefixes = 'JKLMNOPQ'
suffix = 'ack'
xsuffix = 'uack'


for letter in prefixes:
n = 0
if prefixes[n] == 'O' or 'Q':
print prefixes[n] + xsuffix
else:
print letter + suffix
 
--- I know it doesn't work, but want to know if I am on the right track. And 
what is the solution?
 
Thanks
 
Ben
**
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/22355b63/attachment.htm
From maitj at vianet.ca  Tue Apr 12 19:19:08 2005
From: maitj at vianet.ca (Jeffrey Maitland)
Date: Tue Apr 12 19:19:11 2005
Subject: [Tutor] Re: New to programming question
In-Reply-To: <b930511705041209564b3f9255@mail.gmail.com>
References: <b930511705041209564b3f9255@mail.gmail.com>
Message-ID: <20050412171908.26970.qmail@mail.vianet.ca>

Ben Markwell writes: 

> This is an exercise from "How to think like a Computer Scientist." 
> 
> 
> The following example shows how to use concatenation and a for loop to 
> generate an abecedarian series. "Abecedarian" refers to a series or list in 
> which the elements appear in alphabetical order. For example, in Robert 
> McCloskey's book *Make Way for Ducklings*, the names of the ducklings are 
> Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs 
> these names in order:  
> 
> prefixes = "JKLMNOPQ" 
> suffix = "ack"  
> 
> for letter in prefixes: 
> print letter + suffix  
> 
> The output of this program is:  
> 
> Jack 
> Kack 
> Lack 
> Mack 
> Nack 
> Oack 
> Pack 
> Qack  
> 
> Of course, that's not quite right because "Ouack" and "Quack" are 
> misspelled.*
> * 
> 
> *As an exercise, modify the program to fix this error.
> * 
> 
> ==================================================
>  
> In trying to solve the problem I have come up with the following:
>  
> prefixes = 'JKLMNOPQ'
> suffix = 'ack'
> xsuffix = 'uack' 
> 
> 
> for letter in prefixes:
> n = 0
> if prefixes[n] == 'O' or 'Q':
> print prefixes[n] + xsuffix
> else:
> print letter + suffix
>  
> --- I know it doesn't work, but want to know if I am on the right track. And 
> what is the solution?
>  
> Thanks
>  
> Ben
> **

Well you did come up with a way that would work sort of and you seem to be 
ont eh right track. I would make 1 small change if using your approach. 

prefixes = 'JKLMNOPQ'
suffix = 'ack' 

for letter in prefixes:
  if letter == 'O' or letter == 'Q': print letter + 'u' + suffix
  else: print letter + suffix 

However there are other methodes to solve this problem but following the 
logic you are using this works. 

Jeff 


From bvande at po-box.mcgill.ca  Tue Apr 12 19:30:39 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 12 19:32:51 2005
Subject: [Tutor] New to programming question
In-Reply-To: <b930511705041209564b3f9255@mail.gmail.com>
References: <b930511705041209564b3f9255@mail.gmail.com>
Message-ID: <425C05BF.9000304@po-box.mcgill.ca>

Ben Markwell said unto the world upon 2005-04-12 12:56:
> This is an exercise from "How to think like a Computer Scientist."
> 
> 
> The following example shows how to use concatenation and a for loop to 
> generate an abecedarian series. "Abecedarian" refers to a series or list in 
> which the elements appear in alphabetical order. For example, in Robert 
> McCloskey's book *Make Way for Ducklings*, the names of the ducklings are 
> Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs 
> these names in order: 
> 
> prefixes = "JKLMNOPQ" 
> suffix = "ack" 
> 
> for letter in prefixes: 
> print letter + suffix 
> 
> The output of this program is: 
> 
> Jack 
> Kack 
> Lack 
> Mack 
> Nack 
> Oack 
> Pack 
> Qack 
> 
> Of course, that's not quite right because "Ouack" and "Quack" are 
> misspelled.*
> *
> 
> *As an exercise, modify the program to fix this error.
> *
> 
> ==================================================
>  
> In trying to solve the problem I have come up with the following:
>  
> prefixes = 'JKLMNOPQ'
> suffix = 'ack'
> xsuffix = 'uack'
> 
> 
> for letter in prefixes:
> n = 0
> if prefixes[n] == 'O' or 'Q':
> print prefixes[n] + xsuffix
> else:
> print letter + suffix
>  
> --- I know it doesn't work, but want to know if I am on the right track. And 
> what is the solution?
>  
> Thanks
>  
> Ben
> **
>

Hi Ben,

in generally, it is a good idea to say *why* it doesn't work.
Sometimes it won't be clear what you expected as output, so it also
won't be clear why you are disappointed.

That said, see if this helps:

>>> if 'Q' == 'O' or 'Q': print "Yep (or is it?)"
...
Yep (or is it?)
>>> if 'B' == 'O' or 'Q': print "Yep (or is it?)"
...
Yep (or is it?)


Probably not what is wanted. What happens here is Python first evaluates
'Q' == 'O'
and, if it evaluates to true, returns it. But, in neither case does it 
evaluate to true. So Python then turns to evaluating 'Q'. But that 
*always* evaluates to true. So Python returns 'Q', and the if test 
above is always met. See:

>>> if 'Q': print "That evaluated to True"
...
That evaluated to True
>>> False or 'Q'
'Q'
>>> 42==42 or 'Q'
True
>>> 42==17 or 'Q'
'Q'
>>>

There are a couple of different ways to get the test I think you want.
Here's what I'd do:

>>> if 'Q' in ('O', 'Q'): print "Thank goodness!"
...
Thank goodness!
>>> if 'B' in ('O', 'Q'): print "Thank goodness!"
...
>>>

Now, fix that up so it is not testing a hardcoded value (i.e. make it
other than "if 'Q' ... ") and see if that helps.

Post again if not.

Best,

Brian vdB


From bill.mill at gmail.com  Tue Apr 12 19:46:12 2005
From: bill.mill at gmail.com (Bill Mill)
Date: Tue Apr 12 19:46:14 2005
Subject: [Tutor] Pass By Reference
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0C0@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0C0@riv-excha5.echostar.com>
Message-ID: <797fe3d405041210467f111f7e@mail.gmail.com>

On Apr 12, 2005 12:20 PM, Gooch, John <John.Gooch@echostar.com> wrote:
>  
> I have a class named 'Dir' that I want to be put into another class
> 'DirList' ( essential a linked list of Dir objects ) using the 'insert()'
> method. The syntax is 'DirList.insert( Dir )' which works, but then I try to
> access the 'getSize()' function of the 'Dir' class from *inside* of the
> DirList class, it gives me this -> 
>     'I added a node for dir d:/ with size <bound method Dir.getSize of
> <__main__.Dir instance at 0x00E18CD8>>' 
>   
> Any ideas on what I am doing wrong? 
>   

1) Linked lists are almost always worthless in python. Why not use a
list instead?

2) what's being printed is a function reference - i.e. you're doing:

self.a_dir_instance.getSize

instead of:

self.a_dir_instance.getSize()

which actually calls the function, instead of just returning a pointer to it.

Peace
Bill Mill
bill.mill at gmail.com
From alexis1981 at gmail.com  Tue Apr 12 20:14:29 2005
From: alexis1981 at gmail.com (Alexis)
Date: Tue Apr 12 20:14:36 2005
Subject: [Tutor] Python starting books
Message-ID: <63f959a05041211147d31e373@mail.gmail.com>

Hi, i would like to know if someone could recommend me some books to
get started not only the first book to read but if possible a few to
continue learning also.

thnx in advance
From askoose at sandia.gov  Tue Apr 12 20:25:01 2005
From: askoose at sandia.gov (Kooser, Ara S)
Date: Tue Apr 12 20:25:19 2005
Subject: [Tutor] Python starting books
Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0B06D7@ES21SNLNT.srn.sandia.gov>

I've used http://www.freenetpages.co.uk/hp/alan.gauld/ Alan Gauld's both
for myself and to teach my students.

Ara



"There is something to be learned from a rainstorm. When meeting with a
sudden shower, you try not to get wet and run quickly along the road.
But doing such things as passing under the eaves of houses, you still
get wet. When you are resolved from the beginning, you will not be
perplexed, though you still get the same soaking." - Yamamoto Tsunetomo


-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Alexis
Sent: Tuesday, April 12, 2005 12:14 PM
To: tutor@python.org
Subject: [Tutor] Python starting books


Hi, i would like to know if someone could recommend me some books to get
started not only the first book to read but if possible a few to
continue learning also.

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


From alexis1981 at gmail.com  Tue Apr 12 20:30:38 2005
From: alexis1981 at gmail.com (Alexis)
Date: Tue Apr 12 20:30:42 2005
Subject: [Tutor] Python starting books
In-Reply-To: <A0CE32554BD73A4481FE85C3F39DB6FC0B06D7@ES21SNLNT.srn.sandia.gov>
References: <A0CE32554BD73A4481FE85C3F39DB6FC0B06D7@ES21SNLNT.srn.sandia.gov>
Message-ID: <63f959a050412113067f367ed@mail.gmail.com>

Thnx for the info.

Unfortunately the site is unavailable

Not Found
The requested URL /hp/alan.gauld/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to
use an ErrorDocument to handle the request.

Will try searching for these documents later and tell you if i find anything

Thanks again,
Alexis

On Apr 12, 2005 3:25 PM, Kooser, Ara S <askoose@sandia.gov> wrote:
> I've used http://www.freenetpages.co.uk/hp/alan.gauld/ Alan Gauld's both
> for myself and to teach my students.
> 
> Ara
> 
> "There is something to be learned from a rainstorm. When meeting with a
> sudden shower, you try not to get wet and run quickly along the road.
> But doing such things as passing under the eaves of houses, you still
> get wet. When you are resolved from the beginning, you will not be
> perplexed, though you still get the same soaking." - Yamamoto Tsunetomo
> 
> 
> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
> Behalf Of Alexis
> Sent: Tuesday, April 12, 2005 12:14 PM
> To: tutor@python.org
> Subject: [Tutor] Python starting books
> 
> Hi, i would like to know if someone could recommend me some books to get
> started not only the first book to read but if possible a few to
> continue learning also.
> 
> thnx in advance
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
>
From askoose at sandia.gov  Tue Apr 12 20:34:36 2005
From: askoose at sandia.gov (Kooser, Ara S)
Date: Tue Apr 12 20:34:49 2005
Subject: [Tutor] Python starting books
Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0B06D9@ES21SNLNT.srn.sandia.gov>

You can also check out How to Think Like a Computer Scientist at
http://www.ibiblio.org/obp/thinkCSpy/ .

Alan's page is up I checked it using Firefox.

Ara



"There is something to be learned from a rainstorm. When meeting with a
sudden shower, you try not to get wet and run quickly along the road.
But doing such things as passing under the eaves of houses, you still
get wet. When you are resolved from the beginning, you will not be
perplexed, though you still get the same soaking." - Yamamoto Tsunetomo


-----Original Message-----
From: Alexis [mailto:alexis1981@gmail.com] 
Sent: Tuesday, April 12, 2005 12:31 PM
To: Kooser, Ara S
Cc: tutor@python.org
Subject: Re: [Tutor] Python starting books


Thnx for the info.

Unfortunately the site is unavailable

Not Found
The requested URL /hp/alan.gauld/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use
an ErrorDocument to handle the request.

Will try searching for these documents later and tell you if i find
anything

Thanks again,
Alexis

On Apr 12, 2005 3:25 PM, Kooser, Ara S <askoose@sandia.gov> wrote:
> I've used http://www.freenetpages.co.uk/hp/alan.gauld/ Alan Gauld's 
> both for myself and to teach my students.
> 
> Ara
> 
> "There is something to be learned from a rainstorm. When meeting with 
> a sudden shower, you try not to get wet and run quickly along the 
> road. But doing such things as passing under the eaves of houses, you 
> still get wet. When you are resolved from the beginning, you will not 
> be perplexed, though you still get the same soaking." - Yamamoto 
> Tsunetomo
> 
> 
> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On 
> Behalf Of Alexis
> Sent: Tuesday, April 12, 2005 12:14 PM
> To: tutor@python.org
> Subject: [Tutor] Python starting books
> 
> Hi, i would like to know if someone could recommend me some books to 
> get started not only the first book to read but if possible a few to 
> continue learning also.
> 
> thnx in advance _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
>


From geek_show at dsl.pipex.com  Tue Apr 12 21:10:00 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Tue Apr 12 21:10:07 2005
Subject: [Tutor] Python starting books
In-Reply-To: <63f959a05041211147d31e373@mail.gmail.com>
References: <63f959a05041211147d31e373@mail.gmail.com>
Message-ID: <425C1D08.6080700@dsl.pipex.com>

Alexis wrote:
> Hi, i would like to know if someone could recommend me some books to
> get started not only the first book to read but if possible a few to
> continue learning also.
> 
> thnx in advance
> _______________________________________________

Hi Alexis

Books I found really helpful were/are:

Magnus Lie Hetland's "Practical Python"
Alan Gauld's "Learn to program using Python"
Deitel & Co's "Python: How to program"

along with a number of very help tutorials on the web (check out the 
Python website) and of course, the "Python reference" by Beazley (altho' 
not a good intro unless you are comfortable with programming generally)

HtH
/j
From dyoo at hkn.eecs.berkeley.edu  Tue Apr 12 21:34:20 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 12 21:34:26 2005
Subject: [Tutor] Python starting books
In-Reply-To: <63f959a050412113067f367ed@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504121226190.18086-100000@hkn.eecs.berkeley.edu>



> The requested URL /hp/alan.gauld/ was not found on this server.
>
> Additionally, a 404 Not Found error was encountered while trying to use
> an ErrorDocument to handle the request.

Hi Alexis,

Odd!  It might be that Alan's hosting service is doing something bonkers;
perhaps the service's virtual hosting setup?

Can you try visiting the page again?  Here's the URL:

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

I did a quick Google search: there appears to be an older mirror of the
page here:

    http://www.com-it.net.au/tutorials/learning_to_program/

although I'm not sure how old this mirror is.

If you are still unable to get to Alan's tutorial through the web, I'm
sure someone here would be happy to send an archive of the tutorial and
send it to you through email.


Best of wishes to you!

From magoldfish at gmail.com  Tue Apr 12 22:20:58 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Tue Apr 12 22:21:00 2005
Subject: [Tutor] when to use properties?
Message-ID: <5e183f3d05041213201a2f9868@mail.gmail.com>

Are there guidelines for when properties should be used vs. instance
variables?  For example, it often seems more convenient to directly
use instance variables instead of properties, like MyClass2 listed
below.  Is one class more pythonic than the other?

# Example 1: class w/props vs. no-propt
class MyClass1(object):
  def __init__(self, value=0):
     self._value = value
  def getValue(self):
     return self._value
  def setValue(self, value):
     self._value = value
  value = property(getValue, setValue)

class MyClass2(object):
  def __init__(self, value=0):
     self.value = value

x1 = MyClass1(3)
x1.value = 3

# same as this?
x2 = MyClass2(3)
x2.value = 3

On the other hand, I can see how classes that dynamically generate
"properties" might find the construct convenient:

# Example 2: properties "on-the-fly"
import math
class RightTriangle(object):
  def __init__ (self, a=3, b=4):
     self.a = a
     self.b = b
  def getHypotenuse(self):
     return sqrt(a**2 + b**2)
  hypotenuse = property(getHypotenuse)

t = RightTriangle()
t.hypotenuse         # returns 5.0

But in Example2 it's still not clear to me whether properties buy
anything-- why not just use the getter function?

Marcus
From dyoo at hkn.eecs.berkeley.edu  Tue Apr 12 22:59:56 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 12 22:59:58 2005
Subject: [Tutor] Python starting books (fwd)
Message-ID: <Pine.LNX.4.44.0504121359480.13920-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Tue, 12 Apr 2005 17:16:18 -0300
From: Alexis <alexis1981@gmail.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Python starting books

Hi people thanks to all of you for the suggestions, I am currently
reading some programming books but it seems as if i can't findn a
suitable one to get me started the way i want, i mean not only
learning the basics but getting prepared for more complex programming,
i will try to take a look at these books tonight.

I have never posted in a mailing list and was even hesitant to do so.

Thanks to al of you for being so kind.

Best Regards,
Alexis

On Apr 12, 2005 4:34 PM, Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
>
>
> > The requested URL /hp/alan.gauld/ was not found on this server.
> >
> > Additionally, a 404 Not Found error was encountered while trying to use
> > an ErrorDocument to handle the request.
>
> Hi Alexis,
>
> Odd!  It might be that Alan's hosting service is doing something bonkers;
> perhaps the service's virtual hosting setup?
>
> Can you try visiting the page again?  Here's the URL:
>
>     http://www.freenetpages.co.uk/hp/alan.gauld/
>
> I did a quick Google search: there appears to be an older mirror of the
> page here:
>
>     http://www.com-it.net.au/tutorials/learning_to_program/
>
> although I'm not sure how old this mirror is.
>
> If you are still unable to get to Alan's tutorial through the web, I'm
> sure someone here would be happy to send an archive of the tutorial and
> send it to you through email.
>
> Best of wishes to you!
>
>

From dyoo at hkn.eecs.berkeley.edu  Tue Apr 12 23:22:23 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 12 23:22:27 2005
Subject: [Tutor] when to use properties?
In-Reply-To: <5e183f3d05041213201a2f9868@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504121401090.13920-100000@hkn.eecs.berkeley.edu>



On Tue, 12 Apr 2005, Marcus Goldfish wrote:

> Are there guidelines for when properties should be used vs. instance
> variables?

Hi Marcus,


In Python, it's easy to modify things so that things that look like
instance variable access are automatically shunted off to do programatic
stuff.

In Python, I'd go with the simple instance variable stuff, since it's easy
to go back and turn something into a property when you need it.  Go with
instance variables first.

There was an interesting article by Phillip Eby about what conventions
work and don't work when one makes a jump from Java to Python:

    http://dirtsimple.org/2004/12/python-is-not-java.html



> On the other hand, I can see how classes that dynamically generate
> "properties" might find the construct convenient:
>
> # Example 2: properties "on-the-fly"
> import math
> class RightTriangle(object):
>   def __init__ (self, a=3, b=4):
>      self.a = a
>      self.b = b
>   def getHypotenuse(self):
>      return sqrt(a**2 + b**2)
>   hypotenuse = property(getHypotenuse)
>
> t = RightTriangle()
> t.hypotenuse         # returns 5.0
>
> But in Example2 it's still not clear to me whether properties buy
> anything-- why not just use the getter function?

Here, it's just pure syntactic sugar.  There's nothing functionally
different at all: it's just how it reads.  So, we really aren't getting
anything.  But I wouldn't discount syntax outright:  people read programs
just as much as computers execute them.

in the case when we're defining a setter, we may want the assignment to
stand out syntactically, since mutation is always a bit scary.  *grin*

That is, something like:

    money.amount = 16

stands out more as an mutation --- an assignment --- and has a higher
chance to catch the human reader's eye.  The setter method:

    money.setAmount(16)

might be easier to overlook on a visual scan, since the setter is just
another method call in what could be a page full of method calls.


That being said, I personally haven't used properties in my own code, only
because it confuses my friends who are still used to languages like Java,
where Java doesn't allow one to overload attribute access.  Properties
appear to make Python syntax a little more distinctive.

Best of wishes!

From jfouhy at paradise.net.nz  Wed Apr 13 00:10:34 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Wed Apr 13 00:10:39 2005
Subject: [Tutor] Question about Frames and Scrollbars
In-Reply-To: <BAY106-F180D1AA0B10F958875CB0F89330@phx.gbl>
References: <BAY106-F180D1AA0B10F958875CB0F89330@phx.gbl>
Message-ID: <1113343834.425c475a5c7ca@www.paradise.net.nz>

A couple of options...

You can pack a scrollbar on the right hand side of the containing frame and use
the yscrollcommand option to associate it with the frame --- see Fredrik Lundh's
Tkinter pages for an example.

Or you could grab Python MegaWidgets from http://pmw.sourceforge.com/ and use a
Pmw.ScrolledFrame instead, which will do the scrollbars for you automatically.
(this is my recommended option)

-- 
John.
From kent37 at tds.net  Wed Apr 13 01:33:57 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 13 01:34:02 2005
Subject: [Tutor] Python starting books
In-Reply-To: <63f959a05041211147d31e373@mail.gmail.com>
References: <63f959a05041211147d31e373@mail.gmail.com>
Message-ID: <425C5AE5.2010500@tds.net>

Alexis wrote:
> Hi, i would like to know if someone could recommend me some books to
> get started not only the first book to read but if possible a few to
> continue learning also.

If you have some programming background I recommend "Learning Python". "Python Cookbook" is an 
excellent intermediate-level book to deepen your understanding of Python.

Kent

From jcahl at psci.net  Wed Apr 13 03:05:41 2005
From: jcahl at psci.net (Jim and Laura Ahl)
Date: Wed Apr 13 03:05:54 2005
Subject: [Tutor] Python backwards program
Message-ID: <000601c53fc4$ed4af660$946f31d8@DJM96611>

I am very new to programming and I have an assignment to have a raw_input string that is inputted by the user and then is printed backwards.  Can anyone help me?  I can get it to print regular but backwards in not working.

Thank You
Jim 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050412/0273228a/attachment.htm
From tameyer at ihug.co.nz  Wed Apr 13 03:15:14 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr 13 03:16:24 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E80297B94F@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0084@its-xchg4.massey.ac.nz>

> I am very new to programming and I have an assignment
> to have a raw_input string that is inputted by the user
> and then is printed backwards.  Can anyone help me?  I can
> get it to print regular but backwards in not working.

I guess that I shouldn't give code if this is for an assignment, but if you
are using Python 2.4, then try seeing what the "reversed()" built-in
function does.  If you're not using Python 2.4, then read up about "slices"
- which is when you get subsections of a string (e.g. "tony"[2:4] is "ny").
You can pass a 'direction' in a slice as well.

=Tony.Meyer

From ojokimu at yahoo.co.uk  Wed Apr 13 03:16:57 2005
From: ojokimu at yahoo.co.uk (John Ridley)
Date: Wed Apr 13 03:16:59 2005
Subject: [Tutor] when to use properties?
In-Reply-To: 6667
Message-ID: <20050413011657.13010.qmail@web26805.mail.ukl.yahoo.com>


--- Marcus Goldfish <magoldfish@gmail.com> wrote:
> Are there guidelines for when properties should be used vs. instance
> variables?  For example, it often seems more convenient to directly
> use instance variables instead of properties, like MyClass2 listed
> below.  Is one class more pythonic than the other?

Hello Marcus

One guideline for using properties is to simply ask yourself: do I need
to run other code when getting, setting or deleting this attribute?
Here's a demo of what I mean, based on your first example class:

>>> class MyClass1(object):
...    def __init__(self, value=0):
...       self.__value = value
...    def getValue(self):
...       # log attribute usage
...       print repr(self),': value accessed'
...       return self.__value
...    def setValue(self, value):
...       # validate new values
...       if not isinstance(value, int) or value < 0:
...          raise ValueError, 'positive integer required'
...       self.__value = value
...    def delValue(self):
...       # reset to 0, instead of deleting
...       self.__value = 0
...    value = property(getValue, setValue, delValue)
...
>>> c = MyClass1()
>>> c.value = -1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 11, in setValue
ValueError: positive integer required
>>> c.value = 9
>>> print c.value
<__main__.MyClass1 object at 0x402b6c6c> :value accessed
9
>>> del c.value
>>> v = c.value
<__main__.MyClass1 object at 0x402b6c6c> : value accessed
>>> print v
0
>>>

Note that you could also do all of this by calling the methods
directly. For example, you could set the value to 1 by calling
self.setValue(1) or delete it by calling self.delValue(). The nice
thing about using properties, though, is that everything is accessed
through a single attribute name. So if there are lots of attributes
which need special get/set/del handling, you'll end up with much
cleaner code.

As to which way of doing things is the most pythonic: well, as always,
it depends on what you are trying to achieve - if your code is not
doing what you want it to do, then that is about as unpythonic as it
can get :-)

HTH

John Ridley

Send instant messages to your online friends http://uk.messenger.yahoo.com 
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 04:09:55 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 04:10:06 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0084@its-xchg4.massey.ac.nz>
Message-ID: <Pine.LNX.4.44.0504121907350.601-100000@hkn.eecs.berkeley.edu>



On Wed, 13 Apr 2005, Tony Meyer wrote:

> > I am very new to programming and I have an assignment to have a
> > raw_input string that is inputted by the user and then is printed
> > backwards.  Can anyone help me?  I can get it to print regular but
> > backwards in not working.
>
> I guess that I shouldn't give code if this is for an assignment, but if
> you are using Python 2.4, then try seeing what the "reversed()" built-in
> function does.  If you're not using Python 2.4, then read up about
> "slices" - which is when you get subsections of a string (e.g.
> "tony"[2:4] is "ny"). You can pass a 'direction' in a slice as well.


It might also help to have a better feeling for what Jim already knows.
If this is a school assignment, I doubt that reversed() is allowed, nor
reverse slices, since that would make the problem too easy.  *cough*

Jim, can you give a brief description of what things you've learned
already?  Do you already know about loops?

From leec03273 at mac.com  Wed Apr 13 06:03:19 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Wed Apr 13 06:03:24 2005
Subject: [Tutor] Re: GUI module selection? 
In-Reply-To: <5c6ab478aba34c763a2a6906724bfa59@mac.com>
References: <7b64106f164cbe3aa3d747d9520b9649@redivi.com>
	<ba486524bb882b9bb4c0a4dfa292b067@conncoll.edu>
	<2f4f83fe12fb301cac600685df80421b@redivi.com>
	<5c6ab478aba34c763a2a6906724bfa59@mac.com>
Message-ID: <d7c8bb99c6a11868510629c5fb3aaf56@mac.com>

I'm trying to narrow down the detailed trials I need to go through in 
selecting basic GUI module approaches (just getting started in this 
Python "playground" - dev platform Mac OS X).

Maybe these old eyes are just missing it, but I can't seem to satisfy 
my curiosity on the following:

1)  Use of GTK+, PyGTK and Gazpacho with Python 2.4 in general

2)  GTK+, PyGTK and Gazpacho binaries for Mac OS X in general and more 
specifically for MacPython 2.4.1

3)  wxPython vs GTK+ (vs Tkinter?) as a starting point for developing 
multimedia apps (for building sophisticated multimedia presentations) 
potentially for cross platform (and pyObjC for Mac only)  -  
opinions/pointers anyone or maybe *another* better course?

Thanks,
Lee C


		

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 06:46:39 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 06:46:42 2005
Subject: [Tutor] Python backwards program (fwd)
Message-ID: <Pine.LNX.4.44.0504122146350.26088-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Tue, 12 Apr 2005 22:37:44 -0500
From: Jim and Laura Ahl <jcahl@psci.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Python backwards program

I have read about loops, strings, tuples.  I am taking this class on distance education and I am lost with this assignment.  I have read what Tony has wrote and that does me no good.  I do not understand what he is talking about.  I understand how slicing works and what the numbers mean.  I know what the -1 and such like that mean.  I know what the len function does.  I am wasting you guys time.

Thanks
Jim
  ----- Original Message -----
  From: Danny Yoo
  To: Tony Meyer
  Cc: 'Jim and Laura Ahl' ; tutor@python.org
  Sent: Tuesday, April 12, 2005 9:09 PM
  Subject: RE: [Tutor] Python backwards program




  On Wed, 13 Apr 2005, Tony Meyer wrote:

  > > I am very new to programming and I have an assignment to have a
  > > raw_input string that is inputted by the user and then is printed
  > > backwards.  Can anyone help me?  I can get it to print regular but
  > > backwards in not working.
  >
  > I guess that I shouldn't give code if this is for an assignment, but if
  > you are using Python 2.4, then try seeing what the "reversed()" built-in
  > function does.  If you're not using Python 2.4, then read up about
  > "slices" - which is when you get subsections of a string (e.g.
  > "tony"[2:4] is "ny"). You can pass a 'direction' in a slice as well.


  It might also help to have a better feeling for what Jim already knows.
  If this is a school assignment, I doubt that reversed() is allowed, nor
  reverse slices, since that would make the problem too easy.  *cough*

  Jim, can you give a brief description of what things you've learned
  already?  Do you already know about loops?


From shaleh at speakeasy.net  Wed Apr 13 06:49:01 2005
From: shaleh at speakeasy.net (Sean Perry)
Date: Wed Apr 13 06:51:48 2005
Subject: [Tutor] sorting a list of dictionaries
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>
Message-ID: <425CA4BD.1090807@speakeasy.net>

Gooch, John wrote:
> I am working on a dictionary sorting problem just like the one in the email
> thread at the bottom of this message. My question about their solution is:
> In these lines:
> 	lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
> 	where field is either 'name' or 'size'.
> 
> What is "n:" and what is "lambda m" ? 
> 

#!/usr/bin/python 


lst = [{"foo": 6, "bar": 10}, {"foo": 1, "bar": 2}]
field = "foo"

sort_func = lambda m, n: cmp(m.get(field), n.get(field))

lst.sort(sort_func)

print sort_func(lst[0], lst[1])
print lst

lambda creates a nameless function.
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 07:02:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 07:02:18 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <Pine.LNX.4.44.0504122146350.26088-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504122150490.26088-100000@hkn.eecs.berkeley.edu>


Hello Jim,


> I have read about loops, strings, tuples.

Can you show us an example of a loop?  Can you show us the last program
that you've written?

It sounds like you've done a lot of reading.  The problem with learning
how to program is that you can't just read it: you actually have to write
programs and watch them run.  I think you need to make that book knowledge
into something concrete.

For example, If we give you some string, like:

######
s = "hello world"
######

can you get Python to say:

######
hheelllloo  wwoorrlldd
######

That is, can you write a program that will print out each letter in 's',
but doubled up?



> I am wasting you guys time.

I do not know that.  We will not do your homework for you, so if you're
just expecting a direct homework solution, we will not help you, and you
will be wasting our time.

But if you're really interested in learning, start asking questions, and
start playing with the interpreter.  If there is something you do not
understand yet, we'll do what we can to help you find good answers, and
we'll try to point you toward resources that can help.

And we'll try to be your cheering squad, if you need one.


Best of wishes to you.

From leec03273 at mac.com  Wed Apr 13 07:13:33 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Wed Apr 13 07:13:40 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <Pine.LNX.4.44.0504122146350.26088-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504122146350.26088-100000@hkn.eecs.berkeley.edu>
Message-ID: <31abd51aeaa42e886953c013c02239b8@mac.com>

for the slicing see: http://docs.python.org/lib/typesseq.html

for a longhand loop approach see: 
http://docs.python.org/tut/node6.html#SECTION006200000000000000000



On Apr 13, 2005, at 12:46 AM, Danny Yoo wrote:

>
>
> ---------- Forwarded message ----------
> Date: Tue, 12 Apr 2005 22:37:44 -0500
> From: Jim and Laura Ahl <jcahl@psci.net>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] Python backwards program
>
> I have read about loops, strings, tuples.  I am taking this class on 
> distance education and I am lost with this assignment.  I have read 
> what Tony has wrote and that does me no good.  I do not understand 
> what he is talking about.  I understand how slicing works and what the 
> numbers mean.  I know what the -1 and such like that mean.  I know 
> what the len function does.  I am wasting you guys time.
>
> Thanks
> Jim
>   ----- Original Message -----
>   From: Danny Yoo
>   To: Tony Meyer
>   Cc: 'Jim and Laura Ahl' ; tutor@python.org
>   Sent: Tuesday, April 12, 2005 9:09 PM
>   Subject: RE: [Tutor] Python backwards program
>
>
>
>
>   On Wed, 13 Apr 2005, Tony Meyer wrote:
>
>>> I am very new to programming and I have an assignment to have a
>>> raw_input string that is inputted by the user and then is printed
>>> backwards.  Can anyone help me?  I can get it to print regular but
>>> backwards in not working.
>>
>> I guess that I shouldn't give code if this is for an assignment, but 
>> if
>> you are using Python 2.4, then try seeing what the "reversed()" 
>> built-in
>> function does.  If you're not using Python 2.4, then read up about
>> "slices" - which is when you get subsections of a string (e.g.
>> "tony"[2:4] is "ny"). You can pass a 'direction' in a slice as well.
>
>
>   It might also help to have a better feeling for what Jim already 
> knows.
>   If this is a school assignment, I doubt that reversed() is allowed, 
> nor
>   reverse slices, since that would make the problem too easy.  *cough*
>
>   Jim, can you give a brief description of what things you've learned
>   already?  Do you already know about loops?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From tameyer at ihug.co.nz  Wed Apr 13 07:10:39 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr 13 07:17:10 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E80297BA01@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB008F@its-xchg4.massey.ac.nz>

> I have read about loops, strings, tuples.  I am taking this 
> class on distance education and I am lost with this 
> assignment.  I have read what Tony has wrote and that does me 
> no good.  I do not understand what he is talking about.

Which bits?  The whole lot?  I teach university students programming, so
maybe the language doesn't fit with you.  Whatever it is, just say what
doesn't make sense and I'll happily rephrase it, or expand, or whatever is
needed.

> I understand how slicing works and what the numbers mean.  I 
> know what the -1 and such like that mean.  I know what the 
> len function does. 

Why then do you not understand that the answer is simply this?

"""
my_string = raw_input("Prompt:")
print my_string[::-1]
"""

(I'm not trying to be offensive; I would like to know why you don't
understand that, if you understand how slicing works).

As Danny said, if you can't simply use slicing (it is pretty simple), then
you're probably after a loop.  You want to run through the string, but with
a negative step.  The most explicit way to do this is to have an index
variable that keeps track of where you are up to in the string.  Normally
this would go from 0 to the length of the string, but you want it to go
backwards, so from the length of the string to 0.  Each time around the
loop, you want the index to go down one.

So:

start index at length of string
while index has not reached 0:
    print character at string[index]
    decrease index by one

Do you see what that is doing?  It translates very simply into Python (one
of the advantages of the language):

index = len(my_string)
while index >= 0:
    print my_string[index]
    index = index -1

This will of course print out the string one character per line, which isn't
what you want.  But that's easy enough to change.

There are other ways of doing this, but I suspect something like the above
is what you are after in a beginning course.  You could, for example, build
a new (reversed) string, rather than printing it out as you go, and then
print that out.

In C, it would look something like this:

"""
for (unsigned int i=<strlen(my_string); i>=0; ++i)
{
    printf("%c", my_string[i]);
}
"""

Which is a fairly common sort of exercise when you're learning C, since C
doesn't have the nice slicing capabilities that Python does.

> I am wasting you guys time.

Not at all.  We come here to try and help.

=Tony.Meyer

From tameyer at ihug.co.nz  Wed Apr 13 07:13:26 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Wed Apr 13 07:18:52 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E80297BA14@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0090@its-xchg4.massey.ac.nz>

> We will not do your homework for you
[snip]

The slicing answer I posted is possibly the answer, but I assume that the
loop solution, which I didn't post (in Python), is what is actually
required.  If slicing is what is wanted, then I apologise for giving an
answer! :)

=Tony.Meyer

From sean.fioritto at gmail.com  Mon Apr 11 21:16:30 2005
From: sean.fioritto at gmail.com (Sean Fioritto)
Date: Wed Apr 13 08:06:40 2005
Subject: [Tutor] Cell Bio Newbie Here
In-Reply-To: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
References: <6.2.1.2.0.20050411144951.020fb5e8@pop.ece.neu.edu>
Message-ID: <5f1d9b0c05041112164c507eab@mail.gmail.com>

The reason you are looping forever is because you are not resetting
current_count to zero.

Let's step through your logic, assume that current_count = 2 
- you enter into the if part of your logic
- prompt the user for a password
- user enters a password, let's assume it's not unicorn, and you store
that in password
- current_count is incremented by one so it's now 3

- go to the top of the while loop, password is not equal to unicorn
- current count is = to 3, so we enter the else
- print "That must have been complicated"

Go to the top of the while loop
our password was never changed so we enter the while loop
current_count was never changed(it is still 3), so we go into the else statement
print print "That must have been complicated"

go to the top of the while loop
...and you see that we're stuck.

underneat this line, and within the else you need to add a line to
reset current_count

It will look like this:
else:
   print "That must have been complicated"
   curent_count = 0

So now when current_count == 3
go to the top of the while loop
password is wrong so go into the loop
current_count is not less than count so go into the else statement
print "That must have been complicated"
current_count is now 0

- go to the top of the while loop
- you enter into the if part of your logic because current_count is
less than count
- prompt the user for a password
- user enters a password, let's assume it's not unicorn, and you store
that in password
- and so on...

I'm pretty sure that fixes it. Good luck!

- Sean



On Apr 11, 2005 11:54 AM, glaevsky@ece.neu.edu <glaevsky@ece.neu.edu> wrote:
> Hey all,
> 
> Sorry for the bother, thanks for the help.
> 
> I'm trying to write a password guessing program to keep track of
> how many times the user has entered the password wrong.
> If it is more than 3 times, print ``That must have been complicated.''
> 
> Following is what I got.  If I type "unicorn" it goes straight to "welcome
> in." Great.  But after my third mistake, it just loops in "That must have
> been complicated."
> 
> I'd like for someone to tell me "why" i screwed up.  Not to just fix it.
> 
> Thank you so much in advance.  And to give you a little smile for a Monday,
> I've been working on this for days....argh
> 
> #first of all, why does this have to be here?
> password="foobar"
> 
> count=3
> current_count=0
> 
> while password !="unicorn":
>      if current_count<count:
>          password=raw_input("Password:")
>          current_count=current_count+1
>      else:
>          print "That must have been complicated"
> 
> print "Welcome in"
> Best,
> 
> Gary
> 
> Gary Laevsky, Ph.D.
> Keck Facility Manager, CenSSIS
> Northeastern University
> 302 Stearns
> 360 Huntington Ave.
> Boston, MA 02115
> voice(617) 373 - 2589<br>
> fax(617) 373 - 7783<br><br>
> 
> http://www.censsis.neu.edu
> 
> http://www.ece.neu.edu/groups/osl
> 
> http://www.keck3dfm.neu.edu
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From project5 at redrival.net  Wed Apr 13 08:13:39 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 08:17:19 2005
Subject: [Tutor] Re: sorting a list of dictionaries
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>
Message-ID: <loom.20050413T080640-216@post.gmane.org>

Gooch, John <John.Gooch <at> echostar.com> writes:

> 	lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
> 	where field is either 'name' or 'size'.
> What is "n:" and what is "lambda m" ? 

You could rewrite that in a more readable manner as follows:


def comparedict(dict1, dict2):
    "Compares the values of a certain key in the two dictionaries."
    item1 = dict1[field]
    item2 = dict2[field]
    return cmp(item1, item2)

lst.sort(comparedict)


m and n then correspond to dict1/dict2 (function arguments), lambda is in this
context just a different way of defining a function. The net result is a
comparison function which is called by the sort() method in order to determine
which of two dictionaries is 'smaller' or 'larger'.

Yours,

Andrei


From project5 at redrival.net  Wed Apr 13 08:27:57 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 08:31:31 2005
Subject: [Tutor] Re: Python starting books (fwd)
References: <Pine.LNX.4.44.0504121359480.13920-100000@hkn.eecs.berkeley.edu>
Message-ID: <loom.20050413T081542-836@post.gmane.org>

> From: Alexis <alexis1981 <at> gmail.com>
> Hi people thanks to all of you for the suggestions, I am currently
> reading some programming books but it seems as if i can't findn a
> suitable one to get me started the way i want, i mean not only
> learning the basics but getting prepared for more complex programming,

I would say that learning the basics *is* getting prepared for more complex
programming. Typically you start with defining variables, doing simple
calculations, getting user input, get to know some modules in the standard
library, etc. Then you go on to classes (this is often a difficult topic). What
you do from there depends on your needs. You might want to dive in GUI
programming, web applications, scientific stuff, games, etc. and read up on that
particular topic.

The "How to Think Like a Computer Scientist" tutorial has some implementations
of common (but not necessarily useful to you) algorithms - e.g. trees - which
other books don't offer. You can also read those chapters on their own if you're
interested, but prefer to follow a different tutorial instead. In fact, you can
read texts about topics like that even if they're not Python-specific: if they
convey their ideas clearly, you can implement such things on your own.

Yours,

Andrei

From project5 at redrival.net  Wed Apr 13 08:40:49 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 08:45:13 2005
Subject: [Tutor] Re: when to use properties?
References: <5e183f3d05041213201a2f9868@mail.gmail.com>
Message-ID: <loom.20050413T082945-330@post.gmane.org>

Marcus Goldfish <magoldfish <at> gmail.com> writes:

> Are there guidelines for when properties should be used vs. instance
> variables?  For example, it often seems more convenient to directly
> use instance variables instead of properties, like MyClass2 listed
> below.  Is one class more pythonic than the other?

In Python I tend to use methods directly, even though I think properties are
clearer and I actively avoid calling getters/setters directly in Delphi. I just
can't be bothered to write the extra line for some reason :). 

On the other hand, I never write getters/setters just for the sake of it. In
your example I would not have a self._value, but a self.value which is accessed
directly, since the getter and setter don't do anything special anyway. Now, if
I had such code and needed to add some processing before accessing the variable,
I might change it into a property and add the appropriate methods, so that the
interface remains the same.

Yours,

Andrei


From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 09:15:32 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 09:15:36 2005
Subject: [Tutor] Re: Python starting books (fwd)
In-Reply-To: <loom.20050413T081542-836@post.gmane.org>
Message-ID: <Pine.LNX.4.44.0504130007340.9965-100000@hkn.eecs.berkeley.edu>


> > Hi people thanks to all of you for the suggestions, I am currently
> > reading some programming books but it seems as if i can't findn a
> > suitable one to get me started the way i want, i mean not only
> > learning the basics but getting prepared for more complex programming,
>
> I would say that learning the basics *is* getting prepared for more
> complex programming.


[some text cut]

One of the better books I've seen that talks about advanced topics is Mark
Pilgrim's "Dive into Python" book:

    http://diveintopython.org/

But I agree with Andrei: getting the basics down will pay dividends.
Especially how to use functions effectively.  I wouldn't worry about
hitting complex Python programming too quickly: you can get a lot of
millage out of simple techniques.

And these techniques don't even have to be particularly tied to Python.
One of the other best books I've read about programming is Code Complete:

    http://www.cc2e.com/

and the book makes the effort to show that there are fundamentals of good
programming that transcend a particular language.

Code Complete is the kind of book I'd recommend to a person who has had
about a year of programming experience, since a lot of what he says makes
a heck of a lot of sense after one has written a few coding blunders under
their belt.  *grin*


Best of wishes to you!

From project5 at redrival.net  Wed Apr 13 09:25:47 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 09:29:39 2005
Subject: [Tutor] Re: New to programming question
References: <b930511705041209564b3f9255@mail.gmail.com>
Message-ID: <loom.20050413T085752-437@post.gmane.org>

Ben Markwell <benmarkwell <at> gmail.com> writes:

<snip>
> if prefixes[n] == 'O' or 'Q':

A tip: when working with several boolean (and/or/not) conditions in one test,
it's helpful to use parentheses in order to make sure you get what you expect.
Let me demonstrate.

The example above is equivalent to:

  if (prefixes[n] == 'O') or ('Q')  [1]

but you probably meant to write:

  if prefixes[n] == ('O' or 'Q')    [2]


With the parentheses it's easier to follow what is going on. In case [1], first
prefixes[n] == 'O' is evaluated (which might or might not return a True). Then
('Q') is evaluated (which is True in a boolean context), which means that the
expression is sort of equivalent to:
 
  if (either True or False) or (True)

which is obviously always True.


Case [2] can be regarded in a similar manner. First ('O' or 'Q') is evaluated.
Let's see what this means. Both 'O' and 'Q' are True in a boolean context, but
what is the *result* of ('O' or 'Q')? After all, the result of this operation is
what you compare with prefixes[n]. You probably don't know the answer to this
question and that should trigger some alarm bells: it's never a good sign if you
don't understand your own code :).
Fortunately we have the Python interpreter available:

>>> ('O' or 'Q')
'O'

Aha! Well, this means that approach [2] is the same as:

  if prefixes[n] == 'O'

This is obviously not what you wanted to achieve.

Actually, I've jumped a bit too fast to a conclusion here, by assuming that ('O'
or 'Q') always returns 'O', just because that's what happened in my 1 test on 1
machine on 1 version of Python. This is a dangerous assumption: perhaps
elsewhere it could return 'Q' or True or 1 (all of these are equivalent in a
boolean expression)? 
In this case it turns out that it is correct (you can read the docs to find out
about how it works, or play around in the interpreter to get a feeling for it),
but be careful with such assumptions, they can bite you. For example let's thest
the assumption that a dictionary remembers the order the keys are entered in:

>>> d = {4:0, 5:0, 6:0}
>>> d.keys()
[4, 5, 6]

Look, it does! However, a different test reveals this:

>>> d = {4:0, 5:0, 1:0}
>>> d.keys()
[1, 4, 5]

Aha! So it sorts the keys (both tests support this conclusion). Or does it?

>>> d = {4:0, -1:0, 5:0}
>>> d.keys()
[4, 5, -1]

Nope, not sorted, not ordered - exactly as the Python specification states,
dictionaries are unordered.

Yours,

Andrei

From cyresse at gmail.com  Wed Apr 13 10:31:18 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Wed Apr 13 10:31:21 2005
Subject: [Tutor] Re: GUI module selection?
In-Reply-To: <d7c8bb99c6a11868510629c5fb3aaf56@mac.com>
References: <7b64106f164cbe3aa3d747d9520b9649@redivi.com>
	<ba486524bb882b9bb4c0a4dfa292b067@conncoll.edu>
	<2f4f83fe12fb301cac600685df80421b@redivi.com>
	<5c6ab478aba34c763a2a6906724bfa59@mac.com>
	<d7c8bb99c6a11868510629c5fb3aaf56@mac.com>
Message-ID: <f2ff2d0504130131201d849@mail.gmail.com>

Hi Lee, 

I work with wxPython and some assorted wrappers.

Personally, I always found Tkinter a little... unsatisfying. You can do 
perfectly good GUIs in it, as long as they don't get too complex, but yeah, 
never appealed to me.

wxPython is a lot more powerful than Tkinter, but with power comes 
complexity. 
It has several wrappers and graphics designers, most free, some not.

I use Pythoncard, a wrapper which simplifies GUI design dramatically; for 
anything overly complex, you can still drop to wxPython, but otherwise 
PythonCard hides all the fiddly bits quite nicely.
PythonCard is inspired by HyperCard, which makes me nostalgic for when I was 
13.

wxDesigner is a commercial toolkit based on the wx library. 

PythonCard http://pythoncard.sourceforge.net/
wxDesigner http://wiki.wxpython.org/index.cgi/wxDesigner

I can't honestly comment on the GTK+ versus wxPython, nor on the 
cross-platform capability of GTK+, 
but I can say that for all intents wxPython is cross-platform, quite easily.

Regards, 

Liam Clarke

On 4/13/05, Lee Cullens <leec03273@mac.com> wrote:
> 
> I'm trying to narrow down the detailed trials I need to go through in
> selecting basic GUI module approaches (just getting started in this
> Python "playground" - dev platform Mac OS X).
> 
> Maybe these old eyes are just missing it, but I can't seem to satisfy
> my curiosity on the following:
> 
> 1) Use of GTK+, PyGTK and Gazpacho with Python 2.4 in general
> 
> 2) GTK+, PyGTK and Gazpacho binaries for Mac OS X in general and more
> specifically for MacPython 2.4.1
> 
> 3) wxPython vs GTK+ (vs Tkinter?) as a starting point for developing
> multimedia apps (for building sophisticated multimedia presentations)
> potentially for cross platform (and pyObjC for Mac only) -
> opinions/pointers anyone or maybe *another* better course?
> 
> Thanks,
> Lee C
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/cfc778e5/attachment.html
From kent37 at tds.net  Wed Apr 13 11:52:20 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 13 11:52:25 2005
Subject: [Tutor] sorting a list of dictionaries
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0DE5D0BF@riv-excha5.echostar.com>
Message-ID: <425CEBD4.9080502@tds.net>

> -----Original Message-----
> From: sigurd@12move.de [mailto:sigurd@12move.de] 
> Sent: Thursday, December 09, 2004 12:19 PM
> To: tutor@python.org
> Subject: Re: [Tutor] sorting a list of dictionaries
> 
> 
> On  9 Dez 2004, ljholish@speakeasy.net wrote:
> 
> 
>>I have a list of dictionaries, each representing info about a file, 
>>something like:
>>
>>[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
>>
>>I want to present a sorted list of all the files' data, sorting on the 
>>keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) 
>>across all the dictionaries. Can someone point me towards an efficient 
>>solution for accomplishing the sort? (The list has 1000s of files).
> 
> 
> That's easy to achieve, since sort takes a custom sort function as optional
> argument.  Now you need only a function which takes the values of the fileds
> and compares them.
> 
> E.g.
> 
> lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
> where field is either 'name' or 'size'.

In Python 2.4 a more efficient way of doing this is to use the key parameter to sort() with an 
itemgetter function:

from operator import itemgetter
lst.sort(key=itemgetter('field'))

Kent

From albertito_g at hotmail.com  Wed Apr 13 14:51:26 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 14:51:29 2005
Subject: [Tutor] Question about Frames and Scrollbars
In-Reply-To: <1113343834.425c475a5c7ca@www.paradise.net.nz>
Message-ID: <BAY106-F39A531559B74ED3ACE4CC089340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/35136afd/attachment.htm
From slgeorge at gmail.com  Wed Apr 13 15:04:15 2005
From: slgeorge at gmail.com (Steve George)
Date: Wed Apr 13 15:04:26 2005
Subject: [Tutor] Re: GUI module selection?
In-Reply-To: <d7c8bb99c6a11868510629c5fb3aaf56@mac.com>
References: <7b64106f164cbe3aa3d747d9520b9649@redivi.com>
	<ba486524bb882b9bb4c0a4dfa292b067@conncoll.edu>
	<2f4f83fe12fb301cac600685df80421b@redivi.com>
	<5c6ab478aba34c763a2a6906724bfa59@mac.com>
	<d7c8bb99c6a11868510629c5fb3aaf56@mac.com>
Message-ID: <3fe17b6905041306043df3b4ee@mail.gmail.com>

Hi Lee,

You can currently use Pygtk on OSX as long as you use the Apple X
server.  The easiest way is through fink which has 2.4:

http://fink.sourceforge.net/pdb/search.php?summary=pygtk

There are efforts underway to port GTK+ to OSX natively by Hubert
Figui?re, but he's only just started:

http://www.figuiere.net/hub/blog/

The best way to learn about Pygtk is through the list:

http://www.daa.com.au/mailman/listinfo/pygtk

or http://www.pygtk.org

If your application is going to be mostly used from Linux then pygtk
is a good choice as it's bundled in with the majority of
distributions.  If it's cross-platform then WX is probably better as
they've focused on this area.  If it's Mac OSX then PyObj seems the
way to go.

Cheers,

Steve

On 4/13/05, Lee Cullens <leec03273@mac.com> wrote:
> I'm trying to narrow down the detailed trials I need to go through in
> selecting basic GUI module approaches (just getting started in this
> Python "playground" - dev platform Mac OS X).
> 
> Maybe these old eyes are just missing it, but I can't seem to satisfy
> my curiosity on the following:
> 
> 1)  Use of GTK+, PyGTK and Gazpacho with Python 2.4 in general
> 
> 2)  GTK+, PyGTK and Gazpacho binaries for Mac OS X in general and more
> specifically for MacPython 2.4.1
> 
> 3)  wxPython vs GTK+ (vs Tkinter?) as a starting point for developing
> multimedia apps (for building sophisticated multimedia presentations)
> potentially for cross platform (and pyObjC for Mac only)  -
> opinions/pointers anyone or maybe *another* better course?
> 
> Thanks,
> Lee C
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From albertito_g at hotmail.com  Wed Apr 13 15:04:29 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 15:04:33 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <000601c53fc4$ed4af660$946f31d8@DJM96611>
Message-ID: <BAY106-F36220B9B0E1C0E418DCA7789340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/9061fa3c/attachment.html
From feziwe at sanbi.ac.za  Wed Apr 13 17:14:46 2005
From: feziwe at sanbi.ac.za (Feziwe Mpondo)
Date: Wed Apr 13 15:08:01 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <BAY106-F36220B9B0E1C0E418DCA7789340@phx.gbl>
References: <BAY106-F36220B9B0E1C0E418DCA7789340@phx.gbl>
Message-ID: <425D3766.6060501@sanbi.ac.za>

Alberto Troiano wrote:

> You can do this:
>
> >>> word=raw_input("Type the word: ")
> Type the word: Kokiri Forest
> >>> print word
> Kokiri Forest
> >>> print word[::-1]
> tseroF irikoK
>
> But I saw that this gave you a hard time so this is an alternate 
> longer way:
>
> >>> backword=""
> >>> counter=len(word)
>
> >>> while counter!=0:
>              backword+=word[counter-1]
>              counter-=1
>
> >>> print backword
> tseroF irikoK
>
> So choose the one you want and feel free to ask in case of any doubt
>
> Regards
>
> Alberto
>
>
>  Gaucho
> >From: "Jim and Laura Ahl" <jcahl@psci.net> >To: <tutor@python.org> 
> >Subject: [Tutor] Python backwards program >Date: Tue, 12 Apr 2005 
> 20:05:41 -0500 > >I am very new to programming and I have an 
> assignment to have a raw_input string that is inputted by the user and 
> then is printed backwards. Can anyone help me? I can get it to print 
> regular but backwards in not working. > >Thank You >Jim 
> >_______________________________________________ >Tutor maillist - 
> Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
i am able to type, what i can't seem to do is seeing it print or 
executing the command on the shell window
From albertito_g at hotmail.com  Wed Apr 13 15:21:04 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 15:21:07 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <425D3766.6060501@sanbi.ac.za>
Message-ID: <BAY106-F361457018FBFB964B7428B89340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/014598b0/attachment.htm
From albertito_g at hotmail.com  Wed Apr 13 15:30:26 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 15:30:31 2005
Subject: [Tutor] Multithreading and Daemon Program
Message-ID: <BAY106-F12670BDB098BA9E523F23C89340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/f2ac5351/attachment.html
From ryan at acceleration.net  Wed Apr 13 15:35:13 2005
From: ryan at acceleration.net (Ryan Davis)
Date: Wed Apr 13 15:35:19 2005
Subject: [Tutor] Re: when to use properties?
In-Reply-To: <loom.20050413T082945-330@post.gmane.org>
Message-ID: <20050413133517.EDDCF1E4002@bag.python.org>

I agree with Andrei:

Use an instance variable until you need it to do something special, and then convert it to a property.


Thanks,
Ryan 
-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Andrei
Sent: Wednesday, April 13, 2005 2:41 AM
To: tutor@python.org
Subject: [Tutor] Re: when to use properties?

Marcus Goldfish <magoldfish <at> gmail.com> writes:

> Are there guidelines for when properties should be used vs. instance
> variables?  For example, it often seems more convenient to directly
> use instance variables instead of properties, like MyClass2 listed
> below.  Is one class more pythonic than the other?

In Python I tend to use methods directly, even though I think properties are
clearer and I actively avoid calling getters/setters directly in Delphi. I just
can't be bothered to write the extra line for some reason :). 

On the other hand, I never write getters/setters just for the sake of it. In
your example I would not have a self._value, but a self.value which is accessed
directly, since the getter and setter don't do anything special anyway. Now, if
I had such code and needed to add some processing before accessing the variable,
I might change it into a property and add the appropriate methods, so that the
interface remains the same.

Yours,

Andrei


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

From pierre.barbier at cirad.fr  Wed Apr 13 15:51:19 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Wed Apr 13 15:50:31 2005
Subject: [Tutor] Multithreading and Daemon Program
In-Reply-To: <BAY106-F12670BDB098BA9E523F23C89340@phx.gbl>
References: <BAY106-F12670BDB098BA9E523F23C89340@phx.gbl>
Message-ID: <425D23D7.3070406@cirad.fr>

Ok, the first question is an OS related question. What OS do you use ?

For the second, this kind of deamon are usually done using processes 
rather than threads. This is a lot safer and easier to achieve. I 
suppose you know how to start a new process. On UNIX, the simplest way 
to achieve what you want is simply to call os.fork() : all open sockets 
are available on the child process and you can continue safely the 
communication with your client.

Pierre

Alberto Troiano a ?crit :
> Hey
> Back again I'm need to make a daemon application and to manage multithreading
> The program has to check every 3 seconds if is there images inside one folder
> (That's only for you to know what I'm doing in case you needed)
> My first problem is that I can imagine a way to do a daemon.How can I make it 
> start with the OS???and How can I bind it to the task bar(where Messenger is)????
>  
> The second problem is that I have to start a thread for each user that connects 
> to the app, but I don't understand how to use this. I've read the multithread's 
> archives but I can't crack them.
> Suppose I have this function:
> def foo():
>     print hello*30
>  
> def foo2():
>     print bye*30
>  
> How can I make this functions to run simoultaneosly using threads?????
> That'll help understand
>  
> Thanks in advanced
>  
> Alberto
>  
>  
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From jcahl at psci.net  Wed Apr 13 15:51:25 2005
From: jcahl at psci.net (Jim and Laura Ahl)
Date: Wed Apr 13 15:51:40 2005
Subject: [Tutor] Python backwards program
References: <BAY106-F36220B9B0E1C0E418DCA7789340@phx.gbl>
	<425D3766.6060501@sanbi.ac.za>
Message-ID: <002001c5402f$e63f0ee0$846931d8@DJM96611>

Thanks for the encouragement, here is what I have so far.

word=raw_input("Enter a Word or string:")
print word
print word[::-1]
raw_input("\n\nPress the enter key to exit.")

In the print word [::-1] line it gives me this message (sequence index must be an integer)  What does that mean

I have wrote 3 other programs in the class.

A famous quote program where the user inputs their favorite quote, and author and it prints it out.

Two number program the user inputs two numbers and the program adds them together, subtracts, multiply, divide, and hexed.

A fortune cookie program that randomly gives one fortune out of 5 to the user.

Jim
  ----- Original Message ----- 
  From: Feziwe Mpondo 
  To: Alberto Troiano 
  Cc: jcahl@psci.net ; tutor@python.org 
  Sent: Wednesday, April 13, 2005 10:14 AM
  Subject: Re: [Tutor] Python backwards program


  Alberto Troiano wrote:

  > You can do this:
  >
  > >>> word=raw_input("Type the word: ")
  > Type the word: Kokiri Forest
  > >>> print word
  > Kokiri Forest
  > >>> print word[::-1]
  > tseroF irikoK
  >
  > But I saw that this gave you a hard time so this is an alternate 
  > longer way:
  >
  > >>> backword=""
  > >>> counter=len(word)
  >
  > >>> while counter!=0:
  >              backword+=word[counter-1]
  >              counter-=1
  >
  > >>> print backword
  > tseroF irikoK
  >
  > So choose the one you want and feel free to ask in case of any doubt
  >
  > Regards
  >
  > Alberto
  >
  >
  >  Gaucho
  > >From: "Jim and Laura Ahl" <jcahl@psci.net> >To: <tutor@python.org> 
  > >Subject: [Tutor] Python backwards program >Date: Tue, 12 Apr 2005 
  > 20:05:41 -0500 > >I am very new to programming and I have an 
  > assignment to have a raw_input string that is inputted by the user and 
  > then is printed backwards. Can anyone help me? I can get it to print 
  > regular but backwards in not working. > >Thank You >Jim 
  > >_______________________________________________ >Tutor maillist - 
  > Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor
  >
  >------------------------------------------------------------------------
  >
  >_______________________________________________
  >Tutor maillist  -  Tutor@python.org
  >http://mail.python.org/mailman/listinfo/tutor
  >  
  >
  i am able to type, what i can't seem to do is seeing it print or 
  executing the command on the shell window

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/2a88e84a/attachment.html
From kent37 at tds.net  Wed Apr 13 16:14:01 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 13 16:14:03 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <002001c5402f$e63f0ee0$846931d8@DJM96611>
References: <BAY106-F36220B9B0E1C0E418DCA7789340@phx.gbl>	<425D3766.6060501@sanbi.ac.za>
	<002001c5402f$e63f0ee0$846931d8@DJM96611>
Message-ID: <425D2929.80900@tds.net>

Jim and Laura Ahl wrote:
> Thanks for the encouragement, here is what I have so far.
>  
> word=raw_input("Enter a Word or string:")
> print word
> print word[::-1]
> raw_input("\n\nPress the enter key to exit.")
>  
> In the print word [::-1] line it gives me this message (sequence index 
> must be an integer)  What does that mean

What version of Python are you using? "Extended slices" like print word[::-1] have only been 
supported since Python 2.3.

Kent

From ARobert at MFS.com  Wed Apr 13 16:54:45 2005
From: ARobert at MFS.com (Robert, Andrew)
Date: Wed Apr 13 16:54:55 2005
Subject: [Tutor] Odd problem with variable substitution and command execution
Message-ID: <968452DD78695147AA4A369C3DF9E40A039506C4@BOSMAILBOX3.corp.mfs.com>

Hi Everyone,

I am trying to do an MQ inquiry but I am having mixed results.

If I do the command direct via a print statement like the one below, it
works,


print 'Queue Description:\t' , q.inquire(CMQC.MQCA_Q_DESC)


When I try to cycle through an array of command line supplied keys, it
fails.


while counter < arg_array_size:
    arg1=valid_keys[sys.argv[counter]]
    arg2 = 'q.inquire(CMQC.'+valid_keys[sys.argv[counter]]+')'
    print arg1,"     ",arg2
    counter = counter +1

Variable arg1 successfully mines the dictionary to return the key it is
looking for.

Variable arg2 successfully forms the q command like you see in the print
statement above.

When I do the print statement, the value of arg2 is printed instead of
being executed.

Does anyone know how to get around this problem?

Thank you, 
Andrew Robert 
Systems Architect 
Information Technologies
MFS Investment Management
Phone:  617-954-5882 
Pager:   781-945-1742
E-mail:  arobert@mfs.com 
Linux User Number: #201204 



"MFS Relay Service" made the following
 annotations on 04/13/2005 11:02:45 AM
------------------------------------------------------------------------------
This email communication and any attachments may contain proprietary, confidential, or privileged information.  If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited.  The sender does not waive confidentiality or any privilege by mistransmission.  If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments.
==============================================================================

From albertito_g at hotmail.com  Wed Apr 13 17:17:44 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 17:17:48 2005
Subject: [Tutor] Multithreading and Daemon Program
In-Reply-To: <425D23D7.3070406@cirad.fr>
Message-ID: <BAY106-F147A5BA86A22478A413BA489340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/37436840/attachment.html
From jsoares at Safe-mail.net  Wed Apr 13 18:15:32 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Wed Apr 13 18:15:41 2005
Subject: [Tutor] Re: Interesting anomaly with the Eight Queens problem
Message-ID: <N1-GZa7YcBm@Safe-mail.net>



I read through Magnus Hetland's book and noticed the Eight Queens problem, which I had solved some time ago using Visual Basic.



This time, I wanted to use a non-recursive solution. I randomly place each queen on board coordinates running from 0,0(top left hand corner of board) to 7,7(lower right hand corner of board)



Here's the interesting part: I can only get eight queens safely on the board perhaps every one in 20 runs. At least 12 or 13 of those times, I can place seven queens, while five or six times, I can only place six queens or even five!



Once a queen is safely placed, I establish her "territory". Once this is done, when I try to place a subsequent queen, I check for all placed queen's territories. Once I place six or seven queens, I have to give the program a lot more tries to try to find a safe square. And it can't always be done.



Does this sound right? Does trying to place each queen randomly cause this anomaly?



I can post my code(beginner code!) if anyone is interested in seeing it.



Best,



John



=================================
John Soares, Webmaster
Family Safe Surfinghttp://www.family-safe-surfing.net
jsoares@family-safe-surfing.net
jsoares@safe-mail.net

Tel: (810) 343-0571
Fax: (866) 895-3082

"Your best bet for online family-friendly resources"
=================================



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/b90ea036/attachment.html
From leec03273 at mac.com  Wed Apr 13 19:04:03 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Wed Apr 13 19:04:11 2005
Subject: [Tutor] Re: Interesting anomaly with the Eight Queens problem
In-Reply-To: <N1-GZa7YcBm@Safe-mail.net>
References: <N1-GZa7YcBm@Safe-mail.net>
Message-ID: <0795071e3ed550790295b0099d251d4f@mac.com>

John

The type of problem you mention and the extent of positioning you go to 
could result in an incomplete solution.  In very general terms one 
would need to place the first Queen then find an appropriate position 
for the second, and each of the remaining Queens in turn until either 
there are no appropriate positions to be found or all eight Queens have 
been positioned.  If all eight Queens can not be positioned, then the 
first Queen would be moved and the remaining Queen positioning worked 
through again.

This is a "made for recursion" type of problem, but could be done with 
nested loops.

The "Trying everything" approach can , of course, be a very lengthy 
process.  I seem to remember a more sophisticated model for this type 
of problem (I think somehow related to linear algebra) but can't recall 
the specifics at the moment.  Maybe one of the more academic (an 
younger) members of this list can point you in such a direction.

Lee C

On Apr 13, 2005, at 12:15 PM, jsoares@Safe-mail.net wrote:

> I read through Magnus Hetland's book and noticed the Eight Queens 
> problem, which I had solved some time ago using Visual Basic.
>
> This time, I wanted to use a non-recursive solution. I randomly place 
> each queen on board coordinates running from 0,0(top left hand corner 
> of board) to 7,7(lower right hand corner of board)
>
> Here's the interesting part: I can only get eight queens safely on the 
> board perhaps every one in 20 runs. At least 12 or 13 of those times, 
> I can place seven queens, while five or six times, I can only place 
> six queens or even five!
>
> Once a queen is safely placed, I establish her "territory". Once this 
> is done, when I try to place a subsequent queen, I check for all 
> placed queen's territories. Once I place six or seven queens, I have 
> to give the program a lot more tries to try to find a safe square. And 
> it can't always be done.
>
> Does this sound right? Does trying to place each queen randomly cause 
> this anomaly?
>
> I can post my code(beginner code!) if anyone is interested in seeing 
> it.
>
> Best,
>
> John
>
> =================================
> John Soares, Webmaster
> Family Safe Surfinghttp://www.family-safe-surfing.net
> jsoares@family-safe-surfing.net
> jsoares@safe-mail.net
>
> Tel: (810) 343-0571
> Fa x: (866) 895-3082
>
> "Your best bet for online family-friendly resources"
> =================================
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From askoose at sandia.gov  Wed Apr 13 19:09:16 2005
From: askoose at sandia.gov (Kooser, Ara S)
Date: Wed Apr 13 19:09:33 2005
Subject: [Tutor] Re: Interesting anomaly with the Eight Queens
 problem
Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0B06F7@ES21SNLNT.srn.sandia.gov>

If you go here http://en.wikipedia.org/wiki/Eight_queens_puzzle Down at
the bottom page is a very short python program that gives the solutions
to the eight queens problem in a very neat manner.

Ara




"There is something to be learned from a rainstorm. When meeting with a
sudden shower, you try not to get wet and run quickly along the road.
But doing such things as passing under the eaves of houses, you still
get wet. When you are resolved from the beginning, you will not be
perplexed, though you still get the same soaking." - Yamamoto Tsunetomo


-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Lee Cullens
Sent: Wednesday, April 13, 2005 11:04 AM
To: jsoares@Safe-mail.net
Cc: tutor@python.org
Subject: Re: [Tutor] Re: Interesting anomaly with the Eight Queens
problem


John

The type of problem you mention and the extent of positioning you go to 
could result in an incomplete solution.  In very general terms one 
would need to place the first Queen then find an appropriate position 
for the second, and each of the remaining Queens in turn until either 
there are no appropriate positions to be found or all eight Queens have 
been positioned.  If all eight Queens can not be positioned, then the 
first Queen would be moved and the remaining Queen positioning worked 
through again.

This is a "made for recursion" type of problem, but could be done with 
nested loops.

The "Trying everything" approach can , of course, be a very lengthy 
process.  I seem to remember a more sophisticated model for this type 
of problem (I think somehow related to linear algebra) but can't recall 
the specifics at the moment.  Maybe one of the more academic (an 
younger) members of this list can point you in such a direction.

Lee C

On Apr 13, 2005, at 12:15 PM, jsoares@Safe-mail.net wrote:

> I read through Magnus Hetland's book and noticed the Eight Queens
> problem, which I had solved some time ago using Visual Basic.
>
> This time, I wanted to use a non-recursive solution. I randomly place
> each queen on board coordinates running from 0,0(top left hand corner 
> of board) to 7,7(lower right hand corner of board)
>
> Here's the interesting part: I can only get eight queens safely on the
> board perhaps every one in 20 runs. At least 12 or 13 of those times, 
> I can place seven queens, while five or six times, I can only place 
> six queens or even five!
>
> Once a queen is safely placed, I establish her "territory". Once this
> is done, when I try to place a subsequent queen, I check for all 
> placed queen's territories. Once I place six or seven queens, I have 
> to give the program a lot more tries to try to find a safe square. And

> it can't always be done.
>
> Does this sound right? Does trying to place each queen randomly cause
> this anomaly?
>
> I can post my code(beginner code!) if anyone is interested in seeing
> it.
>
> Best,
>
> John
>
> =================================
> John Soares, Webmaster
> Family Safe Surfinghttp://www.family-safe-surfing.net
> jsoares@family-safe-surfing.net
> jsoares@safe-mail.net
>
> Tel: (810) 343-0571
> Fa x: (866) 895-3082
>
> "Your best bet for online family-friendly resources" 
> =================================
>
> _______________________________________________
> 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 leec03273 at mac.com  Wed Apr 13 19:17:40 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Wed Apr 13 19:17:48 2005
Subject: [Tutor] Re: Interesting anomaly with the Eight Queens problem
In-Reply-To: <0795071e3ed550790295b0099d251d4f@mac.com>
References: <N1-GZa7YcBm@Safe-mail.net>
	<0795071e3ed550790295b0099d251d4f@mac.com>
Message-ID: <fdc21ac9626ee5890babfc535d8b9aab@mac.com>

So there is no misunderstanding, the trial positioning would be 
applicable to all levels, not just the first. In other words, solving 
for each of the remaining Queens in turn is the same as for the first 
Queen, except for the eighth Queen where no lower level positioning 
need be considered,


On Apr 13, 2005, at 1:04 PM, Lee Cullens wrote:

> John
>
> The type of problem you mention and the extent of positioning you go 
> to could result in an incomplete solution.  In very general terms one 
> would need to place the first Queen then find an appropriate position 
> for the second, and each of the remaining Queens in turn until either 
> there are no appropriate positions to be found or all eight Queens 
> have been positioned.  If all eight Queens can not be positioned, then 
> the first Queen would be moved and the remaining Queen positioning 
> worked through again.
>
> This is a "made for recursion" type of problem, but could be done with 
> nested loops.
>
> The "Trying everything" approach can , of course, be a very lengthy 
> process.  I seem to remember a more sophisticated model for this type 
> of problem (I think somehow related to linear algebra) but can't 
> recall the specifics at the moment.  Maybe one of the more academic 
> (an younger) members of this list can point you in such a direction.
>
> Lee C
>
> On Apr 13, 2005, at 12:15 PM, jsoares@Safe-mail.net wrote:
>
>> I read through Magnus Hetland's book and noticed the Eight Queens 
>> problem, which I had solved some time ago using Visual Basic.
>>
>> This time, I wanted to use a non-recursive solution. I randomly place 
>> each queen on board coordinates running from 0,0(top left hand corner 
>> of board) to 7,7(lower right hand corner of board)
>>
>> Here's the interesting part: I can only get eight queens safely on 
>> the board perhaps every one in 20 runs. At least 12 or 13 of those 
>> times, I can place seven queens, while five or six times, I can only 
>> place six queens or even five!
>>
>> Once a queen is safely placed, I establish her "territory". Once this 
>> is done, when I try to place a subsequent queen, I check for all 
>> placed queen's territories. Once I place six or seven queens, I have 
>> to give the program a lot more tries to try to find a safe square. 
>> And it can't always be done.
>>
>> Does this sound right? Does trying to place each queen randomly cause 
>> this anomaly?
>>
>> I can post my code(beginner code!) if anyone is interested in seeing 
>> it.
>>
>> Best,
>>
>> John
>>
>> =================================
>> John Soares, Webmaster
>> Family Safe Surfinghttp://www.family-safe-surfing.net
>> jsoares@family-safe-surfing.net
>> jsoares@safe-mail.net
>>
>> Tel: (810) 343-0571
>> Fa x: (866) 895-3082
>>
>> "Your best bet for online family-friendly resources"
>> =================================
>>
>> _______________________________________________
>> 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 leec03273 at mac.com  Wed Apr 13 19:39:34 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Wed Apr 13 19:39:41 2005
Subject: [Tutor] Re: GUI module selection?
In-Reply-To: <3fe17b6905041306043df3b4ee@mail.gmail.com>
References: <7b64106f164cbe3aa3d747d9520b9649@redivi.com>
	<ba486524bb882b9bb4c0a4dfa292b067@conncoll.edu>
	<2f4f83fe12fb301cac600685df80421b@redivi.com>
	<5c6ab478aba34c763a2a6906724bfa59@mac.com>
	<d7c8bb99c6a11868510629c5fb3aaf56@mac.com>
	<3fe17b6905041306043df3b4ee@mail.gmail.com>
Message-ID: <77399acdb9cf43b75facf4baa8dd1d7b@mac.com>

Thank you, Liam and Steve, for the informative feedback.

Lee C

From kent37 at tds.net  Wed Apr 13 19:55:01 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 13 19:55:02 2005
Subject: [Tutor] Odd problem with variable substitution and command
	execution
In-Reply-To: <968452DD78695147AA4A369C3DF9E40A039506C4@BOSMAILBOX3.corp.mfs.com>
References: <968452DD78695147AA4A369C3DF9E40A039506C4@BOSMAILBOX3.corp.mfs.com>
Message-ID: <425D5CF5.6060306@tds.net>

Robert, Andrew wrote:
> Hi Everyone,
> 
> I am trying to do an MQ inquiry but I am having mixed results.
> 
> If I do the command direct via a print statement like the one below, it
> works,
> 
> 
> print 'Queue Description:\t' , q.inquire(CMQC.MQCA_Q_DESC)
> 
> 
> When I try to cycle through an array of command line supplied keys, it
> fails.
> 
> 
> while counter < arg_array_size:
>     arg1=valid_keys[sys.argv[counter]]
>     arg2 = 'q.inquire(CMQC.'+valid_keys[sys.argv[counter]]+')'
>     print arg1,"     ",arg2
>     counter = counter +1

You are confusing strings with executable code. What you are doing here is essentially
print 'MQCA_Q_DESC' , 'q.inquire(CMQC.MQCA_Q_DESC)'

Note the quotes around the second string - not very exciting.

You could use eval() to get around this but there are better ways. You just need to get an attribute 
of CMQC by name, then call q.inquire() with that attribute. Something like this should work:

while counter < arg_array_size:
     arg1=valid_keys[sys.argv[counter]]

     # if arg1 is the string "MQCA_Q_DESC" then the next line is the same
     # as saying queryParam = CMQC.MQCA_Q_DESC
     queryParam = getattr(CMQC, arg1)

     # Now we can use queryParam directly
     arg2 = q.inquire(queryParam)
     print arg1,"     ",arg2
     counter = counter +1

I have no way to test this so write back if you have trouble with it.

Kent

From magoldfish at gmail.com  Wed Apr 13 20:22:30 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Wed Apr 13 20:22:36 2005
Subject: [Tutor] Re: when to use properties?
In-Reply-To: <20050413133517.EDDCF1E4002@bag.python.org>
References: <loom.20050413T082945-330@post.gmane.org>
	<20050413133517.EDDCF1E4002@bag.python.org>
Message-ID: <5e183f3d05041311225b4adbd6@mail.gmail.com>

Thanks for all of the comments!  The general theme of "don't use a
property unless you need to" is intuitive, and is what I was hoping
the consensus would be.

This raised another design issue for me, tho', regarding property
validation.  In C#/Java, I would typically do validation in all of my
setter methods, but is this really pythonic?  It seems OO--
encapsulation-- but also seems to be one of the biggest wastes of
coding time & typing in those languages.

As a simple example, consider the following class:

#   Example: mixing instance attributes with properties.  Is it pythonic to
#   validate property data in setters?  Note that tens and ones are never
#   validated, so the class can break by setting these directly...
class SillyDecimal(object):
    def __init__(self, arg=17):
        if isinstance(arg, tuple):
            self.tens = arg[0]
            self.ones = arg[1]
        else:
            self.number = arg
    
    def getNumber(self):
        return self.tens*10 + self.ones
    def setNumber(self, value):
        if value < 0 or value > 99:
            raise ArgumentException("Must in [0, 99]")
        self.tens = value // 10
        self.ones = value % 10
    number = property(getNumber, setNumber, None, "Complete number, [0-99]")

x = SillyDecimal()
x.number, x.tens, x.ones        # returns (17, 7, 1)


Notice that while "tens", "ones" and "number" all appear as
attributes, only "number" has its input validated.  Since the class is
designed to only hold numbers 0 - 99, one can 'break' it by setting
self.tens=11, for example.  Of course this is just a toy example, but
the point should be clear: when is it pythonic to do
attribute/property validation?
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 20:41:40 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 20:41:42 2005
Subject: [Tutor] help (fwd)
Message-ID: <Pine.LNX.4.44.0504131141370.7178-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Wed, 13 Apr 2005 17:12:55 +0200
From: Feziwe Mpondo <feziwe@sanbi.ac.za>
To: tutor-owner@python.org
Subject: help

how to run a programm after you have typed in the commands

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 20:43:35 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 20:43:38 2005
Subject: [Tutor] Python backwards program (fwd)
Message-ID: <Pine.LNX.4.44.0504131143320.7178-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Wed, 13 Apr 2005 09:01:16 -0500
From: Jim and Laura Ahl <jcahl@psci.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Python backwards program (fwd)

Danny

I cannot write a program that gives me a double letter.

I can get each letter separate or pieces or parts of the word

Jim
  ----- Original Message -----
  From: Danny Yoo
  To: jcahl@psci.net
  Cc: Tutor
  Sent: Wednesday, April 13, 2005 12:02 AM
  Subject: Re: [Tutor] Python backwards program (fwd)



  Hello Jim,


  > I have read about loops, strings, tuples.

  Can you show us an example of a loop?  Can you show us the last program
  that you've written?

  It sounds like you've done a lot of reading.  The problem with learning
  how to program is that you can't just read it: you actually have to write
  programs and watch them run.  I think you need to make that book knowledge
  into something concrete.

  For example, If we give you some string, like:

  ######
  s = "hello world"
  ######

  can you get Python to say:

  ######
  hheelllloo  wwoorrlldd
  ######

  That is, can you write a program that will print out each letter in 's',
  but doubled up?



  > I am wasting you guys time.

  I do not know that.  We will not do your homework for you, so if you're
  just expecting a direct homework solution, we will not help you, and you
  will be wasting our time.

  But if you're really interested in learning, start asking questions, and
  start playing with the interpreter.  If there is something you do not
  understand yet, we'll do what we can to help you find good answers, and
  we'll try to point you toward resources that can help.

  And we'll try to be your cheering squad, if you need one.


  Best of wishes to you.


From cpu.crazy at gmail.com  Wed Apr 13 19:05:29 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed Apr 13 20:52:35 2005
Subject: [Tutor] Defining a function (Joseph Q.)
In-Reply-To: <20050412165543.12A091E4012@bag.python.org>
References: <20050412165543.12A091E4012@bag.python.org>
Message-ID: <6.1.0.6.2.20050413105727.01ebd418@pop.gmail.com>

Oh, now I understand....

def silly(a_name_I_picked_at_random):   # well, not quite

...     print a_name_I_picked_at_random     # at random ;-)
...


>>>silly(42)

42

The name a_name_I_picked_at_random is like a "placeholder" inside the
function for whatever input we gave to the function. And *that* can be
any object

So you can have silly say something serious like:

def silly(a_name_I_picked_at_random):   # well, not quite

         print a_name_I_picked_at_random     # at random ;-)

def silly(this_is_serious):
         print 'this is serious"

But I get an error!
Traceback (most recent call last):
   File "C:\Python24\saved\tmp1.py", line 7, in -toplevel-
     silly(this_is_serious)
NameError: name 'this_is_serious' is not defined

But you can have silly say something silly and also say something serious 
right? If so.... how?

args has confused me, but I'm slowly picking it up.

Thanks Brian, Jeff, Liam for your help.
         Joseph
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/f36c07e0/attachment.html
From cpu.crazy at gmail.com  Wed Apr 13 19:08:22 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed Apr 13 20:52:40 2005
Subject: [Tutor] Tk code problem (Joseph Q.)
In-Reply-To: <20050412165543.12A091E4012@bag.python.org>
References: <20050412165543.12A091E4012@bag.python.org>
Message-ID: <6.1.0.6.2.20050413110702.01f1ed90@pop.gmail.com>


>It works if you run from the command line instead of inside IDLE. I 
>thought IDLE was supposed to be
>able to run Tkinter programs since Python 2.3 but it doesn't seem to work?



><snip>....
>AFAIK IDLE runs on Linux. There are many other possibilities listed here:
>http://www.python.org/moin/IntegratedDevelopmentEnvironments
>
>eric is popular...
>
>Kent

Thanks for the link and tips.
         Joe 

From cpu.crazy at gmail.com  Wed Apr 13 19:17:56 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed Apr 13 20:52:50 2005
Subject: [Tutor] Cell Bio Newbie Here (Gary L) (Joseph Q.)
In-Reply-To: <20050411200208.F3A651E400E@bag.python.org>
References: <20050411200208.F3A651E400E@bag.python.org>
Message-ID: <6.1.0.6.2.20050413111517.01f1e968@pop.gmail.com>

At 02:02 PM 4/11/2005, you wrote:
>Send Tutor mailing list submissions to
>         tutor@python.org
>Hey all,
>
>Sorry for the bother, thanks for the help....


#first of all, why does this have to be here?
>password="foobar"
>
>count=3
>current_count=0
>
>while password !="unicorn":
>      if current_count<count:
>          password=raw_input("Password:")
>          current_count=current_count+1
>      else:
>          print "That must have been complicated"
>
>
>print "Welcome in"

Just wondering... would breaking the loop at 3 counts work at all? Or would 
it screw it up?

Joe  

From project5 at redrival.net  Wed Apr 13 20:55:34 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 21:00:43 2005
Subject: [Tutor] Re: help (fwd)
References: <Pine.LNX.4.44.0504131141370.7178-100000@hkn.eecs.berkeley.edu>
Message-ID: <loom.20050413T205102-583@post.gmane.org>

> From: Feziwe Mpondo <feziwe <at> sanbi.ac.za>
> 
> how to run a programm after you have typed in the commands

Depends on where you type those commands. 

If you type them in the interactive interpreter, they are executed whenever you
press Enter. However, this method does not allow you to run the same program
twice (except by typing it in twice of course).

A better method is to use a text editor (you could use PythonWin, IDLE, SciTE,
Spe  or even Notepad). Type the code and, if you have an editor with good Python
support, locate its Run command in the menus and use it. If you use a plain text
generic editor, save the program and double-click on it in Explorer (if you're
on Windows) or launch it by typing at the command line:

  python <path-to-newly-saved-script>myscript.py

Yours,

Andrei

From bvande at po-box.mcgill.ca  Wed Apr 13 21:35:27 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Wed Apr 13 21:36:01 2005
Subject: [Tutor] Defining a function (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050413105727.01ebd418@pop.gmail.com>
References: <20050412165543.12A091E4012@bag.python.org>
	<6.1.0.6.2.20050413105727.01ebd418@pop.gmail.com>
Message-ID: <425D747F.30303@po-box.mcgill.ca>

Joseph Quigley said unto the world upon 2005-04-13 13:05:

<SNIP>

> def silly(this_is_serious):
>         print 'this is serious"
> 
> But I get an error!
> Traceback (most recent call last):
>   File "C:\Python24\saved\tmp1.py", line 7, in -toplevel-
>     silly(this_is_serious)
> NameError: name 'this_is_serious' is not defined
> 
> But you can have silly say something silly and also say something 
> serious right? If so.... how?
> 
> args has confused me, but I'm slowly picking it up.
> 
> Thanks Brian, Jeff, Liam for your help.
>         Joseph

Hi Joseph,

you are welcome. :-)

There are at least a couple of things still awry. Take a look:

 >>> def silly(this_is_serious):
... 	print 'this is serious"   # bad quotes -- no function!
Traceback (  File "<interactive input>", line 2
     print 'this is serious"   # bad quotes -- no function!
                                                          ^
SyntaxError: EOL while scanning single-quoted string
 >>> def silly(this_is_serious):
... 	print 'this is serious'
... 	
 >>> silly(42)
this is serious


I think what you are doing is mistaking the role of the name 
this_is_serious *inside* your function definition and the role of 
names *outside* your definition. Outside of your definition, you've 
not made this_is_serious be bound to anything, so it is an undefined name.

 >>> some_serious_thing
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'some_serious_thing' is not defined
 >>> silly(some_serious_thing)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
NameError: name 'some_serious_thing' is not defined

See, it is the same error whether you just try to access the name or 
send the name as a function argument. The name hasn't been given a value.

And that is still true with your this_is_serious name. You gave it a 
value, but *only* inside your function definition. Compare:

 >>> some_serious_thing = 'My, but you are grave!'
 >>> silly(some_serious_thing)
this is serious
 >>> this_is_serious = 'Indeed'
 >>> silly(this_is_serious)
this is serious
 >>>


A few other things: the simple function here can be defined so as to 
take no arguments at all. After all, it doesn't use them. So:

 >>> def simple_silly():
... 	print 'this is serious'
... 	
 >>> simple_silly(42)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: simple_silly() takes no arguments (1 given)
 >>> simple_silly()
this is serious
 >>>


Also, the names inside and outside your function are independent. 
Wittiness:

 >>> def might_confuse(my_value):
... 	print my_value
... 	
 >>> my_value = 42
 >>> your_value = 'something completely different'
 >>> might_confuse(your_value)
something completely different
 >>>


HTH. Please excuse any incoherency; I'm stuck in bed with my 'Welcome 
to Spring!' head cold :-)

Brian vdB

From project5 at redrival.net  Wed Apr 13 21:44:56 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 13 21:49:35 2005
Subject: [Tutor] Re: when to use properties?
References: <loom.20050413T082945-330@post.gmane.org>
	<20050413133517.EDDCF1E4002@bag.python.org>
	<5e183f3d05041311225b4adbd6@mail.gmail.com>
Message-ID: <loom.20050413T205943-679@post.gmane.org>

Marcus Goldfish <magoldfish <at> gmail.com> writes:

> This raised another design issue for me, tho', regarding property
> validation.  In C#/Java, I would typically do validation in all of my
> setter methods, but is this really pythonic?  It seems OO--
> encapsulation-- but also seems to be one of the biggest wastes of
> coding time & typing in those languages.

I wouldn't validate unless there's some subtle (hard to detect) bad
behavior that might catch people off-guard and unless I'm dealing with an
untrustworthy and potentially malicious data provider (in other words, 
the user :)). Even then, it might be better/easier to use catch exceptions 
than to validate in advance.

Let's say we take your example and feed a list to it as a number. It will
crash even without the validation. There's nothing subtle about it, and 
it's good enough "validation" for me. 

If you drop the validation and feed it a number larger than 99 or lower
than 0, it will work just fine, even though it's going beyond its stated
intended use. In fact, the validation makes it *less useful*, because it 
wouldn't permit the user to use the class to its full capabilities. 
Perhaps the user doesn't want to feed your class with numbers, but with 
some objects which mimmick part of the integer behavior 
(http://docs.python.org/ref/numeric-types.html), but not the comparison to an
integer. The validation makes that impossible too. That sounds
a bit useless in this particular fantasy case, but there are plenty of other
cases where it's very useful.

Regarding the integrity of the class: if you prepend _ or __ to internal
attributes/methods, users of your class know that they're not supposed to mess
around with them. They *can*, but from that point on, it's no longer your
responsibility to protect them from themselves. Python works on the assumption
that programmers are responsible adults :).

Yours,

Andrei


From benvinger at yahoo.co.uk  Wed Apr 13 21:53:47 2005
From: benvinger at yahoo.co.uk (Ben Vinger)
Date: Wed Apr 13 21:53:50 2005
Subject: how to run a programm after you have typed in the commands (was Re:
	[Tutor] help (fwd))
In-Reply-To: 6667
Message-ID: <20050413195347.25758.qmail@web25804.mail.ukl.yahoo.com>

It sounds like you've been using the Python
interactive prompt such as IDLE.   You can type the
same Python statements you've used there into a text
editor or Python IDE and save it.
Let's say you have created a Python program/script
called hello.py in a text editor and saved it. You can
now open a command prompt (Windows) or console (linux)
in the directory where your program is saved.
 Then type:
python hello.py 

If you are using Windows and this does not work, it
will be because Python is not in your system path.
Good luck
Ben



--- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
> ---------- Forwarded message ----------
> Date: Wed, 13 Apr 2005 17:12:55 +0200
> From: Feziwe Mpondo <feziwe@sanbi.ac.za>
> To: tutor-owner@python.org
> Subject: help
> 
> how to run a programm after you have typed in the
> commands
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

Send instant messages to your online friends http://uk.messenger.yahoo.com 
From cpu.crazy at gmail.com  Wed Apr 13 21:33:14 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed Apr 13 22:07:49 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Message-ID: <6.1.0.6.2.20050413132955.01eed5e8@pop.gmail.com>

 >Well you did come up with a way that would work sort of and you seem to be
 >ont eh right track. I would make 1 small change if using your approach.
 >
 >prefixes = 'JKLMNOPQ'
 >suffix = 'ack'
 >
 >for letter in prefixes:
 >  if letter == 'O' or letter == 'Q': print letter + 'u' + suffix
 >  else: print letter + suffix
 >
 >However there are other methods to solve this problem but following the
 >logic you are using this works.

 >Jeff

I also learned an easier way to do that:

prefixes = 'JKLMNOPQ'
suffix = 'ack'

for letter in prefixes:
   if letter == ('O') or ('Q'):
	print letter + 'u' + suffix
   else:
	print letter + suffix

Joseph Q.
   

From geek_show at dsl.pipex.com  Wed Apr 13 22:08:10 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Wed Apr 13 22:08:19 2005
Subject: how to run a programm after you have typed in the commands (was
	Re:	[Tutor] help (fwd))
In-Reply-To: <20050413195347.25758.qmail@web25804.mail.ukl.yahoo.com>
References: <20050413195347.25758.qmail@web25804.mail.ukl.yahoo.com>
Message-ID: <425D7C2A.1040903@dsl.pipex.com>

Ben Vinger wrote:
> It sounds like you've been using the Python
> interactive prompt such as IDLE.   You can type the
> same Python statements you've used there into a text
> editor or Python IDE and save it.
> Let's say you have created a Python program/script
> called hello.py in a text editor and saved it. You can
> now open a command prompt (Windows) or console (linux)
> in the directory where your program is saved.
>  Then type:
> python hello.py 
> 
> If you are using Windows and this does not work, it
> will be because Python is not in your system path.
> Good luck
> Ben
> 
> 
> 
> --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
>>
>>---------- Forwarded message ----------
>>Date: Wed, 13 Apr 2005 17:12:55 +0200
>>From: Feziwe Mpondo <feziwe@sanbi.ac.za>
>>To: tutor-owner@python.org
>>Subject: help
>>
>>how to run a programm after you have typed in the
>>commands
>>
Molo Feziwe
If you are using Linux, don't forget to make your program executable by 
including the "she-bang" *before* any of your Python code, such as: 
#!/bin/sh
If you want to then run it by itself (i.e. just on the command line) 
chmod u+x myfile.py and then at the command line you can just type in 
myfile.py and the programme will execute. Pretty neat, eh?

If you're using Windows, I haven't a clue so follow the other guys' advice.

Best wishes

/j
From TIMOTHYG at motorola.com  Wed Apr 13 22:15:43 2005
From: TIMOTHYG at motorola.com (Gallagher Timothy-TIMOTHYG)
Date: Wed Apr 13 22:16:31 2005
Subject: [Tutor] _winreg problems enumerating 
Message-ID: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB32@mi06exm01.fhills.aieg.mot.com>

am new to python and want to learn this language.  I am having troubles
finding examples and tutorials for use on windows boxes.  I do most of my
stuff in perl and php but want better socket support, so I am giving python
a try.  I am writing a script to connect to remote registry's because of
this new IM virus.  I can create reg entries and delete them but I cannot
enumerate them, here is my code.

import _winreg

host = "127.0.0.1" # local host
key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
E_key = _winreg.EnumValue(key,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")


I get an error when I run the script:

Traceback (most recent call last):
  File "reg4.py", line 9, in ?
    E_key = _winreg.EnumValue(key,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\R
un")
TypeError: an integer is required

Can someone tell me what I am doing wrong???

Thanks 


Timothy F. Gallagher
Timothyg- at -Motorola.com

 
 
 

From pxlpluker at cfl.rr.com  Wed Apr 13 22:19:05 2005
From: pxlpluker at cfl.rr.com (pxlpluker)
Date: Wed Apr 13 22:19:14 2005
Subject: [Tutor] i need to see a var from any where in my app - im clueless
Message-ID: <425D7EB9.10204@cfl.rr.com>

    
i have read the book and searched the group too
----------------------------------------------
im not gettin it.
i want to read a global (OPTIONS) from file1 from a class method
(func1) in file2
but i cant see the OPTION from func1


----------------------------------------------
#file1.py
import file2
import sys

OPTION = sys.argv[1:]
pass
a=global2.class1()
a.func1()

#file2.py
import __main__
pass
class class1:
.    def func1(self):
.        pass
-------------------------------------------
From albertito_g at hotmail.com  Wed Apr 13 22:25:51 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 13 22:25:55 2005
Subject: [Tutor] i need to see a var from any where in my app - im clueless
In-Reply-To: <425D7EB9.10204@cfl.rr.com>
Message-ID: <BAY106-F29D0CDEA709B851A7AE06489340@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/4cfd723b/attachment.htm
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 22:32:22 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 22:32:25 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <Pine.LNX.4.44.0504131143320.7178-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504131146120.7178-100000@hkn.eecs.berkeley.edu>

> I cannot write a program that gives me a double letter.
> I can get each letter separate or pieces or parts of the word


Hi Jim,

[Please don't reply just to me: use the Reply-to-All feature on your email
program.  This allows your reply to be seen by the rest of us here.  I
want to make sure your questions won't get lost by my negligence.]


Can you show us what you've tried so far?  That might help us see why
you're running into problems.

The major problem we have in trying to help with this stuff is that we can
not be mind readers: the only channel we can use to see what's going on is
what you show us, and if you don't give us information, we really can't
see what's happening.


So, when you say something like:

> I cannot write a program that gives me a double letter.

then, it's very useful if you can show us what you tried to do, even if it
didn't work.  We really don't care if you get it exactly right: we really
more interested in how you do things: we really want to see how you're
approaching these kinds of problems.


Let's take a hypothetical situation.  If you had shown us something like
this:

######
>>> s = "hello world"
>>> for letter in s:
...     print letterletter
...
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: name 'letterletter' is not defined
######

that in itself tells us a lot more than "I can't do it."  It's not just an
"error": there's a reason behind it, and that's something we can tackle.

The silly thing that today's education systems have done is to make the
act of making a mistake or error something shameful, so I can see why
you're hesitating to show things to us.  But that's totally wrong: you
need to be willing to show us things that don't work.  A failure itself is
valuable, and we can learn things from them.


Continuing on this idea, when you say:

> I can get each letter separate or pieces or parts of the word

then, show us how you are doing that.  Show us how you are printing each
letter separately.

Seeing what you can do can be as informative to us as seeing what you're
getting stuck on.  Don't be afraid to copy-and-paste programs into your
replies.

I guess I'm trying to say: stop being so shy about sharing your code!
*grin*

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 22:44:01 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 22:44:05 2005
Subject: [Tutor] help (fwd)
Message-ID: <Pine.LNX.4.44.0504131343230.7178-100000@hkn.eecs.berkeley.edu>


[Hi Mark, I'm not the original poster of the question.  I've forwarded
your reply back to tutor as well as the original poster.  Thanks!]


---------- Forwarded message ----------
Date: Wed, 13 Apr 2005 14:56:18 -0400
From: "Leeds, Mark" <mleeds@mlp.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: RE: [Tutor] help (fwd)

You name the file say danny.py And then at the prompt ( if you are in
linux, I don't use windows so I hope that you are in linux ) type Python
danny.py.

			mark

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Danny Yoo
Sent: Wednesday, April 13, 2005 2:42 PM
To: Tutor
Subject: [Tutor] help (fwd)



---------- Forwarded message ----------
Date: Wed, 13 Apr 2005 17:12:55 +0200
From: Feziwe Mpondo <feziwe@sanbi.ac.za>
To: tutor-owner@python.org
Subject: help

how to run a programm after you have typed in the commands

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

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 13 22:56:39 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 13 22:56:43 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <002001c5402f$e63f0ee0$846931d8@DJM96611>
Message-ID: <Pine.LNX.4.44.0504131348070.7178-100000@hkn.eecs.berkeley.edu>



> I have wrote 3 other programs in the class.

Hi Jim,

[cut]

Ok, that's where I have to stop you for a moment.

We're not going to do your homework problems; please understand that we
actually don't care if you get your homework done.  And I really hope that
people don't just start blurting stuff at Jim for the other three homework
problems he's dumping on us.

You mentioned earlier that you didn't understand backwards slices, so how
can you use them with a clear conscience without knowing why they work?
Why don't you ask more questions?


We really care about helping you figure out how to solve your problems
yourself.  But if you just pick and choose answers from generous folks,
and present that as your own work to your class, without really
understanding what's going on, then you are wasting our time.

From amonroe at columbus.rr.com  Thu Apr 14 00:17:09 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu Apr 14 00:18:07 2005
Subject: [Tutor] Multithreading and Daemon Program
In-Reply-To: <BAY106-F147A5BA86A22478A413BA489340@phx.gbl>
References: <BAY106-F147A5BA86A22478A413BA489340@phx.gbl>
Message-ID: <6780494424.20050413181709@columbus.rr.com>

> An IP Camera will send images to the server via ftp to a folder.
> Each user has a folder and I want to know how I can make my app to
> check the folders ('cause there is going to be many cameras sending
> files and that means that the app will have to check every folder)
> every x seconds?

> Will I have to make one process for every user or one for each
> user??????

I bet you could get it to work both ways (seperate threads for each
folder, or a single thread that checks all the folders one at at time).

Once you detect that there are pictures in someone's folder, what do
you do with them?

Also I posted this short message about my first experiences with
threading about a year ago, in case it helps:

> - def a function that you want to get executed in a subthread
> - create a new thread, feed it the name of the function above
> - start the new thread
> 
> at this point, you need not execute any further statements in your
> program. The main program will wait indefinitely for the child thread
> to complete. Once it's done, the main program will exit too. It's kind
> of neat to watch, the first time you try it.

Alan

From jfouhy at paradise.net.nz  Thu Apr 14 01:12:58 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Thu Apr 14 01:13:03 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050413132955.01eed5e8@pop.gmail.com>
References: <6.1.0.6.2.20050413132955.01eed5e8@pop.gmail.com>
Message-ID: <1113433978.425da77aa3acb@www.paradise.net.nz>

Quoting Joseph Quigley <cpu.crazy@gmail.com>:

> prefixes = 'JKLMNOPQ'
> suffix = 'ack'
> 
> for letter in prefixes:
>  if letter == ('O') or ('Q'):
> 	print letter + 'u' + suffix
>  else:
> 	print letter + suffix

Hi Joseph,

This still won't work.  The reason is that your if statement is interpreted like
this:

if letter == 'O':
    print letter + 'u' + suffix
elif 'Q':
    print letter + 'u' + suffic
else:
    print letter + suffix

Do you see?  The == "binds more tightly" than the or.  And, in python, 'Q' is
considered True for the purposes of tests.

So this is what happens:

>>> prefixes = 'JKLMNOPQ'
>>> suffix = 'ack'
>>> 
>>> for letter in prefixes:
...   if letter == ('O') or ('Q'):
...     print letter + 'u' + suffix
...   else:
...     print letter + suffix
... 
Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack
>>> 

What you can do instead is this:

for letter in prefixes:
    if letter in ['O', 'Q']:
        print letter + 'u' + suffix
    else:
        print letter + suffix

HTH.

-- 
John.
From tameyer at ihug.co.nz  Thu Apr 14 01:38:58 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Thu Apr 14 01:39:08 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E80297BCF1@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB0096@its-xchg4.massey.ac.nz>

> In the print word [::-1] line it gives me this message
> (sequence index must be an integer)  What does that mean

As others have said, it means you're using Python 2.2 or older (so can't use
extended slicing).  It seems likely that what you're after is the loop
approach that has been mentioned by various people, including me.  Have a go
with that method, and give us the code that you have, along with any
error/output that you get.

=Tony.Meyer

From luke.jordan at gmail.com  Thu Apr 14 01:53:40 2005
From: luke.jordan at gmail.com (Luke Jordan)
Date: Thu Apr 14 01:53:43 2005
Subject: [Tutor] "Dispatching" functions with args
Message-ID: <ea0feb80050413165357880f9a@mail.gmail.com>

Hi!

I am using a suggestion from this list to handle calling different
functions conditionallly based on user input. What I'm trying to do is
have functions that are 'configurable' in the sense that a choice from
the user affects the way it performs.

This works:

    def aFunc():
        print "aFunc"

    def dispatch(func):
        while func is not None:
            func = func()

But this does not:

    def aFunc(configArg):
        print "aFunc with argument"
        print configArg

    def anotherFunc(configArg):
        print "anotherFunc with argument"
        print configArg  
        return aFunc,1

    def dispatch(func,configArg):
        while func is not None and configArg is not None:
            func = func(configArg)

    dispatch(anotherFunc,1)

I get TypeErrored:

Traceback (most recent call last):
  File "E:/gibberish/current work/test2.py", line 14, in ?
    dispatch(aFunc,1)
  File "E:/gibberish/current work/test2.py", line 12, in dispatch
    func = func(funcArg)
TypeError: 'tuple' object is not callable

I understand *that* a tuple is not callable, but not why this is
happening here, or how to solve this problem.

Thanks in advance for your input!

Luke

-- 
"Scalpel....blood bucket....priest....next patient."
From jfouhy at paradise.net.nz  Thu Apr 14 02:14:07 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Thu Apr 14 02:14:11 2005
Subject: [Tutor] "Dispatching" functions with args
In-Reply-To: <ea0feb80050413165357880f9a@mail.gmail.com>
References: <ea0feb80050413165357880f9a@mail.gmail.com>
Message-ID: <1113437647.425db5cf23656@www.paradise.net.nz>

Quoting Luke Jordan <luke.jordan@gmail.com>:

> But this does not:
> 
>  def aFunc(configArg):
>  print "aFunc with argument"
>  print configArg
> 
>  def anotherFunc(configArg):
>  print "anotherFunc with argument"
>  print configArg 
>  return aFunc,1
   ^^^^^^^^^^^^^^

>  def dispatch(func,configArg):
>  while func is not None and configArg is not None:
>  func = func(configArg)
> 
>  dispatch(anotherFunc,1)
> 

The line I have underlined is returning a tuple.  So, when you do 

func = func(configArg)

It has the effect of setting 

func = (aFunc, 1)

which you then try to call.

Instead, you could try:

func, configArg = func(configArg)

Of course, you would then need to ensure that any function you could call (such
as aFunc) also returns an appropriate tuple, otherwise the unpacking will fail.
(or wrap it in an if statement or a try:except block or something)

-- 
John.
From cyresse at gmail.com  Thu Apr 14 03:44:46 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Thu Apr 14 03:44:50 2005
Subject: [Tutor] _winreg problems enumerating
In-Reply-To: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB32@mi06exm01.fhills.aieg.mot.com>
References: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB32@mi06exm01.fhills.aieg.mot.com>
Message-ID: <f2ff2d0504131844bdce117@mail.gmail.com>

Hi Tim, 

Hmmm, I may have to play with _winreg, is is new with Python 2.4?

Anyway, from the _winreg docs - 

 *EnumValue*( key, index) Enumerates values of an open registry key, 
returning a tuple. 

key is an already open key, or any one of the predefined HKEY_* constants. 

index is an integer that identifies the index of the value to retrieve. 

The function retrieves the name of one subkey each time it is called. It is 
typically called repeatedly, until an EnvironmentError exception is raised, 
indicating no more values.
 

There's your issue - 
E_key = 
_winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
 
The second value needs to be an integer that is an index.
 
Typical usage would look like this - 
 i = 0
regKeys = []
try:
while 1:
regKeys.append(_winreg.EnumValue(key, i))
i += 1
except EnvironmentError:
pass


Good luck, 

Liam Clarke

 

On 4/14/05, Gallagher Timothy-TIMOTHYG <TIMOTHYG@motorola.com> wrote:
> 
> am new to python and want to learn this language. I am having troubles
> finding examples and tutorials for use on windows boxes. I do most of my
> stuff in perl and php but want better socket support, so I am giving 
> python
> a try. I am writing a script to connect to remote registry's because of
> this new IM virus. I can create reg entries and delete them but I cannot
> enumerate them, here is my code.
> 
> import _winreg
> 
> host = "127.0.0.1 <http://127.0.0.1>" # local host
> key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
> E_key = _winreg.EnumValue(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
> 
> I get an error when I run the script:
> 
> Traceback (most recent call last):
> File "reg4.py", line 9, in ?
> E_key = _winreg.EnumValue(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\R
> un")
> TypeError: an integer is required
> 
> Can someone tell me what I am doing wrong???
> 
> Thanks
> 
> Timothy F. Gallagher
> Timothyg- at -Motorola.com <http://Motorola.com>
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/c50361a3/attachment.html
From maxnoel_fr at yahoo.fr  Thu Apr 14 04:26:46 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 14 04:26:50 2005
Subject: [Tutor] when to use properties?
In-Reply-To: <Pine.LNX.4.44.0504121401090.13920-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504121401090.13920-100000@hkn.eecs.berkeley.edu>
Message-ID: <a6b478f55ed0d9339317852d54e61645@yahoo.fr>


On Apr 12, 2005, at 23:22, Danny Yoo wrote:

> There was an interesting article by Phillip Eby about what conventions
> work and don't work when one makes a jump from Java to Python:
>
>     http://dirtsimple.org/2004/12/python-is-not-java.html

	A very interesting read. Thanks for the link, Danny!

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From benmarkwell at gmail.com  Thu Apr 14 04:33:55 2005
From: benmarkwell at gmail.com (Ben Markwell)
Date: Thu Apr 14 04:34:00 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
In-Reply-To: <1113433978.425da77aa3acb@www.paradise.net.nz>
References: <6.1.0.6.2.20050413132955.01eed5e8@pop.gmail.com>
	<1113433978.425da77aa3acb@www.paradise.net.nz>
Message-ID: <b9305117050413193349a2fe70@mail.gmail.com>

Thanks for everybodys input. Am learning slowly but surely.

Ben


On 4/13/05, jfouhy@paradise.net.nz <jfouhy@paradise.net.nz> wrote:
> 
> Quoting Joseph Quigley <cpu.crazy@gmail.com>:
> 
> > prefixes = 'JKLMNOPQ'
> > suffix = 'ack'
> >
> > for letter in prefixes:
> > if letter == ('O') or ('Q'):
> > print letter + 'u' + suffix
> > else:
> > print letter + suffix
> 
> Hi Joseph,
> 
> This still won't work. The reason is that your if statement is interpreted 
> like
> this:
> 
> if letter == 'O':
> print letter + 'u' + suffix
> elif 'Q':
> print letter + 'u' + suffic
> else:
> print letter + suffix
> 
> Do you see? The == "binds more tightly" than the or. And, in python, 'Q' 
> is
> considered True for the purposes of tests.
> 
> So this is what happens:
> 
> >>> prefixes = 'JKLMNOPQ'
> >>> suffix = 'ack'
> >>>
> >>> for letter in prefixes:
> ... if letter == ('O') or ('Q'):
> ... print letter + 'u' + suffix
> ... else:
> ... print letter + suffix
> ...
> Juack
> Kuack
> Luack
> Muack
> Nuack
> Ouack
> Puack
> Quack
> >>>
> 
> What you can do instead is this:
> 
> for letter in prefixes:
> if letter in ['O', 'Q']:
> print letter + 'u' + suffix
> else:
> print letter + suffix
> 
> HTH.
> 
> --
> John.
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/cad0fbc9/attachment-0001.htm
From sbrozo at zoominternet.net  Thu Apr 14 05:04:24 2005
From: sbrozo at zoominternet.net (sbrozo)
Date: Thu Apr 14 05:04:33 2005
Subject: [Tutor] checking elements of a list
Message-ID: <000e01c5409e$a9dcafb0$87989a18@usernm9nbw71q0>

def computer_move(board, computer, human):
    board = board[:]
    BEST_MOVES = [4,0,2,6,8,1,3,5,7]
    corners = [(0,8),(2,6)]
    print "I shall take square number",
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print move
            return move
        board[move] = EMPTY
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print move
            return move
        board[move] = EMPTY
    for move in legal_moves(board): # trying to prevent trap of taking 2 corners first with the computer always taking the center
        board[move] = computer
        for pair in corners:
            if board[pair[0]] == board[pair[1]] == human: # checking if corners human
                BEST_MOVES = [1,3,5,7]
                print move
                return move
            board[move] = EMPTY
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print move
            return move

def next_turn(turn):
    if turn == X:
        return O
    else:
        return X

This is one of the functions in a tic tac toe game from "Python Programming (for the absolute beginner)" by Michael Dawson and it asks to improve on the computer AI.
I put in a list with the name corners to have it test the board and if I have taken 2 diagonal corners then have the computer use a new list of BEST_MOVES for a reply.
It works if I have taken corners pair (0,8) from the list but not when I take the (2,6) pair. I have reversed the pairs in the 'corners' list but it still only works with the (0,8)
pair. Do you need the code for the entire game to follow my train of thought? I am an extreme newbie as I'm sure you can tell, and I have spent hours trying to 
complete this exercise. Many thanks in advance for any advice you can pass along.
Steve Brozo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/53030e99/attachment.htm
From dyoo at hkn.eecs.berkeley.edu  Thu Apr 14 07:24:33 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 14 07:24:38 2005
Subject: [Tutor] Python backwards program
In-Reply-To: <Pine.LNX.4.44.0504131348070.7178-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504132218050.2158-100000@hkn.eecs.berkeley.edu>



> We're not going to do your homework problems; please understand that we
> actually don't care if you get your homework done.  And I really hope that
> people don't just start blurting stuff at Jim for the other three homework
> problems he's dumping on us.

Hi Jim,

Ok, I screwed up big time today, and I'd better say this in public, so
that people know that I made a huge mistake.  I usually make small ones
that can be easily corrected, but I get the feeling I did damage today,
and I wish I could take it back.

Jim, I sincerely apologize about snapping at you like that.  I was wrong
to do so, especially since I completely misread your sentence.  I thought
you were saying that those were three other problems that you had to do
soon, when you had actually wrote that those were three programs that you
had written already.

But even so, I had no excuse to say things like that.  I will try to
better answer your questions, without making such stupid mistakes.  And I
hope that folks on the list will forgive me for the bad temper in my last
emails.

Sincerely,
Danny Yoo

From jcahl at psci.net  Thu Apr 14 08:09:14 2005
From: jcahl at psci.net (Jim and Laura Ahl)
Date: Thu Apr 14 08:09:27 2005
Subject: [Tutor] (no subject)
Message-ID: <008601c540b8$7fb47460$376931d8@DJM96611>

How come when I ask it to print i[2:4] from an inputted string it gives me the letters between two and four

But when I ask it to print i[-1:-4] it does not print anything.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/326c29ee/attachment.html
From bvande at po-box.mcgill.ca  Thu Apr 14 09:10:46 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Thu Apr 14 09:11:34 2005
Subject: [Tutor] (no subject)
In-Reply-To: <008601c540b8$7fb47460$376931d8@DJM96611>
References: <008601c540b8$7fb47460$376931d8@DJM96611>
Message-ID: <425E1776.1040009@po-box.mcgill.ca>

Jim and Laura Ahl said unto the world upon 2005-04-14 02:09:
> How come when I ask it to print i[2:4] from an inputted string it
> gives me the letters between two and four
> 
> But when I ask it to print i[-1:-4] it does not print anything.
> 
> Jim
> 

Hi Jim,

good to see you are still working at it. And posting some bits of code 
to focus a response around is helpful :-)

 >>> 'my test string'[-1:-4]
''

This tells Python to start at the end of the string and go *forward*, 
one position at a time, up to, but not including, the -4 position. 
But, since there is nothing forward from the end of the string, this 
gives the empty string.

That suggests we need to one of two things:

 >>> 'my test string'[-1:-4:-1]
'gni'
 >>>

That says start at the end and go *backwards*, one position at a time, 
up to, but not including, the -4 position.

Or,

 >>> 'my test string'[-4:-1]
'rin'
 >>>

This says start at the -4 position and go forwards, one position at a 
time, up to, but not including the -1 position (i.e. the last letter).

We can also do
 >>> 'my test string'[-4:]
'ring'
 >>>

to remove the "but not including the -1 position" part of the instruction.

Try playing around with indexes using 1, 2, or 3, `slots'[*] and 
specifying all, none, or some, and see what comes out. If you don't 
understand the results, post again with the examples you don't understand.

[*] slots? I mean:
'I am indexed with 1 slot'[4]
'I am indexed with 2 slots'[4:6]
'I am indexed with 3 slots'[4:6:1]
'None of my slots have been "specified" '[:]

(There must be a better term that `slots', but it is 3am :-)

Best,

Brian vdB

From project5 at redrival.net  Thu Apr 14 09:08:52 2005
From: project5 at redrival.net (Andrei)
Date: Thu Apr 14 09:13:53 2005
Subject: [Tutor] Re: (no subject)
References: <008601c540b8$7fb47460$376931d8@DJM96611>
Message-ID: <loom.20050414T090416-58@post.gmane.org>

Jim and Laura Ahl <jcahl <at> psci.net> writes:

> How come when I ask it to print i[2:4] from an inputted string it gives me the
letters between two and four
> 
> But when I ask it to print i[-1:-4] it does not print anything.

Because the range is counting forward from -1 (the last element) onward, and
since there's nothing after the last element, it can't print anything. It's the
same as typing range(5,2) for example. If you want it to give you the letters
beteen -1 and -4 backwards, type i[-1:-4:-1] (I'm not sure that works in older
Pythons). If you need the last 4 letters, type i[-4:].

Yours,

Andrei

From ewald.ertl at hartter.com  Thu Apr 14 09:21:04 2005
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Thu Apr 14 09:21:08 2005
Subject: [Tutor] (no subject)
In-Reply-To: <008601c540b8$7fb47460$376931d8@DJM96611>
References: <008601c540b8$7fb47460$376931d8@DJM96611>
Message-ID: <20050414092104.0000396f@sunray2.hartter.com>

Hi Jim, 

on Thu, 14 Apr 2005 01:09:14 -0500  "Jim and Laura Ahl" <jcahl@psci.net> wrote :
---------------------------------------------------------------------------------------------

Jim and Laura Ahl > How come when I ask it to print i[2:4] from an inputted string it gives me the letters between two and four
Jim and Laura Ahl > 
Jim and Laura Ahl > But when I ask it to print i[-1:-4] it does not print anything.

Here you extract a slice starting with the last entry in i and ending much earlier, 
so you are asking for a slice with a negative length. 

Perhaps what you like is print i[-4:-1] ? 

------------------- end ----------------------
HTH Ewald 

From kent37 at tds.net  Thu Apr 14 12:23:36 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 14 12:23:41 2005
Subject: [Tutor] _winreg problems enumerating
In-Reply-To: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB32@mi06exm01.fhills.aieg.mot.com>
References: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB32@mi06exm01.fhills.aieg.mot.com>
Message-ID: <425E44A8.9000405@tds.net>

Gallagher Timothy-TIMOTHYG wrote:
> am new to python and want to learn this language.  I am having troubles
> finding examples and tutorials for use on windows boxes.  I do most of my
> stuff in perl and php but want better socket support, so I am giving python
> a try.  I am writing a script to connect to remote registry's because of
> this new IM virus.  I can create reg entries and delete them but I cannot
> enumerate them, here is my code.
> 
> import _winreg
> 
> host = "127.0.0.1" # local host
> key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
> E_key = _winreg.EnumValue(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")

_winreg is pretty low level. It can only access one level down from the current key. Here is a 
program that navigates a path in the registry one step at a time:

import _winreg

def openKey(key, path):
     pathElements = path.split('\\')
     for elem in pathElements:
         key = _winreg.OpenKey(key, elem)
     return key

key = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

runKey = openKey(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
print _winreg.QueryInfoKey(runKey)

Kent

From singingxduck at gmail.com  Thu Apr 14 12:58:29 2005
From: singingxduck at gmail.com (Orri Ganel)
Date: Thu Apr 14 12:58:33 2005
Subject: [Tutor] odd behavior within __init__
Message-ID: <3449428f050414035828eff1e8@mail.gmail.com>

Hello all,

As part of a project i'm doing (mostly for the fun of it), I have a
class which creates a sort of wrapper around any object to make it
suitable for use in a custom container.  However, if the class
receives an already wrapped object, I want it to just return the
object (same id and everything as the original). Now, the following
seems to work in the __init__ method (due to output), but then it
disappears as soon as the __init__ method is left:

class Node:
...
def __init__(self, cargo=None, prev=None, next=None, nod=False):
               """x.__init__(...) initializes x; see
x.__class__.__doc__ for signature"""
               if not isinstance(cargo, Node) or nod:
                   self.cargo = cargo
                   self.prev = prev
                   self.next = next
               else:
                   self = cargo
                   print id(self), id(cargo)
                   print self.cargo

>>> a = Node(1)
>>> b = Node(a)
12932600 12932600
1
>>> id(b)
12960632

Any ideas on why this happens, or suggestions as to how to implement
the behavior I'm looking for (in which b and a would refer to the same
object, have the same id, etc.), would be greatly appreciated.

Thanks in advance,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
From maxnoel_fr at yahoo.fr  Thu Apr 14 13:15:09 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 14 13:15:18 2005
Subject: [Tutor] odd behavior within __init__
In-Reply-To: <3449428f050414035828eff1e8@mail.gmail.com>
References: <3449428f050414035828eff1e8@mail.gmail.com>
Message-ID: <6feb54b6a8332af4a834590892d2a05e@yahoo.fr>


On Apr 14, 2005, at 12:58, Orri Ganel wrote:

>>>> a = Node(1)
>>>> b = Node(a)
> 12932600 12932600
> 1
>>>> id(b)
> 12960632
>
> Any ideas on why this happens, or suggestions as to how to implement
> the behavior I'm looking for (in which b and a would refer to the same
> object, have the same id, etc.), would be greatly appreciated.

	Well, if you want b and a to refer to the same object, just use b = a. 
Everything is a reference in Python, make use of this feature. (at that 
point, I expect Alan to drop in and explain why what I said is not 
entirely accurate, but good enough ;) )

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From rmkrauter at yahoo.com  Thu Apr 14 13:33:02 2005
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Thu Apr 14 13:33:50 2005
Subject: [Tutor] odd behavior within __init__
In-Reply-To: <3449428f050414035828eff1e8@mail.gmail.com>
References: <3449428f050414035828eff1e8@mail.gmail.com>
Message-ID: <425E54EE.4050701@yahoo.com>

Orri Ganel wrote:
> Hello all,
> 
> As part of a project i'm doing (mostly for the fun of it), I have a
> class which creates a sort of wrapper around any object to make it
> suitable for use in a custom container.  However, if the class
> receives an already wrapped object, I want it to just return the
> object (same id and everything as the original). Now, the following
> seems to work in the __init__ method (due to output), but then it
> disappears as soon as the __init__ method is left:
> 
> class Node:
> ...
> def __init__(self, cargo=None, prev=None, next=None, nod=False):
>                """x.__init__(...) initializes x; see
> x.__class__.__doc__ for signature"""
>                if not isinstance(cargo, Node) or nod:
>                    self.cargo = cargo
>                    self.prev = prev
>                    self.next = next
>                else:
>                    self = cargo
>                    print id(self), id(cargo)
>                    print self.cargo
> 
> 
>>>>a = Node(1)
>>>>b = Node(a)
> 
> 12932600 12932600
> 1
> 
>>>>id(b)
> 
> 12960632
> 
> Any ideas on why this happens, or suggestions as to how to implement
> the behavior I'm looking for (in which b and a would refer to the same
> object, have the same id, etc.), would be greatly appreciated.
> 
> Thanks in advance,
> Orri
> 


Orri,

Maybe you could use a factory. It would allow you to simplify your Node 
class, and encapsulate the instantiation behavior you want outside the 
class.


class Node(object):
     def __init__(self,cargo=None,prev=None,next=None):
         self.cargo = cargo
         self.prev = prev
         self.next = next

def factory(cargo=None,prev=None,next=None):
     if isinstance(cargo,Node):
         return cargo
     else:
         return Node(cargo,prev,next)


n1 = factory(1)
print id(n1)
n2 = factory(n1)
print id(n2)


Good luck,

Rich
From benmarkwell at gmail.com  Thu Apr 14 14:14:12 2005
From: benmarkwell at gmail.com (Ben Markwell)
Date: Thu Apr 14 14:14:26 2005
Subject: [Tutor] Question regarding the len function of a list while using a
	loop
Message-ID: <b9305117050414051443b383ff@mail.gmail.com>

Could somebody explain to me why the code I used to complete this exercise 
doesn't work. 
And how do you send an integer to len?

Thanks

Ben

==================================


*As an exercise, write a loop that traverses a list and prints the length of 
each element. What happens if you send an integer to len?

*>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
>>> i = 0
>>> while i < len(foo):
print len(foo[i])
i = i+1


5

Traceback (most recent call last):
File "<pyshell#28>", line 2, in -toplevel-
print len(foo[i])
TypeError: len() of unsized object
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/290cccd1/attachment.htm
From kent37 at tds.net  Thu Apr 14 14:18:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 14 14:18:36 2005
Subject: [Tutor] i need to see a var from any where in my app - im clueless
In-Reply-To: <425D7EB9.10204@cfl.rr.com>
References: <425D7EB9.10204@cfl.rr.com>
Message-ID: <425E5F91.5080407@tds.net>

pxlpluker wrote:
> i want to read a global (OPTIONS) from file1 from a class method
> (func1) in file2
> but i cant see the OPTION from func1
> 
> 
> ----------------------------------------------
> #file1.py
> import file2
> import sys
> 
> OPTION = sys.argv[1:]
> pass
> a=global2.class1()

Presumably you mean file2.class1() here; global2 is not defined

> a.func1()

One good option is just to pass OPTION as a parameter here:
a.func1(OPTION)

> 
> #file2.py
> import __main__

Alternately you can
import file1
then in func1() you can refer to file1.OPTION

Kent

> pass
> class class1:
> .    def func1(self):
> .        pass
> -------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From maxnoel_fr at yahoo.fr  Thu Apr 14 14:26:31 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 14 14:26:35 2005
Subject: [Tutor] Question regarding the len function of a list while using
	a loop
In-Reply-To: <b9305117050414051443b383ff@mail.gmail.com>
References: <b9305117050414051443b383ff@mail.gmail.com>
Message-ID: <9238a2523d0e4b24deffa22b9b3d2f86@yahoo.fr>


On Apr 14, 2005, at 14:14, Ben Markwell wrote:

> Could somebody explain to me why the code I used to complete this 
> exercise doesn't work.
>  And how do you send an integer to len?

	Well, I think you've successfully completed that exercise. len() 
doesn't work on integers because integers don't have a length.

	Think of it that way:
- "foo" is a string of length 3 (it contains 3 elements (characters))
- [1, 2, 3] is a list of length 3 (it contains 3 elements)
- {'a': 1, 'b': 2, 'foo': 5} is a dict of length 3 (it contains 3 
elements)
- 100 is an integer. How, as a human being, would you define its 
"length"? How many elements does it contain? It doesn't make sense, 
does it?

	Well, you have it. Numbers (ints, floats...) don't have a length. 
Therefore, calling len() on an integer is a non-sense that results in 
an exception.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From kent37 at tds.net  Thu Apr 14 14:30:52 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 14 14:31:04 2005
Subject: [Tutor] How to calculate pi with another formula?
In-Reply-To: <6.2.1.2.2.20050412032247.0552f3e0@rcblue.com>
References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com>	<41828B7F.1060608@aon.at>
	<6.2.1.2.2.20050412032247.0552f3e0@rcblue.com>
Message-ID: <425E627C.2040707@tds.net>

Dick Moores wrote:
> Now to my new question. I have an artist friend who knows an artist who 
> needs pi expressed in base 12. I don't know how many digits he needs, 
> but I think he'll take what he can get. Is there a way to use 
> math.log(x, base) with the decimal module to accomplish this? Or is 
> there another way? Or is there no way?

I think I would try to write a program that converts base-10 decimal fractions to base 12. Then feed 
it the output of a pi-generating program.

Kent

From cyresse at gmail.com  Thu Apr 14 14:49:48 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Thu Apr 14 14:49:53 2005
Subject: [Tutor] Is it cookielib or is it me?
Message-ID: <f2ff2d050414054977ed4eae@mail.gmail.com>

Hi all, 

It's probably me, actually, I was hoping someone who spot my error.
I am attempting to use cookielib, and running into difficulties.
I have been following this recipe - 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930
as an example, as the official documentation is a bit sparse, but it seems 
rather easy.

However, as my code will demonstrate -

>>> import re
>>> import urllib2
>>> import cookielib
>>>
>>> a = re.compile('href\=\"showthread.php\?s\=.+?pagenumber=(?P<pagenum>\d+?)\"',
re.IGNORECASE)
>>>
>>> Jar = cookielib.MozillaCookieJar(filename = 'c:/cookies.txt')
>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(Jar))
>>> urllib2.install_opener(opener)

Now, that's all by the recipe I linked too. No exceptions, so I figured it 
was good.

>>> f = urllib2.urlopen('
http://www.gpforums.co.nz/forumdisplay.php?s=&forumid=7029')
>>> j = f.read()
>>> ww = a.finditer(j)
>>> print ww.next().group()
href="showthread.php
?s=43bcebcf4dba6878802b25cb126ed1f7&threadid=267930&pagenumber=2"

Now, that's an issue. When I'm in a cookied session in Firefox, that link 
would be

showthread.php?s=&threadid=267930&pagenumber=2

Hmm... so I check by requesting an url that needs a cookie to get into - 

>>> f = urllib2.urlopen('
http://www.gpforums.co.nz/newthread.php?s=&action=newthread&forumid=7029')
>>> print f.read() 

<lots snipped>
You are not logged in, or you do not have permission to access this page. 
This could be due to one of several reasons:
</lots>

Now, I'm using the exact same cookies.txt ol Firefox uses, so I'm a little 
perplexed. I check to see if I've actually got a cookie - 

>>> print Jar
<_MozillaCookieJar.MozillaCookieJar[<Cookie bblastvisit=1113481269 for 
.gpforums.co.nz/>, <Cookie sessionhash=f6cba21ed58837ab935a564e6b9c3b05 for 
.gpforums.co.nz/>, <Cookie bblastvisit=1113481269 for .www.gpforums.co.nz/>, 
<Cookie sessionhash=f6cba21ed58837ab935a564e6b9c3b05 for 
.www.gpforums.co.nz/>]>

Which is exactly how that cookie looks, both in my cookies.txt, and when I 
packet sniff it going out.

I also tried it the way shown in the recipe, including changing the 
User-Agent - 

>>> txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows 
NT)'} 
>>> print txheaders
{'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
>>> theurl = '
http://www.gpforums.co.nz/newthread.php?s=&action=newthread&forumid=7029'
>>> req = urllib2.Request(theurl, data = None, headers = txheaders)
>>> handle = urllib2.urlopen(req)
>>> g = handle.read()
>>> print g

<lots snipped>
You are not logged in, or you do not have permission to access this page. 
This could be due to one of several reasons:
</lots>


So yeah, I'm at a loss, no doubt my mistake is painfully obvious when 
pointed out, but any pointing would be greatly appreciated.

Regards, 

Liam Clarke

<packet captures follow>

GET /newthread.php?s=&action=newthread&forumid=7029 HTTP/1.1\r\n
 Request Method: GET
 Request URI: /newthread.php?s=&action=newthread&forumid=7029
 Request Version: HTTP/1.1
 Accept-Encoding: identity\r\n
 Host: www.gpforums.co.nz\r\n
 Cookie: bblastvisit=1113481269; 
sessionhash=f6cba21ed58837ab935a564e6b9c3b05; bblastvisit=1113481269; 
sessionhash=f6cba21ed58837ab935a564e6b9c3b05\r\n
 Connection: close\r\n
 User-agent: Python-urllib/2.4\r\n
 \r\n

...and the response

Hypertext Transfer Protocol
 HTTP/1.1 200 OK\r\n
 Request Version: HTTP/1.1
 Response Code: 200
 Date: Thu, 14 Apr 2005 12:44:12 GMT\r\n
 Server: Apache/2.0.46 (CentOS)\r\n
 Accept-Ranges: bytes\r\n
 X-Powered-By: PHP/4.3.2\r\n
 Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=
gpforums.co.nz\r\n
 Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=
www.gpforums.co.nz\r\n
 Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=
gpforums.co.nz\r\n
 Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=
www.gpforums.co.nz\r\n


-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050415/7859d007/attachment-0001.html
From cpu.crazy at gmail.com  Thu Apr 14 00:57:27 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 14 15:20:57 2005
Subject: [Tutor] Craps, eternal loop (Joseph Q.)
Message-ID: <6.1.0.6.2.20050413165446.01ebd8b0@pop.gmail.com>

I get an eternal loop on this game that I don't want and can't figure out 
how to fix.
BTW any of you know the rules to craps? I don't remember them all so this 
game may be different than the casino version.

Here's my code:

import random

# generate random numbers 1 - 6

loop = True
def play_again():
     play_again = raw_input("Play again? (Y/N)\n>> ")
     if play_again == ("Y") or ("y") or ("Yes") or ("yes") or ("YES"):
         crapps()
     else:
         loop = False
         print "\nCome play again."

def roll():
     raw_input("\nPress the 'Enter' key (Return) to roll.")

def crapps():
     while loop:
         die1 = random.randrange(6) + 1
         die2 = random.randrange(6) + 1
         die1_2 = random.randrange(6) + 1
         die2_2 = random.randrange(6) + 1

         total_cash = 100

         title_ = "The fun game of craps."
         print title_.title()

         print "You have %d dollars on hand." % total_cash
         print "Now you will wager 10 dollars for the game."
         total = die1 + die2
         total_2 = die1_2 + die2_2

         roll()
         print "\nYou rolled a", die1, "and a", die2, "for a total of", total
         raw_input("\nPress the 'Enter' key (Return) to let your opponent 
roll")
         print "\nYour opponent rolled a", die1_2, "and a", die2_2, "for a 
total of", total_2

         if total > total_2:
             total_cash = total_cash + 10
             print "\nYou won! You now have %d dollars on hand." % total_cash
             play_again()


         else:
             total_cash = total_cash - 10
             print "You lost. Too bad. Better luck next time."
             if total_cash < 0:
                 print "Get out of this casino and work! You're in debt!"
             elif total_cash == 0:
                 print "Better stop now before you get into debt."

             play_again()

crapps()

I also can't get the counter to save the added or removed money. every time 
I play again, I always have $100

Thanks,
    Joe

From albertito_g at hotmail.com  Thu Apr 14 16:05:57 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu Apr 14 16:06:02 2005
Subject: [Tutor] Question regarding the len function of a list while using
	aloop
In-Reply-To: <b9305117050414051443b383ff@mail.gmail.com>
Message-ID: <BAY106-F2101CB1401448F27A6D25189350@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/8191dc60/attachment.htm
From TIMOTHYG at motorola.com  Thu Apr 14 16:06:12 2005
From: TIMOTHYG at motorola.com (Gallagher Timothy-TIMOTHYG)
Date: Thu Apr 14 16:06:19 2005
Subject: [Tutor] _winreg problems enumerating
Message-ID: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB92@mi06exm01.fhills.aieg.mot.com>

It seems to work but the output isn't right.  I do have 10 things in the Run
folder but the out put is not telling me what they are, it just says none
for each entry.  I guess that I am not sure what to do now.  I can do this
in Perl and other languages but I really want to learn Python.

Here is what I have done:
import _winreg
host = "127.0.0.1" # local host
key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
hkey = _winreg.OpenKey(key,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
i = 0
regKeys = []
try:
  while 1:
    test_key = regKeys.append(_winreg.EnumValue(hkey, i))
    print test_key
    i += 1
except EnvironmentError:
     pass

when I run this script I am getting this for my output:
None
None
None
None
None
None
None
None
None
None



Thanks 
Tim

Timothy F. Gallagher
Timothyg- AT 0-Motorola.com


?

________________________________________
From: Liam Clarke [mailto:cyresse@gmail.com] 
Sent: Wednesday, April 13, 2005 9:45 PM
To: Gallagher Timothy-TIMOTHYG; tutor@python.org
Subject: Re: [Tutor] _winreg problems enumerating

Hi Tim, 

Hmmm, I may have to play with _winreg, is is new with Python 2.4?

Anyway, from the _winreg docs - 
EnumValue(
key, index)
Enumerates values of an open registry key, returning a tuple. 
key is an already open key, or any one of the predefined HKEY_* constants. 
index is an integer that identifies the index of the value to retrieve. 
The function retrieves the name of one subkey each time it is called. It is
typically called repeatedly, until an EnvironmentError exception is raised,
indicating no more values.

There's your issue - 
E_key =
_winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
The second value needs to be an integer that is an index.
Typical usage would look like this - 
i = 0
regKeys = []
try:
? while 1:
????? regKeys.append(_winreg.EnumValue(key, i))
?????? i += 1
except EnvironmentError:
???? pass


Good luck, 

Liam Clarke

On 4/14/05, Gallagher Timothy-TIMOTHYG <TIMOTHYG@motorola.com> wrote:
am new to python and want to learn this language.??I am having troubles
finding examples and tutorials for use on windows boxes.??I do most of my
stuff in perl and php but want better socket support, so I am giving python 
a try.??I am writing a script to connect to remote registry's because of
this new IM virus.??I can create reg entries and delete them but I cannot
enumerate them, here is my code.

import _winreg

host = " 127.0.0.1" # local host
key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
E_key = _winreg.EnumValue(key,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") 

I get an error when I run the script:

Traceback (most recent call last):
??File "reg4.py", line 9, in ?
????E_key = _winreg.EnumValue(key,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\R 
un")
TypeError: an integer is required

Can someone tell me what I am doing wrong???

Thanks

Timothy F. Gallagher
Timothyg- at -Motorola.com

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



-- 
'There is only one basic human right, and that is to do as you damn well
please.
And with it comes the only basic human duty, to take the consequences.' 
From John.Gooch at echostar.com  Thu Apr 14 16:55:47 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Thu Apr 14 16:56:07 2005
Subject: [Tutor] _winreg problems enumerating
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2CB@riv-excha5.echostar.com>

Let me know if there is a Tkinter list that is more appropriate for this
question.

I am writing a function whose job is it delete all of the selected items in
a Listbox. The only ways I can think of doing this is to 
1) Get list of selected items using the listbox.curselection and then delete
each item one at a time.
2) Iterate through each item in the listbox and then call
listbox.delete(index) on each one that is selected.

The problem with each one is:
1) once the first item in the list of indexes is deleted, I think all of the
remaining items will "shift down" and their index number will change,
resulting in problem such as "index out of bounds", or deleting the wrong
item.
2) Skip over a selected item if there are two selected items next to each
other. i.e. indexes 1 and 2 are selected, the for loop hits index 1 and
deletes it, the original "1" is gone and now the previous "2" becomes "1"(
shifts down ), the for loop continues on to index "2", failing to delete the
new index "1". 

Is there an algorithm that can delete the selected items in one pass? Or
would I have to iterate over the listbox items until finally it does not
find any selected items.

Thank You, 

John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 

From cpu.crazy at gmail.com  Thu Apr 14 16:46:13 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 14 17:13:30 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Message-ID: <6.1.0.6.2.20050414084315.01f2f680@pop.gmail.com>

 >>>>if letter == 'O':
 >    print letter + 'u' + suffix
 >elif 'Q':
 >    print letter + 'u' + suffic
 >else:
 >    print letter + suffix
 >
 >Do you see?  The == "binds more tightly" than the or.  And, in python, 'Q' is
 >considered True for the purposes of tests.
 >
 >So this is what happens:
 >
 >>>> prefixes = 'JKLMNOPQ'
 >>>> suffix = 'ack'
 >>>>
 >>>> for letter in prefixes:
 >
 >...   if letter == ('O') or ('Q'):
 >...     print letter + 'u' + suffix
 >...   else:
 >...     print letter + suffix
 >...
 >Juack
 >Kuack
 >Luack
 >Muack
 >Nuack
 >Ouack
 >Puack
 >Quack
 >
 >>>>
 >
 >What you can do instead is this:
 >
 >for letter in prefixes:
 >    if letter in ['O', 'Q']:
 >        print letter + 'u' + suffix
 >    else:
 >        print letter + suffix

Oh, ok. Sorry, my bad :)
So there is a special use for ==. I must look into this.
Thanks,
	Joe


From jsmith at medplus.com  Thu Apr 14 17:28:01 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Thu Apr 14 17:28:31 2005
Subject: [Tutor] Craps, eternal loop (Joseph Q.)
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C033942BD@medexch1.medplus.com>

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Joseph Quigley
Sent: Wednesday, April 13, 2005 6:57 PM
To: tutor@python.org
Subject: [Tutor] Craps, eternal loop (Joseph Q.)


>I get an eternal loop on this game that I don't want and can't figure
out 
>how to fix.
>BTW any of you know the rules to craps? I don't remember them all so
this 
>game may be different than the casino version.

This is your problem:
     if play_again == ("Y") or ("y") or ("Yes") or ("yes") or ("YES"):

Which is interpreted as (note the extra parens):
     if (play_again == ("Y")) or ("y") or ("Yes") or ("yes") or ("YES"):

What you want is:
     if play_again in ("Y","y","Yes","yes","YES"):
Or better yet:
     if play_again.upper() in ('Y','YES'):

Jeff
From jcahl at psci.net  Thu Apr 14 18:08:22 2005
From: jcahl at psci.net (Jim and Laura Ahl)
Date: Thu Apr 14 18:09:07 2005
Subject: [Tutor] (no subject)
References: <008601c540b8$7fb47460$376931d8@DJM96611>
	<425E1776.1040009@po-box.mcgill.ca>
Message-ID: <003f01c5410c$322fe5e0$486931d8@DJM96611>

Jim and Laura Ahl said unto the world upon 2005-04-14 02:09:
> How come when I ask it to print i[2:4] from an inputted string it
> gives me the letters between two and four
> 
> But when I ask it to print i[-1:-4] it does not print anything.
> 
> Jim
> 

Hi Jim,

good to see you are still working at it. And posting some bits of code 
to focus a response around is helpful :-)

 >>> 'my test string'[-1:-4]
''

This tells Python to start at the end of the string and go *forward*, 
one position at a time, up to, but not including, the -4 position. 
But, since there is nothing forward from the end of the string, this 
gives the empty string.

That suggests we need to one of two things:

 >>> 'my test string'[-1:-4:-1]
'gni'
 >>>
When I do this it tells me that the sequence index must be an integer.  What is that telling me and how do I fix that? Jim

That says start at the end and go *backwards*, one position at a time, 
up to, but not including, the -4 position.

Or,

 >>> 'my test string'[-4:-1]
'rin'
 >>>

This says start at the -4 position and go forwards, one position at a 
time, up to, but not including the -1 position (i.e. the last letter).

We can also do
 >>> 'my test string'[-4:]
'ring'
 >>>
Ok, I agree with what this is doing.  So if I type in  print i[-1] this gives me that last letter of the string. But when I type in  print i[-1:] it does nothing, because there is nothing after -1.  So I need to find some charecter that takes the string in the opposite direction.  like  print i[-1:-4]  but that does not print anything (why)?  When I put another number behind this it gives me it must be an integer    print  i[-1:-4:-1]  so what have I got messed up and why can't this work?  And if an iputted word or string in typed in how do you tell it to go to the end of it and stop?  I assumed that  print i[-1:]  would have done it

to remove the "but not including the -1 position" part of the instruction.

Try playing around with indexes using 1, 2, or 3, `slots'[*] and 
specifying all, none, or some, and see what comes out. If you don't 
understand the results, post again with the examples you don't understand.

[*] slots? I mean:
'I am indexed with 1 slot'[4]
'I am indexed with 2 slots'[4:6]
'I am indexed with 3 slots'[4:6:1]
'None of my slots have been "specified" '[:]

(There must be a better term that `slots', but it is 3am :-)

Best,

Brian vdB

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/44f9c000/attachment.htm
From kent37 at tds.net  Thu Apr 14 19:00:15 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 14 19:00:19 2005
Subject: [Tutor] (no subject)
In-Reply-To: <003f01c5410c$322fe5e0$486931d8@DJM96611>
References: <008601c540b8$7fb47460$376931d8@DJM96611>	<425E1776.1040009@po-box.mcgill.ca>
	<003f01c5410c$322fe5e0$486931d8@DJM96611>
Message-ID: <425EA19F.4000809@tds.net>

Jim and Laura Ahl wrote:
>  >>> 'my test string'[-1:-4:-1]
> 'gni'
>  >>>
> When I do this it tells me that the sequence index must be an integer.  
> What is that telling me and how do I fix that? Jim

It's telling you that it doesn't support "extended slicing" - indexes with three components. Upgrade 
to Python 2.3 or later to make it work.

Kent

From cpu.crazy at gmail.com  Thu Apr 14 18:59:50 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 14 19:00:58 2005
Subject: [Tutor] Craps, eternal loop (Joseph Q.)
In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C033942BD@medexch1.medplus. com>
References: <C4C644CF4ADA9448904C3E8BACC4B97C033942BD@medexch1.medplus.com>
Message-ID: <6.1.0.6.2.20050414105833.01f0fbb0@pop.gmail.com>

Thanks a lot. Now I need to find the rules.

BTW. What about the counter? If I win I get 110 dollars. On the next round 
I start out with 100 dollars again, when I should have 110!

Joe

From bvande at po-box.mcgill.ca  Thu Apr 14 19:15:44 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Thu Apr 14 19:17:07 2005
Subject: [Tutor] Question regarding the len function of a list while using
	a	loop
In-Reply-To: <b9305117050414051443b383ff@mail.gmail.com>
References: <b9305117050414051443b383ff@mail.gmail.com>
Message-ID: <425EA540.8060100@po-box.mcgill.ca>

Ben Markwell said unto the world upon 2005-04-14 08:14:
> Could somebody explain to me why the code I used to complete this exercise 
> doesn't work. 
> And how do you send an integer to len?
> 
> Thanks
> 
> Ben
> 
> ==================================
> 
> 
> *As an exercise, write a loop that traverses a list and prints the length of 
> each element. What happens if you send an integer to len?
> 
> *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
> 
>>>>i = 0
>>>>while i < len(foo):
> 
> print len(foo[i])
> i = i+1
> 
> 
> 5
> 
> Traceback (most recent call last):
> File "<pyshell#28>", line 2, in -toplevel-
> print len(foo[i])
> TypeError: len() of unsized object


Hi Ben,

Max and Alberto have already explained why you got the error message.

Depending on the context in which you are doing this, the having the 
error crash the program might be what is desired. (I get that the 
context is simply an exercise, but let's pretend it is an actual 
program, written in anger :-).) Or, you might want your program to 
handle the problem more elegantly.

Using the general framework Alberto suggested, here's a way to do that 
(I've also thrown some string formatting in to make the output more 
friendly):

 >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
 >>> for item in foo:
... 	try:
... 		print "Item: %s has length %s" %(item, len(item))
... 	except TypeError:
... 		print "Item: %s has no length" %item
... 		
Item: spam! has length 5
Item: 1 has no length
Item: ['brie', 'cheddar', 'swiss'] has length 3
Item: [1, 2, 3] has length 3
 >>>

This works by attempting to do the thing in the try part, and catching 
any case than raises a TypeError (as your original code did), doing 
the routine of the except block instead.

Does that make sense?

If not, post back and I can try to explain in more detail.

Best,

Brian vdB

From geek_show at dsl.pipex.com  Thu Apr 14 19:22:03 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Thu Apr 14 19:22:11 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050414084315.01f2f680@pop.gmail.com>
References: <6.1.0.6.2.20050414084315.01f2f680@pop.gmail.com>
Message-ID: <425EA6BB.5070902@dsl.pipex.com>

Joseph Quigley wrote:
>  >>>>if letter == 'O':
>  >    print letter + 'u' + suffix
>  >elif 'Q':
>  >    print letter + 'u' + suffic
>  >else:
>  >    print letter + suffix
>  >
>  >Do you see?  The == "binds more tightly" than the or.  And, in python, 
> 'Q' is
>  >considered True for the purposes of tests.
>  >
>  >So this is what happens:
>  >
>  >>>> prefixes = 'JKLMNOPQ'
>  >>>> suffix = 'ack'
>  >>>>
>  >>>> for letter in prefixes:
>  >
>  >...   if letter == ('O') or ('Q'):
>  >...     print letter + 'u' + suffix
>  >...   else:
>  >...     print letter + suffix
>  >...
>  >Juack
>  >Kuack
>  >Luack
>  >Muack
>  >Nuack
>  >Ouack
>  >Puack
>  >Quack
>  >
>  >>>>
>  >
>  >What you can do instead is this:
>  >
>  >for letter in prefixes:
>  >    if letter in ['O', 'Q']:
>  >        print letter + 'u' + suffix
>  >    else:
>  >        print letter + suffix
> 
> Oh, ok. Sorry, my bad :)
> So there is a special use for ==. I must look into this.
> Thanks,
>     Joe
> 


"=" is for assignment of a value to a variable, as in a = 33
"==" is equivalent to, as in 2 * 2 == 4

I've been caught out on more than a few occasions on this distinction!! :)

HtH

/j
From dyoo at hkn.eecs.berkeley.edu  Thu Apr 14 19:30:48 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 14 19:30:52 2005
Subject: [Tutor] Python backwards program (fwd)
Message-ID: <Pine.LNX.4.44.0504141030410.19957-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Thu, 14 Apr 2005 00:41:40 -0500
From: Jim and Laura Ahl <jcahl@psci.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Python backwards program

I thought you were on me a bit but I am so frustrated at this point.  My instructor wrote and told me it was easy.  So if it is easy why am I having so much trouble.  I figured the other three programs by just reading the book and working on the computer.  Does the 2.2 python have the ability to do this?

I think that the program will work with something like this in an expanded form.

The following gives me the last letter of the string.

backwords=raw_input("enter number or string:")
print backwords[-1]

I have looked on a couple of sites and it says to use
s.reverse()
this does not work for some reason

Jim
  ----- Original Message -----
  From: Danny Yoo
  To: Jim and Laura Ahl
  Cc: Tutor ; Feziwe Mpondo
  Sent: Thursday, April 14, 2005 12:24 AM
  Subject: Re: [Tutor] Python backwards program




  > We're not going to do your homework problems; please understand that we
  > actually don't care if you get your homework done.  And I really hope that
  > people don't just start blurting stuff at Jim for the other three homework
  > problems he's dumping on us.

  Hi Jim,

  Ok, I screwed up big time today, and I'd better say this in public, so
  that people know that I made a huge mistake.  I usually make small ones
  that can be easily corrected, but I get the feeling I did damage today,
  and I wish I could take it back.

  Jim, I sincerely apologize about snapping at you like that.  I was wrong
  to do so, especially since I completely misread your sentence.  I thought
  you were saying that those were three other problems that you had to do
  soon, when you had actually wrote that those were three programs that you
  had written already.

  But even so, I had no excuse to say things like that.  I will try to
  better answer your questions, without making such stupid mistakes.  And I
  hope that folks on the list will forgive me for the bad temper in my last
  emails.

  Sincerely,
  Danny Yoo


From Andrew.Sakal at wellsfargo.com  Thu Apr 14 01:54:46 2005
From: Andrew.Sakal at wellsfargo.com (Andrew.Sakal@wellsfargo.com)
Date: Thu Apr 14 19:32:11 2005
Subject: [Tutor] Text Boxes - deleting and inserting
Message-ID: <B5610F8C7569934E8E65080E1FCCF024448DDC@msgswbmnmsp04.wellsfargo.com>

Sean Fioritto?

 

If this is the same Sean who I used to live behind in mesa, AZ...drop me
a line some time!

 

Andrew Sakal

Personal Banker

Desert Foothills

MAC S3836-011

(480)460-4166 office

 

This message may contain confidential and/or privileged information. If
you are not the addressee or authorized to receive this for the
addressee, you must not use, copy, disclose, or take any action based on
this message or any information herein. If you have received this
message in error, please advise the sender immediately by reply e-mail
and delete this message. Thank you for your cooperation.

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050413/47734a18/attachment.htm
From bvande at po-box.mcgill.ca  Thu Apr 14 19:31:51 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Thu Apr 14 19:33:09 2005
Subject: [Tutor] New to programming question (Ben M.) (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050414084315.01f2f680@pop.gmail.com>
References: <6.1.0.6.2.20050414084315.01f2f680@pop.gmail.com>
Message-ID: <425EA907.9030006@po-box.mcgill.ca>

Joseph Quigley said unto the world upon 2005-04-14 10:46:

<SNIP>

>  >Do you see?  The == "binds more tightly" than the or.  And, in python, 
> 'Q' is
>  >considered True for the purposes of tests.

<SNIP>

>  >What you can do instead is this:
>  >
>  >for letter in prefixes:
>  >    if letter in ['O', 'Q']:
>  >        print letter + 'u' + suffix
>  >    else:
>  >        print letter + suffix
> 
> Oh, ok. Sorry, my bad :)
> So there is a special use for ==. I must look into this.
> Thanks,
>     Joe

Hi Joe,

I'm not sure what you mean by a "special use", but maybe this will help:

In arithmetic:

4 * 10 + 2 = 42

as

( 4 * 10 + 2 ) = ( ( 4 * 10 ) + 2 )

This is because '*' comes before '+' in the oder of operations when 
parenthesis don't settle the issue. One way to express that is to say 
"'*' binds more tightly than '+'".

In Python '==' binds more tightly than 'or'. So:

( a == b or c ) == ( ( a == b ) or c )

Hence:
 >>> 42==0 or True
True
 >>> 42 == 0 or 42 == True
False
 >>> # Better is
 >>> 42 in (0, True)
False
 >>>

Does that help?

Best,

Brian vdB

From bill.mill at gmail.com  Thu Apr 14 19:53:41 2005
From: bill.mill at gmail.com (Bill Mill)
Date: Thu Apr 14 19:53:46 2005
Subject: [Tutor] How to calculate pi with another formula?
In-Reply-To: <425E627C.2040707@tds.net>
References: <6.1.2.0.2.20041028093827.06b2ac00@rcblue.com>
	<41828B7F.1060608@aon.at>
	<6.2.1.2.2.20050412032247.0552f3e0@rcblue.com>
	<425E627C.2040707@tds.net>
Message-ID: <797fe3d4050414105328c89a9d@mail.gmail.com>

On 4/14/05, Kent Johnson <kent37@tds.net> wrote:
> Dick Moores wrote:
> > Now to my new question. I have an artist friend who knows an artist who
> > needs pi expressed in base 12. I don't know how many digits he needs,
> > but I think he'll take what he can get. Is there a way to use
> > math.log(x, base) with the decimal module to accomplish this? Or is
> > there another way? Or is there no way?
> 
> I think I would try to write a program that converts base-10 decimal fractions to base 12. Then feed
> it the output of a pi-generating program.
> 

I just thought I would reference the fascinating thread that ensued
from this request on comp.lang.python :
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/1839b7d733ae37d0/3b5f7138f0e5fbd1?q=pi+base+12&rnum=1#3b5f7138f0e5fbd1

Peace
Bill Mill
bill.mill at gmail.com
From project5 at redrival.net  Thu Apr 14 19:55:18 2005
From: project5 at redrival.net (Andrei)
Date: Thu Apr 14 20:01:17 2005
Subject: [Tutor] Re: Craps, eternal loop (Joseph Q.)
References: <6.1.0.6.2.20050413165446.01ebd8b0@pop.gmail.com>
Message-ID: <loom.20050414T194929-661@post.gmane.org>

Joseph Quigley <cpu.crazy <at> gmail.com> writes:

> I also can't get the counter to save the added or removed money. every time 
> I play again, I always have $100

Without reading all the code (there might be other issues) I've snipped the
parts of the code away which are not interesting to this question, which
highlights the cause:

def play_again():
    crapps()

def crapps():
     while loop:
         total_cash = 100
         if total > total_2:
             total_cash = total_cash + 10
             play_again()
         else:
             total_cash = total_cash - 10
             play_again()


total_cash is a local variable in the crapps function and is reset to 100 at the
start of every loop. Move this initialization to a different place (I'm not sure
when exactly you want to reset it as I don't know your intentions, but perhaps
before the loop, or make it a global variable and only initialize it at the
start of the program).

Yours,

Andrei

From bvande at po-box.mcgill.ca  Thu Apr 14 20:04:44 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Thu Apr 14 20:06:52 2005
Subject: [Tutor] (no subject)
In-Reply-To: <003f01c5410c$322fe5e0$486931d8@DJM96611>
References: <008601c540b8$7fb47460$376931d8@DJM96611>
	<425E1776.1040009@po-box.mcgill.ca>
	<003f01c5410c$322fe5e0$486931d8@DJM96611>
Message-ID: <425EB0BC.3060600@po-box.mcgill.ca>

Jim and Laura Ahl said unto the world upon 2005-04-14 12:08:

<SNIP>

>>>> 'my test string'[-1:-4:-1]
> 'gni'
>>>> 
> When I do this it tells me that the sequence index must be an 
> integer.  What is that telling me and how do I fix that? Jim


Kent addressed that already. But, my mistake for not thinking about
which versions of Python my examples required.

<SNIP>

> We can also do
>>>> 'my test string'[-4:]
> 'ring'
>>>> 
> Ok, I agree with what this is doing.  So if I type in  print i[-1] 
> this gives me that last letter of the string. But when I type in 
> print i[-1:] it does nothing, because there is nothing after -1. So
>  I need to find some charecter that takes the string in the 
> opposite direction.  like  print i[-1:-4]  but that does not print 
> anything (why)?

 >>> '[-1:] does give something!'[-1:]
'!'
 >>>

Again (from my last post on the thread):

> This tells Python to start at the end of the string and go 
> *forward*, one position at a time, up to, but not including, the -4
>  position. But, since there is nothing forward from the end of the
>  string, this gives the empty string.

I don't know how to say that more clearly :-) Perhaps you could say
more about why it doesn't help? (It is also possible you weren't 
asking again -- your email client isn't putting in quote marks so it 
is hard to be sure, and I've deleted the original email. If you 
weren't asking again; never mind ;-)


> When I put another number behind this it gives me it must be an 
> integer    print  i[-1:-4:-1]  so what have I got messed up and why
>  can't this work?

Again, see Kent's post.


> And if an iputted word or string in typed in how do you tell it to
> go to the end of it and stop?  I assumed that print i[-1:]  would
> have done it

Go to the end from where?
 >>> 'a string'[-1:] # "start at the last character, and go forward."
'g'
 >>> 'a string'[3:]  # "start at the 4th character, and go forward."
'tring'
 >>> 'a string'[0:]  # "start at the 1st character, and go forward."
'a string'
 >>>

([3:] gives 4th on, as indicies start at 0; thus [0:] gives the whole 
string.)

<SNIP>

(from my last post on the thread):
> [*] slots? I mean: 'I am indexed with 1 slot'[4] 'I am indexed with
>  2 slots'[4:6] 'I am indexed with 3 slots'[4:6:1] 'None of my slots
>  have been "specified" '[:]
> 
> (There must be a better term that `slots', but it is 3am :-)

Some one wrote me off list to mention I was looking for "index 
parameters". Thanks, anonymous donor!

Best to all,

Brian vdB

From bvande at po-box.mcgill.ca  Thu Apr 14 20:22:51 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Thu Apr 14 20:25:20 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <Pine.LNX.4.44.0504141030410.19957-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504141030410.19957-100000@hkn.eecs.berkeley.edu>
Message-ID: <425EB4FB.3050507@po-box.mcgill.ca>

> 
> ---------- Forwarded message ----------
> Date: Thu, 14 Apr 2005 00:41:40 -0500
> From: Jim and Laura Ahl <jcahl@psci.net>
> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] Python backwards program
> 
> I thought you were on me a bit but I am so frustrated at this point.  My instructor wrote and told me it was easy.  So if it is easy why am I having so much trouble.  I figured the other three programs by just reading the book and working on the computer.  Does the 2.2 python have the ability to do this?
> 
> I think that the program will work with something like this in an expanded form.
> 
> The following gives me the last letter of the string.
> 
> backwords=raw_input("enter number or string:")
> print backwords[-1]
> 
> I have looked on a couple of sites and it says to use
> s.reverse()
> this does not work for some reason
> 
> Jim

Hi Jim,

do you know about the dir function? You can use it to show you all 
methods of an object. (Methods are, more or less, the things an object 
comes with support for doing to it. Ugly vagueness, but roughly right.)

The output of dir statements on my computer will be a bit different 
than yours, as I am using Python 2.4.1. But here is the result of 
doing dir on a string and a list:

 >>> dir('a string')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__ge__', '__getattribute__', '__getitem__', 
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', 
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 
'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 >>> dir(['a', 'list'])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', 
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__setslice__', '__str__', 'append', 'count', 'extend', 'index', 
'insert', 'pop', 'remove', 'reverse', 'sort']
 >>>

 >>> 'some string'.reverse()
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'str' object has no attribute 'reverse'
 >>>

And, that is what we would expect, as dir('a string') didn't show us 
any reverse method. *But* dir(['a', 'list']) did! So:

 >>> my_list = ['this', 'is', 'my', 'list']
 >>> my_list.reverse()
 >>> my_list
['list', 'my', 'is', 'this']
 >>>

Does your version of Python have list.reverse()? (I've no idea when 
that got in, but I assume its been there since God was a lad.)

If so, one way you could solve your problem would be to take a string, 
convert it into a list, reverse the list, and then make a string out 
of the list again. To try that, you will want to combine some or all 
of the list and str builtin functions, and the string.split and 
string.join methods.[*] I'm still leaving work for you to do -- which 
pieces and how to combine them? Give it a try and show us what you've 
done.

[*] Really old Pythons do not have string methods at all. If yours is 
that old, we will have to suggest something else.

Run this:

 >>> if 'join' in dir(str):
         print "My Python version has string methods"
     else:
         print "Oh, oh. I *really* need to upgrade my Python"

HTH,

Brian vdB

From dyoo at hkn.eecs.berkeley.edu  Thu Apr 14 20:52:12 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 14 20:52:17 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <Pine.LNX.4.44.0504141030410.19957-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504141147360.1011-100000@hkn.eecs.berkeley.edu>


> Does the 2.2 python have the ability to do this?

Hi Jim,

Python 2.2 is actually a bit old; you may want to update the version of
Python on your system to Python 2.4.  You can find it here:

    http://www.python.org/2.4/

A lot of the approaches you were trying earlier used features that were
added in the 2.3 or 2.4 Python series; they're absent from Python 2.2.


> The following gives me the last letter of the string.
>
> backwords=raw_input("enter number or string:")
> print backwords[-1]

Yes, this is an interesting approach!  We can go along this approach a
little more, if you'd like.  The code above is getting the last letter, so
we're closer to printing out the word backwards.

How would you print out the second to last letter of the string?

From john.ertl at fnmoc.navy.mil  Thu Apr 14 20:59:42 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Thu Apr 14 20:56:38 2005
Subject: [Tutor] how to display an image using python
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C60D@lanexc107p.fnmoc.navy.mil>

All,

I have asked this question before, but one more time most have commented
about manipulation but displaying the image has become the big issue.  I
want to display png and gif images on a Linux machine using python.  I am
using PyNGL to make the images and PIL to manipulate them but I cannot load
xv on the machines and PIL uses xv to display.  I have looked at
PythonMagick but I could not even get past installing it.  It does not have
a setup.py and uses boost.  I am hoping for a more straightforward Python
way.  

Thanks,

John Ertl 
From jsoares at Safe-mail.net  Thu Apr 14 21:06:36 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Thu Apr 14 21:06:49 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
Message-ID: <N1-8X3PiOiw@Safe-mail.net>



I've seen a couple of nice tutorials on recursion, and a lot of awful ones. The latter always trot out the fibonacci and factorial examples for some reason. And that's about it! The good ones showed me how to trace through recursive calls and gave me practical examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc)



What I want to know is this: what are other specific situations where a recursive algorithm would be better or easier to program than an iterative one?



I know that the Eight Queens puzzle is a good recursion candidate, but I don't understand why as yet. I'm still on simple recursion, and am just beginning to understand backtracking in a simple example, like adding numbers in an array.



>From what I've read, it seems like two dimensional games or puzzles would be good candidates for recursive programming. Also, things like random maze generation...I saw something on Pierzonski's(sic) Carpet, but I didn't really understand it. I did understand that anything to do with manipulating patterns might be a good recursion candidate.



If this is too general a question, perhaps you can tell me when NOT to use recursion(where it would be inappropriate or inefficient).



I'd certainly like to learn what seems like a powerful tool, but I don't want to use it where I shouldn't.



Any hints appreciated.



John



=================================
John Soares, Webmaster
Family Safe Surfinghttp://www.family-safe-surfing.net
jsoares@family-safe-surfing.net
jsoares@safe-mail.net

"Your best bet for online family-friendly resources"
=================================



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/ac31f9ca/attachment.html
From dyoo at hkn.eecs.berkeley.edu  Thu Apr 14 21:25:18 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 14 21:25:23 2005
Subject: [Tutor] how to display an image using python
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C60D@lanexc107p.fnmoc.navy.mil>
Message-ID: <Pine.LNX.4.44.0504141212290.8093-100000@hkn.eecs.berkeley.edu>



> xv on the machines and PIL uses xv to display.  I have looked at
> PythonMagick but I could not even get past installing it.  It does not have
> a setup.py and uses boost.  I am hoping for a more straightforward Python
> way.

Hi John,


You may want to try PyGame:

    http://www.pygame.org/

Although it's mainly for game development, it provides a simple graphics
API that we can use to display images.  If you're running Linux, it's
likely that you have the Simple DirectMedia Layer (SDL) library installed.


I'm not too familiar with the API, but I was able to get some kind of
working example.  We can first construct an image surface:

    http://www.pygame.org/docs/ref/pygame_image.html

by loading one from our file:

######
>>> import pygame.image
>>> picture = pygame.image.load("na-cat.gif")
>>>
>>> picture.get_size()
(256, 48)
######


At this point, 'picture' contains a "surface":

    http://www.pygame.org/docs/ref/Surface.html

We can copy ('blit') this surface onto our main screen:


######
>>> import pygame.display
>>> pygame.display.set_mode(picture.get_size())
<Surface(256x48x16 SW)>
>>> main_surface = pygame.display.get_surface()
>>> main_surface.blit(picture, (0, 0))
>>> pygame.display.update()
######


I hope this helps!

From john.ertl at fnmoc.navy.mil  Thu Apr 14 21:33:32 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Thu Apr 14 21:30:28 2005
Subject: [Tutor] how to display an image using python
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C60E@lanexc107p.fnmoc.navy.mil>

Danny,

Pygame.org...I would not have thought to look there.  In my google it did
not pop up.  I will definitely take a look and thanks for the example. 

John Ertl 

-----Original Message-----
From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
Sent: Thursday, April 14, 2005 12:25
To: Ertl, John
Cc: Tutor
Subject: Re: [Tutor] how to display an image using python


> xv on the machines and PIL uses xv to display.  I have looked at
> PythonMagick but I could not even get past installing it.  It does not
have
> a setup.py and uses boost.  I am hoping for a more straightforward Python
> way.

Hi John,


You may want to try PyGame:

    http://www.pygame.org/

Although it's mainly for game development, it provides a simple graphics
API that we can use to display images.  If you're running Linux, it's
likely that you have the Simple DirectMedia Layer (SDL) library installed.


I'm not too familiar with the API, but I was able to get some kind of
working example.  We can first construct an image surface:

    http://www.pygame.org/docs/ref/pygame_image.html

by loading one from our file:

######
>>> import pygame.image
>>> picture = pygame.image.load("na-cat.gif")
>>>
>>> picture.get_size()
(256, 48)
######


At this point, 'picture' contains a "surface":

    http://www.pygame.org/docs/ref/Surface.html

We can copy ('blit') this surface onto our main screen:


######
>>> import pygame.display
>>> pygame.display.set_mode(picture.get_size())
<Surface(256x48x16 SW)>
>>> main_surface = pygame.display.get_surface()
>>> main_surface.blit(picture, (0, 0))
>>> pygame.display.update()
######


I hope this helps!
From denise.hartley at gmail.com  Thu Apr 14 21:35:53 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Thu Apr 14 21:35:57 2005
Subject: [Tutor] high score lists
Message-ID: <8daabe560504141235fd68ff9@mail.gmail.com>

Anyone have some good beginning ideas/references to creating a high
score list and storing scores in a simple python game? (if there's
something in the pygames module, or a simpler python way).  I'm
mod'ing a space invaders-type game and would like to add a high score
list :)

Thanks!

~Denise
From cyresse at gmail.com  Thu Apr 14 21:58:03 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Thu Apr 14 21:58:07 2005
Subject: [Tutor] _winreg problems enumerating
In-Reply-To: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB92@mi06exm01.fhills.aieg.mot.com>
References: <F9E096BB9A87B340AAAD51DFC9F275AC080BBB92@mi06exm01.fhills.aieg.mot.com>
Message-ID: <f2ff2d050414125866bba3df@mail.gmail.com>

Hi Tim,

Change this - 

try:
while 1:
test_key = regKeys.append(_winreg.EnumValue(hkey, i))
print test_key
i += 1
except EnvironmentError:
pass

to

try:
while 1:
regKeys.append(_winreg.EnumValue(hkey, i))
print regKeys[i]
i += 1
except EnvironmentError:
pass


What this does test_key = regKeys.append(_winreg.EnumValue(hkey, i)) is 
assign to test_key any value the append may return, which is None.

Out of curiosity, you know how lists work in Python?


Regards, 


Liam Clarke


On 4/15/05, Gallagher Timothy-TIMOTHYG <TIMOTHYG@motorola.com> wrote:
> 
> It seems to work but the output isn't right. I do have 10 things in the 
> Run
> folder but the out put is not telling me what they are, it just says none
> for each entry. I guess that I am not sure what to do now. I can do this
> in Perl and other languages but I really want to learn Python.
> 
> Here is what I have done:
> import _winreg
> host = "127.0.0.1 <http://127.0.0.1>" # local host
> key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
> hkey = _winreg.OpenKey(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
> i = 0
> regKeys = []
> try:
> while 1:
> test_key = regKeys.append(_winreg.EnumValue(hkey, i))
> print test_key
> i += 1
> except EnvironmentError:
> pass
> 
> when I run this script I am getting this for my output:
> None
> None
> None
> None
> None
> None
> None
> None
> None
> None
> 
> Thanks
> Tim
> 
> Timothy F. Gallagher
> Timothyg- AT 0-Motorola.com <http://0-Motorola.com>
> 
> 
> 
> ________________________________________
> From: Liam Clarke [mailto:cyresse@gmail.com]
> Sent: Wednesday, April 13, 2005 9:45 PM
> To: Gallagher Timothy-TIMOTHYG; tutor@python.org
> Subject: Re: [Tutor] _winreg problems enumerating
> 
> Hi Tim,
> 
> Hmmm, I may have to play with _winreg, is is new with Python 2.4?
> 
> Anyway, from the _winreg docs -
> EnumValue(
> key, index)
> Enumerates values of an open registry key, returning a tuple.
> key is an already open key, or any one of the predefined HKEY_* constants.
> index is an integer that identifies the index of the value to retrieve.
> The function retrieves the name of one subkey each time it is called. It 
> is
> typically called repeatedly, until an EnvironmentError exception is 
> raised,
> indicating no more values.
> 
> There's your issue -
> E_key =
> _winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
> The second value needs to be an integer that is an index.
> Typical usage would look like this -
> i = 0
> regKeys = []
> try:
> while 1:
> regKeys.append(_winreg.EnumValue(key, i))
> i += 1
> except EnvironmentError:
> pass
> 
> Good luck,
> 
> Liam Clarke
> 
> On 4/14/05, Gallagher Timothy-TIMOTHYG <TIMOTHYG@motorola.com> wrote:
> am new to python and want to learn this language.I am having troubles
> finding examples and tutorials for use on windows boxes.I do most of my
> stuff in perl and php but want better socket support, so I am giving 
> python
> a try.I am writing a script to connect to remote registry's because of
> this new IM virus.I can create reg entries and delete them but I cannot
> enumerate them, here is my code.
> 
> import _winreg
> 
> host = " 127.0.0.1 <http://127.0.0.1>" # local host
> key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
> E_key = _winreg.EnumValue(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
> 
> I get an error when I run the script:
> 
> Traceback (most recent call last):
> File "reg4.py", line 9, in ?
> E_key = _winreg.EnumValue(key,
> r"SOFTWARE\Microsoft\Windows\CurrentVersion\R
> un")
> TypeError: an integer is required
> 
> Can someone tell me what I am doing wrong???
> 
> Thanks
> 
> Timothy F. Gallagher
> Timothyg- at -Motorola.com <http://Motorola.com>
> 
> _______________________________________________
> Tutor maillist-Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> --
> 'There is only one basic human right, and that is to do as you damn well
> please.
> And with it comes the only basic human duty, to take the consequences.'
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050415/d9907098/attachment.htm
From python at jayloden.com  Thu Apr 14 22:18:59 2005
From: python at jayloden.com (Jay Loden)
Date: Thu Apr 14 22:19:30 2005
Subject: [Tutor] how to display an image using python
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C60D@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C60D@lanexc107p.fnmoc.navy.mil>
Message-ID: <200504142119.00032.python@jayloden.com>

If you don't mind using an external program, you could use the 'display' 
command from ImageMagick. 

-Jay

On Thursday 14 April 2005 07:59 pm, Ertl, John wrote:
> All,
>
> I have asked this question before, but one more time most have commented
> about manipulation but displaying the image has become the big issue.  I
> want to display png and gif images on a Linux machine using python.  I am
> using PyNGL to make the images and PIL to manipulate them but I cannot load
> xv on the machines and PIL uses xv to display.  I have looked at
> PythonMagick but I could not even get past installing it.  It does not have
> a setup.py and uses boost.  I am hoping for a more straightforward Python
> way.
>
> Thanks,
>
> John Ertl
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From benmarkwell at gmail.com  Thu Apr 14 23:51:20 2005
From: benmarkwell at gmail.com (Ben Markwell)
Date: Thu Apr 14 23:51:26 2005
Subject: [Tutor] Question regarding the len function of a list while using
	a loop
In-Reply-To: <425EA540.8060100@po-box.mcgill.ca>
References: <b9305117050414051443b383ff@mail.gmail.com>
	<425EA540.8060100@po-box.mcgill.ca>
Message-ID: <b93051170504141451e6b15ed@mail.gmail.com>

Yes this does make sense. Thank you

On 4/14/05, Brian van den Broek <bvande@po-box.mcgill.ca> wrote:
> 
> Ben Markwell said unto the world upon 2005-04-14 08:14:
> > Could somebody explain to me why the code I used to complete this 
> exercise
> > doesn't work.
> > And how do you send an integer to len?
> >
> > Thanks
> >
> > Ben
> >
> > ==================================
> >
> >
> > *As an exercise, write a loop that traverses a list and prints the 
> length of
> > each element. What happens if you send an integer to len?
> >
> > *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
> >
> >>>>i = 0
> >>>>while i < len(foo):
> >
> > print len(foo[i])
> > i = i+1
> >
> >
> > 5
> >
> > Traceback (most recent call last):
> > File "<pyshell#28>", line 2, in -toplevel-
> > print len(foo[i])
> > TypeError: len() of unsized object
> 
> Hi Ben,
> 
> Max and Alberto have already explained why you got the error message.
> 
> Depending on the context in which you are doing this, the having the
> error crash the program might be what is desired. (I get that the
> context is simply an exercise, but let's pretend it is an actual
> program, written in anger :-).) Or, you might want your program to
> handle the problem more elegantly.
> 
> Using the general framework Alberto suggested, here's a way to do that
> (I've also thrown some string formatting in to make the output more
> friendly):
> 
> >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
> >>> for item in foo:
> ... try:
> ... print "Item: %s has length %s" %(item, len(item))
> ... except TypeError:
> ... print "Item: %s has no length" %item
> ...
> Item: spam! has length 5
> Item: 1 has no length
> Item: ['brie', 'cheddar', 'swiss'] has length 3
> Item: [1, 2, 3] has length 3
> >>>
> 
> This works by attempting to do the thing in the try part, and catching
> any case than raises a TypeError (as your original code did), doing
> the routine of the except block instead.
> 
> Does that make sense?
> 
> If not, post back and I can try to explain in more detail.
> 
> Best,
> 
> Brian vdB
> 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/87422d4c/attachment.htm
From amonroe at columbus.rr.com  Fri Apr 15 00:06:53 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri Apr 15 00:07:52 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <N1-8X3PiOiw@Safe-mail.net>
References: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <187166278485.20050414180653@columbus.rr.com>


> I know that the Eight Queens puzzle is a good recursion candidate,
> but I don't understand why as yet. I'm still on simple recursion,
> and am just beginning to understand backtracking in a simple
> example, like adding numbers in an array.

If you make a typo when typing an email, do you delete the whole
message and start over? Probably not :^)

With recursion, you can just back up a few steps to the parts that were
known to be working and carry on again from there.

Alan

From amonroe at columbus.rr.com  Fri Apr 15 00:11:48 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri Apr 15 00:12:47 2005
Subject: [Tutor] high score lists
In-Reply-To: <8daabe560504141235fd68ff9@mail.gmail.com>
References: <8daabe560504141235fd68ff9@mail.gmail.com>
Message-ID: <124166573399.20050414181148@columbus.rr.com>

> Anyone have some good beginning ideas/references to creating a high
> score list and storing scores in a simple python game? (if there's
> something in the pygames module, or a simpler python way).  I'm
> mod'ing a space invaders-type game and would like to add a high score
> list :)

Quick and dirty approach: make a list of tuples
[ (40000, 'John Doe'),
  (30000, 'Steve Austin') ]

You can append new ones to the end of the list, sort it, reverse it,
etc.

Alan

From denise.hartley at gmail.com  Fri Apr 15 00:12:46 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Fri Apr 15 00:12:51 2005
Subject: [Tutor] "paused" graphic leaves a 'residue' when returning to game?
Message-ID: <8daabe5605041415123e95caed@mail.gmail.com>

Another quick question:

I can pause and unpause the little game I created, and I have a
graphic to display over top of the game screen when it is paused,
which tells the user which key to press to unpause, right?  It's set
up the same way as my "game over" graphic.  But in any case, when I
unpause, it leaves this "residue" of the "paused" text on the game
screen. the moving game characters move over it and sort of wipe it
out, but I have no idea why it's there or how to clear it!

Has anyone else encountered a problem like this before? I can post the
specific code if that would be helpful.  I've tried to clear the
screen, refresh, etc., and since the pause screen uses the same code
as the game over screen I figured the former should not leave a
residue if the latter does not.  Any suggestions for things to try
out, to fix this?

Thanks a ton!

~Denise
From dyoo at hkn.eecs.berkeley.edu  Fri Apr 15 00:21:49 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 15 00:22:04 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <Pine.LNX.4.44.0504141448350.5516-100000@hkn.eecs.berkeley.edu>


> What I want to know is this: what are other specific situations where a
> recursive algorithm would be better or easier to program than an
> iterative one?

Hello,

Programs that have to deal with data often have an internal structure that
mimics that data.  A program that deals with lists looks slightly
different from one that doesn't deal with lists.  And if the data that we
deal with is recursive, then we may want our program to have a recursive
structure too.  So recursive algorithms work best on recursive data.

This is a bit circular, so let's sketch a quick example to make this
concrete.

If we were to write a program to grab all the names in a directory of
files, we have a situation where the thing that we're processing has an
internal structure that itself can contain substructures.  Your computer's
file system has a recursive shape!

When use use a general term "file", we really mean one of the following:

    1. a directory
    2. a regular, non-directory file

And we know that a directory is itself a list of files.  Slightly more
formally, we can use a few funny symbols and say that:

    file      ::= directory | regularfile
    directory ::= list of file

    "A file is made up of either a directory or a regular file"
    "A directory is made up of a list of files"

It's a little loopy if you think about it, which is exactly why programs
that deal with directories are often recursive.



If we wanted to get a list of all the regular files in a particular
directory, then it's natural for our program's structure to mimic this
recursive structure.  We might say:

### Pseudocode ###
def listAllRegularFilesInDirectory(someDirectory):
    ## ... fill me in.  We'll probably have to refer to
    ## listAllRegularFilesInFile() somewhere in here.


def listAllRegularFilesInFile(someFile):
    if someFile is a directory:
        return listAllRegularFilesInDirectory(someFile)
    else if someFile is a regular file:
        return listAllRegularFilesInRegularFile(someFile)


def listAllRegularFilesInRegularFile(someRegularFile):
    ## ... fill me in.  This one is easy: just return a list with a single
    #  element.
######

This is a quick sketch of a recursive program to get at all the regular
files, and its form is strongly influenced by the data structure that it
works with.

Once we have the recursive version working, we can optimize it to remove
the explicit recursion by using a stack.  But the fundamental algorithm
for going through the directories is recursive traversal.


Does this make sense?  There are actually a lot of data out there that
have recursive structure.  One of the the most visible being web pages,
since web pages have links to other web pages.

So recursion is very fundamental: master it, and certain programs get a
lot easier to solve.  But I have no clue why factorial() seems to be the
main doorway to recursion.  *grin*


Most Lisp or Scheme books will use recursive ideas as a major focus, so if
you really want to learn more, you might want to look at a book like "How
To Design Programs":

    http://www.htdp.org/

or the Little Schemer.

Best of wishes!

From kent37 at tds.net  Fri Apr 15 00:23:54 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 15 00:23:59 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <N1-8X3PiOiw@Safe-mail.net>
References: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <425EED7A.6070300@tds.net>

jsoares@Safe-mail.net wrote:
> I've seen a couple of nice tutorials on recursion, and a lot of awful 
> ones. The latter always trot out the fibonacci and factorial examples 
> for some reason. And that's about it! The good ones showed me how to 
> trace through recursive calls and gave me practical examples(tictactoe, 
> magic squares, Tower of Hanoi, 4-Square, etc)
> 
> What I want to know is this: what are other specific situations where a 
> recursive algorithm would be better or easier to program than an 
> iterative one?

Many algorithms that break down into sub-parts that have the same structure as the main algorithm 
can naturally be expressed recursively.

For example flattening a list that may contain sublists can be expressed something like this:
def flatten(l):
   result = []
   for item in l:
     if type(item) == list:  # (This test is a bit simplistic)
       result.extend(flatten(item))
     else:
       result.append(item)

Another good candidate for recursive processing is tree algorithms, for example printing out nodes 
of a tree.

I once wrote an audit engine for a dom tree that recursively descends the dom tree and a tree of 
audit rules at the same time. I wrote about it here:
http://www.pycs.net/users/0000323/stories/2.html

There are non-recursive ways of doing these things also. But IMO the recursive formulation is often 
easier to understand.

Kent

From kent37 at tds.net  Fri Apr 15 00:24:55 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 15 00:24:58 2005
Subject: [Tutor] high score lists
In-Reply-To: <124166573399.20050414181148@columbus.rr.com>
References: <8daabe560504141235fd68ff9@mail.gmail.com>
	<124166573399.20050414181148@columbus.rr.com>
Message-ID: <425EEDB7.1040809@tds.net>

R. Alan Monroe wrote:
>>Anyone have some good beginning ideas/references to creating a high
>>score list and storing scores in a simple python game? (if there's
>>something in the pygames module, or a simpler python way).  I'm
>>mod'ing a space invaders-type game and would like to add a high score
>>list :)
> 
> 
> Quick and dirty approach: make a list of tuples
> [ (40000, 'John Doe'),
>   (30000, 'Steve Austin') ]
> 
> You can append new ones to the end of the list, sort it, reverse it,
> etc.

And you can use the pickle module to save and restore the list.

Kent

From jfouhy at paradise.net.nz  Fri Apr 15 00:26:34 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Fri Apr 15 00:26:39 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <N1-8X3PiOiw@Safe-mail.net>
References: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <1113517594.425eee1a203b2@www.paradise.net.nz>

Quoting "jsoares@Safe-mail.net" <jsoares@Safe-mail.net>:

> If this is too general a question, perhaps you can tell me when NOT to
> use recursion(where it would be inappropriate or inefficient).

In my opinion ---

Some problems are naturally recursive.  A good example is traversing data
structures (particularly trees), but there are other problems where there is an
obvious solution in terms of solving the same problem on smaller subinstances,
which obviously lends itself well to a recursive function.

In terms of efficiency: You should write your program first in the most obvious,
easy-to-understand way.  This may involve recursion if you are dealing with
naturally recursive data structures.  Then run your program and see if it's
slow.  If it is, try to figure out where the slowness is, either with profiling
or with theory.  If you conclude that your recursive function is slowing the
program down, then you can look to replace it with something else.

(I guess the traditional example of when it would be inappropriate is Pascall's
triangle --- ie: computing (n, r) == n!/(n-r)!r!.  The recursive algorithm looks
like this;

def C(n, r):
    """ Compute N choose R.

    Require:
        assert((type(n), type(r)) == (int, int))
        assert(n >= r)
        assert(r >= 0)
    """
    
    if r in (0, n):
        return 1
    else:
        return C(n-1, r-1) + C(n-1, r)

But if you do this, you end up computing a lot of values multiple times.  It
works better if you use an array to build up the answers from the bottom --- a
technique called dynamic programming. )

-- 
John.
From albertito_g at hotmail.com  Fri Apr 15 00:28:04 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr 15 00:28:08 2005
Subject: [Tutor] high score lists
In-Reply-To: <425EEDB7.1040809@tds.net>
Message-ID: <BAY106-F37C0A481BB44035652949989350@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/96c0a299/attachment.htm
From gsf at panix.com  Fri Apr 15 00:43:26 2005
From: gsf at panix.com (Gabriel Farrell)
Date: Fri Apr 15 00:43:29 2005
Subject: [Tutor] sys.path.append issues with cgi
Message-ID: <20050414224326.GA28341@panix.com>

Hello all,

I'm trying to modify the sys.path in my cgi scripts to import modules
that I've installed in my home directory.  The top of the script reads
as follows:


#!/usr/local/bin/python

import cgi, sys
sys.path.append('/net/u/16/g/gsf/lib/python2.4/site-packages')
from ElementTree import Element, SubElement, tostring


But my traceback reads:

ImportError: No module named ElementTree


The appended path is the same I've added to my PYTHONPATH variable and
it works fine from the python interactive prompt.  I thought it might
be a permissions issue since it's a cgi script so I chmodded
everything up to the ElementTree directory 755 but still no luck.

TIA,
gabe
From jfouhy at paradise.net.nz  Fri Apr 15 00:43:28 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Fri Apr 15 00:44:37 2005
Subject: [Tutor] _winreg problems enumerating
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2CB@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2CB@riv-excha5.echostar.com>
Message-ID: <1113518608.425ef2105029c@www.paradise.net.nz>

Quoting "Gooch, John" <John.Gooch@echostar.com>:

> I am writing a function whose job is it delete all of the selected items
> in a Listbox.

I think this problem is the same as the general problem of deleting a selection
of items from a python list.  The general solution is to iterate through the
list of selected indices backwards.

eg:

>>> from Tkinter import *
>>> tk = Tk()
>>> lb = Listbox(tk, selectmode=EXTENDED)
>>> lb.pack()
>>> for i in range(10):  # Inserting integers, so initially the item in each
...  lb.insert(END, i)   # position will be the same as its index.
... 
>>> lb.curselection()
('2', '4', '5', '7')
>>> for i in lb.curselection()[-1::-1]:
...  lb.delete(i)
... 
>>> lb.get(0, END)
(0, 1, 3, 6, 8, 9)
>>> 


From gsf at panix.com  Fri Apr 15 00:48:03 2005
From: gsf at panix.com (Gabriel Farrell)
Date: Fri Apr 15 00:48:05 2005
Subject: [Tutor] sys.path.append issues with cgi
In-Reply-To: <20050414224326.GA28341@panix.com>
References: <20050414224326.GA28341@panix.com>
Message-ID: <20050414224803.GA24181@panix.com>

Sorry, addendum to that post.  The line 

from ElementTree import Element, SubElement, tostring

should read 

from elementtree.ElementTree import Element, SubElement, tostring

but that still doesn't work.


gabe
From denise.hartley at gmail.com  Fri Apr 15 01:33:42 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Fri Apr 15 01:33:46 2005
Subject: [Tutor] high score lists
In-Reply-To: <8daabe5605041416304be68e26@mail.gmail.com>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
Message-ID: <8daabe5605041416337f05159e@mail.gmail.com>

my apologize to Alberto - instead of replying to the whole list, I
accidentally replied only to him! Here are my replies, for anyone else
who might be reading/interested:


This is what I have so far:

high_scorelist = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
                 (823,"Grant"), (779,"Aaron"), (702,"Pete"),
                 (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]

userscore = (441,"Joe")

def add_score(userscore):
   if userscore[0] > high_scorelist[len(high_scorelist)-1][0]:
       print "You made the high score list!"
       high_scorelist.append(userscore)
       high_scorelist.sort(reverse=True)
       del high_scorelist[len(high_scorelist)-1]
       return high_scorelist
   else:
       print high_scorelist

I had to enter in the variable for "userscore" like that, when I add a
tuple directly into the add_score function, it seems to delete the
last item in the list (i.e., the one I just added) BEFORE it sorts it
(i.e., removing the lowest score).  I have no idea why this is.  But
if I define userscore = (465,"Jane"), for instance, and then run
add_score(userscore), it'll change and print my 10-person high score
list, just like I want it to.  But the problem remains both how I
could display this (if even just in the python window), and how I
could get my program to create the tuple to plug in there.  (I also
just ended up writing the list like [score,user] because I couldnt
figure out how to get it to sort by the second half of the tuple.  I
need a better tutorial book, I think!)

Thanks again for any suggestions/pointers!

~Denise

and  a question about sorting (either way):

 I am trying it out with a list of tuples right now. The first problem
 I ran into is that when i sort it (scorelist.sort(reverse=True)), it
 sorts by the person's name (the first entry), and not by the score.
 plus I'm not quite sure yet how I'd get the user's name or score
 *into* the list - without manually adding it as a tuple? Since I can't
 do something like ... ("John", 100) .... username = "John", userscore
 = 100, if userscore > lowestuserscore etc.

 With a dictionary, could I point something like username to key and
 something like userscore to value?

 But then the problem with dictionaries comes back around to sorting
 too: Can I sort (and then display) a dictionary?

 Also, thanks for the idea about the pickle module - where can I get
 that and documentation for it?

 Thank you guys for your suggestions, and I apologize for the "newbie"
 level of my questions.  I am trying to answer as much as I can from
 the tutorial materials I have here, but they don't always explain
 everything (such as what the "cmp=None, key=None" means in the ( )
 helper of the .sort function.  I figured reverse=True/False out by
 playing with it).

 I really appreciate all this help! I'm trying to make this game for a
 birthday joke for the person who is teaching me programming, so
 obviously I cant ask him for help!

 :)  Denise



> On 4/14/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> >
> >
> > Hi
> >
> > I've read somewhere that the appropiate way to make a best score list is
> > with a dictionarie
> >
> > So you'll have something like this:
> >
> > best_score={"Peter":100,"Jhon":23}
> >
> > Best Regards
> >
> > Alberto
> >
> >
> >
> >
> >  Gaucho>From: Kent Johnson <kent37@tds.net> >CC: Python tutor
> > <tutor@python.org> >Subject: Re: [Tutor] high score lists >Date: Thu, 14 Apr
> > 2005 18:24:55 -0400 > >R. Alan Monroe wrote: >>>Anyone have some good
> > beginning ideas/references to creating a >>>high >>>score list and storing
> > scores in a simple python game? (if there's >>>something in the pygames
> > module, or a simpler python way). I'm >>>mod'ing a space invaders-type game
> > and would like to add a high >>>score >>>list :) >> >> >>Quick and dirty
> > approach: make a list of tuples >>[ (40000, 'John Doe'), >> (30000, 'Steve
> > Austin') ] >> >>You can append new ones to the end of the list, sort it,
> > reverse >>it, >>etc. > >And you can use the pickle module to save and
> > restore the list. > >Kent >
> > >_______________________________________________ >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 maxnoel_fr at yahoo.fr  Fri Apr 15 02:40:54 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 15 02:40:59 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <N1-8X3PiOiw@Safe-mail.net>
References: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <e3cefb6edff8ae6a007181a7f5cd4008@yahoo.fr>


On Apr 14, 2005, at 21:06, jsoares@Safe-mail.net wrote:

> I've seen a couple of nice tutorials on recursion, and a lot of?awful 
> ones. The latter always trot out the fibonacci and factorial examples 
> for some reason. And that's about it! The good ones showed me how to 
> trace through recursive calls and gave me practical 
> examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc)
>
> What I want to know is this: what are other specific situations where 
> a recursive algorithm would be better or easier to program than an 
> iterative one?

	Heh. This is perhaps one of the few times where Microsoft makes 
something easy to explain. If you've used Windows 2.0 or later, chances 
are you've seen an excellent example of recursive programming: the 
world's second-most used productivity application, Minesweeper.

	In Minesweeper, when you click on a tile that doesn't contain a mine, 
the number of mines in adjacent tiles appears. But you've probably seen 
that if there are no mines in any of the adjacent tiles, the program 
explores all the "safe zone" instead of letting you click on all those 
empty tiles. That is recursion.

	The way it does that is as follows (this is simplified pseudocode, 
which doesn't take into account edges, among other things):


def explore(minefield, (y, x)):
     numMines = countSurroundingMines(minefield, (y, x))
     minefield[(y, x)] = EXPLORED
     if numMines == 0:
         for i in ((y-1, x), (y+1, x), (y, x-1), (y, x+1)):
             if minefield[i] != EXPLORED:
                 explore(minefield, i)


	Voil?. Aside from the GUI and this piece of code, writing an 
implementation of the Windows Minesweeper is perfectly trivial. In 
fact, I did just that a few years ago on my dear TI-92 to learn how to 
use recursion. You should do the same if you've got a few hours of 
spare time, it's an enlightening experience. ^^

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From maxnoel_fr at yahoo.fr  Fri Apr 15 02:59:41 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 15 02:59:46 2005
Subject: [Tutor] high score lists
In-Reply-To: <8daabe5605041416337f05159e@mail.gmail.com>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
Message-ID: <954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>


On Apr 15, 2005, at 01:33, D. Hartley wrote:

> This is what I have so far:
>
> high_scorelist = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
>                  (823,"Grant"), (779,"Aaron"), (702,"Pete"),
>                  (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]
>
> userscore = (441,"Joe")
>
> def add_score(userscore):
>    if userscore[0] > high_scorelist[len(high_scorelist)-1][0]:
>        print "You made the high score list!"
>        high_scorelist.append(userscore)
>        high_scorelist.sort(reverse=True)
>        del high_scorelist[len(high_scorelist)-1]
>        return high_scorelist
>    else:
>        print high_scorelist

	Okay, a few little comments:
- high_scorelist[len(high_scorelist)-1] can be written as 
high_scorelist[-1]. Python slicing operators are very powerful.
- That's me nitpicking, but you should pick a naming convention for 
your whole program (camelCase, names_with_underscores or whatever) and 
stick to it. It makes things more readable. For example, userscore and 
high_scorelist should be named userScore and highScoreList, or 
user_score and high_score_list.
- Since lists are mutable objects, the function add_score, by way of 
the append and sort methods, modifies the high_scorelist list in place. 
Why do you return it afterwards?

> I had to enter in the variable for "userscore" like that, when I add a
> tuple directly into the add_score function, it seems to delete the
> last item in the list (i.e., the one I just added) BEFORE it sorts it
> (i.e., removing the lowest score).  I have no idea why this is.  But
> if I define userscore = (465,"Jane"), for instance, and then run
> add_score(userscore), it'll change and print my 10-person high score
> list, just like I want it to.

	What did your code look like when it did that?

> (I also
> just ended up writing the list like [score,user] because I couldnt
> figure out how to get it to sort by the second half of the tuple.  I
> need a better tutorial book, I think!)

	Not really. Writing things that way is the natural thing to do (even 
though it might feel counter-intuitive at the beginning), as it allows 
you to do what you want without extra code, and the less code you write 
for a given functionality, the better. Every line of code you write is 
a liability.
	Formatting data for display is left to the programmer (i.e. you). The 
user never sees what the internal data structure looks like, so when 
you're designing it, the only thing you should take into account is how 
easy to use it's going to be for *you*, the programmer.

> but they don't always explain
>  everything (such as what the "cmp=None, key=None" means in the ( )
>  helper of the .sort function.  I figured reverse=True/False out by
>  playing with it).

	cmp is a user-supplied comparison function. When it is given 2 
arguments, x and y, it must return -1 when x < y, 0 when x == y and 1 
when x > y. it allows you to sort the list based on arbitrary criteria 
without having to re-write a sort function.
	If it is None, the default sort function is used.
	I'm still using Python 2.3, so someone else will have to tell you what 
the "key" argument is.

	Oh, and when you're wondering what something does, remember that:
- Experimenting is good.
- Your 2 best friends are the interactive Python shell, and the help() 
function.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From keridee at jayco.net  Fri Apr 15 03:08:58 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri Apr 15 03:08:15 2005
Subject: [Tutor] Re: Defining a function (Joseph Q.)
References: <6.1.0.6.2.20050411181959.01edc008@pop.gmail.com><425BF262.2010005@po-box.mcgill.ca>
	<20050412165457.31157.qmail@mail.vianet.ca>
Message-ID: <005401c54157$c49a3d90$515428cf@JSLAPTOP>

> Also I would like to point out that
> def foo(*args): #this allows for any number of arguments to be passed.
>
> The *args is powerful when used correctly. *args is a list of any length 
> of arguments being passed to the function and/or class, and the arguments 
> passed can be any type/object you want to pass .
> So you might do something like.
> def foo(*args):
>  print len(args)
> # this prints the length of the list of the arguements passed
> # so using that function you would see something like. in the example I 
> only used basic types but you can pass objects as well.
>>>foo(1, 2, 3, "cat", "mouse", ['bee', 'honey', 'stinger'])
> 6
> Notice that the length that is returned is only 6 but there are 8 items so 
> it appears to have been passed to the function.   In actuallity it is only 
> 6 items.  There is 3 integers, then 2 strings, then 1 list that is 3 items 
> long. Thus the length of the list args is 6 items long. I wouldn't 
> recomend passing mixed types like this to a function using args because it 
> can get very confusing.

The star sugar sytax goes even further though....

def foo(*args):
    print len(args)

foo(1,2,3,"cat","mouse",*['bee','honey','stinger'])
8

The star in the call means to apply each member of the list as an argument. 
Isn't that cool?

HTH,
Jacob 

From missive at hotmail.com  Fri Apr 15 03:23:05 2005
From: missive at hotmail.com (Lee Harr)
Date: Fri Apr 15 03:23:09 2005
Subject: [Tutor] Re: PyGTk and Glade help
Message-ID: <BAY2-F111BE44F61109D914B2A41B1360@phx.gbl>

>We are developing a CBT based "Free Software" for our
>social activities. We are using PyGTK alongwith Glade.
>
>We want to print a document through Printer and also
>we want to provide "Sound" support in our software.
>
>Has somebody worked on PyGTK or Python? We are not
>getting the PyGTK API's for sound and printing
>support.
>Can somebody help us?
>


It's a bit scary that your message is the first hit on this
google search:
http://www.google.com/search?q=pygtk+printing

Looks like you might find some good help on the pygtk
mailing list though:
http://www.daa.com.au/mailman/listinfo/pygtk

_________________________________________________________________
Don't just search. Find. Check out the new MSN Search! 
http://search.msn.com/

From leec03273 at mac.com  Fri Apr 15 03:24:37 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Fri Apr 15 03:24:44 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <e3cefb6edff8ae6a007181a7f5cd4008@yahoo.fr>
References: <N1-8X3PiOiw@Safe-mail.net>
	<e3cefb6edff8ae6a007181a7f5cd4008@yahoo.fr>
Message-ID: <467405de22c7cc57844986096533619a@mac.com>


It is really more of a question of the type of problem and the solution  
approach in general.  For example, one can find the intersection of two  
lines with a simple equation, but that equation depends on the  
dimension the lines are in (2D, 3D, ...).  If one were working in 2D  
space only, then the simple equation is the simplest solution.  However  
if one wanted a function that would work in any space, then setting up  
the problem as a matrix and solving it recursively might be a better  
approach.

One more concrete consideration is that if you find yourself tackling a  
problem with nested looping and the algorithm at each level is mostly  
the same, then perhaps recursion would be better.

Some time ago I wrote a recursion article for an audience using Lingo  
scripting (in Macromedia Director). The actual code at the end is Lingo  
(not all that different) but the thrust of the article is constructing  
a recursive solution for matrix type problems (more than one unknown in  
an equation).

I put the pdf in my .Mac account if you wish to view it.

http://homepage.mac.com/lee_cullens/ 
A_Simple_Recursive_Solution_(article_v2).pdf

Of course, with Python we have math packages to do the grunt work, but  
it helps to understand the problem.

Lee C


> On Apr 14, 2005, at 21:06, jsoares@Safe-mail.net wrote:
>
>> I've seen a couple of nice tutorials on recursion, and a lot of?awful  
>> ones. The latter always trot out the fibonacci and factorial examples  
>> for some reason. And that's about it! The good ones showed me how to  
>> trace through recursive calls and gave me practical  
>> examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc)
>>
>> What I want to know is this: what are other specific situations where  
>> a recursive algorithm would be better or easier to program than an  
>> iterative one?

From jfouhy at paradise.net.nz  Fri Apr 15 03:32:02 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Fri Apr 15 03:32:07 2005
Subject: [Tutor] high score lists
In-Reply-To: <954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
Message-ID: <1113528722.425f1992dccc0@www.paradise.net.nz>

Quoting Max Noel <maxnoel_fr@yahoo.fr>:

> On Apr 15, 2005, at 01:33, D. Hartley wrote:
> > (I also
> > just ended up writing the list like [score,user] because I couldnt
> > figure out how to get it to sort by the second half of the tuple. I
> > need a better tutorial book, I think!)
> 	I'm still using Python 2.3, so someone else will have to tell you what
> the "key" argument is.

Interestingly, the key argument is the solution to this problem:

>>> arr = zip(range(10), range(10,0,-1))
>>> arr
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]
>>> arr.sort(key=lambda x: x[1])
>>> arr
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9), (0, 10)]

Basically, key takes a function which, given a list element, returns the value
you actually want to sort by.
 
> - Your 2 best friends are the interactive Python shell, and the help() 
> function.

True, although help(sort) could be more helpful...

>>> help([].sort)

Help on built-in function sort:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

>>>

-- 
John.
From singingxduck at gmail.com  Fri Apr 15 05:02:32 2005
From: singingxduck at gmail.com (Orri Ganel)
Date: Fri Apr 15 05:02:36 2005
Subject: [Tutor] odd behavior within __init__
In-Reply-To: <425E54EE.4050701@yahoo.com>
References: <3449428f050414035828eff1e8@mail.gmail.com>
	<425E54EE.4050701@yahoo.com>
Message-ID: <3449428f05041420022fe8c7f1@mail.gmail.com>

On 4/14/05, Rich Krauter <rmkrauter@yahoo.com> wrote:
> Maybe you could use a factory. It would allow you to simplify your Node
> class, and encapsulate the instantiation behavior you want outside the
> class.

Thanks for the suggestion; I think that's what I'll do. 

On 4/14/05, Max Noel <maxnoel_fr@yahoo.fr> wrote:
>        Well, if you want b and a to refer to the same object, just use b = a.

If you'll look at my code, you'll see that I *did* try that approach,
and it did not persist past __init__ for some reason:

class Node:
...
def __init__(self, cargo=None, prev=None, next=None, nod=False):
              """x.__init__(...) initializes x; see
x.__class__.__doc__ for signature"""
              if not isinstance(cargo, Node) or nod:
                  self.cargo = cargo
                  self.prev = prev
                  self.next = next
              else:
#################################
                  self = cargo  ## see?
#################################
                  print id(self), id(cargo)
                  print self.cargo

>>> a = Node(1)
>>> b = Node(a)
12932600 12932600
1
>>> id(b)
12960632

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
From smichr at bigfoot.com  Fri Apr 15 06:07:19 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 15 06:08:16 2005
Subject: [Tutor] high score lists
In-Reply-To: <20050414233350.C6CD31E400F@bag.python.org>
Message-ID: <DC78D05C-AD63-11D9-828B-000393C0D100@bigfoot.com>

On Thursday, Apr 14, 2005, D. Hartley wrote:

> and  a question about sorting (either way):
>
>  I am trying it out with a list of tuples right now. The first problem
>  I ran into is that when i sort it (scorelist.sort(reverse=True)), it
>  sorts by the person's name (the first entry), and not by the score.

You aren't trying to do any fancy comparison; you just want to compare 
the 2nd values in a tuple rather than the tuple itself (in the case 
where the name comes first). So you supply a 2 argument function that 
returns the comparison of the 2nd values of two tuples:

###
def mycmp(a, b):
	return cmp(a[1], b[1])
###

And now do your sort like this:

###
high_scorelist.sort(cmp=mycmp, reverse=True)
###

On the other hand, if you put the numbers first then the task of 
printing is the problem..but that's easily overcome in your loop that 
prints the values: just print the number first!

###
for score, who in highscores:
	print score, who
###

which gives,
200 Nina
20 Ben
2 Raj

If you want to get the numbers looking pretty, try finding the longest 
number and then justify all numbers in a space that big:

###
highscores = [(200, 'Nina') , (20, 'Ben') , (2, 'Raj')]
longest_num = max( [ len(str(score)) for score,who in highscores] )
for score, who in highscores:
	print str(score).rjust(longest_num), who
###

which gives
200 Nina
  20 Ben
   2 Raj

>  plus I'm not quite sure yet how I'd get the user's name or score
>  *into* the list - without manually adding it as a tuple? Since I can't
>  do something like ... ("John", 100) .... username = "John", userscore
>  = 100, if userscore > lowestuserscore etc.
>

Your code was this:
#-----------------------------------------------------------------
def add_score(userscore):                                       #1
    if userscore[0] > high_scorelist[len(high_scorelist)-1][0]:  #2
        print "You made the high score list!"                    #3
        high_scorelist.append(userscore)                         #4
        high_scorelist.sort(reverse=True)                        #5
        del high_scorelist[len(high_scorelist)-1]                #6
        return high_scorelist                                    #7
    else:                                                        #8
        print high_scorelist                                     #9
#-----------------------------------------------------------------

Lines 2-7 handle the case when the user beats the high score but if 
they don't you go to line 9 and just print the high score without 
inserting them in the list to see if they make it. How about modifying 
this so the "else" part...
	appends the user to the list;
	sorts the list;
	keeps only the first 10 items;
	prints the list

List slices are a nice way to get the first 10 (or whatever) items of a 
list:

###
 >>> def first10(l):
...  return l[:10]
...
 >>> print first10(range(20))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> print first10(range(3))
[0, 1, 2]
###

One final note, in lines 2 and 6 you use "len(high_scorelist)-1" to get 
the last item of the list. A nice way to get the last item in the list 
is to use the index "-1" which refers to the "last one" in a list.  
(You can use negative indices, too.)

BTW, the HOWTO on sorting < 
http://www.amk.ca/python/howto/sorting/sorting.html > is helpful and 
the site starship site < 
http://starship.python.net/crew/theller/pyhelp.cgi > is a nice place to 
do a search of KEYWORDS (like sort) in python documentation.

HTH,
/c

From jcahl at psci.net  Fri Apr 15 06:09:01 2005
From: jcahl at psci.net (Jim and Laura Ahl)
Date: Fri Apr 15 06:09:13 2005
Subject: [Tutor] Python backwards program (fwd)
References: <Pine.LNX.4.44.0504141147360.1011-100000@hkn.eecs.berkeley.edu>
Message-ID: <000d01c54170$dc330180$526931d8@DJM96611>

Hello, I wanted to thank all of you who helped me with the backwards program.  I finally got off my stubborn butt and downloaded 2.4.1 and the program finally works.  That 2.2 was not compatible with the way I was thinking, or maybe I wasn't compatible with it was thinking who knows.  

i = raw_input("Enter a word.")
print i[::-1]
raw_input("\n\nPress the enter key to exit.")

Thanks for allowing me to take some of your precious time.

Jim
  ----- Original Message ----- 
  From: Danny Yoo 
  To: jcahl@psci.net 
  Cc: Tutor 
  Sent: Thursday, April 14, 2005 1:52 PM
  Subject: Re: [Tutor] Python backwards program (fwd)



  > Does the 2.2 python have the ability to do this?

  Hi Jim,

  Python 2.2 is actually a bit old; you may want to update the version of
  Python on your system to Python 2.4.  You can find it here:

      http://www.python.org/2.4/

  A lot of the approaches you were trying earlier used features that were
  added in the 2.3 or 2.4 Python series; they're absent from Python 2.2.


  > The following gives me the last letter of the string.
  >
  > backwords=raw_input("enter number or string:")
  > print backwords[-1]

  Yes, this is an interesting approach!  We can go along this approach a
  little more, if you'd like.  The code above is getting the last letter, so
  we're closer to printing out the word backwards.

  How would you print out the second to last letter of the string?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/61ec0aec/attachment.htm
From smichr at bigfoot.com  Fri Apr 15 06:25:59 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 15 06:26:51 2005
Subject: [Tutor] high score lists
In-Reply-To: <20050415040821.5106F1E400F@bag.python.org>
Message-ID: <77E669DA-AD66-11D9-828B-000393C0D100@bigfoot.com>


On Thursday, Apr 14, 2005, I wrote:

> which gives
> 200 Nina
>   20 Ben
>    2 Raj
>

oops, copy and paste error...should be:

200 Nina
  20 Ben
   2 Raj

From project5 at redrival.net  Fri Apr 15 08:21:54 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr 15 08:26:06 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
References: <N1-8X3PiOiw@Safe-mail.net>
Message-ID: <loom.20050415T081100-388@post.gmane.org>

 <jsoares <at> Safe-mail.net> writes:

> If this is too general a question, perhaps you can tell me when NOT to use
recursion(where it would be
> inappropriate or inefficient).

Easy way to kill a Python program:

>>> def a():
...     a()

Recursion is dangerous if its depth is unchecked. I've recently seen a recursive
quicksort implementation run wild for example, killing the program without any
error message (not in Python, but the principle is the same regardless the
programming language).

You can use recursion it for a shortest route algorithm, given a group of points
with certain connections between them (if there aren't too many points,
otherwise you'll hit a recursion depth limit or a stack overflow). Or for a menu
navigation system, where a showmenu() routine calls itself to display submenus.

Yours,

Andrei

From project5 at redrival.net  Fri Apr 15 08:26:09 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr 15 08:34:24 2005
Subject: [Tutor] Re: high score lists
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
Message-ID: <loom.20050415T082234-84@post.gmane.org>

Alberto Troiano <albertito_g <at> hotmail.com> writes:

> I've read somewhere that the appropiate way to make a best score list is with
a dictionarie
> So you'll have something like this:
> best_score={"Peter":100,"Jhon":23} 

I don't see how that is in any way superior to a list of tuples. In fact, it has
distinct disadvantages, in that you'll have to do a 'lot' of work to get the
scores listed from high to low (which is what is usually done with them). The
situation would improve if you'd use the score as key and the player as value.
But even then it's still easier to keep them in a list of tuples, because it's
easier to do manipulations like "remove the lowest score" when you insert a
higher one.

Yours,

Andrei

From John.Gooch at echostar.com  Fri Apr 15 16:31:35 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Fri Apr 15 16:31:44 2005
Subject: [Tutor] sorting a list of dictionaries
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2D4@riv-excha5.echostar.com>

Ken, 

I misspoke when I said these were lists of dictionaries, they are actually
lists of object that have a "getSize()" getter function that returns the
size of their contents, which I would like to use for sorting.

Thank You,

John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 


-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf
Of Kent Johnson
Sent: Wednesday, April 13, 2005 3:52 AM
Cc: tutor@python.org
Subject: Re: [Tutor] sorting a list of dictionaries


> -----Original Message-----
> From: sigurd@12move.de [mailto:sigurd@12move.de]
> Sent: Thursday, December 09, 2004 12:19 PM
> To: tutor@python.org
> Subject: Re: [Tutor] sorting a list of dictionaries
> 
> 
> On  9 Dez 2004, ljholish@speakeasy.net wrote:
> 
> 
>>I have a list of dictionaries, each representing info about a file,
>>something like:
>>
>>[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
>>
>>I want to present a sorted list of all the files' data, sorting on the
>>keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) 
>>across all the dictionaries. Can someone point me towards an efficient 
>>solution for accomplishing the sort? (The list has 1000s of files).
> 
> 
> That's easy to achieve, since sort takes a custom sort function as 
> optional argument.  Now you need only a function which takes the 
> values of the fileds and compares them.
> 
> E.g.
> 
> lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
> where field is either 'name' or 'size'.

In Python 2.4 a more efficient way of doing this is to use the key parameter
to sort() with an 
itemgetter function:

from operator import itemgetter
lst.sort(key=itemgetter('field'))

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From jsoares at Safe-mail.net  Fri Apr 15 17:00:31 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Fri Apr 15 17:00:54 2005
Subject: [Tutor] re: recursion
Message-ID: <N1-HIxAyLXy@Safe-mail.net>



Thanks for all the replies to my "use of recursion" question. I now have six clear situations where recursion would be best. The consensus seems to be that if you have anything that might contain something underneath it(like a main menu with submenus), you have a good recursion candidate.



Best,



John



jsoares@safe-mail.net





-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050415/874fdcac/attachment.htm
From kent37 at tds.net  Fri Apr 15 17:15:38 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 15 17:15:42 2005
Subject: [Tutor] sorting a list of dictionaries
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2D4@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2D4@riv-excha5.echostar.com>
Message-ID: <425FDA9A.2000002@tds.net>

Gooch, John wrote:
> Ken, 
> 
> I misspoke when I said these were lists of dictionaries, they are actually
> lists of object that have a "getSize()" getter function that returns the
> size of their contents, which I would like to use for sorting.

It the objects are instances of SomeClass, I think you could use
lst.sort(key=SomeClass.getSize)

otherwise you could use
lst.sort(key=lambda x: x.getSize())

Kent

> 
> Thank You,
> 
> John A. Gooch
> Systems Administrator
> IT - Tools
> EchoStar Satellite L.L.C.
> 9601 S. Meridian Blvd.
> Englewood, CO  80112
> Desk: 720-514-5708 
> 
> 
> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf
> Of Kent Johnson
> Sent: Wednesday, April 13, 2005 3:52 AM
> Cc: tutor@python.org
> Subject: Re: [Tutor] sorting a list of dictionaries
> 
> 
> 
>>-----Original Message-----
>>From: sigurd@12move.de [mailto:sigurd@12move.de]
>>Sent: Thursday, December 09, 2004 12:19 PM
>>To: tutor@python.org
>>Subject: Re: [Tutor] sorting a list of dictionaries
>>
>>
>>On  9 Dez 2004, ljholish@speakeasy.net wrote:
>>
>>
>>
>>>I have a list of dictionaries, each representing info about a file,
>>>something like:
>>>
>>>[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
>>>
>>>I want to present a sorted list of all the files' data, sorting on the
>>>keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) 
>>>across all the dictionaries. Can someone point me towards an efficient 
>>>solution for accomplishing the sort? (The list has 1000s of files).
>>
>>
>>That's easy to achieve, since sort takes a custom sort function as 
>>optional argument.  Now you need only a function which takes the 
>>values of the fileds and compares them.
>>
>>E.g.
>>
>>lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
>>where field is either 'name' or 'size'.
> 
> 
> In Python 2.4 a more efficient way of doing this is to use the key parameter
> to sort() with an 
> itemgetter function:
> 
> from operator import itemgetter
> lst.sort(key=itemgetter('field'))
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From maxnoel_fr at yahoo.fr  Fri Apr 15 17:26:18 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 15 17:26:23 2005
Subject: [Tutor] high score lists
In-Reply-To: <1113528722.425f1992dccc0@www.paradise.net.nz>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
	<1113528722.425f1992dccc0@www.paradise.net.nz>
Message-ID: <8e6dda137533de4296dba1fb056888b8@yahoo.fr>


On Apr 15, 2005, at 03:32, jfouhy@paradise.net.nz wrote:

> Interestingly, the key argument is the solution to this problem:
>
>>>> arr = zip(range(10), range(10,0,-1))
>>>> arr
> [(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 
> 2), (9, 1)]
>>>> arr.sort(key=lambda x: x[1])
>>>> arr
> [(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 
> 9), (0, 10)]
>
> Basically, key takes a function which, given a list element, returns 
> the value
> you actually want to sort by.

	This absolutely rocks!
	Okay, I hope the default version of Python in Mac OS 10.4 will be 
2.4... Or else I'll have to move my lazy arse and install it by hand. 
Meh.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From jsoares at Safe-mail.net  Fri Apr 15 19:19:37 2005
From: jsoares at Safe-mail.net (jsoares@Safe-mail.net)
Date: Fri Apr 15 19:19:41 2005
Subject: [Tutor] Re: Recommendations needed for a good data structures text
Message-ID: <N1-L7Dtg2ye@Safe-mail.net>



I have never taken a formal course in data structures, and I'm beginning to think I need one. I am mostly self-taught, with most of my formal coursework in computer languages and not computer science.



Can anyone recommend a good data structures text that is not too heavy on math and theory? One that I can read on my own without having to take a course? 



I need something very practical, with many short examples. I'm trying to learn to program 2D games like checkers, card games, etc. 



I've been to Amazon and have seen many data structures books, but most received mixed reviews. Many emphasize fluency in C++ or Java, both of which I've used, but not for awhile. Quite a few also state that you need a rigorous math background.



My ideal data structures book:



1. Language-neutral



2. Many pseudocode examples



3. Light to medium math, math proofs, and theoretical discussions.



4. Real world examples and programs, not math related. Games related examples or other practical examples would be very helpful.



Thanks for any hints.



Best,



John



jsoares@safe-mail.net



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050415/e11159a7/attachment.htm
From dyoo at hkn.eecs.berkeley.edu  Fri Apr 15 20:14:13 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 15 20:14:19 2005
Subject: [Tutor] Python backwards program (fwd)
In-Reply-To: <000d01c54162$aca593a0$7f6f31d8@DJM96611>
Message-ID: <Pine.LNX.4.44.0504151105470.2484-100000@hkn.eecs.berkeley.edu>


[Jim, when you reply, please send to tutor@python.org.  Don't just send
your reply only to me.  Use your email client's Reply-To-All feature.]



[Jim]
>   > The following gives me the last letter of the string.
>   >
>   > backwords=raw_input("enter number or string:")
>   > print backwords[-1]


[Danny]
>   Yes, this is an interesting approach!  We can go along this approach a
>   little more, if you'd like.  The code above is getting the last letter, so
>   we're closer to printing out the word backwards.
>
>   How would you print out the second to last letter of the string?


[Jim]
> To print out the second to the last letter it would be
> backwords[-2]



Yes.  So let's see what we have so far:

######
backwords=raw_input("enter number or string:")
print backwords[-1]
print backwords[-2]
######

This works if the 'backwords' word is two letters long.

So it's a partial solution: we still need to do a little bit to make this
work on any word.

From dyoo at hkn.eecs.berkeley.edu  Fri Apr 15 20:32:43 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 15 20:32:51 2005
Subject: [Tutor] Re: Recommendations needed for a good data structures text
In-Reply-To: <N1-L7Dtg2ye@Safe-mail.net>
Message-ID: <Pine.LNX.4.44.0504151121510.2484-100000@hkn.eecs.berkeley.edu>



On Fri, 15 Apr 2005 jsoares@Safe-mail.net wrote:

> Can anyone recommend a good data structures text that is not too heavy
> on math and theory?
>
> I need something very practical, with many short examples. I'm trying to
> learn to program 2D games like checkers, card games, etc.

The book "Game Programming With Python" caught my eye in the
bookstore:

http://www.amazon.com/exec/obidos/tg/detail/-/1584502584/103-7768168-5400617?v=glance

but I haven't read it yet.  Can anyone here give a review of it?

From jeffshannon at gmail.com  Fri Apr 15 20:48:41 2005
From: jeffshannon at gmail.com (Jeff Shannon)
Date: Fri Apr 15 20:48:44 2005
Subject: [Tutor] odd behavior within __init__
In-Reply-To: <5d0204a1050415114757452c29@mail.gmail.com>
References: <3449428f050414035828eff1e8@mail.gmail.com>
	<425E54EE.4050701@yahoo.com>
	<3449428f05041420022fe8c7f1@mail.gmail.com>
	<5d0204a1050415114757452c29@mail.gmail.com>
Message-ID: <5d0204a1050415114841b3681c@mail.gmail.com>

(Oops, forgot to change this to go to the list...)

On 4/14/05, Orri Ganel <singingxduck@gmail.com> wrote:
> On 4/14/05, Rich Krauter <rmkrauter@yahoo.com> wrote:
>
> On 4/14/05, Max Noel <maxnoel_fr@yahoo.fr> wrote:
> >        Well, if you want b and a to refer to the same object, just use b = a.
>
> If you'll look at my code, you'll see that I *did* try that approach,
> and it did not persist past __init__ for some reason:

That's because you re-bound the local name 'self', but that doesn't
affect anything outside the local namespace.  Remember, __init__()
returns None; the object has already been allocated before __init__()
is called, and while __init__() can mutate the object it can't affect
the reference that the interpreter has created.  (Unless you resort to
hacking the contents of the parent frame, but we won't get into that.
You *don't* want to do this.)

In this case, I agree that a factory is your best bet.

Jeff Shannon


>
> class Node:
> ...
> def __init__(self, cargo=None, prev=None, next=None, nod=False):
>               """x.__init__(...) initializes x; see
> x.__class__.__doc__ for signature"""
>               if not isinstance(cargo, Node) or nod:
>                   self.cargo = cargo
>                   self.prev = prev
>                   self.next = next
>               else:
> #################################
>                   self = cargo  ## see?
> #################################
>                   print id(self), id(cargo)
>                   print self.cargo
>
> >>> a = Node(1)
> >>> b = Node(a)
> 12932600 12932600
> 1
> >>> id(b)
> 12960632
>
> --
> Email: singingxduck AT gmail DOT com
> AIM: singingxduck
> Programming Python for the fun of it.
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From denise.hartley at gmail.com  Fri Apr 15 21:30:26 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Fri Apr 15 21:30:30 2005
Subject: [Tutor] high score lists
In-Reply-To: <8e6dda137533de4296dba1fb056888b8@yahoo.fr>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
	<1113528722.425f1992dccc0@www.paradise.net.nz>
	<8e6dda137533de4296dba1fb056888b8@yahoo.fr>
Message-ID: <8daabe56050415123026459e6c@mail.gmail.com>

Hello, everyone!

Thank you for your very helpful comments.  A few follow up questions,
and then I'll show you where I've come so far:

1. Max - I think you're right about keeping it (score, name).  It *is*
much simpler to work with it that way, and would be easier to change
the display and just have the code work in an intuitive way for me, at
the moment.

2. To everyone who suggested indexing with [-1]: thank you for the
reminder! I have done this before but was, as I often do, "playing on
hard" when I wrote the whole "len(high_scorelist)-1" business. Simple
is better!

3.  Re: "key" and "cmp" and figuring out what things do..  I
appreciate all of your explanations, although with my extremely
limited programming experience, even some of the basic explanations
are beyond me.  Of course if I keep the list arranged by (score, name)
rather than the other way around, it does not matter at this exact
moment, but I'm still unclear on how to practically use these
elements.  I'll just have to play with them more.  the "arr =
zip(range(10),range(10,0,-1)" example was interesting, although I had
trouble following how it marked out what it was sorting by (i.e.,
"key=lambda x: x[1]"  .... ???).  It's just an issue of not having
enough familiarity with reading other people's code, I think.  I'll
have to get it to successfully work in something of my own, probably,
before it will make sense.  Unless you can explain what "lambda x:
x[1]" does, in preschool-speak ;)  But regardless, I *am* storing all
this information away, and I know it's helping me learn, piece by
piece.  I very much appreciate it all!

4. Now, onto displaying the score list.  I have managed to get it to
work as follows:

high_scorelist = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
                  (823,"Grant"), (779,"Aaron"), (702,"Pete"),
                  (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]

def add_score():
    name = read_string("What's your name?")
    score = read_number("What was your score?")
    userscore = (score,name)
    if userscore[0] > high_scorelist[-1][0]:
        print "You made the high score list!"
        high_scorelist.append(userscore)
        if len(high_scorelist) > 10:
            high_scorelist.sort(reverse=True)
            del high_scorelist[-1]
            for score, name in high_scorelist:
                print name," - ",score
    else:
        print "Sorry, didn't quite make the high score list!"
        for score, name in high_scorelist:
            print name," - ",score


Of course at this point it's asking the user for their name/score, and
eventually I will make the program supply the score, but I set it up
this way just for the purposes of testing the score program.  In any
case, when I entered in a score that would make the list, it did as
follows:

>>> add_score()
What's your name?Jack
What was your score? 581
You made the high score list!
Denise  -  1000
Denise  -  945
Denise  -  883
Grant  -  823
Aaron  -  779
Pete  -  702
Jack  -  581
Tom  -  555
Tom  -  443
Robin  -  442
>>> 

If I enter in a score that does not make it, it prints the "didnt make
it" message and the scores, in the same format as above.

Now, this is not the world's most elegant code, clearly, and it will
get changed a lot between now and when it goes in the game, simply
because I have to make it work IN the game.  Even allowing it to run
in the python window (I'd rather have it display on the graphics
window, but I dont know how, so I'm focusing on making it work first),
I'll want it to test whether the score makes the list before it asks
the user for their name (otherwise, why would it matter!).  Also, I
hard-coded in the " - " between the name and the score - I'd like to
put a couple of tabs in there and have the scores in a left-aligned
column an inch or two over from the names.  I know one of my old
tutorial packages had a command for inserting tabs into strings, but
now I cant find it.  Does anyone know?  Also how to make the scores
line up in a column (and not just a fixed amount of space, either
through tabs or hard-coding)?

At that point I'll have a program that works and displays a
not-too-bad-looking high score list.  Then I can worry about importing
the score, and provide an update.


So I'm sure that's probably way too much information for most of you!!
But my remaining questions are these:

1. what is/where can i get the "pickle" module for storing/saving
changes to the high score list?
2. tabs/aligning the score in a column when i display it
3. displaying the score/scorelist stuff on the graphics window instead
of the python window
4. key=lambda x: x[1] ?

Thank you so much for all of your suggestions!  I can't wait until I
learn enough python to be able to give some help back :)

~Denise
From smichr at bigfoot.com  Fri Apr 15 22:19:49 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 15 22:21:52 2005
Subject: [Tutor] high score lists
In-Reply-To: <20050415193121.6EE9B1E4017@bag.python.org>
Message-ID: <B7E1E3A5-ADEB-11D9-828B-000393C0D100@bigfoot.com>


On Friday, Apr 15, 2005, at 14:31 America/Chicago, 
tutor-request@python.org wrote:

> So I'm sure that's probably way too much information for most of you!!
> But my remaining questions are these:
>
> 1. what is/where can i get the "pickle" module for storing/saving
> changes to the high score list?
> 2. tabs/aligning the score in a column when i display it

The Python Cookbook is a good place to look to see if someone has 
already provided a recipe:
	http://aspn.activestate.com/ASPN/Cookbook/Python/

There are 2 table indenters at
	http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662

In my previous post there is a suggestion on using the longest number 
to print all teh numbers in a space that big.  (There was also an error 
in my understanding of your program where you checked the user's score 
against the *lowest* score in the list, not the highest--sorry about 
that!)

> 3. displaying the score/scorelist stuff on the graphics window instead
> of the python window
> 4. key=lambda x: x[1] ?
>
You can think of the "key" option like this: when sort comes to compare 
elements x and y it gives you the option of telling *what* you want to 
compare about x and y.  You might, for example, want to sort a list of 
strings based on their *length* not on their alphabetical position. To 
do so, write a 1-argument function that returns the length of a string:

###
Python 2.4 (#1, Apr  4 2005, 13:57:19)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> l=['sea', 'd', 'bee']
 >>> l.sort()              #the normal sort
 >>> l
['bee', 'd', 'sea']
 >>> def strlen(x):        # the 1-argument function
...     return len(x)
...
 >>> l.sort(key=strlen)
 >>> l
['d', 'sea', 'bee']      #the length sort; it's stable so sea is still 
before bee
 >>> def length_alph(x):  #'key' function if you want length first and 
then alphabetical
...     return (len(x),x)
...
 >>> l.sort(key=length_alph); l
['d', 'bee', 'sea']
###

> Thank you so much for all of your suggestions!  I can't wait until I
> learn enough python to be able to give some help back :)
>
This list is a great place for learning.  It's one of the things that 
has made working with Python so enjoyable and productive. (Thanks to 
all!)

/c

From jeffpeery at yahoo.com  Fri Apr 15 23:33:46 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Fri Apr 15 23:33:50 2005
Subject: [Tutor] py2exe
Message-ID: <20050415213346.89516.qmail@web30502.mail.mud.yahoo.com>

hello, I am using py2exe. for most of my applications it has been great. although this last one I built and when I try to execute it I get an error:
 
RunTime Error: this application has requested the runtime to terminate in an unusual way. please contact the applications support team for more info.
 
does anyone know what this means? thanks.
 
Jeff
 
 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050415/94d919fc/attachment.html
From denise.hartley at gmail.com  Fri Apr 15 23:51:46 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Fri Apr 15 23:51:49 2005
Subject: [Tutor] high score lists
In-Reply-To: <B7E1E3A5-ADEB-11D9-828B-000393C0D100@bigfoot.com>
References: <20050415193121.6EE9B1E4017@bag.python.org>
	<B7E1E3A5-ADEB-11D9-828B-000393C0D100@bigfoot.com>
Message-ID: <8daabe5605041514511908606d@mail.gmail.com>

Thanks, I'll look at the cookbook! I didnt know it was available online.

I did look at your example about using the longest number, but I
couldnt really understand all of the code, and ended up deciding to
arrange it so that the two columns were left-aligned: it looked like
it would align them down the center in your example? Let me know if I
am misunderstanding something.

Re: the key discussion: that was very helpful, thank you! So if I had
a list of tuples, and I wanted to use the "key" function to arrange
the list of tuples by the second tuple item, I would define a function
that returns the second tuple item, and then do key=find_second()? or
could i just do key=[1]? since i'm sorting tuples by a part of a
tuple, it gets more confusing than when I was sorting simple lists.

~Denise
From jfouhy at paradise.net.nz  Sat Apr 16 00:06:52 2005
From: jfouhy at paradise.net.nz (John Fouhy)
Date: Sat Apr 16 00:06:51 2005
Subject: [Tutor] Re: Recursion....what are the best situations to use it?
In-Reply-To: <loom.20050415T081100-388@post.gmane.org>
References: <N1-8X3PiOiw@Safe-mail.net>
	<loom.20050415T081100-388@post.gmane.org>
Message-ID: <42603AFC.6040008@paradise.net.nz>

Andrei wrote:
> Recursion is dangerous if its depth is unchecked. I've recently seen a recursive
> quicksort implementation run wild for example, killing the program without any
> error message (not in Python, but the principle is the same regardless the
> programming language).

I recall an assignment I once had for an algorithms course --- I think 
it was to implement and analyse Strassen's algorithm.

My recursive algorithm would run out of stack space when the input 
matrices got too large.  But I was programming in Java, and the JVM 
allows you to set the stack size.

So, by plotting input size when it crashes vs stack size, I was able to 
get a nice graph displaying the space complexity of the algorithm :-)

-- 
John.
From John.Gooch at echostar.com  Sat Apr 16 00:03:50 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Sat Apr 16 00:11:10 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>

I have a couple of questions:

Is there a way to create multiple __init__ routines in a Python Class?

Secondly, I cannot remember how to make it so that when you start typing in
a defined function name, it pops up a tooltip showing the functions syntax.
	ex: def delRecord( some params ):
	dr = delRecord()
	dr.someCommand( <-- tooltip popups up here

Thank You, 


John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 
From jfouhy at paradise.net.nz  Sat Apr 16 00:20:48 2005
From: jfouhy at paradise.net.nz (John Fouhy)
Date: Sat Apr 16 00:20:48 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>
Message-ID: <42603E40.9010909@paradise.net.nz>

Gooch, John wrote:
  > Is there a way to create multiple __init__ routines in a Python Class?

Not directly (well, not that I know of).  But you can always emulate it.

eg:

class Foo(object):
   def __init__(self, init, *args, **kw):
     if init == 'this':
       self._initThis(*args, **kw)
     elif init == 'that':
       self.initThat(*args, **kw)

<shrug>

If you're using inheritance, you'll need to do a little more work inside 
each branch of the if statement.

-- 
John.
From bvande at po-box.mcgill.ca  Sat Apr 16 00:21:41 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sat Apr 16 00:22:41 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>
Message-ID: <42603E75.7030608@po-box.mcgill.ca>

Gooch, John said unto the world upon 2005-04-15 18:03:
> I have a couple of questions:
> 
> Is there a way to create multiple __init__ routines in a Python Class?

Hi John,

I'm not sure what you mean by that. Could be me, or could be the 
question. :-)


> Secondly, I cannot remember how to make it so that when you start typing in
> a defined function name, it pops up a tooltip showing the functions syntax.
> 	ex: def delRecord( some params ):
> 	dr = delRecord()
> 	dr.someCommand( <-- tooltip popups up here

Many Python-aware editors use the first line of the docstring to 
construct the tooltip:

def silly():
     '''This will be the tooltip.

     This will be more documentation.'''
     pass

HTH,

Brian vdB
From maxnoel_fr at yahoo.fr  Sat Apr 16 01:12:51 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr 16 01:12:57 2005
Subject: [Tutor] high score lists
In-Reply-To: <8daabe56050415123026459e6c@mail.gmail.com>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
	<1113528722.425f1992dccc0@www.paradise.net.nz>
	<8e6dda137533de4296dba1fb056888b8@yahoo.fr>
	<8daabe56050415123026459e6c@mail.gmail.com>
Message-ID: <4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>


On Apr 15, 2005, at 21:30, D. Hartley wrote:

> Unless you can explain what "lambda x:
> x[1]" does, in preschool-speak ;)

	That's an anonymous function, also known as a lambda function. Let's 
take an example:

 >>> a = range(10)
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> map(lambda x: 2*x, a)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

	The first and second lines should be obvious ;) . Now, on line 3, I 
use two things:
1) The "map" function. It takes 2 arguments: a function and an iterable 
(a list, here). It then applies the function to each member of the 
list, and returns the result.
2) A lambda function. "lambda x: 2*x" is a function that takes 1 
argument, x, and returns 2*x. You see, I couldn't be bothered with 
def'ing such a trivial function earlier in the program. I could have 
done that instead:

 >>> def twice(x):
 >>>     return 2*x
 >>> a = range(10)
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> map(twice, a)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

	And the result would have been the same. So a lambda function is just 
a 1-line function you only want to use as an argument to another 
function (functions are objects) and can't be bothered with/don't want 
to def elsewhere in the program. That's all.

> Does anyone know?  Also how to make the scores
> line up in a column (and not just a fixed amount of space, either
> through tabs or hard-coding)?

	The "rjust" string method is what you're looking for, methinks. 
help("".rjust) for more information. :)

> 1. what is/where can i get the "pickle" module for storing/saving
> changes to the high score list?

	pickle is part of the standard Python distribution. import pickle is 
all you need to do.

> 3. displaying the score/scorelist stuff on the graphics window instead
> of the python window

	That's heavily dependent on what you're using. Pygame? Tkinter? 
Something else?

> Thank you so much for all of your suggestions!  I can't wait until I
> learn enough python to be able to give some help back :)

	That moment will come sooner than you think. Python is remarkably easy 
to learn, especially with the help of this mailing list. It's amazing 
the insight you gain by trying to help others.
	I've been using Python for about 6 months now, and it definitely is my 
favorite language. I can't wait to do some serious programming in it 
(don't have enough time at the moment, with all the work I have to do 
in Java... But as soon as Shadowrun 4 hits the stores, I'll start 
working on a character generator, perhaps learning PyObjC in the 
process).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"


From kent37 at tds.net  Sat Apr 16 01:40:30 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 01:40:35 2005
Subject: [Tutor] Jython
In-Reply-To: <4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>
References: <425EEDB7.1040809@tds.net>	<BAY106-F37C0A481BB44035652949989350@phx.gbl>	<8daabe5605041416031d8c7d4a@mail.gmail.com>	<8daabe5605041416304be68e26@mail.gmail.com>	<8daabe5605041416337f05159e@mail.gmail.com>	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>	<1113528722.425f1992dccc0@www.paradise.net.nz>	<8e6dda137533de4296dba1fb056888b8@yahoo.fr>	<8daabe56050415123026459e6c@mail.gmail.com>
	<4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>
Message-ID: <426050EE.7060703@tds.net>

Max Noel wrote:
>     I've been using Python for about 6 months now, and it definitely is 
> my favorite language. I can't wait to do some serious programming in it 
> (don't have enough time at the moment, with all the work I have to do in 
> Java...

You might want to look into Jython. It is Python implemented in Java, it runs on the Java VM and 
interoperates with Java libraries. I have transitioned from Java to Jython in the last couple of 
years while working in a Java shop.
http://www.jython.org

Kent

From denise.hartley at gmail.com  Sat Apr 16 01:46:30 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Sat Apr 16 01:46:34 2005
Subject: Fwd: [Tutor] high score lists
In-Reply-To: <4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>
References: <425EEDB7.1040809@tds.net>
	<BAY106-F37C0A481BB44035652949989350@phx.gbl>
	<8daabe5605041416031d8c7d4a@mail.gmail.com>
	<8daabe5605041416304be68e26@mail.gmail.com>
	<8daabe5605041416337f05159e@mail.gmail.com>
	<954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr>
	<1113528722.425f1992dccc0@www.paradise.net.nz>
	<8e6dda137533de4296dba1fb056888b8@yahoo.fr>
	<8daabe56050415123026459e6c@mail.gmail.com>
	<4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>
Message-ID: <8daabe56050415164624a017a8@mail.gmail.com>

Thanks for the extra info on the lambda function.  That clears it out
a lot! I'll be sure to save that.

Re: "....The "rjust" string method is what you're looking for, methinks.
help("".rjust) for more information. :) ...."

Thanks!  That does have helpful information about what arguments are
required.  That would right-align my right column, then? That would
look nice.  But where would you put it to make the other column line
up? I wish 'help' gave examples!

Re:  pickle: Tried to look into how to use this - looks like it
involves opening/closing files...? and dumping? and usr bins? ha ha.
LOST.  This might have to be another thread!



> That's heavily dependent on what you're using. Pygame? Tkinter?
> Something else?

I'm using the pygame module, yep. begin_graphics( ), end_graphics( ),
etc.  Any ideas?

Thanks again!
~Denise


---------- Forwarded message ----------
From: Max Noel <maxnoel_fr@yahoo.fr>
Date: Apr 15, 2005 4:12 PM
Subject: Re: [Tutor] high score lists
To: "D. Hartley" <denise.hartley@gmail.com>
Cc: Python tutor <tutor@python.org>



On Apr 15, 2005, at 21:30, D. Hartley wrote:

> Unless you can explain what "lambda x:
> x[1]" does, in preschool-speak ;)

       That's an anonymous function, also known as a lambda function. Let's
take an example:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(lambda x: 2*x, a)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

       The first and second lines should be obvious ;) . Now, on line 3, I
use two things:
1) The "map" function. It takes 2 arguments: a function and an iterable
(a list, here). It then applies the function to each member of the
list, and returns the result.
2) A lambda function. "lambda x: 2*x" is a function that takes 1
argument, x, and returns 2*x. You see, I couldn't be bothered with
def'ing such a trivial function earlier in the program. I could have
done that instead:

>>> def twice(x):
>>>     return 2*x
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(twice, a)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

       And the result would have been the same. So a lambda function is just
a 1-line function you only want to use as an argument to another
function (functions are objects) and can't be bothered with/don't want
to def elsewhere in the program. That's all.

> Does anyone know?  Also how to make the scores
> line up in a column (and not just a fixed amount of space, either
> through tabs or hard-coding)?

       The "rjust" string method is what you're looking for, methinks.
help("".rjust) for more information. :)

> 1. what is/where can i get the "pickle" module for storing/saving
> changes to the high score list?

       pickle is part of the standard Python distribution. import pickle is
all you need to do.

> 3. displaying the score/scorelist stuff on the graphics window instead
> of the python window

       That's heavily dependent on what you're using. Pygame? Tkinter?
Something else?

> Thank you so much for all of your suggestions!  I can't wait until I
> learn enough python to be able to give some help back :)

       That moment will come sooner than you think. Python is remarkably easy
to learn, especially with the help of this mailing list. It's amazing
the insight you gain by trying to help others.
       I've been using Python for about 6 months now, and it definitely is my
favorite language. I can't wait to do some serious programming in it
(don't have enough time at the moment, with all the work I have to do
in Java... But as soon as Shadowrun 4 hits the stores, I'll start
working on a character generator, perhaps learning PyObjC in the
process).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge a
perfect, immortal machine?"
From denise.hartley at gmail.com  Sat Apr 16 01:52:56 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Sat Apr 16 01:52:59 2005
Subject: [Tutor] newbie intro to pickle
Message-ID: <8daabe560504151652371813f6@mail.gmail.com>

Hello everyone! (Yes, another thread from me).  I had a question that
started in another thread, but it has turned into a huge, gaping chasm
of confusion for me on its own, so I thought I would start another
thread with a more specific subject line.


I am working on creating a high score list for the game I'm making,
and want to be able to save the new added scores to it.  I was told to
use pickle (import pickle), which is part of python.

So I imported it, asked the shell window for 'help' (egad, technical
jargon!) and did a search on python, same result.  None of my
beginners' tutorials have anything about pickle, unfortunately (very
frustrating!)

Does anyone know if there are some *beginner*-user-friendly tutorials
out there for pickle? Or can give a sample of how you would implement
it into a VERY SIMPLE program? Obviously I can get to the "import
pickle" step, but once I'm past that, I'm totally lost!

Thanks :)

~Denise
From tameyer at ihug.co.nz  Sat Apr 16 02:03:11 2005
From: tameyer at ihug.co.nz (Tony Meyer)
Date: Sat Apr 16 02:03:22 2005
Subject: [Tutor] newbie intro to pickle
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8029D800C@its-xchg4.massey.ac.nz>
Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>

> Does anyone know if there are some *beginner*-user-friendly tutorials
> out there for pickle? Or can give a sample of how you would implement
> it into a VERY SIMPLE program? Obviously I can get to the "import
> pickle" step, but once I'm past that, I'm totally lost!

There's the example in the documentation:

<http://docs.python.org/lib/pickle-example.html>

But to put it really simply, you can just use it like this:

>>> import pickle
>>> my_list = [4,5,6,6]
>>> pickle.dump(my_list, file("temp.pik", "w"))

(restart Python here to show that it works across sessions)

>>> import pickle
>>> my_list_reloaded = pickle.load(file("temp.pik"))
>>> my_list_reloaded
[4, 5, 6, 6]

=Tony.Meyer

From kent37 at tds.net  Sat Apr 16 02:07:46 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 02:07:55 2005
Subject: [Tutor] high score lists
In-Reply-To: <8daabe5605041514511908606d@mail.gmail.com>
References: <20050415193121.6EE9B1E4017@bag.python.org>	<B7E1E3A5-ADEB-11D9-828B-000393C0D100@bigfoot.com>
	<8daabe5605041514511908606d@mail.gmail.com>
Message-ID: <42605752.7080806@tds.net>

D. Hartley wrote:
> Re: the key discussion: that was very helpful, thank you! So if I had
> a list of tuples, and I wanted to use the "key" function to arrange
> the list of tuples by the second tuple item, I would define a function
> that returns the second tuple item, and then do key=find_second()? or
> could i just do key=[1]? 

Close but not quite. You define a function that takes one argument (the tuple) and returns the 
second item:
def find_second(tup):
   return tup[1]

then use key=find_second <- note NO parentheses, you are passing a reference to the function as the 
key parameter. If you write key=find_second() you are calling find_second and using the result as 
the key parameter. which will not do what you want.

BTW (Denise don't worry if you don't understand this, I thought some of the other readers might be 
interested) the operator module defines a function that *creates* a function to get items. So you 
could use this:
import operator
lst.sort(key=operator.itemgetter(1))

In this case you do call the itemgetter function; its return value is itself a function of one argument.

  >>> import operator
  >>> get1 = operator.itemgetter(1)
  >>> get1([1,2,3])
2
  >>> get1('abc')
'b'
  >>> get1( (1,2,3) )
2

Kent

From dyoo at hkn.eecs.berkeley.edu  Sat Apr 16 03:31:45 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Apr 16 03:31:49 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E2@riv-excha5.echostar.com>
Message-ID: <Pine.LNX.4.44.0504151824340.3317-100000@hkn.eecs.berkeley.edu>



On Fri, 15 Apr 2005, Gooch, John wrote:

> Is there a way to create multiple __init__ routines in a Python Class?

Hi John,


In general, Python doesn't support "overloading".  Overloading wouldn't
interact well at all with functions that can take a variable number of
arguments.

That being said, can you write a really general initializer that fits all
your cases?  If so, then you might provide a set of utility factory
functions to simplify calling the general initializer.


For example:

######
>>> class BankAccount:
...     def __init__(self, name, initialAmount):
...         self.name = name
...         self.amount = initialAmount
...
>>> def makeBankruptAccount(name):
...     return BankAccount(name, 0)
...
>>> def makeMillionareAccount(name):
...     return BankAccount(name, 10 ** 6)
...
>>> def makeAnonymousDonor(amount):
...     return BankAccount(None, amount)
...
######

Best of wishes!

From keridee at jayco.net  Sat Apr 16 03:40:16 2005
From: keridee at jayco.net (Jacob S.)
Date: Sat Apr 16 03:39:19 2005
Subject: [Tutor] high score lists
References: <B7E1E3A5-ADEB-11D9-828B-000393C0D100@bigfoot.com>
Message-ID: <001d01c54225$44949ae0$4e5428cf@JSLAPTOP>

> You can think of the "key" option like this: when sort comes to compare 
> elements x and y it gives you the option of telling *what* you want to 
> compare about x and y.  You might, for example, want to sort a list of 
> strings based on their *length* not on their alphabetical position. To do 
> so, write a 1-argument function that returns the length of a string:
>
> ###
> Python 2.4 (#1, Apr  4 2005, 13:57:19)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> l=['sea', 'd', 'bee']
> >>> l.sort()              #the normal sort
> >>> l
> ['bee', 'd', 'sea']
> >>> def strlen(x):        # the 1-argument function
> ...     return len(x)
> ...
> >>> l.sort(key=strlen)
> >>> l
> ['d', 'sea', 'bee']      #the length sort; it's stable so sea is still 
> before bee
> >>> def length_alph(x):  #'key' function if you want length first and
> then alphabetical
> ...     return (len(x),x)
> ...
> >>> l.sort(key=length_alph); l
> ['d', 'bee', 'sea']
> ###

Great.  len is a function though. Why use a second layer of function when 
len is a function in itself?

>>> l = ['d','sea','bee']
>>> l.sort(key=len)
>>> l
['d', 'bee', 'sea']
>>>

Jacob 

From keridee at jayco.net  Sat Apr 16 03:50:18 2005
From: keridee at jayco.net (Jacob S.)
Date: Sat Apr 16 03:49:25 2005
Subject: [Tutor] high score lists
References: <425EEDB7.1040809@tds.net><BAY106-F37C0A481BB44035652949989350@phx.gbl><8daabe5605041416031d8c7d4a@mail.gmail.com><8daabe5605041416304be68e26@mail.gmail.com><8daabe5605041416337f05159e@mail.gmail.com><954263c7fcc9ac72911dc6a2f4ffd050@yahoo.fr><1113528722.425f1992dccc0@www.paradise.net.nz><8e6dda137533de4296dba1fb056888b8@yahoo.fr><8daabe56050415123026459e6c@mail.gmail.com><4074d0c3b17dda5417256b1ee8f02365@yahoo.fr>
	<8daabe56050415164624a017a8@mail.gmail.com>
Message-ID: <002601c54226$abfd1e90$4e5428cf@JSLAPTOP>

> Re:  pickle: Tried to look into how to use this - looks like it
> involves opening/closing files...? and dumping? and usr bins? ha ha.
> LOST.  This might have to be another thread!

Pickle is simple enough.

#################

import pickle

filename = "myfile.txt"    ## Change this with an appropriate filename

f1 = open(filename,"w")
highScoreList = [(200,"Jacob"),(175,"Diane"),(100,"Gary")]   ## This is your 
highscore list

pickle.dump(f1,highScoreList)

f1.close()

##################

and then to retrieve the list, even after the program closes

##################

import pickle

filename = "myfile.txt"   # This has to be the same filename as before

f1 = open(filename,"r")
highScoreList = pickle.load(f1)

f1.close()
#####################

HTH,
Jacob 

From denise.hartley at gmail.com  Sat Apr 16 03:57:47 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Sat Apr 16 03:57:52 2005
Subject: [Tutor] newbie intro to pickle
In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>
References: <ECBA357DDED63B4995F5C1F5CBE5B1E8029D800C@its-xchg4.massey.ac.nz>
	<ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>
Message-ID: <8daabe560504151857386b3af7@mail.gmail.com>

Thanks, Tony, your example is much clearer (to me!) than that on the
python page.  A couple quick questions about it:

So the .dump command is, in effect, saving the file, correct? which
takes the object you're saving (in my case it would be
high_scorelist), and ("filename","..... what is the "w" ?)  Why does
the temp file you're saving into end in .pik?

Then import is, in effect, loading the file (the score list) from
wherever you saved it.  do you have to give it a new name? (i.e.,
"my_list_reloaded"?) I'm thinking not. i could import the file right
before the high score list is displayed in the game, and dump  right
after a new score is added/the list is changed?

Thanks for creating an easy-to-follow example!

:)

~Denise

On 4/15/05, Tony Meyer <tameyer@ihug.co.nz> wrote:
> > Does anyone know if there are some *beginner*-user-friendly tutorials
> > out there for pickle? Or can give a sample of how you would implement
> > it into a VERY SIMPLE program? Obviously I can get to the "import
> > pickle" step, but once I'm past that, I'm totally lost!
> 
> There's the example in the documentation:
> 
> <http://docs.python.org/lib/pickle-example.html>
> 
> But to put it really simply, you can just use it like this:
> 
> >>> import pickle
> >>> my_list = [4,5,6,6]
> >>> pickle.dump(my_list, file("temp.pik", "w"))
> 
> (restart Python here to show that it works across sessions)
> 
> >>> import pickle
> >>> my_list_reloaded = pickle.load(file("temp.pik"))
> >>> my_list_reloaded
> [4, 5, 6, 6]
> 
> =Tony.Meyer
> 
>
From keridee at jayco.net  Sat Apr 16 04:11:45 2005
From: keridee at jayco.net (Jacob S.)
Date: Sat Apr 16 04:11:34 2005
Subject: [Tutor] newbie intro to pickle
References: <ECBA357DDED63B4995F5C1F5CBE5B1E8029D800C@its-xchg4.massey.ac.nz><ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>
	<8daabe560504151857386b3af7@mail.gmail.com>
Message-ID: <006801c54229$c3b923f0$4e5428cf@JSLAPTOP>

> Thanks, Tony, your example is much clearer (to me!) than that on the
> python page.  A couple quick questions about it:
>
> So the .dump command is, in effect, saving the file, correct? which
> takes the object you're saving (in my case it would be
> high_scorelist), and ("filename","..... what is the "w" ?)  Why does
> the temp file you're saving into end in .pik?
>
> Then import is, in effect, loading the file (the score list) from
> wherever you saved it.  do you have to give it a new name? (i.e.,
> "my_list_reloaded"?) I'm thinking not. i could import the file right
> before the high score list is displayed in the game, and dump  right
> after a new score is added/the list is changed?
>
> Thanks for creating an easy-to-follow example!
>
> :)
>
> ~Denise

Okay,

pickle writes ("w") text to a file.  The tempfile he's saving it as ends in 
pik because he wants it to.
I assume you're using Windows?  Go to control panel, folder options, view, 
and make sure the "Hide extensions for known file types" is unchecked.
Then go to a folder that has any file in it. You'll see file extensions on 
the names.  i.e.  myfile.txt
Extensions are just something the operating system, in this case Windows, 
uses to know what program to use to open the file.  Since you are 
controlling the file temp.pik or whatever it's called, it doesn't matter 
what the operating system knows about it.  You could even give it four 
letters, or two, or even one letter, or believe it or not, not any extension 
at all.
It does not matter when you use the exact same filename reloading.

As for the variable name, it doesn't usually matter what the variable name 
was before!  Any python tutorial will show you at least that reassigning a 
variable will make the variable point to the new value and the old value 
will be lost.  In this case, the old variable is not lost, because you can 
still reload it from the file.

Okay, I'm done,
Jacob 

From dianahawks at optusnet.com.au  Sat Apr 16 04:25:55 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Sat Apr 16 04:27:33 2005
Subject: [Tutor] exceptions
Message-ID: <000801c5422b$9f8ef3e0$9b07a4cb@dianahawks>

Hello list,

I have been trying to trap a string entry by raising an exception.  The code follows - but the exception is never raised.  What am I doing wrong?

TIA Diana

 try:
            
            self.guess = int(self.num_ent.get())

            self.num_ent.delete(0,END)
            self.num_ent.focus_set()
        
            
            if self.guess < self.number:            
                message = str(self.guess) + " is too low. You need to guess higher"

            if self.guess > self.number:      
                message = str(self.guess) + " is too high. You need to guess lower"
            
            if self.guess == self.number:
                message = str(self.guess) + " is the correct number!"
                self.message_txt.config(state = NORMAL)
                self.message_txt.config(state = DISABLED)
        
            self.message_txt.config(state = NORMAL)
            self.message_txt.delete(0.0, END)
            self.message_txt.insert(0.0, message)
            self.message_txt.config(state = DISABLED)


 except(ValueError):
         message = str(self.guess) + " is not a number. Please try again!"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050416/db143c3e/attachment.html
From smichr at bigfoot.com  Sat Apr 16 05:21:51 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Sat Apr 16 05:22:41 2005
Subject: [Tutor] high score lists
In-Reply-To: <001d01c54225$44949ae0$4e5428cf@JSLAPTOP>
Message-ID: <ACBF5ED2-AE26-11D9-8E4E-000393C0D100@bigfoot.com>


On Friday, Apr 15, 2005, at 20:40 America/Chicago, Jacob S. - 
keridee@jayco.net wrote:

> Great.  len is a function though. Why use a second layer of function 
> when len is a function in itself?
>
>>>> l = ['d','sea','bee']
>>>> l.sort(key=len)
>>>> l
> ['d', 'bee', 'sea']
>>>>
>
>
LOL :-) Oooh, that's nice! OK, instead of wasting a post in admiration, 
how about something else that is a possibility since sort() is stable:

###
 >>> l = ['d','sea','bee']
 >>> l.sort() #get them in lexical order
 >>> l
['bee', 'd', 'sea']
 >>> l.sort(key=len) #now get similar lengths together
 >>> l
['d', 'bee', 'sea']
 >>>
###

/c

From smichr at bigfoot.com  Sat Apr 16 05:47:34 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Sat Apr 16 05:48:24 2005
Subject: [Tutor] high score lists
In-Reply-To: <20050415234653.8B9EB1E4013@bag.python.org>
Message-ID: <4462C4BA-AE2A-11D9-8E4E-000393C0D100@bigfoot.com>


On Friday, Apr 15, 2005, at 18:46 America/Chicago, 
tutor-request@python.org wrote:

> I did look at your example about using the longest number, but I
> couldnt really understand all of the code, and ended up deciding to
> arrange it so that the two columns were left-aligned: it looked like
> it would align them down the center in your example? Let me know if I
> am misunderstanding something.
>
Those that are fluent in using the string formatting will groan, but I 
usually don't need fancy formatting and can get by with pretty simple 
commands. I just printed the first column right formatted and printed 
the name right next to it (so it appeared to be left formatted). The 
comma in the print statement added the space.

Here is my simple-minded way of thinking about the two column problem:
	
1) get the data into fixed width strings
2) add those two strings together and print them

Now, as you are seeing, the alignment options for a string will fill in 
the padding spaces that you need.  Figuring out how long each column 
should *minimally* be (based on the actual data) is an extra layer of 
difficulty, but to keep it simple you could just pick widths that you 
think are reasonable and then do something like this:

###
high = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
                  (823,"Grant"), (779,"Aaron"), (702,"Pete"),
                  (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]

for score, who in high:
	col1 = str(score).rjust(10)
	col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots
	print col1 + col2
###
--the output--
       1000..............Denise
        945..............Denise
        883..............Denise
        823...............Grant
        779...............Aaron
        702................Pete
        555.................Tom
        443.................Tom
        442...............Robin
        404................Pete
--end output--

From bvande at po-box.mcgill.ca  Sat Apr 16 07:14:16 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sat Apr 16 07:23:07 2005
Subject: [Tutor] exceptions
In-Reply-To: <000801c5422b$9f8ef3e0$9b07a4cb@dianahawks>
References: <000801c5422b$9f8ef3e0$9b07a4cb@dianahawks>
Message-ID: <42609F28.9070606@po-box.mcgill.ca>

Diana Hawksworth said unto the world upon 2005-04-15 22:25:
> Hello list,
> 
> I have been trying to trap a string entry by raising an exception.  The code follows - but the exception is never raised.  What am I doing wrong?
> 
> TIA Diana
> 
>  try:
>             
>             self.guess = int(self.num_ent.get())
> 
>             self.num_ent.delete(0,END)
>             self.num_ent.focus_set()
>         
>             
>             if self.guess < self.number:            
>                 message = str(self.guess) + " is too low. You need to guess higher"
> 
>             if self.guess > self.number:      
>                 message = str(self.guess) + " is too high. You need to guess lower"
>             
>             if self.guess == self.number:
>                 message = str(self.guess) + " is the correct number!"
>                 self.message_txt.config(state = NORMAL)
>                 self.message_txt.config(state = DISABLED)
>         
>             self.message_txt.config(state = NORMAL)
>             self.message_txt.delete(0.0, END)
>             self.message_txt.insert(0.0, message)
>             self.message_txt.config(state = DISABLED)
> 
> 
>  except(ValueError):
>          message = str(self.guess) + " is not a number. Please try again!"
> 

Hi Dianna,

What are you expecting to raise the ValueError? It looks to me like it 
must be the line:

self.guess = int(self.num_ent.get())

But, if that is so, then the assignment to message in your except 
clause won't work, as self.guess won't have been assigned.

I'm no expert, so I may be missing something, but I wouldn't be 
surprised if your num_ent.get() has details that are pertinent. What 
does that method return?

And, while I'm writing, I'd suggest rewriting your lines like:

message = str(self.guess) + " is the correct number!"

in this form instead:

message = "%s is the correct number!" %self.guess

The almost irrelevant benefit is that it is faster. The big plus is 
string formatting is so handy, that I think it helps a lot to get used 
to using it in most cases, even those that are easy to handle with 
string concatenation as you have done.

Best,

Brian vdB

From project5 at redrival.net  Sat Apr 16 11:16:32 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr 16 11:20:37 2005
Subject: [Tutor] Re: newbie intro to pickle
References: <ECBA357DDED63B4995F5C1F5CBE5B1E8029D800C@its-xchg4.massey.ac.nz>
	<ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>
	<8daabe560504151857386b3af7@mail.gmail.com>
Message-ID: <loom.20050416T105855-347@post.gmane.org>

D. Hartley <denise.hartley <at> gmail.com> writes:

> So the .dump command is, in effect, saving the file, correct? which
> takes the object you're saving (in my case it would be
> high_scorelist), and ("filename","..... what is the "w" ?)  Why does
> the temp file you're saving into end in .pik?

Pickling simply converts an object to a string (unpickling does the opposite,
convert a string to an object). The dump() function writes the generated string
directly to a file, but you can use the dumps() function to get the generated
string as such and do something else with it (e.g. put it in a database, send it
by mail, whatever).

>>> mylist = [1, 2, 34, 4.2, 'abc']
>>> s = pickle.dumps(mylist)
>>> s # display the string
"(lp0\nI1\naI2\naI34\naF4.2000000000000002\naS'abc'\np1\na."
>>> pickle.loads(s)
[1, 2, 34, 4.2000000000000002, 'abc']

Pickling is also very useful when combined with the bsddb module, because you
get a fast database which functions very much like a dictionary, and in which
you can put anything you like, as long as you pickle it first.

>>> import bsddb
>>> mydb = bsddb.btopen('game.db')
>>> mydb['highscores'] = pickle.dumps(mylist)
>>> mydb['highestlevel'] = pickle.dumps(21)
>>> mydb['lastplayer'] = pickle.dumps('John Doe')
>>> mydb.close()
>>> mydb = bsddb.btopen('game.db')
>>> pickle.loads(mydb['lastplayer'])
'John Doe'

This is not useful for small amounts of data like the highscores list, but if
you have more data (e.g. level data, dialog texts) and you need quick access to
it without having to keep everything in memory all the time, bsddb is a
comfortable option.

Yours,

Andrei

From project5 at redrival.net  Sat Apr 16 11:32:37 2005
From: project5 at redrival.net (Andrei)
Date: Sat Apr 16 11:36:37 2005
Subject: [Tutor] Re: exceptions
References: <000801c5422b$9f8ef3e0$9b07a4cb@dianahawks>
Message-ID: <loom.20050416T112151-383@post.gmane.org>

Diana Hawksworth <dianahawks <at> optusnet.com.au> writes:

> I have been trying to trap a string entry by raising an exception.  The code
follows - but the exception is
> never raised.  What am I doing wrong?

I've snipped the code that is irrelevant to this question.

>  try:
>          self.guess = int(self.num_ent.get())
>  except(ValueError):
>          message = str(self.guess) + " is not a number. Please try again!"

Obviously it's hard to determine what's happening since I don't know that that
get() returns, nor what you do with the message. Now let's play with that a bit
in the interpreter:

>>> try:
...     guess = int('abc')
... except (ValueError):
...     print 'not a number'
not a number
>>> try:
...     guess = int('4')
... except (ValueError):
...     print 'not a number'
>>> try:
...     guess = int('abc')
... except (ValueError):
...     message = 'not a number'
>>> print message
not a number

The first run demonstrates that the code is working. The second run shows that
if your source doesn't return any invalid data, the exception will not be
raised. The third run shows that the exception is triggered, but you will simply
not notice it if you don't do anything with message. 

By the way, the third implementation contains a potential problem: if the
message variable does not exist before the try-except and everything goes well,
you'll get a NameError if you try to print it. Also if it does exist, it will
need to be reset before the try-except, otherwise afterwards you won't know
whether its value comes from the last try-except or from some time in the past.

On a sidenote: recommended Python style is to use 4 spaces per indentation level.

Yours,

Andrei

From klas.martelleur at telia.com  Sat Apr 16 12:49:39 2005
From: klas.martelleur at telia.com (Klas Marteleur)
Date: Sat Apr 16 12:49:43 2005
Subject: [Tutor] Sort a list into equal sized chunks
Message-ID: <200504161249.39369.klas.martelleur@telia.com>

Hi
I have wrestled with a problem since last weeks knapsack discussion.

This is what i want, but i cant get it into a program.
----------------------------------------
I have a sorted list (for example):
aList = [10,9,8,7,6,5,4,3,2,1]

I have a max value (for example):
maxValue=11

I have another list:
anotherList=[]

After processing "aList" i want my "anotherList" to look like this:
anotherList=[[10,1],[9,2],[8,3],[7,4],6,5]]
were every element is as close to maxValue as possible.
----------------------------------------

Can somebody give me a push in the back?

Kind Regards 
Klas
From kent37 at tds.net  Sat Apr 16 13:52:37 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 13:52:41 2005
Subject: [Tutor] high score lists
In-Reply-To: <4462C4BA-AE2A-11D9-8E4E-000393C0D100@bigfoot.com>
References: <4462C4BA-AE2A-11D9-8E4E-000393C0D100@bigfoot.com>
Message-ID: <4260FC85.2040301@tds.net>

Chris Smith wrote:
> high = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
>                  (823,"Grant"), (779,"Aaron"), (702,"Pete"),
>                  (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]
> 
> for score, who in high:
>     col1 = str(score).rjust(10)
>     col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots
>     print col1 + col2
> ###
> --the output--
>       1000..............Denise
>        945..............Denise
>        883..............Denise
>        823...............Grant
>        779...............Aaron
>        702................Pete
>        555.................Tom
>        443.................Tom
>        442...............Robin
>        404................Pete
> --end output--

Sweet. Note that in Python 2.4 you can write
   col2 = who.rjust(20, '.')
instead of
   col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots

Kent

From kent37 at tds.net  Sat Apr 16 13:57:48 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 13:57:52 2005
Subject: [Tutor] Re: newbie intro to pickle
In-Reply-To: <loom.20050416T105855-347@post.gmane.org>
References: <ECBA357DDED63B4995F5C1F5CBE5B1E8029D800C@its-xchg4.massey.ac.nz>	<ECBA357DDED63B4995F5C1F5CBE5B1E801DB00A5@its-xchg4.massey.ac.nz>	<8daabe560504151857386b3af7@mail.gmail.com>
	<loom.20050416T105855-347@post.gmane.org>
Message-ID: <4260FDBC.8030302@tds.net>

Andrei wrote:
> Pickling is also very useful when combined with the bsddb module, because you
> get a fast database which functions very much like a dictionary, and in which
> you can put anything you like, as long as you pickle it first.
> 
> 
>>>>import bsddb
>>>>mydb = bsddb.btopen('game.db')
>>>>mydb['highscores'] = pickle.dumps(mylist)
>>>>mydb['highestlevel'] = pickle.dumps(21)
>>>>mydb['lastplayer'] = pickle.dumps('John Doe')
>>>>mydb.close()
>>>>mydb = bsddb.btopen('game.db')
>>>>pickle.loads(mydb['lastplayer'])
> 
> 'John Doe'

You might be interested in the shelve module which essentially does this for you. With shelve your 
example would look like this:

import shelve
d = shelve.open('game.db')
d['highscores'] = mylist
d['highestlevel'] = 21
d['lastplayer'] = 'John Doe'

Kent

From albertito_g at hotmail.com  Sat Apr 16 15:10:25 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr 16 15:10:29 2005
Subject: [Tutor] TKinter and things over Linux
Message-ID: <BAY106-F312D59C7558C228AD37F1589370@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050416/440a5da5/attachment.htm
From kent37 at tds.net  Sat Apr 16 15:22:04 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 15:22:09 2005
Subject: [Tutor] Sort a list into equal sized chunks
In-Reply-To: <200504161249.39369.klas.martelleur@telia.com>
References: <200504161249.39369.klas.martelleur@telia.com>
Message-ID: <4261117C.3070500@tds.net>

Klas Marteleur wrote:
> Hi
> I have wrestled with a problem since last weeks knapsack discussion.
> 
> This is what i want, but i cant get it into a program.
> ----------------------------------------
> I have a sorted list (for example):
> aList = [10,9,8,7,6,5,4,3,2,1]
> 
> I have a max value (for example):
> maxValue=11
> 
> I have another list:
> anotherList=[]
> 
> After processing "aList" i want my "anotherList" to look like this:
> anotherList=[[10,1],[9,2],[8,3],[7,4],6,5]]
> were every element is as close to maxValue as possible.

As someone noted, this problem is properly called the bin packing problem. If you google for "bin 
packing problem" there are a number of interesting references. This one is easy to read:
http://www.ams.org/new-in-math/cover/bins1.html

Finding the optimal partition is a hard problem. But for your purposes (sorting files onto DVDs) a 
simple greedy algorithm might be sufficient. Here is a simple implementation of a First Fit 
Decreasing algorithm:

''' Partition a list into sublists whose sums don't exceed a maximum
     using a First Fit Decreasing algorithm. See
     http://www.ams.org/new-in-math/cover/bins1.html
     for a simple description of the method.
'''


class Bin(object):
     ''' Container for items that keeps a running sum '''
     def __init__(self):
         self.items = []
         self.sum = 0

     def append(self, item):
         self.items.append(item)
         self.sum += item

     def __str__(self):
         ''' Printable representation '''
         return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))


def pack(values, maxValue):
     values = sorted(values, reverse=True)
     bins = []

     for item in values:
         # Try to fit item into a bin
         for bin in bins:
             if bin.sum + item <= maxValue:
                 #print 'Adding', item, 'to', bin
                 bin.append(item)
                 break
         else:
             # item didn't fit into any bin, start a new bin
             #print 'Making new bin for', item
             bin = Bin()
             bin.append(item)
             bins.append(bin)

     return bins


if __name__ == '__main__':
     import random

     def packAndShow(aList, maxValue):
         ''' Pack a list into bins and show the result '''
         print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 
'bins'

         bins = pack(aList, maxValue)

         print 'Solution using', len(bins), 'bins:'
         for bin in bins:
             print bin

         print


     aList = [10,9,8,7,6,5,4,3,2,1]
     packAndShow(aList, 11)

     aList = [ random.randint(1, 11) for i in range(100) ]
     packAndShow(aList, 11)


Kent

From missive at hotmail.com  Sat Apr 16 16:57:44 2005
From: missive at hotmail.com (Lee Harr)
Date: Sat Apr 16 16:57:48 2005
Subject: [Tutor] Re: newbie intro to pickle
Message-ID: <BAY2-F286F30ADF5A5C8231E0064B1370@phx.gbl>

>Pickling simply converts an object to a string (unpickling does the 
>opposite,
>convert a string to an object). The dump() function writes the generated 
>string
>directly to a file, but you can use the dumps() function to get the 
>generated
>string as such and do something else with it (e.g. put it in a database, 
>send it
>by mail, whatever).
>
>>>>mylist = [1, 2, 34, 4.2, 'abc']
>>>>s = pickle.dumps(mylist)
>>>>s # display the string
>"(lp0\nI1\naI2\naI34\naF4.2000000000000002\naS'abc'\np1\na."
>>>>pickle.loads(s)
>[1, 2, 34, 4.2000000000000002, 'abc']
>


... and just to complete the connection of dumps to dump,
you could write the string out to a file yourself ...

>>>import pickle
>>>mylist = [1, 2, 34, 4.2, 'abc']
>>>s = pickle.dumps(mylist)
>>>file_object = file('somefile.pickle', 'w') # I don't think there is a 
>>>"standard" suffix
>>>file_object.write(s)
>>>file_object.close()
>>>_file_object = file('somefile.pickle')
>>>_s = file_object.read()
>>>_mylist = pickle.loads(still_s)
>>>_mylist
[1, 2, 34, 4.2000000000000002, 'abc']


Now my question is how do you keep people from just loading
the high score file with whatever scores they want?

This is not to disparage a simple (and probably very useful)
high score file. It is just something that I have been thinking
about doing myself for quite a while, but I can never quite get
a grasp on how I would go about it.

Any thoughts?

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

From amonroe at columbus.rr.com  Sat Apr 16 17:07:21 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat Apr 16 17:08:19 2005
Subject: [Tutor] Re: newbie intro to pickle
In-Reply-To: <BAY2-F286F30ADF5A5C8231E0064B1370@phx.gbl>
References: <BAY2-F286F30ADF5A5C8231E0064B1370@phx.gbl>
Message-ID: <150313905832.20050416110721@columbus.rr.com>


> Now my question is how do you keep people from just loading
> the high score file with whatever scores they want?

> This is not to disparage a simple (and probably very useful)
> high score file. It is just something that I have been thinking
> about doing myself for quite a while, but I can never quite get
> a grasp on how I would go about it.

This is a recurring discussion in a lot of usenet newsgroups. The
prevailing wisdom is: don't bother. Any way you come up with to keep
it secret can be defeated. Period.

Alan

From albertito_g at hotmail.com  Sat Apr 16 18:47:55 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr 16 18:47:58 2005
Subject: [Tutor] TKinter and things over Linux
Message-ID: <BAY106-F131E9B603E3F751509DD7289370@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050416/3e9820d4/attachment.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050416/3e9820d4/text2.html
From phthenry at iglou.com  Sat Apr 16 18:58:33 2005
From: phthenry at iglou.com (Paul Tremblay)
Date: Sat Apr 16 18:57:35 2005
Subject: [Tutor] distutils problem
Message-ID: <20050416165833.GB28939@localhost.localdomain>

I have written a script that is available at:

https://sourceforge.net/projects/rtf2xml/

This script has gotten about 1600 downloads and I have not got many
bug complaints. However, recently I got the bug complaint listed
below. 

This bug--if it is one--seems to be related to the person't version
and setup of python rather than my script. Can anyone make sense of
it?

Thanks 

Paul

forwarded message
=================

I tried to set this up according to the documentation at

  http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml-module

But when I try to run

   python setup.py install

(both as user and as root)

 I get

  xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install

  running install

  error: invalid Python installation: unable to open /usr/lib/python2.3/config/Makefile (No such file or directory)

According to apt-get, I do have Python correctly installed. I also did
this:

    xps8250:/home/chuck/rtf2xml-1.0a# python

     Python 2.3.5 (#2, Mar 26 2005, 17:32:32)

     [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2

However, in /usr/lib/python2.3/   there is no subdirectory for
/config/Makefile, nor any Makefile in any python subtree. I've looked
around the Python online documentation, but haven't found any
clues. Any suggestions?


-- 

************************
*Paul Tremblay         *
*phthenry@iglou.com    *
************************
From light_zls at 163.com  Sat Apr 16 19:18:45 2005
From: light_zls at 163.com (Light)
Date: Sat Apr 16 19:18:58 2005
Subject: [Tutor] distutils problem
In-Reply-To: <20050416165833.GB28939@localhost.localdomain>
References: <20050416165833.GB28939@localhost.localdomain>
Message-ID: <200504170118.46664.light_zls@163.com>

I think he may need to install python-devel.

> I have written a script that is available at:
>
> https://sourceforge.net/projects/rtf2xml/
>
> This script has gotten about 1600 downloads and I have not got many
> bug complaints. However, recently I got the bug complaint listed
> below.
>
> This bug--if it is one--seems to be related to the person't version
> and setup of python rather than my script. Can anyone make sense of
> it?
>
> Thanks
>
> Paul
>
> forwarded message
> =================
>
> I tried to set this up according to the documentation at
>
>  
> http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml
>-module
>
> But when I try to run
>
>    python setup.py install
>
> (both as user and as root)
>
>  I get
>
>   xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install
>
>   running install
>
>   error: invalid Python installation: unable to open
> /usr/lib/python2.3/config/Makefile (No such file or directory)
>
> According to apt-get, I do have Python correctly installed. I also
> did this:
>
>     xps8250:/home/chuck/rtf2xml-1.0a# python
>
>      Python 2.3.5 (#2, Mar 26 2005, 17:32:32)
>
>      [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
>
> However, in /usr/lib/python2.3/   there is no subdirectory for
> /config/Makefile, nor any Makefile in any python subtree. I've looked
> around the Python online documentation, but haven't found any
> clues. Any suggestions?

From phthenry at iglou.com  Sat Apr 16 19:33:48 2005
From: phthenry at iglou.com (Paul Tremblay)
Date: Sat Apr 16 19:32:48 2005
Subject: [Tutor] distutils problem
In-Reply-To: <20050416165833.GB28939@localhost.localdomain>
References: <20050416165833.GB28939@localhost.localdomain>
Message-ID: <20050416173348.GC29325@localhost.localdomain>

On Sat, Apr 16, 2005 at 12:58:33PM -0400, Paul Tremblay wrote:
> I have written a script that is available at:
> 
> https://sourceforge.net/projects/rtf2xml/
> 
> This script has gotten about 1600 downloads and I have not got many
> bug complaints. However, recently I got the bug complaint listed
> below. 
> 
> This bug--if it is one--seems to be related to the person't version
> and setup of python rather than my script. Can anyone make sense of
> it?
> 
> Thanks 
> 
> Paul
> 
> forwarded message
> =================
> 
> I tried to set this up according to the documentation at
> 
>   http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml-module
> 
> But when I try to run
> 
>    python setup.py install
> 
> (both as user and as root)
> 
>  I get
> 
>   xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install
> 
>   running install
> 
>   error: invalid Python installation: unable to open /usr/lib/python2.3/config/Makefile (No such file or directory)
> 
> According to apt-get, I do have Python correctly installed. I also did
> this:
> 
>     xps8250:/home/chuck/rtf2xml-1.0a# python
> 
>      Python 2.3.5 (#2, Mar 26 2005, 17:32:32)
> 
>      [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
> 
> However, in /usr/lib/python2.3/   there is no subdirectory for
> /config/Makefile, nor any Makefile in any python subtree. I've looked
> around the Python online documentation, but haven't found any
> clues. Any suggestions?
> 
> 

Okay, I just did a web search (which I should have done before I
posted this!) and discovered that the problem is probably due to the
user not having the development package of python installed as well. I
posted him and will wait to hear from him.

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@iglou.com    *
************************
From tutor.fisheggs at xoxy.net  Sat Apr 16 14:19:37 2005
From: tutor.fisheggs at xoxy.net (Nigel Rowe)
Date: Sat Apr 16 20:04:48 2005
Subject: [Tutor] How can I avoid cut'n'paste in this case?
Message-ID: <d3qvlr$n5r$1@sea.gmane.org>

Greetings all,
        I hope someone can help me.

I have two modules, both define the same set of classes (with differing
implementations) and a number of utility functions that use those classes.

The utility functions are identical (the differences I need are abstracted
in the classes), so they are cut'n'pasted into both files.

A simplified concrete example (not what I'm doing, but it illustrates the
point):

-- C.py --
|class Comment:
|    def __init__(self, value):
|        self.value = value
|
|    def __str__(self):
|        return "/* " + self.value + " */"
|
|# utility functions
|import time
|def stamp():
|    return Comment(time.asctime())


-- P.py --
|class Comment:
|    def __init__(self, value):
|        self.value = value
|
|    def __str__(self):
|        return "# " + self.value + "\n"
|
|# utility functions
|import time
|def stamp():
|    return Comment(time.asctime())


How can I refactor these modules to avoid the code duplication?

I tried:

|class Comment
|    ...
|from utils import *

where utils.py contains the functions, but when I try to use C.stamp(), I
get:

>>> import C as lang
>>> lang.stamp()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "utils.py", line 3, in stamp
    return Comment(time.asctime())
NameError: global name 'Comment' is not defined

Any suggestions how I could (for instance) emulate a #include "utils.py" or
any other technique to eliminate the dreaded cut'n'paste?

Thanks.
        Nigel

-- 
        Nigel Rowe
        A pox upon the spammers that make me write my address like..
                rho (snail) swiftdsl (stop) com (stop) au

From amonroe at columbus.rr.com  Sat Apr 16 20:19:18 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat Apr 16 20:20:17 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of the
	dis module to another language
Message-ID: <186325423414.20050416141918@columbus.rr.com>

Just curious. Googling for 'python "dis module" convert "another
language" ' only got two hits. So maybe no one is trying it? I was
just daydreaming about a native python compiler, and wondered how
feasible it would be.

Alan

From kent37 at tds.net  Sat Apr 16 20:23:03 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 16 20:23:06 2005
Subject: [Tutor] How can I avoid cut'n'paste in this case?
In-Reply-To: <d3qvlr$n5r$1@sea.gmane.org>
References: <d3qvlr$n5r$1@sea.gmane.org>
Message-ID: <42615807.1030607@tds.net>

Nigel Rowe wrote:
> I have two modules, both define the same set of classes (with differing
> implementations) and a number of utility functions that use those classes.
> 
> The utility functions are identical (the differences I need are abstracted
> in the classes), so they are cut'n'pasted into both files.
> 
> A simplified concrete example (not what I'm doing, but it illustrates the
> point):
> 
> -- C.py --
> |class Comment:
> |    def __init__(self, value):
> |        self.value = value
> |
> |    def __str__(self):
> |        return "/* " + self.value + " */"
> |
> |# utility functions
> |import time
> |def stamp():
> |    return Comment(time.asctime())
> 
> 
> -- P.py --
> |class Comment:
> |    def __init__(self, value):
> |        self.value = value
> |
> |    def __str__(self):
> |        return "# " + self.value + "\n"
> |
> |# utility functions
> |import time
> |def stamp():
> |    return Comment(time.asctime())
> 
> 
> How can I refactor these modules to avoid the code duplication?

You could make stamp() a classmethod of a common base class like this:

# CommentBase.py
import time

class CommentBase(object):
     def stamp(cls):  # cls will be one of the Comment implementations
         return cls(time.asctime())

     stamp = classmethod(stamp)

# C.py
from CommentBase import CommentBase
class Comment(CommentBase):
     def __init__(self, value):
         self.value = value


# Client code
from C import Comment

c = Comment.stamp()  # This becomes CommentBase.stamp(Comment)
print type(c), c.value


Kent

From dianahawks at optusnet.com.au  Sat Apr 16 23:39:22 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Sat Apr 16 23:40:58 2005
Subject: [Tutor] Re: Eceptions
References: <mailman.2891.1113633520.1797.tutor@python.org>
Message-ID: <001801c542cc$c19ed260$3507a4cb@dianahawks>



>     From: "Brian van den Broek" <bvande@po-box.mcgill.ca>
>     To: "Diana Hawksworth" <dianahawks@optusnet.com.au>
>     Cc: <tutor@python.org>
>     Sent: Saturday, April 16, 2005 3:14 PM
>     Subject: Re: [Tutor] exceptions
>     > Diana Hawksworth said unto the world upon 2005-04-15 22:25:
>     > > Hello list,
>     > >
>     > > I have been trying to trap a string entry by raising an exception.
The
>     code follows - but the exception is never raised.  What am I doing
wrong?
>     > >
>     > > TIA Diana
>     > >
>     > >  try:
>     > >
>     > >             self.guess = int(self.num_ent.get())
>     > >
>     > >             self.num_ent.delete(0,END)
>     > >             self.num_ent.focus_set()
>     > >
>     > >
>
> - Ignored:
>     > >             if self.guess < self.number:
>     > >                 message = str(self.guess) + " is too low. You need
to
>     guess higher"
>     > >
>     > >             if self.guess > self.number:
>     > >                 message = str(self.guess) + " is too high. You
need to
>     guess lower"
>     > >
>     > >             if self.guess == self.number:
>     > >                 message = str(self.guess) + " is the correct
number!"
>     > >                 self.message_txt.config(state = NORMAL)
>     > >                 self.message_txt.config(state = DISABLED)
>     > >
>     > >             self.message_txt.config(state = NORMAL)
>     > >             self.message_txt.delete(0.0, END)
>     > >             self.message_txt.insert(0.0, message)
>     > >             self.message_txt.config(state = DISABLED)
>     > >
>     > >
>     > >  except(ValueError):
>     > >          message = str(self.guess) + " is not a number. Please try
>     again!"
>     > >
>     >
>     > Hi Dianna,
>     >
>     > What are you expecting to raise the ValueError? It looks to me like
it
>     > must be the line:
>     >
>     > self.guess = int(self.num_ent.get())
>     >
>     > But, if that is so, then the assignment to message in your except
>     > clause won't work, as self.guess won't have been assigned.
>     >
>     > I'm no expert, so I may be missing something, but I wouldn't be
>     > surprised if your num_ent.get() has details that are pertinent. What
>     > does that method return?
>     >
>     > And, while I'm writing, I'd suggest rewriting your lines like:
>     >
>     > message = str(self.guess) + " is the correct number!"
>     >
>     > in this form instead:
>     >
>     > message = "%s is the correct number!" %self.guess
>     >
>     > The almost irrelevant benefit is that it is faster. The big plus is
>     > string formatting is so handy, that I think it helps a lot to get
used
>     > to using it in most cases, even those that are easy to handle with
>     > string concatenation as you have done.
>     >
>     > Best,
>     >
>     > Brian vdB
>     >
>     >
>     Thanks for your reply Brian.  The num_ent.get() method returns a
number.
>     Actually, it is an Entry box that returns a string, that I then
convert to
>     an integer.  What I would like to do, is, if a user enters a string,
to have
>     the program return an exception. At the moment it just blithely
carries on
>     as if the string that was entered was in fact an integer, and compares
that
>     entered string to a random number!
>
>     Thanks for the hint on string formatting!  I had forgotten about that!
Been doing
>     this for a month only!!!
>
>     Thanks again. Diana
>
>
>
> - Done.
>
>


From geek_show at dsl.pipex.com  Sun Apr 17 00:13:22 2005
From: geek_show at dsl.pipex.com (joe_schmoe)
Date: Sun Apr 17 00:13:31 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F131E9B603E3F751509DD7289370@phx.gbl>
References: <BAY106-F131E9B603E3F751509DD7289370@phx.gbl>
Message-ID: <42618E02.8080301@dsl.pipex.com>

Alberto Troiano wrote:
> Hi everyone
>  
> Sorry to bother you again but I don't know where else to go
>  
> I recently switch to Linux Red Hat AS 3.0 because I have to make a 
> daemon to run in this OS and I'm having a few problems
>  
> I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but 
> could)
>  
> Now I want to program a GUI with Tkinter but when I put the sentence 
> from TKinter import *, it tells me that it doesn't find the module 
> Tkinter. I have downloaded Python 2.3.4 from python.org and follow the 
> steps.
>  
> Secondly I want to know how to run the .py programs and which is the 
> extension of a GUI in Linux (I know that for Windows is .pyw but it 
> doesn't know what are these in Linux)
>  
> Then is there an IDLE for Linux so I can run the program without having 
> to go to the shell????????
>  
> Thanks a lot
>  
> Regards
>  
> Alberto
> 
> ------------------------------------------------------------------------
> 
> Hi everyone
>  
> I recently switch to Linux Red Hat AS 3.0 because I have to make a 
> daemon to run in this OS and I'm having a few problems
>  
> I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but 
> could)
>  
> Now I want to program a GUI with Tkinter but when I put the sentence 
> from TKinter import *, it tells me that it doesn't find the module 
> Tkinter. I have downloaded Python 2.3.4 from python.org and follow the 
> steps.
>  
> Secondly I want to know how to run the .py programs and which is the 
> extension of a GUI in Linux (I know that for Windows is .pyw but it 
> doesn't know what are these in Linux)
>  
> Then is there an IDLE for Linux so I can run the program without having 
> to go to the shell????????
>  
> Thanks a lot
>  
> Regards
>  
> Alberto
> 
> 
Hi Alberto

I am curious why you are using RH3.0 - be aware that many of the system 
calls of later Python releases may expect libraries that aren't part of 
the distro you are using. I couldn't say for sure, but I'd anticipate 
some limits to backwards compatibility.

Anyway, in answer to your question. To find the Tkinter modules, you 
should probably enter "whereis tkinter" at the command line and then 
re-install Python with that in its path, or re-install TKinter with the 
python installation path. RH has a tendency to Red Hat-ise the file 
hierarchy somewhat, so it could just be a case that one or the other 
doesn't know how to find its libraries.

I couldn't tell you what the extensions for GUIs are. Perhaps 
www.python.org might have some clues for that. However, to run python 
programs from the shell, if you have added the she-bang (the #!/bin/sh 
part) as the first line of your program, then just enter python 
my_program.py at the prompt and watch it run!!

I think that idle tends to be the native IDE for python, but there are 
others you could use, some of which might provide you with a GUI IDE so 
you don't have to use the command line. In the interim however, just 
enter idle at the command line and a new window will be spawned with the 
following:
=========================

Python 2.4.1 (#1, Apr  6 2005, 09:36:35)
[GCC 3.3.4] on linux2
Type "copyright", "credits" or "license()" for more information.

     ****************************************************************
     Personal firewall software may warn about the connection IDLE
     makes to its subprocess using this computer's internal loopback
     interface.  This connection is not visible on any external
     interface and no data is sent to or received from the Internet.
     ****************************************************************

IDLE 1.1.1
 >>>

=========================

To use a text editor just enter ctrl + n in this window and then to run 
it, save it as *.py and hit F5 to run in the idle window.

HtH

/j
From bill at celestial.net  Sun Apr 17 00:50:56 2005
From: bill at celestial.net (Bill Campbell)
Date: Sun Apr 17 00:50:21 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <42618E02.8080301@dsl.pipex.com>
References: <BAY106-F131E9B603E3F751509DD7289370@phx.gbl>
	<42618E02.8080301@dsl.pipex.com>
Message-ID: <20050416225056.GA51899@alexis.mi.celestial.com>

On Sat, Apr 16, 2005, joe_schmoe wrote:
>Alberto Troiano wrote:
>>Hi everyone
>> 
>>Sorry to bother you again but I don't know where else to go
>> 
>>I recently switch to Linux Red Hat AS 3.0 because I have to make a 
>>daemon to run in this OS and I'm having a few problems
>> 
>>I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but 
>>could)
>> 
>>Now I want to program a GUI with Tkinter but when I put the sentence 
>>from TKinter import *, it tells me that it doesn't find the module 
>>Tkinter. I have downloaded Python 2.3.4 from python.org and follow the 
>>steps.

The build process for python will pick up installed libraries for various
components (e.g. Berkeley database, Tk, etc.), so if you don't have Tkinter
on your system, and you built python yourself, it probably means that you
don't have the necessary Tk/TCL development libraries installed on the
system.  Careful perusal of the output of the build is necessary to see
what libraries have been built, and which were skipped.  I normally build
using ``make 2>&1 | tee makelist'' which puts all the output in the file
makelist which I can then examine when the make is complete.

>>Secondly I want to know how to run the .py programs and which is the 
>>extension of a GUI in Linux (I know that for Windows is .pyw but it 
>>doesn't know what are these in Linux)

Python scripts should Just Run(tm) whether they have a .py extension or not
on a Linux box.  Linux, and most *nix flavours don't depend on the file
suffix to determine what type of file it is, but generally look at the
first few bytes of the file (if a text file starts with ``#!'' the rest of
the line is taken to be the command to run the script.

...

Bill
--
INTERNET:   bill@Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

When you have an efficient government, you have a dictatorship.
                -- Harry Truman
From tutor.fisheggs at xoxy.net  Sun Apr 17 02:03:05 2005
From: tutor.fisheggs at xoxy.net (Nigel Rowe)
Date: Sun Apr 17 02:03:27 2005
Subject: [Tutor] Re: How can I avoid cut'n'paste in this case?
References: <d3qvlr$n5r$1@sea.gmane.org> <42615807.1030607@tds.net>
Message-ID: <d3s8so$mdj$1@sea.gmane.org>

Kent Johnson wrote:

> Nigel Rowe wrote:
>> I have two modules, both define the same set of classes (with differing
>> implementations) and a number of utility functions that use those
>> classes.
>> 
>> The utility functions are identical (the differences I need are
>> abstracted in the classes), so they are cut'n'pasted into both files.
>> 
>> A simplified concrete example (not what I'm doing, but it illustrates the
>> point):
>> 
>> -- C.py --
>> |class Comment:
>> |    def __init__(self, value):
>> |        self.value = value
>> |
>> |    def __str__(self):
>> |        return "/* " + self.value + " */"
>> |
>> |# utility functions
>> |import time
>> |def stamp():
>> |    return Comment(time.asctime())
>> 
>> 
>> -- P.py --
>> |class Comment:
>> |    def __init__(self, value):
>> |        self.value = value
>> |
>> |    def __str__(self):
>> |        return "# " + self.value + "\n"
>> |
>> |# utility functions
>> |import time
>> |def stamp():
>> |    return Comment(time.asctime())
>> 
>> 
>> How can I refactor these modules to avoid the code duplication?
> 
> You could make stamp() a classmethod of a common base class like this:
> 
> # CommentBase.py
> import time
> 
> class CommentBase(object):
>      def stamp(cls):  # cls will be one of the Comment implementations
>          return cls(time.asctime())
> 
>      stamp = classmethod(stamp)
> 
> # C.py
> from CommentBase import CommentBase
> class Comment(CommentBase):
>      def __init__(self, value):
>          self.value = value
> 
> 
> # Client code
> from C import Comment
> 
> c = Comment.stamp()  # This becomes CommentBase.stamp(Comment)
> print type(c), c.value
> 
> 
> Kent

Thanks Kent, that's an approach that wouldn't have occurred to me. 
Unfortunately it's not going to do the job for me, since it would require
extensive changes to the client code.

ie.
import C as lang
lang.stamp()

would need to be re-written as

import C as lang
lang.Comment.stamp()

The other problem is that there are a LOT of classes, and some of the
utility functions make use of multiple classes.

eg. (not real code)
class this: ...
class that: ...
class other: ...
class something: ...

def utl_1():
    x = this()
    y = other()
def utl_2():
    z = this()
    foo = something()
def utl_3():
    a = something()
    b = other()

(You get the idea.)

Maybe I'm going too far, trying to eliminate the cut'n'paste, but I've
always thought it a bad smell.

-- 
        Nigel Rowe
        A pox upon the spammers that make me write my address like..
                rho (snail) swiftdsl (stop) com (stop) au

From project5 at redrival.net  Sun Apr 17 02:05:11 2005
From: project5 at redrival.net (Andrei)
Date: Sun Apr 17 02:09:08 2005
Subject: [Tutor] Re: newbie intro to pickle
References: <BAY2-F286F30ADF5A5C8231E0064B1370@phx.gbl>
Message-ID: <loom.20050417T014113-241@post.gmane.org>

Lee Harr <missive <at> hotmail.com> writes:

> Now my question is how do you keep people from just loading
> the high score file with whatever scores they want?

I'd say this is impossible particularly with Python, because cheaters could
always look in the source and find out whatever you're doing to the scores and
if they can't get around it, they can certainly feed that routine bogus scores
and get valid (but cheated) score files. Cheating happens even with
closed-source games.

The only reliable way of scoring is to have an application which both runs and
keeps scores on computers you control (i.e. an online in-browser game), without
relying on cookies or any other form of client-side data.

If you just want to keep casual tinkerers from playing with a plain text scores
file, simple safeguards would suffice, like:

- writing a MD5 hash of the scores list along with the scores themselves. If the
scores are modified and the MD5 isn't, the two won't match.

- implementing some trivial obsfucation (as opposed to real encryption)
algorithm which you could apply to the data before writing it. You could for
example use the zlib module for this (compress the result of pickle.dumps and
decompress the string read from file before feeding it to pickle.loads). The
result will look tremendously ugly and scary, plus it will save a few bytes in
storage space if you're lucky :).

- storing the scores in a bsddb (it can be modified by hand, but it looks quite
scary and mistakes might lead to breakage)

It's quite obvious though that no method is good enough if you attach any kind
of value to high scores, by e.g. posting the highest scores on your webpage.

Yours,

Andrei

From project5 at redrival.net  Sun Apr 17 02:19:32 2005
From: project5 at redrival.net (Andrei)
Date: Sun Apr 17 02:23:37 2005
Subject: [Tutor] Re: How can I avoid cut'n'paste in this case?
References: <d3qvlr$n5r$1@sea.gmane.org> <42615807.1030607@tds.net>
	<d3s8so$mdj$1@sea.gmane.org>
Message-ID: <loom.20050417T021104-572@post.gmane.org>

Nigel Rowe <tutor.fisheggs <at> xoxy.net> writes:

> >> I have two modules, both define the same set of classes (with differing
> >> implementations) and a number of utility functions that use those
> >> classes.
> >> The utility functions are identical (the differences I need are
> >> abstracted in the classes), so they are cut'n'pasted into both files.

How about putting all utility functions in a separate module and doing a "from P
import *" or "from C import *" at the top of that module, depending on some
command line parameter or whatever it is that determines which one should be
imported? It's not elegant by any means, but at least you don't have to
copy-paste code around any more and the changes to the existing code are minimal.

> >> How can I refactor these modules to avoid the code duplication?

I would say that the fact that there are two parallel implementations of the
same classes with small differences is worrying as well. There should be an
ancestor layer in there implementing common behavior.

> Maybe I'm going too far, trying to eliminate the cut'n'paste, but I've
> always thought it a bad smell.

It does indeed smell of a maintenance nightmare waiting to happen :). The bad
part is that it tends to get progressively worse. Imagine also what would happen
if you'd get even more of those similar modules. 

Yours,

Andrei



From cyresse at gmail.com  Sun Apr 17 03:14:23 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Sun Apr 17 03:14:27 2005
Subject: [Tutor] "paused" graphic leaves a 'residue' when returning to
	game?
In-Reply-To: <8daabe5605041415123e95caed@mail.gmail.com>
References: <8daabe5605041415123e95caed@mail.gmail.com>
Message-ID: <f2ff2d05041618147d176358@mail.gmail.com>

Hi Denise, 

Are you using Pygame?

On 4/15/05, D. Hartley <denise.hartley@gmail.com> wrote:
> 
> Another quick question:
> 
> I can pause and unpause the little game I created, and I have a
> graphic to display over top of the game screen when it is paused,
> which tells the user which key to press to unpause, right? It's set
> up the same way as my "game over" graphic. But in any case, when I
> unpause, it leaves this "residue" of the "paused" text on the game
> screen. the moving game characters move over it and sort of wipe it
> out, but I have no idea why it's there or how to clear it!
> 
> Has anyone else encountered a problem like this before? I can post the
> specific code if that would be helpful. I've tried to clear the
> screen, refresh, etc., and since the pause screen uses the same code
> as the game over screen I figured the former should not leave a
> residue if the latter does not. Any suggestions for things to try
> out, to fix this?
> 
> Thanks a ton!
> 
> ~Denise
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050417/327b2b97/attachment.htm
From keridee at jayco.net  Sun Apr 17 04:11:35 2005
From: keridee at jayco.net (Jacob S.)
Date: Sun Apr 17 04:10:34 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	thedis module to another language
References: <186325423414.20050416141918@columbus.rr.com>
Message-ID: <001401c542f2$cceed450$0e5428cf@JSLAPTOP>

> Just curious. Googling for 'python "dis module" convert "another
> language" ' only got two hits. So maybe no one is trying it? I was
> just daydreaming about a native python compiler, and wondered how
> feasible it would be.

Well, from the way I understand the google search works, you would have to 
hit a website that contains *exactly* 'dis module' and\or *exactly* 'another 
language' and\or 'python' and\or 'convert'

I hope that your true google search string doesn't contain the two single 
quote on the outside...
That would mean the website would need to look for the whole string exactly.

So basically any website that contains 'dis module', which stands for what 
by that way? Maybe you should try that without the quotes becase of this 
abbreviation that potential hits might not use.

I guess what I'm trying to say is, try generalizing the search.

Maybe other people call what you're asking for by a different name that you 
aren't including.

Such searches aren't a really good way to judge the statistics of said 
projects due to the name idea etc.

Okay, I'm done.
Jacob 

From amonroe at columbus.rr.com  Sun Apr 17 05:43:58 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sun Apr 17 05:44:57 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	thedis module to another language
In-Reply-To: <001401c542f2$cceed450$0e5428cf@JSLAPTOP>
References: <186325423414.20050416141918@columbus.rr.com>
	<001401c542f2$cceed450$0e5428cf@JSLAPTOP>
Message-ID: <19359302980.20050416234358@columbus.rr.com>

>> Just curious. Googling for 'python "dis module" convert "another
>> language" ' only got two hits. So maybe no one is trying it? I was
>> just daydreaming about a native python compiler, and wondered how
>> feasible it would be.

> I hope that your true google search string doesn't contain the two single
> quote on the outside...

Nope. That was just to set it off from the rest of the sentence in the
email.

> So basically any website that contains 'dis module', which stands for what
> by that way?

It's python's included disassembler for its own virtual machine. It's
interesting to play around with. Try:

import dis
dis.dis(name of some function you def'd in your program)


Alan

From shaleh at speakeasy.net  Sun Apr 17 17:51:48 2005
From: shaleh at speakeasy.net (Sean Perry)
Date: Sun Apr 17 17:54:41 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the	dis module to another language
In-Reply-To: <186325423414.20050416141918@columbus.rr.com>
References: <186325423414.20050416141918@columbus.rr.com>
Message-ID: <42628614.40709@speakeasy.net>

R. Alan Monroe wrote:
> Just curious. Googling for 'python "dis module" convert "another
> language" ' only got two hits. So maybe no one is trying it? I was
> just daydreaming about a native python compiler, and wondered how
> feasible it would be.
> 

There is already a python -> exe converter. Comes up on the list now and 
then. What would your idea change?
From maxnoel_fr at yahoo.fr  Sun Apr 17 18:12:39 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sun Apr 17 18:12:42 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the	dis module to another language
In-Reply-To: <42628614.40709@speakeasy.net>
References: <186325423414.20050416141918@columbus.rr.com>
	<42628614.40709@speakeasy.net>
Message-ID: <7ee2a3f256e0ab3c7e55c06faf7980ff@yahoo.fr>


On Apr 17, 2005, at 16:51, Sean Perry wrote:

> R. Alan Monroe wrote:
>> Just curious. Googling for 'python "dis module" convert "another
>> language" ' only got two hits. So maybe no one is trying it? I was
>> just daydreaming about a native python compiler, and wondered how
>> feasible it would be.
>
> There is already a python -> exe converter. Comes up on the list now 
> and then. What would your idea change?

	A lot. py2exe doesn't compile anything. Basically, all it does is 
bundle a Python interpreter and the code in a clickable application so 
that people can run it without having Python installed. As you've 
probably noticed, a py2exe program runs at the exact same speed as that 
same program run with the Python interpreter from the command line.
	Natively compiling a Python program should theoretically yield a 
tremendous increase in execution speed (as in "faster than psyco"), at 
the expense of cross-platformness (you can only run your binary on the 
platform for which it was compiled).

	Honestly, I don't think that'd be useful. I'm no expert on this 
matter, but I know that coding a compiler is an extremely long and 
difficult process, especially when you're dealing with a dynamic 
language like Python. Also, early versions of a compiler are slow, and 
optimizing it is another extremely long and difficult process.
	Witness gcc -- the C language has been around for 30 years, the most 
widely used for 20, the gcc effort is at least 15 years old, yet 
they're still finding ways to make it spit out faster code...
	Which leads me to my next point: if you want your Python program to be 
faster, rewrite the speed-critical parts (there aren't that many of 
them) in C. That way, you can take advantage of 15+ years of compiler 
optimization efforts.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From kent37 at tds.net  Sun Apr 17 18:18:26 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 17 18:18:30 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the	dis module to another language
In-Reply-To: <186325423414.20050416141918@columbus.rr.com>
References: <186325423414.20050416141918@columbus.rr.com>
Message-ID: <42628C52.60706@tds.net>

R. Alan Monroe wrote:
> Just curious. Googling for 'python "dis module" convert "another
> language" ' only got two hits. So maybe no one is trying it? I was
> just daydreaming about a native python compiler, and wondered how
> feasible it would be.

You might be interested in Pyrex and Psyco:
http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
http://psyco.sourceforge.net/

Kent

From cpu.crazy at gmail.com  Sun Apr 17 18:29:13 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sun Apr 17 18:36:23 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
Message-ID: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>

Hi all,
Another function question.....

def bar(x, y):
	return x + y

bar(4, 5)

So I can put anything I want in there. What good is a function like that?
Of course I know about.
def foo():
	print "Hello all you who subscribe to the Python Tutor mailing list!"

So what do you use the
def bar(x, y):
	return x + y

bar(4, 5)

functions for? (I just need a simple example)
Thanks,
	Joe

From klas.martelleur at telia.com  Sun Apr 17 18:45:21 2005
From: klas.martelleur at telia.com (Klas Marteleur)
Date: Sun Apr 17 18:45:24 2005
Subject: [Tutor] Sort a list into equal sized chunks
In-Reply-To: <4261117C.3070500@tds.net>
References: <200504161249.39369.klas.martelleur@telia.com>
	<4261117C.3070500@tds.net>
Message-ID: <200504171845.22297.klas.martelleur@telia.com>

Thanks Kent
Your program does what i wanted to accomplish. But i dont really know why, and 
that disturbs me. 

I guess its the class that confuses me. Could you or sombody else on this list 
help me out by putting some words on what is happening in this program, and 
in which order things are done?

l?rdagen den 16 april 2005 15.22 skrev Kent Johnson:
> class Bin(object):
> ? ? ?''' Container for items that keeps a running sum '''
> ? ? ?def __init__(self):
> ? ? ? ? ?self.items = []
> ? ? ? ? ?self.sum = 0
>
> ? ? ?def append(self, item):
> ? ? ? ? ?self.items.append(item)
> ? ? ? ? ?self.sum += item
>
> ? ? ?def __str__(self):
> ? ? ? ? ?''' Printable representation '''
> ? ? ? ? ?return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))
>
>
> def pack(values, maxValue):
> ? ? ?#values = sorted(values, reverse=True)
> ? ? ?bins = []
>
> ? ? ?for item in values:
> ? ? ? ? ?# Try to fit item into a bin
> ? ? ? ? ?for bin in bins:
> ? ? ? ? ? ? ?if bin.sum + item <= maxValue:
> ? ? ? ? ? ? ? ? ?#print 'Adding', item, 'to', bin
> ? ? ? ? ? ? ? ? ?bin.append(item)
> ? ? ? ? ? ? ? ? ?break
> ? ? ? ? ?else:
> ? ? ? ? ? ? ?# item didn't fit into any bin, start a new bin
> ? ? ? ? ? ? ?#print 'Making new bin for', item
> ? ? ? ? ? ? ?bin = Bin()
> ? ? ? ? ? ? ?bin.append(item)
> ? ? ? ? ? ? ?bins.append(bin)
>
> ? ? ?return bins
>
>
> if __name__ == '__main__':
> ? ? ?import random
>
> ? ? ?def packAndShow(aList, maxValue):
> ? ? ? ? ?''' Pack a list into bins and show the result '''
> ? ? ? ? ?print 'List with sum', sum(aList), 'requires at least',
> (sum(aList)+maxValue-1)/maxValue, 'bins'
>
> ? ? ? ? ?bins = pack(aList, maxValue)
>
> ? ? ? ? ?print 'Solution using', len(bins), 'bins:'
> ? ? ? ? ?for bin in bins:
> ? ? ? ? ? ? ?print bin
>
> ? ? ? ? ?print
>
>
> ? ? ?aList = [10,9,8,7,6,5,4,3,2,1]
> ? ? ?packAndShow(aList, 11)
>
> ? ? ?aList = [ random.randint(1, 11) for i in range(100) ]
> ? ? ?packAndShow(aList, 11)
From keridee at jayco.net  Sun Apr 17 19:08:59 2005
From: keridee at jayco.net (Jacob S.)
Date: Sun Apr 17 19:08:35 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
References: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
Message-ID: <000b01c54370$3db2bfd0$8b5328cf@JSLAPTOP>

> Hi all,
> Another function question.....
>
> def bar(x, y):
> return x + y
>
> bar(4, 5)
>
> So I can put anything I want in there. What good is a function like that?

Alright, so what good is this function?

def bar(x,y,z):   ##Where in this case x, y, and z are strings
    return x+z+y

>>> bar("a","b","-")
'a-b'
>>> bar("1","2","< + >")
'1< + >2'

And, what good is this function?

def bar(x,y):
    return x+y-x*y

>>> bar(1,2)
1
>>> bar(5,7)
-13
>>> bar(1,4)
1

Nothing, apparently, right?  Okay, so you got us, they're just examples. 
But that's what programming is all about.  Taking examples of functions that 
people or tutorials give you and elaborating on them until you can come up 
with your own that do what *you* want.

> Of course I know about.
> def foo():
> print "Hello all you who subscribe to the Python Tutor mailing list!"
>
> So what do you use the
> def bar(x, y):
> return x + y
>
> bar(4, 5)

Not to go against my grain of these are totally useless, but they aren't 
exactly.  Say you don't want to implement the operator module, or you want a 
slightly different effect.

def add(x,y):
    return x+y
def sub(x,y):
    return x-y
def mul(x,y):
    return x*y
def div(x,y):
    return float(x)/y  ## The float is to overcome the integer division 
default

di = {'add':add,
        'sub:sub,
        'mul':mul,
        'div':div}

ask = input("What is the first number? ")
ask2 = input("What is the second number? ")
funct = raw_input("What do you want to do to them? ")
if funct in di:
    print di[funct](ask,ask2)

Again, this may not seem useful now, but with more difficult functions that 
do many more manipulations to the arguments, etc., this is a actually a 
really useful coding technique.

I'm sure other members of this list will help further, so goodbye.
Jacob 

From bvande at po-box.mcgill.ca  Sun Apr 17 19:09:57 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 17 19:11:46 2005
Subject: [Tutor] Re: Eceptions
In-Reply-To: <001801c542cc$c19ed260$3507a4cb@dianahawks>
References: <mailman.2891.1113633520.1797.tutor@python.org>
	<001801c542cc$c19ed260$3507a4cb@dianahawks>
Message-ID: <42629865.60005@po-box.mcgill.ca>

Diana Hawksworth said unto the world upon 2005-04-16 17:39:

<SNIP>

>>    > Diana Hawksworth said unto the world upon 2005-04-15 22:25:
>>    > > Hello list,
>>    > >
>>    > > I have been trying to trap a string entry by raising an exception.
> 
> The
> 
>>    code follows - but the exception is never raised.  What am I doing
> 
> wrong?
> 
>>    > >
>>    > > TIA Diana
>>    > >
>>    > >  try:
>>    > >
>>    > >             self.guess = int(self.num_ent.get())
>>    > >
>>    > >             self.num_ent.delete(0,END)
>>    > >             self.num_ent.focus_set()
>>    > >
>>    > >
>>
>>- Ignored:
>>    > >             if self.guess < self.number:
>>    > >                 message = str(self.guess) + " is too low. You need
> 
> to
> 
>>    guess higher"
>>    > >
>>    > >             if self.guess > self.number:
>>    > >                 message = str(self.guess) + " is too high. You
> 
> need to
> 
>>    guess lower"
>>    > >
>>    > >             if self.guess == self.number:
>>    > >                 message = str(self.guess) + " is the correct
> 
> number!"
> 
>>    > >                 self.message_txt.config(state = NORMAL)
>>    > >                 self.message_txt.config(state = DISABLED)
>>    > >
>>    > >             self.message_txt.config(state = NORMAL)
>>    > >             self.message_txt.delete(0.0, END)
>>    > >             self.message_txt.insert(0.0, message)
>>    > >             self.message_txt.config(state = DISABLED)
>>    > >
>>    > >
>>    > >  except(ValueError):
>>    > >          message = str(self.guess) + " is not a number. Please try
>>    again!"
>>    > >
>>    >
>>    > Hi Dianna,
>>    >
>>    > What are you expecting to raise the ValueError? It looks to me like
> 
> it
> 
>>    > must be the line:
>>    >
>>    > self.guess = int(self.num_ent.get())
>>    >
>>    > But, if that is so, then the assignment to message in your except
>>    > clause won't work, as self.guess won't have been assigned.
>>    >
>>    > I'm no expert, so I may be missing something, but I wouldn't be
>>    > surprised if your num_ent.get() has details that are pertinent. What
>>    > does that method return?
>>    >

<SNIP my suggestion to use string formatting>

>>    >
>>    > Best,
>>    >
>>    > Brian vdB
>>    >
>>    >
>>    Thanks for your reply Brian.  The num_ent.get() method returns a
> 
> number.
> 
>>    Actually, it is an Entry box that returns a string, that I then
> 
> convert to
> 
>>    an integer.  What I would like to do, is, if a user enters a string,
> 
> to have
> 
>>    the program return an exception. At the moment it just blithely
> 
> carries on
> 
>>    as if the string that was entered was in fact an integer, and compares
> 
> that
> 
>>    entered string to a random number!


Hi Diana,

hm, our mail clients between them appear to have made a mess of the 
quoting :-(  This makes it a bit harder to parse the code, but let's try.

I'm still not 100% clear on the role of

self.guess = int(self.num_ent.get())

in your code. Does self.num_ent.get() return a string or an integer? 
Perhaps I'm misreading, but you seem to say both. Your second comment 
is that "it is an Entry box that returns a string" -- I assume you 
mean that at some point it calls the raw_input function, right?

What happens if you enter something like "I am not a number!" at that 
point in the run of self.num_ent.get? If self.num_ent.get() really 
just returns a string, then I'd expect roughly the same thing as what 
happens below:

 >>> my_input = raw_input("Well?\n")
Well?
I am not a number!
 >>> int(my_input)

Traceback (most recent call last):
   File "<pyshell#2>", line 1, in -toplevel-
     int(my_input)
ValueError: invalid literal for int(): I am not a number!
 >>>

I think it would help if you posted the code for the num_ent.get 
method. Otherwise, I at least, am out of stuff to say :-)
(If you post again, please delete the goofy-formatted code quote 
above, and replace with a new copy-paste from your source.)

>>
>>    Thanks for the hint on string formatting!  I had forgotten about that!
> 
> Been doing
> 
>>    this for a month only!!!
>>
>>    Thanks again. Diana


Your welcome. There is a lot to keep in one's head at the beginning, 
isn't there? My money is on the claim that string formatting is a good 
habit to get into early.

Best,

Brian vdB

From maxnoel_fr at yahoo.fr  Sun Apr 17 19:12:32 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sun Apr 17 19:12:37 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
References: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
Message-ID: <0e953b17046cd8c8090a586735055d95@yahoo.fr>


On Apr 17, 2005, at 17:29, Joseph Quigley wrote:

> So what do you use the
> def bar(x, y):
> 	return x + y
>
> bar(4, 5)
>
> functions for? (I just need a simple example)

	Whenever you have something that you may want to do more than once 
and/or in more than one place in your program. Here's a small example: 
a dice-rolling function. Say you're writing a program to automate some 
part of a roleplaying game. At some point you'll want to roll dice. So 
instead of writing the code to do that every time, you just call the 
rollDice function, supplying the number and type of dice you want to 
roll. If you need to roll 2D6, just call rollDice(2, 6).



#!/usr/bin/env python

import random

def rollDice(numDice, numSides):
     dice = [random.randint(1, numSides) for i in range(numDice)]
     return dice



	Here it is in action:

 >>> rollDice(2, 6)
[1, 4]


	Note that rollDice itself calls functions: the randint function from 
the random module, and the built-in range function. (it also uses a 
list comprehension, but that's another topic)

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From leec03273 at mac.com  Sun Apr 17 19:17:11 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Sun Apr 17 19:17:19 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
References: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
Message-ID: <c900501d885ca471a3e3695cdebf8fb3@mac.com>

I think your looking at it too literally Joseph.  Rather than any one 
example, think of a function as a block of code that is used in more 
than one place in your program.  The x + y block of code is just a 
simplistic representation, intended to illustrate without the 
distracting complications of a more involved algorithm.

Functions are also useful (even necessary) in various approaches to 
problem solving.  If you need an example one might be the recursive 
matrix solution approach I posted a link to in another post to this 
list.

Lee C


On Apr 17, 2005, at 12:29 PM, Joseph Quigley wrote:

> Hi all,
> Another function question.....
>
> def bar(x, y):
> 	return x + y
>
> bar(4, 5)
>
> So I can put anything I want in there. What good is a function like 
> that?
> Of course I know about.
> def foo():
> 	print "Hello all you who subscribe to the Python Tutor mailing list!"
>
> So what do you use the
> def bar(x, y):
> 	return x + y
>
> bar(4, 5)
>
> functions for? (I just need a simple example)
> Thanks,
> 	Joe
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From bvande at po-box.mcgill.ca  Sun Apr 17 19:52:08 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 17 19:52:41 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
References: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
Message-ID: <4262A248.7080003@po-box.mcgill.ca>

Joseph Quigley said unto the world upon 2005-04-17 12:29:
> Hi all,
> Another function question.....
> 
> def bar(x, y):
>     return x + y
> 
> bar(4, 5)
> 
> So I can put anything I want in there. What good is a function like that?
> Of course I know about.
> def foo():
>     print "Hello all you who subscribe to the Python Tutor mailing list!"
> 
> So what do you use the
> def bar(x, y):
>     return x + y
> 
> bar(4, 5)
> 
> functions for? (I just need a simple example)
> Thanks,
>     Joe


Hi Joe,

(I see Max and Lee are quicker than I, but I hate to waste the typing! 
So:)

Jacob was, I think, exactly right when in his reply he stressed that 
these were just examples. I don't recall the exact context in the 
thread where such an example came up. But, a safe bet is that whoever 
gave it to you (gosh, hope it wasn't me, or the failure of 
recollection will be a bit of a blusher!) was giving you an example 
where the function definition structure was the complicated thing, not 
the function logic.

Given that Python has a builtin '+' operator, the bar function example 
adds nothing. But, consider this:

 >>> def fancy_bar(x, y):
... 	try:
... 		return x + y
... 	except TypeError:
... 		return str(x) + str(y)

The original bar will barf in cases like bar(42, 'my favourite 
string'). fancy_bar won't. (Of course, it might not have the best 
result either. But it is an example of how you can harness the power 
of function definitions to do something more than do the bare Python 
builtins.)

Perhaps this analogy will hep you grok the point of functions. Have 
you ever defined a macro in a word processor? ('Macro' often has a 
special meaning in some programming languages, but put that aside. I 
mean to focus on the macros of, say, M$ Word.) The point of those is 
to allow you to put a bunch of word processor commands and operations 
into a convenient chunk, ready for easy invocation. You could always 
do the same operations one at a time by hand in the word processor. 
But, if there is a common routine, making a macro for it makes your 
life easier.

Function definitions in a programming language are kind of like macros 
definitions in a word processor. They let you put a bunch of logic 
into one easy to call command. They don't let you do anything you 
couldn't do before. But they save you from having to write the 
explicit step by step instructions each time. (That makes life easier 
and less error-prone.)

Of course, the point of this is more clear where you have more 
complicated logic inside the function body. But the examples people 
have been giving you are trying to keep the body simple, to focus on 
the function structure.

Here's a non-trivial example where a function does useful work. (It 
probably can be done more prettily -- never mind that, it is a 2 
minute rough example :-) :

 >>> def mode_finder(a_sequence):
	'''returns a tuple of the modes of a_sequence.'''
  	count_dict = {}
  	for item in a_sequence:
  		count_dict[item] = count_dict.setdefault(item, 0) + 1
  	max_count = max(count_dict.values())
  	modes = [x for x in count_dict if count_dict[x] == max_count]
  	return tuple(modes)

 >>> mode_finder([1,2,3,1,1,4,4,5,5,3,3,7,8,7])
(1, 3)

The "mode" of a sequence is the most commonly occurring element (or 
elements). That is something one often want to know. The mode_finder 
function wraps the logic for finding it up into a single, nice, easy 
to invoke collection of commands. It is much better than rewriting 
those commands every time you want to find the mode.

Does that help explain why you'd care about functions?

Best,

Brian vdB

From kent37 at tds.net  Sun Apr 17 22:11:21 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 17 22:11:26 2005
Subject: [Tutor] Sort a list into equal sized chunks
In-Reply-To: <200504171845.22297.klas.martelleur@telia.com>
References: <200504161249.39369.klas.martelleur@telia.com>	<4261117C.3070500@tds.net>
	<200504171845.22297.klas.martelleur@telia.com>
Message-ID: <4262C2E9.8060701@tds.net>

Klas Marteleur wrote:
> Thanks Kent
> Your program does what i wanted to accomplish. But i dont really know why, and 
> that disturbs me. 
> 
> I guess its the class that confuses me. Could you or sombody else on this list 
> help me out by putting some words on what is happening in this program, and 
> in which order things are done?

OK, I'll try.

First I define a class to represent a bin of items. What are the characteristics of a bin? A bin 
contains the actual items, which are represented as a list. But a bin also has a sum, the total of 
its items. Keeping a running sum as a separate attribute lets me avoid computing the sums each time 
I want to know what it is.

This is a pretty good example of a simple class, for those listening in. A Bin has a state - its 
list of items and its sum - and two simple behaviors - adding an item and creating a string 
representation.

Let's try one out:

 >>> b=Bin()
 >>> print b
Bin(sum=0, items=[])
 >>> b.append(1)
 >>> print b
Bin(sum=1, items=[1])
 >>> b.append(10)
 >>> print b
Bin(sum=11, items=[1, 10])

I can access the sum and the item list directly:
 >>> b.sum
11
 >>> b.items
[1, 10]

>>class Bin(object):
>>     ''' Container for items that keeps a running sum '''
>>     def __init__(self):
>>         self.items = []
>>         self.sum = 0
>>
>>     def append(self, item):
>>         self.items.append(item)
>>         self.sum += item
>>
>>     def __str__(self):
>>         ''' Printable representation '''
>>         return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))

Now define a function to do the actual bin packing. It takes two arguments - a list of the values to 
be packed, and the maximum sum allowed in a bin.

>>def pack(values, maxValue):

The algorithm works best with a sorted list. If your list is already sorted, you don't need this 
line. If you are using a version of Python older than 2.4, you need to write this differently.
>>     #values = sorted(values, reverse=True)

This is a list of Bins. Initially it is empty.
>>     bins = []
>>

Now start putting items into bins.
>>     for item in values:

Go through the Bins in order, looking for one that can hold the current item
>>         # Try to fit item into a bin
>>         for bin in bins:
>>             if bin.sum + item <= maxValue:

We found a Bin that has room, add the item to the bin and break out of the bin search loop
>>                 #print 'Adding', item, 'to', bin
>>                 bin.append(item)
>>                 break

This code will only be run if the for loop ran to completion - if it did NOT terminate with a break. 
That only happens if we didn't find a Bin with room for the item. So, let's make a new bin.
>>         else:
>>             # item didn't fit into any bin, start a new bin
>>             #print 'Making new bin for', item

Make a new bin
>>             bin = Bin()

Add the item to the bin
>>             bin.append(item)

Add the bin to the list of bins
>>             bins.append(bin)
>>

When we get here all the items have been placed in bins, we are done.
>>     return bins
>>
>>

This is test code
>>if __name__ == '__main__':
>>     import random
>>

Here is a function that packs a list into Bins and prints out the result. It is handy for testing.
>>     def packAndShow(aList, maxValue):
>>         ''' Pack a list into bins and show the result '''
>>         print 'List with sum', sum(aList), 'requires at least',
>>(sum(aList)+maxValue-1)/maxValue, 'bins'
>>
>>         bins = pack(aList, maxValue)
>>
>>         print 'Solution using', len(bins), 'bins:'
>>         for bin in bins:
>>             print bin
>>
>>         print
>>
>>

This is a simple test case
>>     aList = [10,9,8,7,6,5,4,3,2,1]
>>     packAndShow(aList, 11)
>>

Here is a bigger test case using a list of random numbers
>>     aList = [ random.randint(1, 11) for i in range(100) ]
>>     packAndShow(aList, 11)

HTH,
Kent

From garnaez at gmail.com  Sun Apr 17 22:38:14 2005
From: garnaez at gmail.com (gerardo arnaez)
Date: Sun Apr 17 22:38:20 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <148eea710504052000582e43a1@mail.gmail.com>
References: <20050404100100.77EF51E4012@bag.python.org>
	<96964C1C-A534-11D9-88B0-000393C0D100@saysomething.com>
	<148eea71050404125655f05cf5@mail.gmail.com> <4251AF49.1010403@tds.net>
	<148eea710504052000582e43a1@mail.gmail.com>
Message-ID: <148eea7105041713385b06d3f@mail.gmail.com>

Hi all.
I have finished a coumadin dose calcalutor
but want to have it work via a web interface.

The base code is here
 http://mung.net/~dude/coumadinAll.html

but not sure what would be the next step in getting this working
on the web.

is,

I want someone to use a web interface
and type in INR, and the coumadin dose regimen
and have it spit out a value

Any ideas?


> Thanks all all for your time,
> G
>
From alan.gauld at freenet.co.uk  Mon Apr 18 01:07:36 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 01:07:41 2005
Subject: [Tutor] OO newbie
References: <1112901703.4516.55.camel@localhost><00d401c53bb8$2089cc10$46df8751@xp>
	<42567451.5030605@tds.net>
Message-ID: <006801c543a2$3eec3e80$728f8651@xp>

Just back from vacation - hence the delayed response...

> > super is just a convenience feature added to make Python slightly
> > more like some other OOP languages. It is effectively just a
> > wrapper around the explicit call to the super class:
>
> No, super() is much smarter than that and was created to address
deficiencies in direct superclass
> calling. super(C, self) actually finds the class that follows C in
the method resolution order of
> the class of self. This can be very different from just calling the
base class method; in the case
> of multiple inheritance super(C, self) may not ever refer to a base
class of C.

Ah! Ok, I didn't realise that. From my quick read of the super
documentation
I missed that bit and just thought - syntactic sugar...

I see that I'll need to do some more experimenting with super...

Thanks for the clarification Kent,

Alan G.

From amonroe at columbus.rr.com  Mon Apr 18 01:20:40 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Mon Apr 18 01:21:42 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the dis module to another language
In-Reply-To: <42628614.40709@speakeasy.net>
References: <186325423414.20050416141918@columbus.rr.com>
	<42628614.40709@speakeasy.net>
Message-ID: <33429905531.20050417192040@columbus.rr.com>

> R. Alan Monroe wrote:
>> Just curious. Googling for 'python "dis module" convert "another
>> language" ' only got two hits. So maybe no one is trying it? I was
>> just daydreaming about a native python compiler, and wondered how
>> feasible it would be.
>> 

> There is already a python -> exe converter. Comes up on the list now and 
> then. What would your idea change?

The main things about it that would make it appealing to me:

#1 - MUCH MUCH MUCH smaller exes. Speed is not an issue to me, but
filesize is. Have you ever compiled "Hello world" in a new language,
and found that the exe was 100K+, when it really only needs to be less
than 1K? And py2exe... I am not averse to using it, but 800 - 1000K+
exes, well, it's just my pet peeve.

#2 - Love of classic hacking wizardry. :^)

Alan

From alan.gauld at freenet.co.uk  Mon Apr 18 01:25:47 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 01:26:01 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output
	ofthe	dis module to another language
References: <186325423414.20050416141918@columbus.rr.com><42628614.40709@speakeasy.net>
	<7ee2a3f256e0ab3c7e55c06faf7980ff@yahoo.fr>
Message-ID: <008b01c543a4$c9b8dbc0$728f8651@xp>

Sorry to be picky but...

> Witness gcc -- the C language has been around for 30 years, the most
> widely used for 20,

Depends how you define 'most widely used' I guess but the language
with
most code and the most programming jobs is still COBOL(*) by a long
margin.
And going by jobs Java overtook C/C++(combined) a couple of years
ago...
Pure C hasn't been number one at any point in its existence. But it
does depend on how you measure, if you are talking about the number
of platforms it supports then I suspect C wins.

> the gcc effort is at least 15 years old,

At least, I suspect closer to 20. I've been using gcc for 14 and it
was
mature even then (maybe even at version 2!).

> they're still finding ways to make it spit out faster code...

But that's not hard. gcc is a great compiler in many ways but
speed of final code has never been one of them - which is why
Sun, HP, IBM, Borland, Watcom etc can still charge big bucks
for their optimised compilers. The one I know best - from
Sun - is usually 10-30% faster than gcc in final code speed.
But then, who knows better how to optimise for a Sun Sparc
chip than Sun... And at $2000 per copy they can afford the
research. (And we can afford exactly one copy, used for the
final compile! :-)

> Which leads me to my next point: if you want your Python program to
be
> faster, rewrite the speed-critical parts (there aren't that many of
> them) in C.

And that's the real nub, Python is a great scripting language,
where you need C speed - use C!

Alan G.

(*)Remember that most of the really big projects - with several
hundreds of coders - tend to be corporate business applications built
for mainframes - nearly all done in COBOL! If each of the Fortune 500
companies has an average of 10 big projects each with 200 programmers
(not that many on really big job) that's 2000x500 = 1 million COBOL
coders,
not counting the many thousands working on maintaining old legacy
code.


From albertito_g at hotmail.com  Mon Apr 18 01:40:47 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 18 01:40:52 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <20050416225056.GA51899@alexis.mi.celestial.com>
Message-ID: <BAY106-F25D6F29A2BC34D1D81B31289280@phx.gbl>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050417/130197a4/attachment.htm
From alan.gauld at freenet.co.uk  Mon Apr 18 01:47:51 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 01:48:00 2005
Subject: [Tutor] More Function Questions (Joseph Q.)
References: <6.1.0.6.2.20050417102432.01f20070@pop.gmail.com>
Message-ID: <00a901c543a7$e0df30d0$728f8651@xp>

> So what do you use the
> def bar(x, y):
> return x + y
> 
> bar(4, 5)
> 
> functions for? (I just need a simple example)

As an illustration of what a functionlooks like bar is 
fine but as it stands it's not a great example of a 
real function for several reasons:
1) The name is not descriptive of what it does
2) The body is shorter to write than the function call

Functions serve two useful purposes, the first is to make you 
code easier to read by replacing several lines of primitive code 
to a readable and meaningful description. This is known as 
*abstraction*.

The second purpose is to cut down the amount of typing you do
(and help make maintenance easier too). This is because the 
function turns what could be a long sequence of instructions 
into a short function name.

Let's look at a slightly more realistic example:

def average(listOfNums):
   total = 0
   if not type(listOfNums) == list:
      raise TypeError
   for num in listOfNums:
      if not type(num) == int: 
         raise TypeError
      total += num
   return total/len(listOfNums)


Now, it's much easier to type

print average([1,3,4,6,8,9,12])
print average([6,3,8,1,9])

than to try to  retype the code inside the function both times
(and any other time you need to average a list...) and in 
addition your code is much easier to read - 'average' gives 
some idea of what to expect in the result.

BTW You could shorten the function slightly using a list 
comprehension but the basic need for type checking etc is 
still valid and the naming/abstaction issue also still holds.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at freenet.co.uk  Mon Apr 18 02:06:44 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 02:06:44 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output ofthe
	dis module to another language
References: <186325423414.20050416141918@columbus.rr.com><42628614.40709@speakeasy.net>
	<33429905531.20050417192040@columbus.rr.com>
Message-ID: <00cf01c543aa$81d701a0$728f8651@xp>

> #1 - MUCH MUCH MUCH smaller exes. Speed is not an issue to me, but
> filesize is. Have you ever compiled "Hello world" in a new language,
> and found that the exe was 100K+, when it really only needs to be
less
> than 1K?

It is occasionally possible to get such small exes - it used to be
possibly on DOS by compiling to a COM file rather than EXE - but
that's only possible because of the huge size of the library files.
Have you looked at the standard C libraries? On my cygwin install
libc is nearly 800K and libstdc++ is just under 1M...
If you statically link a C program to its libraries it grows rapidly.

The same happens with Python, most python programs in .pyc form)
are quite small, it's the interpreter and library that takes up
the space. So if it's space you are concerned with don't compile
just leave them as .py or .pyc...

> And py2exe... I am not averse to using it, but 800 - 1000K+
> exes, well, it's just my pet peeve.

Yep, which is why I distribute as .pyc and the interpreter
is optional... But it does need savvy users. Otherwise py2exe
keeps the techno-phobes happy and disks are cheap these days...

Alan G.

From dianahawks at optusnet.com.au  Mon Apr 18 02:05:54 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr 18 02:08:30 2005
Subject: [Tutor] Re: Exceptions
References: <mailman.2891.1113633520.1797.tutor@python.org>
	<001801c542cc$c19ed260$3507a4cb@dianahawks>
	<42629865.60005@po-box.mcgill.ca>
Message-ID: <000301c543aa$82b61700$1dc41dd3@dianahawks>

Brian - thanks for your continuing help!  Here is ALL of the code.  Sure
hope you can help. Cheers. Diana

# Number 10
# A Guess the Number program
# Hawksworth - 28/3/05

from Tkinter import *
import random

class Application(Frame):
    """ GUI application  - guess the number game. """
    def __init__(self, master):
        """ Initialize the frame. """
        Frame.__init__(self, master)
        self.grid()
        self.bttn_clicks = 0    # the number of button clicks
        self.create_widgets()
        self.doRandom()
        self.guess = 0


    # a function to randomize a number
    def doRandom(self):
        self.number = random.randrange(10) + 1

    # a function that creates various buttons and text boxes
    def create_widgets(self):
        """ Create button, text, and entry widgets. """
        # create instruction label
        self.inst_lbl = Label(self, text = "Guess a number between 1 and
10.\n"
                              "You have 5 guesses to get it right!", fg =
"blue")
        self.inst_lbl.grid(row = 0,rowspan = 2, column = 0, columnspan = 2,
sticky = W)
        self.inst_lbl = Label(self, text = "Make a guess then press the
Enter key", fg = "red")
        self.inst_lbl.grid(row = 2,column = 0, columnspan = 2, sticky = W)

        # create label for number
        self.num_lbl = Label(self, text = "What's your Guess?: ", fg =
"blue")
        self.num_lbl.grid(row = 3, column = 0, sticky = W)

        # create entry (text)widget to accept number
        self.num_ent = Entry(self, width = 5)
        self.num_ent.grid(row = 3, column = 1, sticky = W)
        self.num_ent.focus_set()
        self.num_ent.bind('<Return>', (lambda event: self.two_commands()))

        # create submit button to call the appropriate message
        self.submit_bttn = Button(self, text = "Tries: 0", command =
self.two_commands)
        self.submit_bttn.grid(row = 4, column = 0, sticky = W)

        # create number of tries button
        """ Create button which displays number of clicks. """
        self.click_bttn = Button(self, text = "Tries: 0", command =
self.two_commands)
        self.click_bttn.grid(row = 4, column = 0, sticky = W)

        # create text widget to display message
        self.message_txt = Text(self, width = 35, height = 5, wrap = WORD)
        self.message_txt.grid(row = 5, column = 0, columnspan = 2, sticky =
W)

        # create reset and quit widgets
        self.bReset = Button(self, text="Reset", command=self.doReset)
        self.bReset.grid(row = 6, column = 1, sticky = W)

        self.bQuit = Button(self, text="Quit", command=self.doQuit)
        self.bQuit.grid(row = 7, column = 0, sticky = W)

   # quit the program
    def doQuit(self):
        self.quit()

   # restore default settings
    def doReset(self):
        self.doRandom()         # randomizing another number
        self.bttn_clicks = 0    # the number of button clicks
        self.tries = 0          # increasing the number of guesses
        self.create_widgets()   # returning to default settings

    # calling the functions to reveal the message
    # and to update the count button
    def two_commands(self):
        self.reveal()
        self.update_count()

    # updating the count button on user click
    def update_count(self):
        """ Increase click count and display new total. """
        self.bttn_clicks += 1
        self.click_bttn["text"] = "Tries: %s" %self.bttn_clicks
        if self.bttn_clicks > 5:
            self.toomany()

    def toomany(self):
        message = "Out of guesses! Your number was: %s" %self.guess + " The
number you wanted was: %s" %self.number
        #message += str(self.number)

        self.message_txt.config(state = NORMAL)
        self.message_txt.delete(0.0, END)
        self.message_txt.insert(0.0, message)
        self.message_txt.config(state = DISABLED)

    # revealing the message comparing the guess with the random number
    def reveal(self):
        """ Display message based on number. Changing text widget to integer
            Correcting the entry of a string variable - except the error
checking isn't working!"""

        try:
            self.guess = int(self.num_ent.get())

        except(ValueError),e:
            message = "%s is not a number. Please try again!" %self.guess

        else:
            self.num_ent.delete(0,END)
            self.num_ent.focus_set()

            if self.guess < self.number:
                message = "%s is too low! You need to guess higher. "
%self.guess

            if self.guess > self.number:
                message = "%s is too high! You need to guess lower."
%self.guess

            if self.guess == self.number:
                message = "%s is the correct number!" %self.guess

                self.message_txt.config(state = NORMAL)
                self.message_txt.config(state = DISABLED)

            self.message_txt.config(state = NORMAL)
            self.message_txt.delete(0.0, END)
            self.message_txt.insert(0.0, message)
            self.message_txt.config(state = DISABLED)


# main
root = Tk()
root.title("Guess the Number Game")
root.geometry("250x250")

app = Application(root)

root.mainloop()


From dianahawks at optusnet.com.au  Mon Apr 18 02:55:43 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr 18 02:57:30 2005
Subject: [Tutor] displaying images
Message-ID: <000801c543b1$5d267140$8c07a4cb@dianahawks>

Hello list!  I am working through "Programming Python" by Mark Lutz. I am puzzled by the following script - as I am not certain what the "../gifs/" means, even though Lutz explains it by saying it is the reference for a GIF stored  "in another directory". I have tried to adapt it - using my own files, but cannot figure out where to store the files I am using.  I have even tried using the full path name for my files without success.  

Can anyone tell me what the line means, please?  Cheers. Diana

gifdir = "../gifs/"
from Tkinter import *
win = Tk()
igm = PhotoImage(file=gifdir+"ora-pp.gif")
Button(win, image = igm).pack()
win.mainloop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050418/8cf748f1/attachment.html
From kent37 at tds.net  Mon Apr 18 03:39:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 18 03:39:48 2005
Subject: [Tutor] displaying images
In-Reply-To: <000801c543b1$5d267140$8c07a4cb@dianahawks>
References: <000801c543b1$5d267140$8c07a4cb@dianahawks>
Message-ID: <42630FDE.60702@tds.net>

Diana Hawksworth wrote:
> Hello list!  I am working through "Programming Python" by Mark Lutz. I 
> am puzzled by the following script - as I am not certain what the 
> "../gifs/" means, even though Lutz explains it by saying it is the 
> reference for a GIF stored  "in another directory". I have tried to 
> adapt it - using my own files, but cannot figure out where to store the 
> files I am using.  I have even tried using the full path name for my 
> files without success. 

In a file path, .. means the parent directory. So "../gifs/" refers to a directory called "gifs" 
that has the same parent as the current working directory.

This program works for me giving the full path to a file. Notice that I used a raw string (r"...") 
so the backslashes don't have any special meaning. Alteratively I could use forward slashes (/) - 
Python on Windows can use either.

from Tkinter import *
win = Tk()
igm = PhotoImage(file=r"D:\Projects\CB\jws\skillsoft_logo.gif")
Button(win, image = igm).pack()
win.mainloop()

Kent

>  
> Can anyone tell me what the line means, please?  Cheers. Diana
>  
> gifdir = "../gifs/"
> from Tkinter import *
> win = Tk()
> igm = PhotoImage(file=gifdir+"ora-pp.gif")
> Button(win, image = igm).pack()
> win.mainloop()
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From dianahawks at optusnet.com.au  Mon Apr 18 03:42:10 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr 18 03:43:53 2005
Subject: [Tutor] displaying images
References: <000801c543b1$5d267140$8c07a4cb@dianahawks>
	<42630FDE.60702@tds.net>
Message-ID: <000401c543b7$d790e2c0$55c41dd3@dianahawks>

Ahhh! Thanks Kent. Shall give that a try. Diana

----- Original Message ----- 
From: "Kent Johnson" <kent37@tds.net>
To: "Diana Hawksworth" <dianahawks@optusnet.com.au>
Cc: <tutor@python.org>
Sent: Monday, April 18, 2005 11:39 AM
Subject: Re: [Tutor] displaying images


> Diana Hawksworth wrote:
> > Hello list!  I am working through "Programming Python" by Mark Lutz. I
> > am puzzled by the following script - as I am not certain what the
> > "../gifs/" means, even though Lutz explains it by saying it is the
> > reference for a GIF stored  "in another directory". I have tried to
> > adapt it - using my own files, but cannot figure out where to store the
> > files I am using.  I have even tried using the full path name for my
> > files without success.
>
> In a file path, .. means the parent directory. So "../gifs/" refers to a
directory called "gifs"
> that has the same parent as the current working directory.
>
> This program works for me giving the full path to a file. Notice that I
used a raw string (r"...")
> so the backslashes don't have any special meaning. Alteratively I could
use forward slashes (/) -
> Python on Windows can use either.
>
> from Tkinter import *
> win = Tk()
> igm = PhotoImage(file=r"D:\Projects\CB\jws\skillsoft_logo.gif")
> Button(win, image = igm).pack()
> win.mainloop()
>
> Kent
>
> >
> > Can anyone tell me what the line means, please?  Cheers. Diana
> >
> > gifdir = "../gifs/"
> > from Tkinter import *
> > win = Tk()
> > igm = PhotoImage(file=gifdir+"ora-pp.gif")
> > Button(win, image = igm).pack()
> > win.mainloop()
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>


From bvande at po-box.mcgill.ca  Mon Apr 18 03:44:42 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Mon Apr 18 03:46:30 2005
Subject: [Tutor] Re: Exceptions
In-Reply-To: <000301c543aa$82b61700$1dc41dd3@dianahawks>
References: <mailman.2891.1113633520.1797.tutor@python.org>
	<001801c542cc$c19ed260$3507a4cb@dianahawks>
	<42629865.60005@po-box.mcgill.ca>
	<000301c543aa$82b61700$1dc41dd3@dianahawks>
Message-ID: <4263110A.60808@po-box.mcgill.ca>

Diana Hawksworth said unto the world upon 2005-04-17 20:05:
> Brian - thanks for your continuing help!  Here is ALL of the code.  Sure
> hope you can help. Cheers. Diana

Hi Diana,

whew! A bit of an adventure, but I think I've got it. (The adventure 
comes in as I have used Tkinter about twice. I've done almost no GUI 
programming; most of it has been in playing with the Pythoncard 
tutorials and demos. :-)

I've snipped away all but the relevant code.

>     def reveal(self):
>         """ Display message based on number. Changing text widget to integer
>             Correcting the entry of a string variable - except the error
> checking isn't working!"""
> 
>         try:
>             self.guess = int(self.num_ent.get())
> 
>         except(ValueError),e:
	
Here, I put in a line:

	      print "I'm in the except block!"  # XXX

This made the message print in the interactive window. (I ran this 
through PythonWin, so had the PythonWin interactive window visible 
underneath your app.) That confirms that the exception is being raised 
and caught as desired. So, it must be that there is something faulty 
in how you are constructing the message.

For future reference, a few print statements sprinkled about are worth 
a lot of debugging time! I like to append mine with # XXX so I can 
quickly find them when it comes time to extract them.

A false start later, I worked it out as below.

>             message = "%s is not a number. Please try again!" %self.guess
> 
>         else:
>             self.num_ent.delete(0,END)
>             self.num_ent.focus_set()
> 
>             if self.guess < self.number:
>                 message = "%s is too low! You need to guess higher. "
> %self.guess
> 
>             if self.guess > self.number:
>                 message = "%s is too high! You need to guess lower."
> %self.guess
> 
>             if self.guess == self.number:
>                 message = "%s is the correct number!" %self.guess
> 
>                 self.message_txt.config(state = NORMAL)
>                 self.message_txt.config(state = DISABLED)

Here's the problem. I don't know the relevant lingo, but this is the 
chunk of code which makes the message display in your widget. *But* it 
is in your else clause in the try/except/else construct. So, if an 
exception is raised, it isn't run. Outdent it so that it is hit 
irrespective of the flow going through the except or the else, and all 
is golden!


>             self.message_txt.config(state = NORMAL)
>             self.message_txt.delete(0.0, END)
>             self.message_txt.insert(0.0, message)
>             self.message_txt.config(state = DISABLED)

HTH,

Brian vdB

From shaleh at speakeasy.net  Mon Apr 18 04:19:17 2005
From: shaleh at speakeasy.net (Sean Perry)
Date: Mon Apr 18 04:22:03 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the dis module to another language
In-Reply-To: <33429905531.20050417192040@columbus.rr.com>
References: <186325423414.20050416141918@columbus.rr.com>	<42628614.40709@speakeasy.net>
	<33429905531.20050417192040@columbus.rr.com>
Message-ID: <42631925.6060904@speakeasy.net>

R. Alan Monroe wrote:
> The main things about it that would make it appealing to me:
> 
> #1 - MUCH MUCH MUCH smaller exes. Speed is not an issue to me, but
> filesize is. Have you ever compiled "Hello world" in a new language,
> and found that the exe was 100K+, when it really only needs to be less
> than 1K? And py2exe... I am not averse to using it, but 800 - 1000K+
> exes, well, it's just my pet peeve.
> 
> #2 - Love of classic hacking wizardry. :^)
> 

The problem is Python is a dynamic language so you HAVE to ship a 
runtime with it. That hello world bin may be small, but you will still 
have the Python runtime (at least a meg or so). Consider also module 
imports. Do they get compiled into the program? Shipped as a dynamic 
linked library?

Personally, it sounds like a nifty learning project. Realistically that 
seems to be the only benefit.
From dianahawks at optusnet.com.au  Mon Apr 18 05:02:02 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Mon Apr 18 05:04:42 2005
Subject: [Tutor] Re: Exceptions
References: <mailman.2891.1113633520.1797.tutor@python.org>
	<001801c542cc$c19ed260$3507a4cb@dianahawks>
	<42629865.60005@po-box.mcgill.ca>
	<000301c543aa$82b61700$1dc41dd3@dianahawks>
	<4263110A.60808@po-box.mcgill.ca>
Message-ID: <000601c543c3$1cc84da0$1207a4cb@dianahawks>

Golden indeed, Brian!  Works like a charm! Thanks heaps. Diana

From olli.rajala at gmail.com  Mon Apr 18 08:22:28 2005
From: olli.rajala at gmail.com (Olli Rajala)
Date: Mon Apr 18 08:22:33 2005
Subject: [Tutor] Problems with encodings
Message-ID: <d838f320050417232236499bf6@mail.gmail.com>

Hi!
Been offlist for a while, but now I started to code an administration
tool for my own photo gallery and have some troubles, so thought to
write and ask some help. :)

So, I'm from Finland and I'm using ISO-8859-15 -encoding but Python
don't "understand" letters outside ASCII. I've read PEP-0263 and tried
to add the encoding line to my sources, but it doesn't help. Here's a
little example:

#!/usr/bin/python2.4
# -*- coding: <iso-8859-15> -*- 
def printHeader():
    print "????"   

Don't know how you see the 4th line, but that's not my "problem", is it? ;)

And I got this error message:
"sys:1: DeprecationWarning: Non-ASCII character '\xe4' in file
generalHtml.py on line 11, but no encoding declared; see
http://www.python.org/peps/pep-0263.html for details"

I code with Kate (2.4, KDE 3.4.0) and everything else works well when
speaking about this encoding thing. I really hope that someone would
know a solution. I don't mind if I have to write only ASCII but I'm
not the only user for that tool, so...

Yours sincerely, 
-- 
Olli Rajala <><
Tampere, Finland
http://www.students.tut.fi/~rajala37/

"In theory, Theory and Practice should be
the same. But in practice, they aren't."
- Murphy's Proverbs
From james2dope at yahoo.com  Sun Apr 17 21:14:07 2005
From: james2dope at yahoo.com (james middendorff)
Date: Mon Apr 18 08:33:24 2005
Subject: [Tutor] help
Message-ID: <20050417191407.33900.qmail@web31009.mail.mud.yahoo.com>

Hello, 
I was wondering if there was a tutorial and or module
that would help me create a program to use a parallel
port to turn on/off a device in linux? I have searched
but cannot find a tutorial on a good way to do this.
The whole project would be to use a parallel port to
control solid state relays, allowing me to drive a rc
car from my pc... Thanks for any help

James 

"I would kill everyone in this room
    for a drop of sweet beer."
     ----Homer Simpson----


		
__________________________________ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/ 
From dyoo at hkn.eecs.berkeley.edu  Mon Apr 18 08:40:25 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Apr 18 08:40:28 2005
Subject: [Tutor] help
In-Reply-To: <20050417191407.33900.qmail@web31009.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.44.0504172337430.29013-100000@hkn.eecs.berkeley.edu>



On Sun, 17 Apr 2005, james middendorff wrote:

> I was wondering if there was a tutorial and or module that would help me
> create a program to use a parallel port to turn on/off a device in
> linux? I have searched but cannot find a tutorial on a good way to do
> this. The whole project would be to use a parallel port to control solid
> state relays, allowing me to drive a rc car from my pc... Thanks for any
> help


Hi James,

You might find the pyParallel project useful:

    http://pyserial.sourceforge.net/pyparallel.html

There's another parallel port module called parapin:

    http://parapin.sourceforge.net/

Both have examples that should help you get started.  Best of wishes!

From dyoo at hkn.eecs.berkeley.edu  Mon Apr 18 08:48:44 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Apr 18 08:48:52 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the dis module to another language
In-Reply-To: <42628C52.60706@tds.net>
Message-ID: <Pine.LNX.4.44.0504172344160.29013-100000@hkn.eecs.berkeley.edu>

> > Just curious. Googling for 'python "dis module" convert "another
> > language" ' only got two hits. So maybe no one is trying it? I was
> > just daydreaming about a native python compiler, and wondered how
> > feasible it would be.
>
> You might be interested in Pyrex and Psyco:
> http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
> http://psyco.sourceforge.net/


PyPy might also be very useful:

    http://codespeak.net/pypy/

The Pypy project already has enough to retarget Python to Common Lisp,
which can be compiled.  It looks like they started thinking of it in 2003,

    http://codespeak.net/pipermail/pypy-dev/2003q4/001048.html

and there's now code in the 'translator' module that does magical stuff.
*grin*

    http://codespeak.net/svn/pypy/dist/pypy/translator/translator.py

From dyoo at hkn.eecs.berkeley.edu  Mon Apr 18 08:55:52 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Apr 18 08:55:56 2005
Subject: [Tutor] Re: If elif not working in comparison
In-Reply-To: <148eea7105041713385b06d3f@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504172351430.29013-100000@hkn.eecs.berkeley.edu>



On Sun, 17 Apr 2005, gerardo arnaez wrote:

> I have finished a coumadin dose calcalutor
> but want to have it work via a web interface.
>
> The base code is here
>  http://mung.net/~dude/coumadinAll.html
>
> but not sure what would be the next step in getting this working
> on the web.

Hi Gerardo,

One place you may want to look at is:

    http://www.python.org/topics/web/

which tries to collect all the web programming resources in one place.


The module you'll probably be working with the most is the 'cgi' library:

    http://www.python.org/doc/lib/module-cgi.html

so you may want to quickly peruse it at some point.


Preston Landers has written a nice CGI tutorial in Python here:

    http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python

It covers many of the fundamental things you'll want to know.  It is a bit
dated (from 1999!) though, so make sure you're talking to folks on Tutor;
we can help point out places where Python's CGI support has improved since
1999.


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

From dyoo at hkn.eecs.berkeley.edu  Mon Apr 18 09:04:03 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Apr 18 09:04:09 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F25D6F29A2BC34D1D81B31289280@phx.gbl>
Message-ID: <Pine.LNX.4.44.0504172357120.29013-100000@hkn.eecs.berkeley.edu>



On Sun, 17 Apr 2005, Alberto Troiano wrote:

> [emvamp.gif]  Gaucho
> Hey everyone I have Python 2.3 installed and when I try to import Tkinter
> I get the following error> >>>import Tkinter Traceback (most recent call
> last): File "", line 1, in ? File
> "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import
> _tkinter # If this fails your Python may not be configured for Tk
> ImportError: No module named _tkinter I have downloaded the
> Python2.3.tar.bz2 and made this steps to install it ./configure
> --enable-unicode=ucs4 make make install The Linux AS 3.0 has Python 2.2
> and even this last one doesn-t load Tkinter what can I do????????????/
> Thanks in advanced Alberto

Hi Alberto,

Your email client is doing hideous things to your message.  *grin*

Try seeing if you can switch to plain text, because it's really darn hard
to see what's happening.  For information on how to do send plain text
emails, see:

    http://www.expita.com/nomime.html


My best guess so far is that the "Tcl/Tk" development support on your
system is spotty: depending on your Linux distribution, you may need to
install additional packages so that Python can find the Tcl/Tk stuff.

Unfortunately, this is distribution specific, so there's not set way for
us to show how to fix this. I'm guessing that you have some sort of Linux
distribution.  Unfortunately, I'm not familiar with Release 3 of any
distribution, so we'll need more information.

Do you mind doing this for us?  Try executing:

#######
import sys
print sys.plaform
print sys.version
#######


Here's what shows up on one of my systems:

#######
>>> import sys
>>> print sys.platform
darwin
>>> print sys.version
2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)]
#######

Show us what happens when you execute those commands, and that'll give us
a better idea what Linux distribution you're running.

Best of wishes to you.

From alan.gauld at freenet.co.uk  Mon Apr 18 10:27:28 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 10:27:24 2005
Subject: [Tutor] displaying images
References: <000801c543b1$5d267140$8c07a4cb@dianahawks>
Message-ID: <00f301c543f0$753bc2f0$728f8651@xp>


> I am working through "Programming Python" by Mark Lutz. 

Thats a prettty advanced book for a tutor list reader... 
but its a good un too.

> ...I am not certain what the "../gifs/" means, 

Its just a path to a directory.

../
means the directory/folder above the current one.

gifs/ 
means the folder called 'gifs'

So if yu had a folder called 'home' with two subfolders 
called 'scripts' and 'gifs' and you were running your 
program in the scripts folder, then '../gifs/' would 
be a reference to the  'home/gifs' folder.

> using my own files, but cannot figure out where to 
> store the files I am using.  

The image gifs need to be in a folder called 'gifs' 
located on the same level as the folder where your 
script is running.

> I have even tried using the full path name for 
> my files without success.  

But that should have worked too... Unless this is a 
web application in which case the "full path" should 
start at your home page folder.

HTH

Alan G
From klappnase at freenet.de  Mon Apr 18 11:03:03 2005
From: klappnase at freenet.de (Michael Lange)
Date: Mon Apr 18 10:59:22 2005
Subject: [Tutor] Problems with encodings
In-Reply-To: <d838f320050417232236499bf6@mail.gmail.com>
References: <d838f320050417232236499bf6@mail.gmail.com>
Message-ID: <20050418110303.7dd94264.klappnase@freenet.de>

On Mon, 18 Apr 2005 09:22:28 +0300
Olli Rajala <olli.rajala@gmail.com> wrote:

> Hi!
> Been offlist for a while, but now I started to code an administration
> tool for my own photo gallery and have some troubles, so thought to
> write and ask some help. :)
> 
> So, I'm from Finland and I'm using ISO-8859-15 -encoding but Python
> don't "understand" letters outside ASCII. I've read PEP-0263 and tried
> to add the encoding line to my sources, but it doesn't help. Here's a
> little example:
> 
> #!/usr/bin/python2.4
> # -*- coding: <iso-8859-15> -*- 
> def printHeader():
>     print "????"   
> 
> Don't know how you see the 4th line, but that's not my "problem", is it? ;)
> 
> And I got this error message:
> "sys:1: DeprecationWarning: Non-ASCII character '\xe4' in file
> generalHtml.py on line 11, but no encoding declared; see
> http://www.python.org/peps/pep-0263.html for details"
> 
> I code with Kate (2.4, KDE 3.4.0) and everything else works well when
> speaking about this encoding thing. I really hope that someone would
> know a solution. I don't mind if I have to write only ASCII but I'm
> not the only user for that tool, so...
> 

Hi Olli,

does it help if you change the second line into:

# -*- coding: iso-8859-15 -*-

?

I *think* that is the correct syntax (at least it works for me).

Michael

From cyresse at gmail.com  Mon Apr 18 12:22:56 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Mon Apr 18 12:23:02 2005
Subject: [Tutor] OO newbie
In-Reply-To: <006801c543a2$3eec3e80$728f8651@xp>
References: <1112901703.4516.55.camel@localhost>
	<00d401c53bb8$2089cc10$46df8751@xp> <42567451.5030605@tds.net>
	<006801c543a2$3eec3e80$728f8651@xp>
Message-ID: <f2ff2d05041803222a52b62@mail.gmail.com>

Hi, 

Just looking at this - 

class SuperDict(dict):
count = 0
def __init__(self, *args, **kw):
self.__class__.count = self.__class__.count+1
if kw.has_key('default'):
self.default=kw.pop('default')
super(C,self).__init__( *args, **kw)


...so, is count like a static attribute in Java (not that I really 
understand those anyway)?

I don't really understand how you access class attributes. Would it just be 
= SuperDict.count = 10?

On 4/18/05, Alan Gauld <alan.gauld@freenet.co.uk> wrote:
> 
> Just back from vacation - hence the delayed response...
> 
> > > super is just a convenience feature added to make Python slightly
> > > more like some other OOP languages. It is effectively just a
> > > wrapper around the explicit call to the super class:
> >
> > No, super() is much smarter than that and was created to address
> deficiencies in direct superclass
> > calling. super(C, self) actually finds the class that follows C in
> the method resolution order of
> > the class of self. This can be very different from just calling the
> base class method; in the case
> > of multiple inheritance super(C, self) may not ever refer to a base
> class of C.
> 
> Ah! Ok, I didn't realise that. From my quick read of the super
> documentation
> I missed that bit and just thought - syntactic sugar...
> 
> I see that I'll need to do some more experimenting with super...
> 
> Thanks for the clarification Kent,
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050418/b362898e/attachment.html
From amonroe at columbus.rr.com  Mon Apr 18 12:51:24 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Mon Apr 18 12:52:22 2005
Subject: [Tutor] Has anyone ever tried to convert the textual output of
	the dis module to another language
In-Reply-To: <Pine.LNX.4.44.0504172344160.29013-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504172344160.29013-100000@hkn.eecs.berkeley.edu>
Message-ID: <51471348633.20050418065124@columbus.rr.com>

>> > Just curious. Googling for 'python "dis module" convert "another
>> > language" ' only got two hits. So maybe no one is trying it? I was
>> > just daydreaming about a native python compiler, and wondered how
>> > feasible it would be.
>>
>> You might be interested in Pyrex and Psyco:
>> http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
>> http://psyco.sourceforge.net/


> PyPy might also be very useful:
>     http://codespeak.net/pypy/

Cool. I also found this while googling around:

http://www.foretec.com/python/workshops/1998-11/proceedings/papers/aycock-211/aycock211.html

Alan

From albertito_g at hotmail.com  Mon Apr 18 15:24:03 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 18 15:24:06 2005
Subject: [Tutor] TKinter and things over Linux
Message-ID: <BAY106-F27E3583D11145EC15F5EB689290@phx.gbl>

Hey
Let me know if this format is better (I use Hotmail in the web so...)

Sadly I'm not in the linux machine so I can't run the command you sent me 
but I shall explain the version just so you know

The fullname version is Red Hat Advanced Server 3.0. This is a commercial 
version of Linux
But it has so many problems and so few documentation that I switched to Red 
Hat 9.0 (I think that you're familiar with this version)

I have installed tcl and tk support and I will download and install the 
anthony's RPMs
What can I do to make Tkinter work on Linux Red Hat 9.0??????????

Thanks in advanced

Alberto





Gaucho
>From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> >To: Alberto Troiano 
><albertito_g@hotmail.com> >CC: Tutor <tutor@python.org> >Subject: Re: 
>[Tutor] TKinter and things over Linux >Date: Mon, 18 Apr 2005 00:04:03 
>-0700 (PDT) > > > >On Sun, 17 Apr 2005, Alberto Troiano wrote: > > > 
>[emvamp.gif] Gaucho > > Hey everyone I have Python 2.3 installed and when I 
>try to import Tkinter > > I get the following error> >>>import Tkinter 
>Traceback (most recent call > > last): File "", line 1, in ? File > > 
>"/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import > > 
>_tkinter # If this fails your Python may not be configured for Tk > > 
>ImportError: No module named _tkinter I have downloaded the > > 
>Python2.3.tar.bz2 and made this steps to install it ./configure > > 
>--enable-unicode=ucs4 make make install The Linux AS 3.0 has Python 2.2 > > 
>and even this last one doesn-t load Tkinter what can I do????????????/ > > 
>Thanks in advanced Alberto > >Hi Alberto, > >Your email client is doing 
>hideous things to your message. *grin* > >Try seeing if you can switch to 
>plain text, because it's really darn hard >to see what's happening. For 
>information on how to do send plain text >emails, see: > > 
>http://www.expita.com/nomime.html > > >My best guess so far is that the 
>"Tcl/Tk" development support on your >system is spotty: depending on your 
>Linux distribution, you may need to >install additional packages so that 
>Python can find the Tcl/Tk stuff. > >Unfortunately, this is distribution 
>specific, so there's not set way for >us to show how to fix this. I'm 
>guessing that you have some sort of Linux >distribution. Unfortunately, I'm 
>not familiar with Release 3 of any >distribution, so we'll need more 
>information. > >Do you mind doing this for us? Try executing: > >####### 
> >import sys >print sys.plaform >print sys.version >####### > > >Here's 
>what shows up on one of my systems: > >####### > >>> import sys > >>> print 
>sys.platform >darwin > >>> print sys.version >2.3 (#1, Sep 13 2003, 
>00:49:11) >[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] >####### > 
> >Show us what happens when you execute those commands, and that'll give us 
> >a better idea what Linux distribution you're running. > >Best of wishes 
>to you. > >_______________________________________________ >Tutor maillist 
>- Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor


From chrisreednotts at lycos.co.uk  Mon Apr 18 15:36:16 2005
From: chrisreednotts at lycos.co.uk (chrisreednotts)
Date: Mon Apr 18 15:59:38 2005
Subject: [Tutor] New User
Message-ID: 17021942738534@lycos-europe.com

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050418/d1ab1d30/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/octet-stream
Size: 224 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050418/d1ab1d30/attachment.obj
From klappnase at freenet.de  Mon Apr 18 17:09:28 2005
From: klappnase at freenet.de (Michael Lange)
Date: Mon Apr 18 17:05:46 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F27E3583D11145EC15F5EB689290@phx.gbl>
References: <BAY106-F27E3583D11145EC15F5EB689290@phx.gbl>
Message-ID: <20050418170928.1bf2798f.klappnase@freenet.de>

On Mon, 18 Apr 2005 13:24:03 +0000
"Alberto Troiano" <albertito_g@hotmail.com> wrote:

Hi Alberto,

> Hey
> Let me know if this format is better (I use Hotmail in the web so...)
> 

Looks pretty much ok to me :-)

> Sadly I'm not in the linux machine so I can't run the command you sent me 
> but I shall explain the version just so you know
> 
> The fullname version is Red Hat Advanced Server 3.0. This is a commercial 
> version of Linux
> But it has so many problems and so few documentation that I switched to Red 
> Hat 9.0 (I think that you're familiar with this version)
> 
> I have installed tcl and tk support and I will download and install the 
> anthony's RPMs
> What can I do to make Tkinter work on Linux Red Hat 9.0??????????
> 

First you should make sure that all necessary RPMs are installed; the basic python
RPM will be installed by default on RedHat 9 but probably not Tkinter ( I'm not sure
how the RPM is called on RedHat, maybe python-tkinter or python-tk or tkinter or... ).

Best regards

Michael
From olli.rajala at gmail.com  Mon Apr 18 17:55:53 2005
From: olli.rajala at gmail.com (Olli Rajala)
Date: Mon Apr 18 17:56:00 2005
Subject: [Tutor] Problems with encodings
In-Reply-To: <20050418110226.7ecadba3.klappnase@freenet.de>
References: <d838f320050417232236499bf6@mail.gmail.com>
	<20050418110226.7ecadba3.klappnase@freenet.de>
Message-ID: <d838f3200504180855381d01ec@mail.gmail.com>

Michael, 
> does it help if you change the second line into:
> 
> # -*- coding: iso-8859-15 -*-
> 
> ?
> 
> I *think* that is the correct syntax (at least it works for me).

Thanks, it doesn't give the error message anymore. But non-ascii
letters still don't go well from my script to browser. They work well
in console, but not when I'm viewing it through FF 1.0.2 (or Konqueror
if that matters, probably not). I'm using Apache2, Python 2.4 and my
system is Ubuntu 5.04. Everything is from Ubuntus package repository,
apt-get is good. :)

Thanks for this info, hope that this other problem could be solved as well.

Yours sincerely, 
-- 
Olli Rajala <><
Tampere, Finland
http://www.students.tut.fi/~rajala37/

"In theory, Theory and Practice should be
the same. But in practice, they aren't."
- Murphy's Proverbs
From maxnoel_fr at yahoo.fr  Mon Apr 18 18:17:20 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Mon Apr 18 18:17:24 2005
Subject: [Tutor] Problems with encodings
In-Reply-To: <d838f3200504180855381d01ec@mail.gmail.com>
References: <d838f320050417232236499bf6@mail.gmail.com>
	<20050418110226.7ecadba3.klappnase@freenet.de>
	<d838f3200504180855381d01ec@mail.gmail.com>
Message-ID: <2eac269879c0d5234fbfbb08812e6097@yahoo.fr>


On Apr 18, 2005, at 16:55, Olli Rajala wrote:

> Michael,
>> does it help if you change the second line into:
>>
>> # -*- coding: iso-8859-15 -*-
>>
>> ?
>>
>> I *think* that is the correct syntax (at least it works for me).
>
> Thanks, it doesn't give the error message anymore. But non-ascii
> letters still don't go well from my script to browser. They work well
> in console, but not when I'm viewing it through FF 1.0.2 (or Konqueror
> if that matters, probably not). I'm using Apache2, Python 2.4 and my
> system is Ubuntu 5.04. Everything is from Ubuntus package repository,
> apt-get is good. :)

	Do you also specify the encoding in the HTML your code generates?

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From olli.rajala at gmail.com  Mon Apr 18 18:22:23 2005
From: olli.rajala at gmail.com (Olli Rajala)
Date: Mon Apr 18 18:22:28 2005
Subject: [Tutor] Problems with encodings
In-Reply-To: <2eac269879c0d5234fbfbb08812e6097@yahoo.fr>
References: <d838f320050417232236499bf6@mail.gmail.com>
	<20050418110226.7ecadba3.klappnase@freenet.de>
	<d838f3200504180855381d01ec@mail.gmail.com>
	<2eac269879c0d5234fbfbb08812e6097@yahoo.fr>
Message-ID: <d838f32005041809227b250749@mail.gmail.com>

Max wrote:
>         Do you also specify the encoding in the HTML your code generates?

Yeah, of course. :) But I was able to find out the problem. I just had
to tell Apache2 I'm using ISO-8859-15 as a default encoding. So, it
seems that everything's working well now. Thanks for asking, though.

Yours, 
-- 
Olli Rajala <><
Tampere, Finland
http://www.students.tut.fi/~rajala37/

"In theory, Theory and Practice should be
the same. But in practice, they aren't."
- Murphy's Proverbs
From alan.gauld at freenet.co.uk  Mon Apr 18 18:58:08 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 18:58:13 2005
Subject: [Tutor] OO newbie
References: <1112901703.4516.55.camel@localhost><00d401c53bb8$2089cc10$46df8751@xp>
	<42567451.5030605@tds.net><006801c543a2$3eec3e80$728f8651@xp>
	<f2ff2d05041803222a52b62@mail.gmail.com>
Message-ID: <013601c54437$cc911f40$728f8651@xp>

> class SuperDict(dict):
>    count = 0
>    def __init__(self, *args, **kw):
>       self.__class__.count = self.__class__.count+1
>       ...
>       super(C,self).__init__( *args, **kw)

>...so, is count like a static attribute in Java 

Yes, it is a class variable - something that tells you about 
the whole class rather than about a single instance of 
the class. In this case it keeps tabs on how many instances 
have been created. [ And if the __del__ decrements the count 
it tells you how many are currently active.]

> I don't really understand how you access class attributes. 
> Would it just be SuperDict.count = 10?

Thats how i would do it, I'm not sure why the OP has used 
the self.__class__ magic stuff...

To me using the class name explicitly is much clearer and simpler.
But there may be some sophisticated pythonic magic at work that 
I'm missing...

Alan G.
From alan.gauld at freenet.co.uk  Mon Apr 18 19:02:23 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 18 19:02:13 2005
Subject: [Tutor] New User
References: 17021942738534@lycos-europe.com
Message-ID: <014601c54438$6463b300$728f8651@xp>


> Would someone have a look at the attached .py file and tell me if i
have
> done it correctly, im running in the dark a bit as i have only
started
> today, the exercise was

Fair enough for a first time yes.
We prefer not to use input to read numbers(*) since it can be abused
as a security loophole so its usually better to use raw_input() for
everything and convert to the appropriate type:

num = int(raw_input('Type a number: '))

But otherwise it looks fine.

(*) And yes, I know my own tutor describes the use of input(), I
really
must get round to removing that bit...

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

From gsf at panix.com  Mon Apr 18 19:14:59 2005
From: gsf at panix.com (Gabriel Farrell)
Date: Mon Apr 18 19:15:03 2005
Subject: [Tutor] sys.path.append issues with cgi
In-Reply-To: <20050414224326.GA28341@panix.com>
References: <20050414224326.GA28341@panix.com>
Message-ID: <20050418171459.GE11812@panix.com>

A follow-up to this post for future reference:

It appears that on my web host the cgi scripts run on a web server
that doesn't have access to the same python and python libs that are
available when I ssh in to my shell account.  So it doesn't matter if
I change the sys.path, because the libs are simply not accessible.
This situation is particular to my web hosting service, so it may not
apply to others who are running python cgi scripts and importing
modules.

gabe


On Thu, Apr 14, 2005 at 06:43:26PM -0400, Gabriel Farrell wrote:
> Hello all,
> 
> I'm trying to modify the sys.path in my cgi scripts to import modules
> that I've installed in my home directory.  The top of the script reads
> as follows:
> 
> 
> #!/usr/local/bin/python
> 
> import cgi, sys
> sys.path.append('/net/u/16/g/gsf/lib/python2.4/site-packages')
> from ElementTree import Element, SubElement, tostring
> 
> 
> But my traceback reads:
> 
> ImportError: No module named ElementTree
> 
> 
> The appended path is the same I've added to my PYTHONPATH variable and
> it works fine from the python interactive prompt.  I thought it might
> be a permissions issue since it's a cgi script so I chmodded
> everything up to the ElementTree directory 755 but still no luck.
> 
> TIA,
> gabe
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From john.ertl at fnmoc.navy.mil  Mon Apr 18 20:02:40 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Mon Apr 18 19:59:28 2005
Subject: [Tutor] Trying to d0 HTTP GET
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C614@lanexc107p.fnmoc.navy.mil>

All,

I am trying to get some binary data from a web service.  None of the tech
guys are around so I am hoping you might be able to shed some light on what
might be happening.

Here is part of the email that explained what I needed to do.

----- clip ---

If you can do an http "get" from Python, you'll be set.
 
http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041512:global_360x181:max_wav_ht:sur
face:00000000:00000000:fcst_ops:0480

It returns an http header like the following (if the grid exists), 
followed by the grid data in big-endian, IEEE format.

         "HTTP/1.1 200 OK\r\n"
         "Server: ISIS/4.0\r\n"
         "Content-type: application/x-grid\r\n"
         "Content-length: 261234\r\n\r\n"

----- end-----

The grid data is in Binary.  How would I get to this?  I would imagine that
since f (the object) exists the call to the web service worked. Now I need
to read the grid...eventually I need to put it into a Numeric array but not
sure how to get just the grid from "f".

As a simple starting point I tried.  

>>> import urllib
>>> f =
urllib.urlopen("http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041800:global_360x18
1:max_wav_ht:surface:00000000:00000000:fcst_ops:0240")
>>> f.info()
<httplib.HTTPMessage instance at 0xb9255f6c>
>>> f.readlines()

I tried read(), readLines() and some other stuff using scipy and Numeric.

The prompt has moved to the next line but nothing else has happened for 30
min or so (I have tried several times).  When I try to close IDLE it says
the program is still running.  How should I be getting this data is it
trying to read the binary and that is why it is stalled?  

Thanks,

John Ertl 

From WilliTf at dshs.wa.gov  Mon Apr 18 20:12:30 2005
From: WilliTf at dshs.wa.gov (Williams, Thomas)
Date: Mon Apr 18 20:13:03 2005
Subject: [Tutor] website information
Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0FD1984E@dshs-exch2.dshs.wa.lcl>

Does anyone know how to prevent this error from occurring: IOError: [Errno
socket error] (10060, 'Operation timed out'). 

 

I have searched for solutions without any success.

 

Tom Williams

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050418/918054a4/attachment.html
From dyoo at hkn.eecs.berkeley.edu  Mon Apr 18 20:20:08 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Apr 18 20:20:15 2005
Subject: [Tutor] website information
In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0FD1984E@dshs-exch2.dshs.wa.lcl>
Message-ID: <Pine.LNX.4.44.0504181117360.14133-100000@hkn.eecs.berkeley.edu>



On Mon, 18 Apr 2005, Williams, Thomas wrote:

> Does anyone know how to prevent this error from occurring: IOError:
> [Errno socket error] (10060, 'Operation timed out').

Hi Tom,

You can adjust the amount of time that sockets will wait, by using
socket.setdefaulttimeout():

    http://www.python.org/doc/lib/module-socket.html#l2h-2615

The documentation there shows how to make sockets never time out.  That
being said, if an operation takes too long, you may want to catch that.


Best of wishes to you!

From jsmith at medplus.com  Mon Apr 18 20:59:22 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Mon Apr 18 20:59:26 2005
Subject: [Tutor] Of fish and foul...(aka the Perl require command)
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C033944E1@medexch1.medplus.com>

Is there a Python equivalent to the Perl

require 5.6.0

Which enforces a minimum interpreter version?

Is there a good Python for Perl Programmers book?  It thought O'Reilly
had one but I couldn't find it.  Was this particular question in the
book you recommend?

Thanks,
Jeff
From albertito_g at hotmail.com  Mon Apr 18 21:03:08 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Mon Apr 18 21:03:13 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <20050418170928.1bf2798f.klappnase@freenet.de>
Message-ID: <BAY106-F2209176C49B1CF1E5A065889290@phx.gbl>

Hi everyone

I have been able to install Python 2.3.4 with Tkinter.
I don't know if there is some kind of knowledge base but if somebody has 
this problem this is what I did:

I have downloaded the tcl/tk rpm from 
http://www.interlink.com.au/anthony/tech/rh9-tcltk/
(They are 8.3.5-185 and fix the bug that Linux Red Hat 9.0 tcl/tk 8.3.5-xx 
has)

I've installed first the tcl package and then the tk package.
Then I've installed Python2.3.4 with the following commands:
./configure --enable-unicode=ucs4
make
make install

That's all

Thanks to all who tried to help me (Now I have a problem with the MySQL 
database but that doesn't fit in this forum ;)

Regards

Alberto


>From: Michael Lange <klappnase@freenet.de>
>To: tutor@python.org
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Mon, 18 Apr 2005 17:09:28 +0200
>
>On Mon, 18 Apr 2005 13:24:03 +0000
>"Alberto Troiano" <albertito_g@hotmail.com> wrote:
>
>Hi Alberto,
>
> > Hey
> > Let me know if this format is better (I use Hotmail in the web so...)
> >
>
>Looks pretty much ok to me :-)
>
> > Sadly I'm not in the linux machine so I can't run the command you sent 
>me
> > but I shall explain the version just so you know
> >
> > The fullname version is Red Hat Advanced Server 3.0. This is a 
>commercial
> > version of Linux
> > But it has so many problems and so few documentation that I switched to 
>Red
> > Hat 9.0 (I think that you're familiar with this version)
> >
> > I have installed tcl and tk support and I will download and install the
> > anthony's RPMs
> > What can I do to make Tkinter work on Linux Red Hat 9.0??????????
> >
>
>First you should make sure that all necessary RPMs are installed; the basic 
>python
>RPM will be installed by default on RedHat 9 but probably not Tkinter ( I'm 
>not sure
>how the RPM is called on RedHat, maybe python-tkinter or python-tk or 
>tkinter or... ).
>
>Best regards
>
>Michael
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From bill at celestial.net  Mon Apr 18 21:27:04 2005
From: bill at celestial.net (Bill Campbell)
Date: Mon Apr 18 21:26:28 2005
Subject: [Tutor] Of fish and foul...(aka the Perl require command)
In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C033944E1@medexch1.medplus.com>
References: <C4C644CF4ADA9448904C3E8BACC4B97C033944E1@medexch1.medplus.com>
Message-ID: <20050418192704.GA10464@alexis.mi.celestial.com>

On Mon, Apr 18, 2005, Smith, Jeff wrote:
>Is there a Python equivalent to the Perl
>
>require 5.6.0
>
>Which enforces a minimum interpreter version?
>
>Is there a good Python for Perl Programmers book?  It thought O'Reilly
>had one but I couldn't find it.  Was this particular question in the
>book you recommend?

Good?  That depends on what your standards are.  I found ``Perl
to Python Migration'' by Martin C. Brown useful.  I think I found
this on bookpool.com, but you can always try bookfinder.com which
can find pretty much anything.

Bill
--
INTERNET:   bill@Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``Are we at last brought to such a humiliating and debasing degradation,
that we cannot be trusted with arms for our own defense? Where is the
difference between having our arms in our own possession and under our own
direction, and having them under the management of Congress? If our defense
be the real object of having those arms, in whose hands can they be trusted
with more propriety, or equal safety to us, as in our own hands?''
    -- Patrick Henry June 9, 1788, in the Virginia Convention on the
    ratification of the Constitution.
From maxnoel_fr at yahoo.fr  Mon Apr 18 21:34:23 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Mon Apr 18 21:34:42 2005
Subject: [Tutor] Of fish and foul...(aka the Perl require command)
In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C033944E1@medexch1.medplus.com>
References: <C4C644CF4ADA9448904C3E8BACC4B97C033944E1@medexch1.medplus.com>
Message-ID: <e1ea76ccdab0878292884579e6ab0747@yahoo.fr>


On Apr 18, 2005, at 19:59, Smith, Jeff wrote:

> Is there a Python equivalent to the Perl
>
> require 5.6.0
>
> Which enforces a minimum interpreter version?

	As far as I know, no. But:

 >>> import sys
 >>> sys.version_info
(2, 3, 0, 'final', 0)
 >>> (2, 4, 0) > sys.version_info
True
 >>> (2, 2, 0) > sys.version_info
False

	So you can create one yourself quite easily.



import sys

def require(version):
     if sys.version_info < version:
         raise OSError, "This program requires Python v%s or later" % 
'.'.join(map(str, version))



 >>> require((2,4,1))
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 3, in require
OSError: This program requires Python v2.4.1 or later


	I'm not really sure what exception I should raise, though -- OSError 
is the most appropriate, but not exactly the Right Thing... Oh, well. 
*shrugs*

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From kent37 at tds.net  Mon Apr 18 22:10:02 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 18 22:10:24 2005
Subject: [Tutor] Trying to d0 HTTP GET
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C614@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C614@lanexc107p.fnmoc.navy.mil>
Message-ID: <4264141A.3010102@tds.net>

Ertl, John wrote:
> All,
> 
> I am trying to get some binary data from a web service.  None of the tech
> guys are around so I am hoping you might be able to shed some light on what
> might be happening.

I would think that
f = urllib.urlopen(...)
data = f.read()

would work. You could try urllib2.urlopen() and see if it is any better.

How big is the data you are expecting?

Kent

> 
> Here is part of the email that explained what I needed to do.
> 
> ----- clip ---
> 
> If you can do an http "get" from Python, you'll be set.
>  
> http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041512:global_360x181:max_wav_ht:sur
> face:00000000:00000000:fcst_ops:0480
> 
> It returns an http header like the following (if the grid exists), 
> followed by the grid data in big-endian, IEEE format.
> 
>          "HTTP/1.1 200 OK\r\n"
>          "Server: ISIS/4.0\r\n"
>          "Content-type: application/x-grid\r\n"
>          "Content-length: 261234\r\n\r\n"
> 
> ----- end-----
> 
> The grid data is in Binary.  How would I get to this?  I would imagine that
> since f (the object) exists the call to the web service worked. Now I need
> to read the grid...eventually I need to put it into a Numeric array but not
> sure how to get just the grid from "f".
> 
> As a simple starting point I tried.  
> 
> 
>>>>import urllib
>>>>f =
> 
> urllib.urlopen("http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041800:global_360x18
> 1:max_wav_ht:surface:00000000:00000000:fcst_ops:0240")
> 
>>>>f.info()
> 
> <httplib.HTTPMessage instance at 0xb9255f6c>
> 
>>>>f.readlines()
> 
> 
> I tried read(), readLines() and some other stuff using scipy and Numeric.
> 
> The prompt has moved to the next line but nothing else has happened for 30
> min or so (I have tried several times).  When I try to close IDLE it says
> the program is still running.  How should I be getting this data is it
> trying to read the binary and that is why it is stalled?  
> 
> Thanks,
> 
> John Ertl 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From denise.hartley at gmail.com  Mon Apr 18 22:12:23 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Mon Apr 18 22:12:27 2005
Subject: Fwd: [Tutor] "paused" graphic leaves a 'residue' when returning to
	game?
In-Reply-To: <f2ff2d05041618147d176358@mail.gmail.com>
References: <8daabe5605041415123e95caed@mail.gmail.com>
	<f2ff2d05041618147d176358@mail.gmail.com>
Message-ID: <8daabe56050418131237484623@mail.gmail.com>

Yes, I am using pygame. Thanks!

---------- Forwarded message ----------
From: Liam Clarke <cyresse@gmail.com>
Date: Apr 16, 2005 6:14 PM
Subject: Re: [Tutor] "paused" graphic leaves a 'residue' when returning to game?
To: "D. Hartley" <denise.hartley@gmail.com>, "tutor@python.org"
<tutor@python.org>


Hi Denise, 

Are you using Pygame?


On 4/15/05, D. Hartley <denise.hartley@gmail.com> wrote:
> 
> Another quick question:
> 
> I can pause and unpause the little game I created, and I have a
> graphic to display over top of the game screen when it is paused,
> which tells the user which key to press to unpause, right?  It's set 
> up the same way as my "game over" graphic.  But in any case, when I
> unpause, it leaves this "residue" of the "paused" text on the game
> screen. the moving game characters move over it and sort of wipe it 
> out, but I have no idea why it's there or how to clear it!
> 
> Has anyone else encountered a problem like this before? I can post the
> specific code if that would be helpful.  I've tried to clear the
> screen, refresh, etc., and since the pause screen uses the same code 
> as the game over screen I figured the former should not leave a
> residue if the latter does not.  Any suggestions for things to try
> out, to fix this?
> 
> Thanks a ton!
> 
> ~Denise
> _______________________________________________ 
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.'
From john.ertl at fnmoc.navy.mil  Mon Apr 18 23:24:37 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Mon Apr 18 23:21:27 2005
Subject: [Tutor] Trying to d0 HTTP GET
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C618@lanexc107p.fnmoc.navy.mil>

This data set is 65160 bytes.  I am having a bit more success with urllib2
but still not there yet...byte swapping and such.  But now I think the
server is having problems.

Thanks for your help.

-----Original Message-----
From: Kent Johnson [mailto:kent37@tds.net]
Sent: Monday, April 18, 2005 13:10
Cc: tutor@python.org
Subject: Re: [Tutor] Trying to d0 HTTP GET

Ertl, John wrote:
> All,
>
> I am trying to get some binary data from a web service.  None of the tech
> guys are around so I am hoping you might be able to shed some light on
what
> might be happening.

I would think that
f = urllib.urlopen(...)
data = f.read()

would work. You could try urllib2.urlopen() and see if it is any better.

How big is the data you are expecting?

Kent

>
> Here is part of the email that explained what I needed to do.
>
> ----- clip ---
>
> If you can do an http "get" from Python, you'll be set.
> 
>
http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041512:global_360x181:max_wav_ht:sur
> face:00000000:00000000:fcst_ops:0480
>
> It returns an http header like the following (if the grid exists),
> followed by the grid data in big-endian, IEEE format.
>
>          "HTTP/1.1 200 OK\r\n"
>          "Server: ISIS/4.0\r\n"
>          "Content-type: application/x-grid\r\n"
>          "Content-length: 261234\r\n\r\n"
>
> ----- end-----
>
> The grid data is in Binary.  How would I get to this?  I would imagine
that
> since f (the object) exists the call to the web service worked. Now I need
> to read the grid...eventually I need to put it into a Numeric array but
not
> sure how to get just the grid from "f".
>
> As a simple starting point I tried. 
>
>
>>>>import urllib
>>>>f =
>
>
urllib.urlopen("http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041800:global_360x18
> 1:max_wav_ht:surface:00000000:00000000:fcst_ops:0240")
>
>>>>f.info()
>
> <httplib.HTTPMessage instance at 0xb9255f6c>
>
>>>>f.readlines()
>
>
> I tried read(), readLines() and some other stuff using scipy and Numeric.
>
> The prompt has moved to the next line but nothing else has happened for 30
> min or so (I have tried several times).  When I try to close IDLE it says
> the program is still running.  How should I be getting this data is it
> trying to read the binary and that is why it is stalled? 
>
> Thanks,
>
> John Ertl
>
> _______________________________________________
> 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 cpu.crazy at gmail.com  Mon Apr 18 22:55:54 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon Apr 18 23:37:20 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
Message-ID: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>

Here I go, hogging the Tutor list again :)

I have a friend who recently got a hush-hush contract. He told me that it 
was for writing an installation program for Windows and that he considered 
python and Tkinter as an option.
I know there are installers written in python for Linux. I suppose they are 
easier to write, than one for Windows?

Now, I'm still new, and can't do GUI yet, but I was wondering.... how hard 
would it be to write a simple installer for windows? None of that fancy INI 
and registry crapp, just a very simple file copier to, oh lets say, My 
Documents?

This isn't a waste of your or my time is it?
Joe  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050418/cb9c2235/attachment.html
From albertito_g at hotmail.com  Tue Apr 19 00:06:02 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 19 00:06:05 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
In-Reply-To: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
Message-ID: <BAY106-F2120CCC6B3B849397BFB7F89290@phx.gbl>

What exactly do you want to do????????

If you want to make a windows installer then you should look for Create 
Install

It's a very simple software that can copy files to a folder and deploy an 
executable

Please post further info about what you want to achieve so I can assist you 
a bit more

Regards

Alberto

>From: Joseph Quigley <cpu.crazy@gmail.com>
>To: tutor@python.org
>Subject: [Tutor] Installation Routines (Joseph Quigley)
>Date: Mon, 18 Apr 2005 14:55:54 -0600
>
>Here I go, hogging the Tutor list again :)
>
>I have a friend who recently got a hush-hush contract. He told me that it 
>was for writing an installation program for Windows and that he considered 
>python and Tkinter as an option.
>I know there are installers written in python for Linux. I suppose they are 
>easier to write, than one for Windows?
>
>Now, I'm still new, and can't do GUI yet, but I was wondering.... how hard 
>would it be to write a simple installer for windows? None of that fancy INI 
>and registry crapp, just a very simple file copier to, oh lets say, My 
>Documents?
>
>This isn't a waste of your or my time is it?
>Joe
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From denise.hartley at gmail.com  Tue Apr 19 00:14:49 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Tue Apr 19 00:14:52 2005
Subject: [Tutor] high score list error and displaying text in the
	game/graphics window
Message-ID: <8daabe5605041815146b5afa8a@mail.gmail.com>

Hi everyone!

Thanks for all your help/ideas for the high score list. I managed to
get one working! Well, almost ;)

It runs in the text (python) window, behind the graphics window. when
you dont make the high score list, it displays a "sorry" message, and
you can keep playing (i.e., hit y/n for a new game).

however if you DO make the high score list, there's a problem.  It
prompts you for your name (in the text window), and then displays the
high score list, just like it should.  But then when you click to the
game window to say y/n for another game, it all closes! (this is
double-clicking on the "play.py" icon).  If I open the doc in IDLE and
then hit F5, it'll let me click back to the game window and hit y/n to
play again, but I dont know why it's crashing the other way.  I've
attached the code file.  Can anyone offer any suggestions?

Alternately,  I'd LOVE to get the game to display all of the text
window messages (and ask for input if the user makes the high score
list) in the game/graphics window, NOT the text window. can anyone
tell me how to do this? it's using pygame.  I'd like to do it that way
anyway, and then also it would solve the problem of clicking back and
forth between the game screen and the python/text window.

Any ideas?

Thanks,

Denise
From denise.hartley at gmail.com  Tue Apr 19 00:15:44 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Tue Apr 19 00:15:47 2005
Subject: [Tutor] Fwd: high score list error and displaying text in the
	game/graphics window
In-Reply-To: <8daabe5605041815146b5afa8a@mail.gmail.com>
References: <8daabe5605041815146b5afa8a@mail.gmail.com>
Message-ID: <8daabe5605041815154b74077b@mail.gmail.com>

d'oh! here's the file I was supposed to attach:  

---------- Forwarded message ----------
From: D. Hartley <denise.hartley@gmail.com>
Date: Apr 18, 2005 3:14 PM
Subject: high score list error and displaying text in the game/graphics window
To: Python tutor <tutor@python.org>


Hi everyone!

Thanks for all your help/ideas for the high score list. I managed to
get one working! Well, almost ;)

It runs in the text (python) window, behind the graphics window. when
you dont make the high score list, it displays a "sorry" message, and
you can keep playing (i.e., hit y/n for a new game).

however if you DO make the high score list, there's a problem.  It
prompts you for your name (in the text window), and then displays the
high score list, just like it should.  But then when you click to the
game window to say y/n for another game, it all closes! (this is
double-clicking on the "play.py" icon).  If I open the doc in IDLE and
then hit F5, it'll let me click back to the game window and hit y/n to
play again, but I dont know why it's crashing the other way.  I've
attached the code file.  Can anyone offer any suggestions?

Alternately,  I'd LOVE to get the game to display all of the text
window messages (and ask for input if the user makes the high score
list) in the game/graphics window, NOT the text window. can anyone
tell me how to do this? it's using pygame.  I'd like to do it that way
anyway, and then also it would solve the problem of clicking back and
forth between the game screen and the python/text window.

Any ideas?

Thanks,

Denise
-------------- next part --------------
#!/usr/bin/env python

#------------------------------------------------------
# Spacin'Vaders 0.1
#
# Created by Rodrigo Vieira
# (icq, msn) = (9027513, rodrigo_eon@hotmail.com)
# email = rodrigo74@gmail.com
#
# License: GPL
#
# Have fun! Feel free to contact me for comments,
# questions or new features :)
#
# Check README.txt for more info
#------------------------------------------------------

#Import Modules
import os, pygame
import random
from pygame.locals import *
from livewires import *
import pickle

fullscreen = 0 #1: starts on fullscreen, 0: starts windowed

def load_image(name, colorkey=None):
    """loads one image in memory"""
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()


def load_sound(name):
    """loads a sound file (.wav) in memory"""
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound


class LifeSprites(pygame.sprite.RenderClear):
    """This class shows the lives left at the bottom-right corner of the screen"""
    def __init__(self, lives):
        pygame.sprite.RenderClear.__init__(self)
        self.startx = 630
        self.starty = 460
        for i in xrange(lives-1):
            s = pygame.sprite.Sprite()
            s.image, s.rect = load_image('ranch_ship_small.bmp', -1)
            s.rect.centerx = self.startx - (i*17)
            s.rect.centery = self.starty
            self.add(s)

    def update(self, lives):
        for sprite in self.sprites():
            sprite.kill()
        for i in xrange(lives-1):
            #create the new one
            s = pygame.sprite.Sprite()
            if i < lives-1:
                s.image, s.rect = load_image('ranch_ship_small.bmp', -1)
            else:
                s.image, s.rect = load_image('blank.bmp', -1)
            s.rect.centerx = self.startx - (i*17)
            s.rect.centery = self.starty
            self.add(s)

    
class ScoreSprites(pygame.sprite.RenderClear):
    """This class shows the score on screen"""
    def __init__(self):
        pygame.sprite.RenderClear.__init__(self)
        #create the inner digit-sprites
        self.startx = 540
        self.starty = 12
        self.img_list = []
        self._sprites = []
        for i in xrange(10):
            self.img_list.append(pygame.image.load(os.path.join('data', str(i) + '.gif')))
        for i in xrange(8):
            s = pygame.sprite.Sprite()
            s.image, s.rect = load_image('0.gif', -1)
            s.rect.centerx = self.startx + (i*11)
            s.rect.centery = self.starty
            self.add(s)
            self._sprites.append(s)

    def update(self, value):
        #pad the value with 0s in the left
        s_value = str(value).zfill(8)
        #write the number
        for i in xrange(8):
            self._sprites[i].image = self.img_list[int(s_value[i])]
        

class EnemySprites(pygame.sprite.RenderClear):
    """This class will hold all the enemy ships (the vader helmets)"""
    def __init__(self, speed):
        pygame.sprite.RenderClear.__init__(self)
        
        #this variable indicates if the enemies 
        #are moving to the left (-1) or right (1)
        self.direction = 1 
        
        #this variable controls if it's time to move the enemies 
        self.counter = 0
        
        #this variable checks if it's time for the enemies to move down
        self.jump_counter = 0
        
        #this one sets how fast the enemies move
        self.speed = speed

        #the sound that plays everytime the enemy moves
        self.moveSound =  load_sound("fx.wav")

    def update(self):
        self.counter += 1
        if self.counter >= 50 - (self.speed * 5): #time to move the enemies?
            self.counter = 0
            self.jump_counter += 1
            go_down = False
            if self.jump_counter > 4: #time to move down and change direction?
                self.jump_counter = 0
                self.direction *= -1
                go_down = True

            #move the enemies!
            self.moveSound.play()
            pygame.sprite.RenderClear.update(self, self.direction, go_down)

    def lowerEnemy(self):
        lower = 0
        for e in self.sprites():
            if e.rect.centery > lower:
                lower = e.rect.centery
        return lower


class Enemy(pygame.sprite.Sprite):
    """This class is for each enemy ship"""
    def __init__(self,startx, starty):
        pygame.sprite.Sprite.__init__(self) #call Sprite intializer
        self.image, self.rect = load_image('pizza_ship.bmp', -1)
        self.rect.centerx = startx
        self.rect.centery = starty
        
    def update(self, direction, go_down):
        jump = 40 #how much the vaders move to the right/left on each jump
        
        if go_down:
            #if a ship is moving down on this round,
            #it doesn't move on the x-axys
            self.rect.move_ip((0, 5))
        else:
            #move a ship in the x-axys.
            #if direction=1, it moves to the right; -1 to the left
            self.rect.move_ip((jump * direction, 0))
        
        #maybe it's time for a shot? :) 
        #the chances are 1/30
        dice = random.randint(0,30)
        global enemy_shot_sprites
        if dice == 1:
            shot = EnemyShot(self.rect.midtop)
            enemy_shot_sprites.add(shot)
    
class EnemyShot(pygame.sprite.Sprite):
    """class for enemy shot (red laser)"""
    def __init__(self, startpos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('red_laser.bmp', -1)
        self.rect.centerx = startpos[0]
        self.rect.centery = startpos[1]
    
    def update(self):
        #move the enemy shot and kill itself
        #if it leaves the screen
        self.rect.move_ip((0,5))
        if self.rect.centery > 480:
            self.kill()

            
class Hero(pygame.sprite.Sprite):
    """This class is for the "hero" ship in the bottom"""
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('ranch_ship.bmp', -1)
        self.blinking = 1 #the hero ship starts blinking (immune)
        self.visible = 1
        self.counter = 0
        self.blank_ship = pygame.image.load(os.path.join('data','blank.bmp'))
        self.normal_ship = pygame.image.load(os.path.join('data','ranch_ship.bmp'))
        #the ship starts around the center of the screen...
        self.rect.centerx = 300
        self.rect.centery = 440
        self.direction = 0 #the ship starts standing still

    def update(self):
        if self.blinking:
            self.counter += 1
            if self.counter % 10 == 0:
                if self.visible:
                    self.image = self.blank_ship
                else:
                    self.image = self.normal_ship
                self.visible = not self.visible
            if self.counter == 150:
                self.blinking = 0
                self.image = pygame.image.load(os.path.join('data','ranch_ship.bmp'))
                self.counter = 0
            colorkey = self.image.get_at((0,0))
            self.image.set_colorkey(colorkey, RLEACCEL)

            
        #check if the ship is out of bounds
        if self.rect.centerx < 20:
            self.rect.centerx = 20
        if self.rect.centerx > 620:
            self.rect.centerx = 620
        
        #move the ship to the left/right, if direction<>0
        self.rect.move_ip((self.direction * 6,0))

class HeroShot(pygame.sprite.Sprite):
    """class for a hero shot (white laser)"""
    def __init__(self, startpos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('white_laser.bmp', -1)
        self.rect.centerx = startpos[0]
        self.rect.centery = startpos[1]
    
    def update(self):
        #moves the shot up, and kills itself
        #if it leaves the screen
        self.rect.move_ip((0,-5))
        if self.rect.centery < 0:
            self.kill()

def createEnemies(screen, speed):
    enemyship_sprites = EnemySprites(speed)
    for rows in xrange(5):
        for cols in xrange(8):
            enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30))
    enemyship_sprites.draw(screen)
    return enemyship_sprites

def createHero(screen):
    global hero
    hero = Hero()
    hero_sprites = pygame.sprite.RenderClear()
    hero_sprites.add(hero)
    hero_sprites.draw(screen)
    return hero_sprites

def showGameOver(screen, background_image):
    sprites = pygame.sprite.RenderClear()
    s = pygame.sprite.Sprite()
    s.image, s.rect = load_image('game_over.GIF', -1)
    s.rect.centerx = 320
    s.rect.centery = 200
    sprites.add(s)
    sprites.clear(screen, background_image)
    sprites.draw(screen)

def main():
    """this function is called when the program starts.
       it initializes everything it needs, then runs in
       a loop until the function returns."""
    pygame.init()
    random.seed()
    total_enemy_hits = 0
    level = 1
    lives = 3
    print "You have", lives, "lives left"
    print "Level 1"

    global screen
    if fullscreen:
        screen = pygame.display.set_mode((640, 480), FULLSCREEN)
    else:
        screen = pygame.display.set_mode((640, 480))

    
    pygame.display.set_caption("Behold, the Awesome Power of Ranch: H.A.P.P.Y. B.I.R.T.H.D.A.Y. v1.0")
    enemy_speed = 1

    #Load music
    explode = load_sound("explode2.wav")
    clearAll = load_sound("impressive.wav")
    laser = load_sound("laser.wav")
    end = load_sound("explode2.wav")

    #load the background image
    background_image, background_rect = load_image('bluebg.bmp')
    screen.blit(background_image, (0,0))
    
    #create a holder for the hero and enemy shots
    hero_shot_sprites = pygame.sprite.RenderClear()
    global enemy_shot_sprites
    enemy_shot_sprites = pygame.sprite.RenderClear()

    #create the score and life sprites
    score_sprites = ScoreSprites()
    life_sprites = LifeSprites(lives)
    
    #create enemy ships!
    enemyship_sprites = createEnemies(screen, enemy_speed)
    
    #create our hero!
    global hero
    hero_sprites = createHero(screen)
    clock = pygame.time.Clock()
    running = 1
    paused = 0
    while running:
        # Make sure game doesn't run at more than 50 frames per second
        clock.tick(50)
        
        #get the keyboard events and act
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_LEFT:
                    hero.direction = -1 #change the hero ship direction
                elif event.key == K_RIGHT:
                    hero.direction = 1  #change the hero ship direction
                elif event.key == K_UP or event.key == K_SPACE or event.key == K_s or event.key == K_LCTRL or event.key == K_RCTRL or event.key == K_d or event.key == K_f or event.key == K_a:
                    #shoots with s,d,f,a, UP or CTRL keys. 
                    if not hero.blinking:
                         hero_shot_sprites.add(HeroShot(hero.rect.midtop))
                         laser.play()
                elif event.key == K_ESCAPE:
                    running = 0 #leave if the user press ESC
                elif event.key == K_p:
                    paused = not paused
                elif event.key == K_q:
                    running = 0 #leave if the user press "q"
                elif event.key == K_F2 or event.key == K_RETURN:
                    pygame.display.toggle_fullscreen()
            elif event.type == KEYUP:
                #if the user leave the left/right buttons, stop moving
                #the hero ship
                if event.key == K_LEFT and hero.direction == -1:
                    hero.direction = 0
                elif event.key == K_RIGHT and hero.direction == 1:
                    hero.direction = 0
            elif event.type == QUIT:
                running = 0 #leave if the user close the window

        if not paused:
            #Clear Everything
            enemyship_sprites.clear(screen, background_image)
            hero_sprites.clear(screen, background_image)
            hero_shot_sprites.clear(screen, background_image)
            enemy_shot_sprites.clear(screen, background_image)
            score_sprites.clear(screen, background_image)
            life_sprites.clear(screen, background_image)
    
            #see if any hero shot collided with enemy shot
            for hit in pygame.sprite.groupcollide(enemy_shot_sprites, hero_shot_sprites, 1, 1):
                pass        
            
            #See if a hero shot hit any enemy vaders
            for hit in pygame.sprite.groupcollide(enemyship_sprites, hero_shot_sprites, 1, 1):
                #yay got one!
                explode.play()
                total_enemy_hits += 1
                if total_enemy_hits % 200 == 0:
                    #killed 200 vaders, got extra life!
                    lives += 1
                    print "You have", lives, "lives left"
                    
                
            #see if the hero was hit by enemy shots
            if not hero.blinking and lives > 0:
                for hit in pygame.sprite.groupcollide(enemy_shot_sprites, hero_sprites, 1, 1):
                    #ouch!!
                    explode.play()
                    hero.blinking = 1
                    lives -= 1
                    hero_sprites = createHero(screen)
                    print "You have", lives, "lives left"
                if enemyship_sprites.lowerEnemy() > 400:
                    #enemy is too low, so you die and the level restarts
                    explode.play()
                    hero.blinking = 1
                    lives -= 1
                    hero_sprites = createHero(screen)
                    enemyship_sprites = createEnemies(screen, enemy_speed)
                    print "You have", lives, "lives left"
                    
    
            if len(enemyship_sprites.sprites()) == 0:
                #you killed'em all!! reset the enemies and make the game a bit faster >:)
                clearAll.play()
                level += 1
                print "Level", level
                hero_shot_sprites = pygame.sprite.RenderClear()
                if enemy_speed < 8: #don't let it get _too_ fast!!!
                    enemy_speed += 1
                enemyship_sprites = createEnemies(screen, enemy_speed)
    
            #update everything
            enemyship_sprites.update()
            hero_sprites.update()
            hero_shot_sprites.update()
            enemy_shot_sprites.update()
            score_sprites.update(total_enemy_hits)
            life_sprites.update(lives)
    
            #Draw Everything
            enemyship_sprites.draw(screen)
            hero_sprites.draw(screen)
            hero_shot_sprites.draw(screen)
            enemy_shot_sprites.draw(screen)
            score_sprites.draw(screen)
            life_sprites.draw(screen)
    
            #game over..
            if lives == 0:
### trying addscore

                end.play()
                showGameOver(screen, background_image)                
                pygame.display.flip()

                def add_score():
                    high_scores = [(1000,"Denise"), (945,"Denise"),
                                   (883,"Denise"),(823,"Grant"),
                                   (779,"Aaron"), (702,"Pete"),
                                   (555,"Tom"), (443,"Tom"),
                                   (442,"Robin"), (4,"Pete")]
 #                   high_scores = pickle.load(file("scores.pik"))
                    score = total_enemy_hits
                    if score > high_scores[-1][0]:
                        print "Ta da! You got", total_enemy_hits, "Ranch Delivery Devices!"
                        name = read_string("You made the high score list! What's your name? ")
                        user_score = (score,name)
                        high_scores.append(user_score)
                        high_scores.sort(reverse=True)
                        del high_scores[-1]
  #                      pickle.dump(high_scores, file("scores.pik", "w"))
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            prefix = 5*" "
                            print prefix,name,slip_amt,score
                    else:
                        print "Sorry, you only got", total_enemy_hits, "Ranch Delivery Devices."
                        print "You didn't quite make the high score list!"
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            prefix = 5*" "
                            print prefix,name,slip_amt,score
                        print "Better luck next time!"
                
                add_score()

                answer = ""
                while not answer in ("y","n"):
                   for event in pygame.event.get():
                      if event.type == KEYDOWN:
                         if event.key == K_n:
                            answer = "n"
                         elif event.key == K_y:
                            answer = "y"
                if answer == "n":
                    running = 0
                else:
                    return 1
    
            #refresh the display
            pygame.event.pump()
            pygame.display.flip()

    #well, nice playing with you...
#    print "Ta da! You got", total_enemy_hits, "Ranch Delivery Devices!"
 #   add_score()
    screen = pygame.display.set_mode((640, 480))
    return 0

#this calls the 'main' function when this script is executed
if __name__ == '__main__':
    playing = 1
    while playing:
        playing = main()
From denise.hartley at gmail.com  Tue Apr 19 00:18:17 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Tue Apr 19 00:18:19 2005
Subject: [Tutor] unrelated sound error - pygame, or other?
In-Reply-To: <d306e2510504171534282ec5aa@mail.gmail.com>
References: <8daabe56050412163474e0bd7f@mail.gmail.com>
	<d306e2510504171534282ec5aa@mail.gmail.com>
Message-ID: <8daabe5605041815183fa70e80@mail.gmail.com>

Another quick question.  I tried to send a file to my friend to test
it out, and it gave her the following sound-related error:

Cannot load sound: data\explode2.wav

Traceback (most recent call last):
  File "D:\Python24\play w paused screen residue.py", line 495, in -toplevel-
    playing = main()
  File "D:\Python24\play w paused screen residue.py", line 318, in main 
    explode = load_sound("explode2.wav")
  File "D:\Python24\play w paused screen residue.py", line 52, in load_sound
    raise SystemExit, message
SystemExit: Mix_LoadWAV_RW with NULL src 

I can tell this is a sound problem, and I thought then that maybe she
hadnt installed pygame or had done it wrong, but she says it's in
there.  This hasnt happened on either of my machines, or a machine at
another friend's house (where I have been working on it too).  Any of
you encounter this problem before, or know what it is?

Thanks again!

~Denise
From alan.gauld at freenet.co.uk  Tue Apr 19 00:48:44 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 00:48:42 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
Message-ID: <01b101c54468$c6db1020$728f8651@xp>

> Now, I'm still new, and can't do GUI yet, but I was wondering....
how hard
> would it be to write a simple installer for windows? None of that
fancy INI
> and registry crapp, just a very simple file copier to, oh lets say,
My
> Documents?

Its not hard, but its not easy either to do it right.
And given the profusion of installers already available
ranging from free to expensive there really is little
point in writing something that probably won't be as
good as the already available alternative.

Remember user expectation, if you write an installer you
should also provide an uninstaller, and link it to the
Control Panel Add/Remove applet. Its no coincidence that
python uses a commercial (Wise) installer for the
Windows distro...

> This isn't a waste of your or my time is it?

No, its a valid question even if the answer is that its probably a bad
idea!

Alan G.

From maxnoel_fr at yahoo.fr  Tue Apr 19 01:43:44 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Tue Apr 19 01:43:57 2005
Subject: [Tutor] unrelated sound error - pygame, or other?
In-Reply-To: <8daabe5605041815183fa70e80@mail.gmail.com>
References: <8daabe56050412163474e0bd7f@mail.gmail.com>
	<d306e2510504171534282ec5aa@mail.gmail.com>
	<8daabe5605041815183fa70e80@mail.gmail.com>
Message-ID: <7efaf53aca84536193e2add74d052db2@yahoo.fr>


On Apr 18, 2005, at 23:18, D. Hartley wrote:

> Another quick question.  I tried to send a file to my friend to test
> it out, and it gave her the following sound-related error:
>
> Cannot load sound: data\explode2.wav
>
> Traceback (most recent call last):
>   File "D:\Python24\play w paused screen residue.py", line 495, in 
> -toplevel-
>     playing = main()
>   File "D:\Python24\play w paused screen residue.py", line 318, in main
>     explode = load_sound("explode2.wav")
>   File "D:\Python24\play w paused screen residue.py", line 52, in 
> load_sound
>     raise SystemExit, message
> SystemExit: Mix_LoadWAV_RW with NULL src
>
> I can tell this is a sound problem, and I thought then that maybe she
> hadnt installed pygame or had done it wrong, but she says it's in
> there.  This hasnt happened on either of my machines, or a machine at
> another friend's house (where I have been working on it too).  Any of
> you encounter this problem before, or know what it is?
>
> Thanks again!
>
> ~Denise

	I'm not familiar with Pygame, but the "NULL src" bit feels like the 
sound file (explode2.wav) is missing, or that at least Pygame can't 
open it.
	Check the relative positions of the program and the WAV file -- it 
looks like they should be in the same directory in order for the 
program to work.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From dianahawks at optusnet.com.au  Tue Apr 19 02:13:13 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Tue Apr 19 02:14:55 2005
Subject: [Tutor] displaying images
References: <000801c543b1$5d267140$8c07a4cb@dianahawks>
	<00f301c543f0$753bc2f0$728f8651@xp>
Message-ID: <001d01c54474$947c5b00$7408a4cb@dianahawks>

Thanks for that Alan.  Have it working - or at least showing images on a
canvas!  Now just need to figure out how to get that image  on an
established Frame!

Cheers. Diana

----- Original Message ----- 
From: "Alan Gauld" <alan.gauld@freenet.co.uk>
To: "Diana Hawksworth" <dianahawks@optusnet.com.au>; <tutor@python.org>
Sent: Monday, April 18, 2005 6:27 PM
Subject: Re: [Tutor] displaying images


>
> > I am working through "Programming Python" by Mark Lutz.
>
> Thats a prettty advanced book for a tutor list reader...
> but its a good un too.
>
> > ...I am not certain what the "../gifs/" means,
>
> Its just a path to a directory.
>
> ../
> means the directory/folder above the current one.
>
> gifs/
> means the folder called 'gifs'
>
> So if yu had a folder called 'home' with two subfolders
> called 'scripts' and 'gifs' and you were running your
> program in the scripts folder, then '../gifs/' would
> be a reference to the  'home/gifs' folder.
>
> > using my own files, but cannot figure out where to
> > store the files I am using.
>
> The image gifs need to be in a folder called 'gifs'
> located on the same level as the folder where your
> script is running.
>
> > I have even tried using the full path name for
> > my files without success.
>
> But that should have worked too... Unless this is a
> web application in which case the "full path" should
> start at your home page folder.
>
> HTH
>
> Alan G


From oasf2004 at yahoo.com  Tue Apr 19 02:55:10 2005
From: oasf2004 at yahoo.com (Hoffmann)
Date: Tue Apr 19 02:55:13 2005
Subject: [Tutor] Newbie question
Message-ID: <20050419005510.3607.qmail@web60006.mail.yahoo.com>

Hi All:

I am a newbie, and I am enjoying to study Python a
lot. I have a question about an example I got from one
of my books.
The program is:

def square(y):
   return y * y

for x in range(1, 11):
   print square(x),

print

Well, I understood the code above. My question is: Is
it really necessary I have the last "print" statment
(last line) in the code?
Thanks a lot in advance.
Hoffmann


		
__________________________________ 
Do you Yahoo!? 
Plan great trips with Yahoo! Travel: Now over 17,000 guides!
http://travel.yahoo.com/p-travelguide
From leec03273 at mac.com  Tue Apr 19 03:07:41 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Tue Apr 19 03:07:46 2005
Subject: [Tutor] Newbie question
In-Reply-To: <20050419005510.3607.qmail@web60006.mail.yahoo.com>
References: <20050419005510.3607.qmail@web60006.mail.yahoo.com>
Message-ID: <47641f0357d9a0b83714aba0f58a38ee@mac.com>

That just gives you a spacer line after your output. To see such as a 
separator change it to   print '*'*10


On Apr 18, 2005, at 8:55 PM, Hoffmann wrote:

> Hi All:
>
> I am a newbie, and I am enjoying to study Python a
> lot. I have a question about an example I got from one
> of my books.
> The program is:
>
> def square(y):
>    return y * y
>
> for x in range(1, 11):
>    print square(x),
>
> print
>
> Well, I understood the code above. My question is: Is
> it really necessary I have the last "print" statment
> (last line) in the code?
> Thanks a lot in advance.
> Hoffmann

From amonroe at columbus.rr.com  Tue Apr 19 03:07:52 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue Apr 19 03:08:53 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
In-Reply-To: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
Message-ID: <157522737586.20050418210752@columbus.rr.com>

> He told me that it
> was for writing an installation program for Windows and that he considered 
> python and Tkinter as an option.
> I know there are installers written in python for Linux. I suppose they are 
> easier to write, than one for Windows?

> Now, I'm still new, and can't do GUI yet, but I was wondering.... how hard 
> would it be to write a simple installer for windows? None of that fancy INI 
> and registry crapp, just a very simple file copier to, oh lets say, My 
> Documents?

> This isn't a waste of your or my time is it?

It's pefectly doable, but with the existence of Innosetup and NSIS,
personally I wouldn't really feel like it was worth it. Just my
opinion, though.

Alan

From m92507 at stumail.nutn.edu.tw  Tue Apr 19 05:51:39 2005
From: m92507 at stumail.nutn.edu.tw (Ching-Yi Chan)
Date: Tue Apr 19 05:56:55 2005
Subject: [Tutor] for loop
Message-ID: <4264804B.2000200@stumail.nutn.edu.tw>

*Ron A*  /Wed Jan  7 18:41:15 EST 2004/

I'm experimenting and would like 'yes' to be printed only if 5 is not in
the list, but I want to look in each list. This prints out two yeses.
How do I get it to print just one 'yes'?

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]

for num in x:
    if 5 in num:
        break
    else:
        print 'yes'  

--------------------------------------------------------------------------

Hi, I read the code and consider for a while, you can try it :

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
print [ e for e in x if 5 in e]


From bvande at po-box.mcgill.ca  Tue Apr 19 05:34:13 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 19 06:00:55 2005
Subject: [Tutor] Newbie question
In-Reply-To: <47641f0357d9a0b83714aba0f58a38ee@mac.com>
References: <20050419005510.3607.qmail@web60006.mail.yahoo.com>
	<47641f0357d9a0b83714aba0f58a38ee@mac.com>
Message-ID: <42647C34.80606@po-box.mcgill.ca>

Lee Cullens said unto the world upon 2005-04-18 21:07:
> That just gives you a spacer line after your output. To see such as a 
> separator change it to   print '*'*10
> 
> 
> On Apr 18, 2005, at 8:55 PM, Hoffmann wrote:
> 
>> Hi All:
>>
>> I am a newbie, and I am enjoying to study Python a
>> lot. I have a question about an example I got from one
>> of my books.
>> The program is:
>>
>> def square(y):
>>    return y * y
>>
>> for x in range(1, 11):
>>    print square(x),
>>
>> print
>>
>> Well, I understood the code above. My question is: Is
>> it really necessary I have the last "print" statment
>> (last line) in the code?
>> Thanks a lot in advance.
>> Hoffmann
>

Hi all,

in the particular case, it is more than just a spacer, I think. It 
serves to break the "print on the same line" feature of the
print some_thing,
statement in the loop. Without it, the next thing printed will be on 
the same line:

 >>> for i in range(1):	# contrived to keep it all in block construct
... 	for i in range(5):
... 			print 'in',
... 	print 'out'
...
in in in in in out

(Unless, of course, that is what Lee meant. In which case--nevermind :-)

Best,

Brian vdB

From leec03273 at mac.com  Tue Apr 19 06:31:21 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Tue Apr 19 06:31:25 2005
Subject: [Tutor] for loop
In-Reply-To: <4264804B.2000200@stumail.nutn.edu.tw>
References: <4264804B.2000200@stumail.nutn.edu.tw>
Message-ID: <72aec6f37f6afddd87ee7fcc14522cdc@mac.com>

  As you probably have already found out the expression
 >>> print [ e for e in x if 5 in e]
will produce
[[8, 4, 5, 6]]

The problem with your original code is that you are printing 'yes' for  
each sub list until you encounter a sub list with 5 whereupon you break  
without printing yes.

If you change your test to check for 5 in a sub list and, print yes and  
break at that point you will get the results you are looking for.

 >>> for num in x:
...      if 5 in num:
...        print "yes"
...        break
...
yes
 >>>

Lee C



On Apr 18, 2005, at 11:51 PM, Ching-Yi Chan wrote:

> *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
>
> I'm experimenting and would like 'yes' to be printed only if 5 is not  
> in
> the list, but I want to look in each list. This prints out two yeses.
> How do I get it to print just one 'yes'?
>
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>
> for num in x:
>     if 5 in num:
>         break
>     else:
>         print 'yes'
>
> ----------------------------------------------------------------------- 
> ---
>
> Hi, I read the code and consider for a while, you can try it :
>
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> print [ e for e in x if 5 in e]
>

From leec03273 at mac.com  Tue Apr 19 06:37:54 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Tue Apr 19 06:38:01 2005
Subject: [Tutor] Newbie question
In-Reply-To: <42647C34.80606@po-box.mcgill.ca>
References: <20050419005510.3607.qmail@web60006.mail.yahoo.com>
	<47641f0357d9a0b83714aba0f58a38ee@mac.com>
	<42647C34.80606@po-box.mcgill.ca>
Message-ID: <9de74aac053137f448dc9d0a73648724@mac.com>

Thank you Brian for making the point that I did such a poor job of 
conveying.  My post did indeed fail to clearly and concisely answer the 
question.

Lee C


On Apr 18, 2005, at 11:34 PM, Brian van den Broek wrote:

> Lee Cullens said unto the world upon 2005-04-18 21:07:
>> That just gives you a spacer line after your output. To see such as a 
>> separator change it to   print '*'*10
>> On Apr 18, 2005, at 8:55 PM, Hoffmann wrote:
>>> Hi All:
>>>
>>> I am a newbie, and I am enjoying to study Python a
>>> lot. I have a question about an example I got from one
>>> of my books.
>>> The program is:
>>>
>>> def square(y):
>>>    return y * y
>>>
>>> for x in range(1, 11):
>>>    print square(x),
>>>
>>> print
>>>
>>> Well, I understood the code above. My question is: Is
>>> it really necessary I have the last "print" statment
>>> (last line) in the code?
>>> Thanks a lot in advance.
>>> Hoffmann
>>
>
> Hi all,
>
> in the particular case, it is more than just a spacer, I think. It 
> serves to break the "print on the same line" feature of the
> print some_thing,
> statement in the loop. Without it, the next thing printed will be on 
> the same line:
>
> >>> for i in range(1):	# contrived to keep it all in block construct
> ... 	for i in range(5):
> ... 			print 'in',
> ... 	print 'out'
> ...
> in in in in in out
>
> (Unless, of course, that is what Lee meant. In which case--nevermind 
> :-)
>
> Best,
>
> Brian vdB
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From leec03273 at mac.com  Tue Apr 19 06:59:43 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Tue Apr 19 06:59:48 2005
Subject: [Tutor] for loop
In-Reply-To: <72aec6f37f6afddd87ee7fcc14522cdc@mac.com>
References: <4264804B.2000200@stumail.nutn.edu.tw>
	<72aec6f37f6afddd87ee7fcc14522cdc@mac.com>
Message-ID: <33360b012237f29a1120cec9341cac94@mac.com>

Well I was reading too fast (as usual) - you wanted to print 'yes'   
only if 5 is not in a sub list but you want to look in all the sub  
lists and yet print 'yes' only once???

So in long hand lets reverse the logic and make sure we print 'yes'  
only once

 >>> yes = 0
 >>> for num in x:
...   if 5 not in num:
...     if not yes:
...       print 'yes'
...       yes = 1
...
yes



>>
On Apr 19, 2005, at 12:31 AM, Lee Cullens wrote:

>  As you probably have already found out the expression
> >>> print [ e for e in x if 5 in e]
> will produce
> [[8, 4, 5, 6]]
>
> The problem with your original code is that you are printing 'yes' for  
> each sub list until you encounter a sub list with 5 whereupon you  
> break without printing yes.
>
> If you change your test to check for 5 in a sub list and, print yes  
> and break at that point you will get the results you are looking for.
>
> >>> for num in x:
> ...      if 5 in num:
> ...        print "yes"
> ...        break
> ...
> yes
> >>>
>
> Lee C
>
>
>
> On Apr 18, 2005, at 11:51 PM, Ching-Yi Chan wrote:
>
>> *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
>>
>> I'm experimenting and would like 'yes' to be printed only if 5 is not  
>> in
>> the list, but I want to look in each list. This prints out two yeses.
>> How do I get it to print just one 'yes'?
>>
>> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>>
>> for num in x:
>>     if 5 in num:
>>         break
>>     else:
>>         print 'yes'
>>
>> ---------------------------------------------------------------------- 
>> ----
>>
>> Hi, I read the code and consider for a while, you can try it :
>>
>> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>> print [ e for e in x if 5 in e]
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From smichr at bigfoot.com  Tue Apr 19 08:11:54 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Tue Apr 19 08:12:55 2005
Subject: [Tutor] snippets helps
In-Reply-To: <20050416022737.DB2381E4012@bag.python.org>
Message-ID: <ED3F0870-B099-11D9-8E73-000393C0D100@bigfoot.com>


In a recent post, I believe it was D Hawksworth that noted,

> So I imported it, asked the shell window for 'help' (egad, technical
> jargon!) and did a search on python, same result.  None of my
> beginners' tutorials have anything about pickle, unfortunately (very
> frustrating!)
>
> Does anyone know if there are some *beginner*-user-friendly tutorials
> out there for pickle? Or can give a sample of how you would implement
> it into a VERY SIMPLE program?

I have often wished for some small examples to break into the sometimes 
dense technical notation. Has the python community ever considered 
writing the "annotated documentation resource?" It would be nice if the 
documentation had more examples that were "VERY SIMPLE" to demonstrate 
the use of some function or its arguments.

Would something like a documentation wiki (if that's the right word) be 
useful wherein each page(?) of the documentation would have a 
reader-modifiable section in which links back to tutor discussions or 
sample code could be put.  Since such annotations might grow long, 
perhaps a link to another page would be better. Would a rating system 
allow the snippets that people find most useful to rise to the top of 
the examples?

I'm not sure what goes into these wiki and whether something like this 
would get used or not.  Perhaps the personal feedback of the tutor list 
is more effective.

Any thoughts?

/c

From smichr at bigfoot.com  Tue Apr 19 08:16:07 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Tue Apr 19 08:17:04 2005
Subject: [Tutor] import problem
Message-ID: <84456682-B09A-11D9-8E73-000393C0D100@bigfoot.com>

I sent the following to the mac-sig without reply (except for an 
autoresponder telling me that a person was out of the office :-)).  Is 
there anyone with a mac that could test this code in the IDE to see if 
you have the same problems? (I don't have problems running it through 
the 2.4 version of python in the terminal.)

=====

I was recently trying to use the timeit module and although I was able 
to do so without problem on a Windows machine, I get a "cannot import 
y1" ImportError from the following script.

###
import timeit
def y1():
	print 'y1 executed'
def y2():
	print 'y2 executed'
for f in [y1,y2]:
	name = f.__name__
	print name; f()
	t=timeit.Timer('%s()' % name, 'from __main__ import %s' % name)
	print t.timeit(1)
###
--the output--
y1
y1 executed
** ImportError

I am using the IDE for 2.3.3 under OS X (10.2.8).

I am able to successfully run timeit in other ways, but I like the 
above way to loop through the codes that I want to test.

/c

From project5 at redrival.net  Tue Apr 19 08:25:43 2005
From: project5 at redrival.net (Andrei)
Date: Tue Apr 19 08:30:15 2005
Subject: [Tutor] Re: Installation Routines (Joseph Quigley)
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
Message-ID: <loom.20050419T081800-528@post.gmane.org>

Joseph Quigley <cpu.crazy <at> gmail.com> writes:

> I have a friend who recently got a hush-hush contract. He told me that it 
> was for writing an installation program for Windows and that he considered 
> python and Tkinter as an option.
> I know there are installers written in python for Linux. I suppose they are 
> easier to write, than one for Windows?

Python isn't really suitable for installing applications because it requires
itself a quite large installation beforehand (unless you freeze it, in which
case you still end up with quite a large overhead; might be a problem for
internet-based distributions). However, if the installation is purely for
computers which already have Python installed and it's not as much about
installing (IOW, registry modifications, making shortcuts, etc.) as it is about
distributing files, then yes, it's a reasonable option. Otherwise I agree with
the other replies: it's better to go for NSIS, InnoSetup or even a
self-extracting executable as produced by just about any zip tool out there -
you get an environment specifically made for this purpose, with nice GUI/wizard
to produce the code and low overhead.

> Now, I'm still new, and can't do GUI yet, but I was wondering.... how hard 
> would it be to write a simple installer for windows? None of that fancy INI 
> and registry crapp, just a very simple file copier to, oh lets say, My 
> Documents?

That would be very easy. Using easygui.py (a Tkinter wrapper) it would be even
absolutely trivial (show a standard directory selection dialog, then copy the
stuff - 5 lines of code or so). It would be cross-platform too.

Yours,

Andrei

From leec03273 at mac.com  Tue Apr 19 08:32:37 2005
From: leec03273 at mac.com (Lee Cullens)
Date: Tue Apr 19 08:32:49 2005
Subject: [Tutor] import problem
In-Reply-To: <84456682-B09A-11D9-8E73-000393C0D100@bigfoot.com>
References: <84456682-B09A-11D9-8E73-000393C0D100@bigfoot.com>
Message-ID: <fc337b05287044b9df6d8ef06d78b0e7@mac.com>

I assume you mean PythonIDE for Python 2.3 (I usually use 2.4 and 
WingIDE).  Here it is (indents screwed up with var font):

HTH,
Lee C

Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)]
Type "copyright", "credits" or "license" for more information.
MacPython IDE 1.0.1
 >>> import timeit
 >>> def y1():
	print 'y1 executed'
...
 >>> def y2():
	print 'y2 executed'
...
 >>> for f in [y1,y2]:
	name = f.__name__
	print name; f()
	t=timeit.Timer('%s()' % name, 'from __main__ import %s' % name)
	print t.timeit(1)
...
y1
y1 executed
y1 executed
0.00186991691589
y2
y2 executed
y2 executed
0.00309705734253
 >>> import sys
 >>> sys.version
'2.3 (#1, Sep 13 2003, 00:49:11) \n[GCC 3.3 20030304 (Apple Computer, 
Inc. build 1495)]'
 >>>



On Apr 19, 2005, at 2:16 AM, Chris Smith wrote:

> I sent the following to the mac-sig without reply (except for an 
> autoresponder telling me that a person was out of the office :-)).  Is 
> there anyone with a mac that could test this code in the IDE to see if 
> you have the same problems? (I don't have problems running it through 
> the 2.4 version of python in the terminal.)
>
> =====
>
> I was recently trying to use the timeit module and although I was able 
> to do so without problem on a Windows machine, I get a "cannot import 
> y1" ImportError from the following script.
>
> ###
> import timeit
> def y1():
> 	print 'y1 executed'
> def y2():
> 	print 'y2 executed'
> for f in [y1,y2]:
> 	name = f.__name__
> 	print name; f()
> 	t=timeit.Timer('%s()' % name, 'from __main__ import %s' % name)
> 	print t.timeit(1)
> ###
> --the output--
> y1
> y1 executed
> ** ImportError
>
> I am using the IDE for 2.3.3 under OS X (10.2.8).
>
> I am able to successfully run timeit in other ways, but I like the 
> above way to loop through the codes that I want to test.
>
> /c
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From project5 at redrival.net  Tue Apr 19 08:46:05 2005
From: project5 at redrival.net (Andrei)
Date: Tue Apr 19 08:50:58 2005
Subject: [Tutor] Re: snippets helps
References: <20050416022737.DB2381E4012@bag.python.org>
	<ED3F0870-B099-11D9-8E73-000393C0D100@bigfoot.com>
Message-ID: <loom.20050419T083017-200@post.gmane.org>

Chris Smith <smichr <at> bigfoot.com> writes:

> I have often wished for some small examples to break into the sometimes 
> dense technical notation. Has the python community ever considered 
> writing the "annotated documentation resource?" It would be nice if the 

I remember someone made some time ago a sort of shell around the Python docs
which allowed adding comments to the official docs. The Python docs are loaded
in a frame, the comments are stored separately by this system. It doesn't seem
to be very widely used, but it's probably still worth a look:
http://pydoc.amk.ca/frame.html

> documentation had more examples that were "VERY SIMPLE" to demonstrate 
> the use of some function or its arguments.

I agree, simple examples are indeed lacking in some parts of the docs. The
cookbook covers the more difficult options/tricks. I'd say Useless Python could
be a candidate for storing such simple examples, but I'm not sure it really has
the infrastructure required to search e.g. for examples using pickle.

> perhaps a link to another page would be better. Would a rating system 
> allow the snippets that people find most useful to rise to the top of 
> the examples?

It would indeed, if someone implemented it :).

> would get used or not.  Perhaps the personal feedback of the tutor list 
> is more effective.

OTOH, finding it yourself is faster than waiting for a reply.

Yours,

Andrei

From alan.gauld at freenet.co.uk  Tue Apr 19 09:24:02 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 09:23:51 2005
Subject: [Tutor] Newbie question
References: <20050419005510.3607.qmail@web60006.mail.yahoo.com>
Message-ID: <01d901c544b0$c3976920$728f8651@xp>

> def square(y):
>    return y * y
> 
> for x in range(1, 11):
>    print square(x),
> 
> print
> 
> Well, I understood the code above. My question is: Is
> it really necessary I have the last "print" statment

No, it just creates a blank line which makes it easier to separate 
the output of the program from the other stuff on the screen. 
Its a convenience feature which although not essential helps 
the user see the results.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
From ewald.ertl at hartter.com  Tue Apr 19 09:29:02 2005
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Tue Apr 19 09:29:06 2005
Subject: [Tutor] for loop
In-Reply-To: <4264804B.2000200@stumail.nutn.edu.tw>
References: <4264804B.2000200@stumail.nutn.edu.tw>
Message-ID: <20050419092902.0000535f@sunray1>

Hi, 

I've slightly modified the for-Loop  containing the "else" and not the if: 

>>> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>>> for num in x:
...     if 5 in num:
...             break
... else:
...     print "YES"
... 
>>>

second test: 

>>> x = [[1,2,3],[2,4,6],[8,4,6],[9,8,7]]
>>> for num in x:
...     if 5 in num:
...             break 
... else:
...     print "YES"
... 
YES
>>> 

The else-Part is only executed, when the for ( or while) - loop is left regularly, without 
a break-statement. 

HTH Ewald 

on Tue, 19 Apr 2005 11:51:39 +0800  Ching-Yi Chan <m92507@stumail.nutn.edu.tw> wrote :
---------------------------------------------------------------------------------------------

Ching-Yi Chan > *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
Ching-Yi Chan > 
Ching-Yi Chan > I'm experimenting and would like 'yes' to be printed only if 5 is not in
Ching-Yi Chan > the list, but I want to look in each list. This prints out two yeses.
Ching-Yi Chan > How do I get it to print just one 'yes'?
Ching-Yi Chan > 
Ching-Yi Chan > x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
Ching-Yi Chan > 
Ching-Yi Chan > for num in x:
Ching-Yi Chan >     if 5 in num:
Ching-Yi Chan >         break
Ching-Yi Chan >     else:
Ching-Yi Chan >         print 'yes'  
Ching-Yi Chan > 
Ching-Yi Chan > --------------------------------------------------------------------------
Ching-Yi Chan > 
Ching-Yi Chan > Hi, I read the code and consider for a while, you can try it :
Ching-Yi Chan > 
Ching-Yi Chan > x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
Ching-Yi Chan > print [ e for e in x if 5 in e]
Ching-Yi Chan > 
Ching-Yi Chan > 
Ching-Yi Chan > _______________________________________________
Ching-Yi Chan > Tutor maillist  -  Tutor@python.org
Ching-Yi Chan > http://mail.python.org/mailman/listinfo/tutor
Ching-Yi Chan > 


------------------- end ----------------------

From alan.gauld at freenet.co.uk  Tue Apr 19 09:37:08 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 09:36:51 2005
Subject: [Tutor] for loop
References: <4264804B.2000200@stumail.nutn.edu.tw>
Message-ID: <01e001c544b2$981704c0$728f8651@xp>

> *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
>
> I'm experimenting and would like 'yes' to be printed only if 5 is
not in
> the list, but I want to look in each list. This prints out two
yeses.
> How do I get it to print just one 'yes'?
>
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>
> for num in x:
>     if 5 in num:
>         break
>     else:
>         print 'yes'

There are several ways to do this but the two  that I would suggest
are:

for num in x:
    if 5 in num:
       found = True
       break

if found: print 'yes'

Or using list comprehensions(Which you probably haven't discovered
yet)

resp = ['yes' for num in x if 5 in num]
if resp: print resp[0]

HTH

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

From alan.gauld at freenet.co.uk  Tue Apr 19 09:56:23 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 09:56:05 2005
Subject: [Tutor] for loop
References: <4264804B.2000200@stumail.nutn.edu.tw><72aec6f37f6afddd87ee7fcc14522cdc@mac.com>
	<33360b012237f29a1120cec9341cac94@mac.com>
Message-ID: <01fc01c544b5$48662430$728f8651@xp>


> Well I was reading too fast (as usual) - you wanted to print 'yes'
> only if 5 is not in a sub list but you want to look in all the sub
> lists and yet print 'yes' only once???

Oops, me too, so in that case....

> So in long hand lets reverse the logic and make sure we print 'yes'
> only once
>
>  >>> yes = 0
>  >>> for num in x:
> ...   if 5 not in num:
> ...     if not yes:
> ...       print 'yes'
> ...       yes = 1
> ...
> yes

Or alternatively use the else construct of a for loop...

for num in x:
   if 5 in x:
      break
else: print 'yes'

The else only gets executed if the loop runs to completion
without a break...

HTH

Alan G.


From albertito_g at hotmail.com  Tue Apr 19 14:49:11 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 19 14:49:15 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F2209176C49B1CF1E5A065889290@phx.gbl>
Message-ID: <BAY106-F30A00F00FD6B1F123BF6C1892A0@phx.gbl>


Hi
I have another problem. It seems that I manage to solve a problem and run 
into another

The problem is that now I can't install MySQLdb (MySQL database module for 
Python 2.3.4)

I try to ./configure and it prints a lot of crap and then says mysql ended 
on exit 1

What can I do??????????

Please help me I'm about to throw my machine over the windows (and I live on 
the 6th)

Thanks in advanced

Alberto

<html><div><IMG height=12 src="http://graphics.hotmail.com/emvamp.gif" 
width=12>&nbsp;Gaucho</div></html>




>From: "Alberto Troiano" <albertito_g@hotmail.com>
>To: klappnase@freenet.de
>CC: tutor@python.org
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Mon, 18 Apr 2005 19:03:08 +0000
>
>Hi everyone
>
>I have been able to install Python 2.3.4 with Tkinter.
>I don't know if there is some kind of knowledge base but if somebody has 
>this problem this is what I did:
>
>I have downloaded the tcl/tk rpm from 
>http://www.interlink.com.au/anthony/tech/rh9-tcltk/
>(They are 8.3.5-185 and fix the bug that Linux Red Hat 9.0 tcl/tk 8.3.5-xx 
>has)
>
>I've installed first the tcl package and then the tk package.
>Then I've installed Python2.3.4 with the following commands:
>./configure --enable-unicode=ucs4
>make
>make install
>
>That's all
>
>Thanks to all who tried to help me (Now I have a problem with the MySQL 
>database but that doesn't fit in this forum ;)
>
>Regards
>
>Alberto
>
>
>>From: Michael Lange <klappnase@freenet.de>
>>To: tutor@python.org
>>Subject: Re: [Tutor] TKinter and things over Linux
>>Date: Mon, 18 Apr 2005 17:09:28 +0200
>>
>>On Mon, 18 Apr 2005 13:24:03 +0000
>>"Alberto Troiano" <albertito_g@hotmail.com> wrote:
>>
>>Hi Alberto,
>>
>> > Hey
>> > Let me know if this format is better (I use Hotmail in the web so...)
>> >
>>
>>Looks pretty much ok to me :-)
>>
>> > Sadly I'm not in the linux machine so I can't run the command you sent 
>>me
>> > but I shall explain the version just so you know
>> >
>> > The fullname version is Red Hat Advanced Server 3.0. This is a 
>>commercial
>> > version of Linux
>> > But it has so many problems and so few documentation that I switched to 
>>Red
>> > Hat 9.0 (I think that you're familiar with this version)
>> >
>> > I have installed tcl and tk support and I will download and install the
>> > anthony's RPMs
>> > What can I do to make Tkinter work on Linux Red Hat 9.0??????????
>> >
>>
>>First you should make sure that all necessary RPMs are installed; the 
>>basic python
>>RPM will be installed by default on RedHat 9 but probably not Tkinter ( 
>>I'm not sure
>>how the RPM is called on RedHat, maybe python-tkinter or python-tk or 
>>tkinter or... ).
>>
>>Best regards
>>
>>Michael
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>
>
>Gaucho
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


From maxnoel_fr at yahoo.fr  Tue Apr 19 14:56:02 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Tue Apr 19 14:59:53 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F30A00F00FD6B1F123BF6C1892A0@phx.gbl>
References: <BAY106-F30A00F00FD6B1F123BF6C1892A0@phx.gbl>
Message-ID: <b505b3d1ad0cb93293218f816d974ae7@yahoo.fr>


On Apr 19, 2005, at 13:49, Alberto Troiano wrote:

>
> Hi
> I have another problem. It seems that I manage to solve a problem and 
> run into another
>
> The problem is that now I can't install MySQLdb (MySQL database module 
> for Python 2.3.4)
>
> I try to ./configure and it prints a lot of crap and then says mysql 
> ended on exit 1
>
> What can I do??????????

	A little Googling informs me that MySQLdb is obsolete and hasn't been 
updated since some time in 2000 (at that time, Python hadn't even 
reached 2.0, had it?).

	You should use MySQL-Python instead, which can be found here: 
http://sourceforge.net/projects/mysql-python . Chances are it's a 
standard distutils module, i.e. you install it with "sudo python 
setup.py install".

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From albertito_g at hotmail.com  Tue Apr 19 15:04:09 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 19 15:04:13 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <b505b3d1ad0cb93293218f816d974ae7@yahoo.fr>
Message-ID: <BAY106-F12AF3993844D4165969338892A0@phx.gbl>


Sorry I have Mysql-python 1.20
that's the one I can not install
I said MySQLdb because I'm still using it for windows
I can't install mysql-python it gives me the error i described

With mysql-python does the sintax change???????What should I import if not 
MySQLdb????????

Thanks in advanced

Alberto


<html><div><IMG height=12 src="http://graphics.hotmail.com/emvamp.gif" 
width=12>&nbsp;Gaucho</div></html>




>From: Max Noel <maxnoel_fr@yahoo.fr>
>To: "Alberto Troiano" <albertito_g@hotmail.com>
>CC: klappnase@freenet.de, tutor@python.org
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Tue, 19 Apr 2005 13:56:02 +0100
>
>
>On Apr 19, 2005, at 13:49, Alberto Troiano wrote:
>
>>
>>Hi
>>I have another problem. It seems that I manage to solve a problem and run 
>>into another
>>
>>The problem is that now I can't install MySQLdb (MySQL database module for 
>>Python 2.3.4)
>>
>>I try to ./configure and it prints a lot of crap and then says mysql ended 
>>on exit 1
>>
>>What can I do??????????
>
>	A little Googling informs me that MySQLdb is obsolete and hasn't been 
>updated since some time in 2000 (at that time, Python hadn't even reached 
>2.0, had it?).
>
>	You should use MySQL-Python instead, which can be found here: 
>http://sourceforge.net/projects/mysql-python . Chances are it's a standard 
>distutils module, i.e. you install it with "sudo python setup.py install".
>
>-- Max
>maxnoel_fr at yahoo dot fr -- ICQ #85274019
>"Look at you hacker... A pathetic creature of meat and bone, panting and 
>sweating as you run through my corridors... How can you challenge a 
>perfect, immortal machine?"
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


From John.Gooch at echostar.com  Tue Apr 19 16:20:00 2005
From: John.Gooch at echostar.com (Gooch, John)
Date: Tue Apr 19 16:20:40 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>

Brian, 

I think in the OO world it is called Polymorphism, where you have a single
function name, but multiple definitions that are distinguished from one
another by the number of arguments, type of arguments, and sometimes (
Smalltalk ) the return type of the function.

Here are some example function declarations ( C++ style )
boolean greaterThan( int A, int B );
boolean greaterThan( char A, char B );
boolean greaterThan( double A, double B );

All of these functions are called as "greaterThan( A,B )" and all of them
return a boolean "true" or "false" value, but the compiler decides which one
of the three functions above gets called depending on the data type of A and
B. My first question was whether or not you can do this in Python with the
__init__ function. In C++ you can have multiple contructors for a class,
with the arguments deciding which contructor is called. Here is an example:

class Circle : Shape {
public:
	Circle();//creates default circle object

	Circle( int x, int y, float radius ); //creates circle object with
specified x,y coordinates and radius
};


now, replace 'Circle' in the 'public:' area with '__init__' and you have a
picture of what I would like to do in Python, but I don't know if the
language support it or not. 

Thank you for answering the second part of the question, I will try that
technique out.


John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 






-----Original Message-----
From: Brian van den Broek [mailto:bvande@po-box.mcgill.ca] 
Sent: Friday, April 15, 2005 4:22 PM
To: Gooch, John
Cc: Python tutor
Subject: Re: [Tutor] Contructor Overloading and Function Tooktips


Gooch, John said unto the world upon 2005-04-15 18:03:
> I have a couple of questions:
> 
> Is there a way to create multiple __init__ routines in a Python Class?

Hi John,

I'm not sure what you mean by that. Could be me, or could be the 
question. :-)


> Secondly, I cannot remember how to make it so that when you start 
> typing in a defined function name, it pops up a tooltip showing the
functions syntax.
> 	ex: def delRecord( some params ):
> 	dr = delRecord()
> 	dr.someCommand( <-- tooltip popups up here

Many Python-aware editors use the first line of the docstring to 
construct the tooltip:

def silly():
     '''This will be the tooltip.

     This will be more documentation.'''
     pass

HTH,

Brian vdB
From jeffpeery at yahoo.com  Tue Apr 19 17:06:10 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Tue Apr 19 17:06:14 2005
Subject: [Tutor] py2exe
In-Reply-To: 6667
Message-ID: <20050419150610.15366.qmail@web30508.mail.mud.yahoo.com>

Ok, thanks again Greg. Although I didn't see a log file, where would it appear and what would the name be... just in case I missed it. thanks.
 
Jeff

Greg Hasseler <ghasseler@gmail.com> wrote:
I meant to send my first reply the list..oops. If it doesn't leave any
log file then I would suggest maybe sending the program source code
itself to the list so that others can review it for potential error.


On 4/18/05, Jeff Peery wrote:
> Hi Greg, thanks for the help. the program does not launch, it crashes
> immediately, and I did not see a log file. I also ran py2exe several times
> over and always the same result. the program runs great in regular python
> mode. any ideas? thanks. 
> 
> Jeff
> 
> Greg Hasseler wrote: 
> Does the application launch at all or does it just immediately crash?
> Look and see if there are any logs available. You may also consider
> running py2exe again.
> 
> On 4/15/05, Jeff Peery wrote:
> > 
> > hello, I am using py2exe. for most of my applications it has been great.
> > although this last one I built and when I try to execute it I get an
> error: 
> > 
> > RunTime Error: this application has requested the runtime to terminate in
> an
> > unusual way. please contact the applications support team for more info. 
> > 
> > does anyone know what this means? thanks. 
> > 
> > Jeff 
> > 
> > 
> > _______________________________________________
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050419/2f09042d/attachment.htm
From jsmith at medplus.com  Tue Apr 19 18:21:35 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Tue Apr 19 18:21:43 2005
Subject: [Tutor] Of fish and foul...(aka the Perl require command)
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C03394594@medexch1.medplus.com>

Thanks,

That does the trick.  Rather than make a function, I'm likely to just
do:

if sys.version_info[:3] < (X,Y,Z):
    raise RuntimeError

Jeff

-----Original Message-----
From: Max Noel [mailto:maxnoel_fr@yahoo.fr] 
Sent: Monday, April 18, 2005 3:34 PM
To: Smith, Jeff
Cc: tutor@python.org
Subject: Re: [Tutor] Of fish and foul...(aka the Perl require command)



On Apr 18, 2005, at 19:59, Smith, Jeff wrote:

> Is there a Python equivalent to the Perl
>
> require 5.6.0
>
> Which enforces a minimum interpreter version?

	As far as I know, no. But:

 >>> import sys
 >>> sys.version_info
(2, 3, 0, 'final', 0)
 >>> (2, 4, 0) > sys.version_info
True
 >>> (2, 2, 0) > sys.version_info
False

	So you can create one yourself quite easily.



import sys

def require(version):
     if sys.version_info < version:
         raise OSError, "This program requires Python v%s or later" % 
'.'.join(map(str, version))



 >>> require((2,4,1))
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 3, in require
OSError: This program requires Python v2.4.1 or later


	I'm not really sure what exception I should raise, though --
OSError 
is the most appropriate, but not exactly the Right Thing... Oh, well. 
*shrugs*

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From john.ertl at fnmoc.navy.mil  Tue Apr 19 18:55:02 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Tue Apr 19 18:51:49 2005
Subject: FW: [Tutor] Trying to d0 HTTP GET
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C61A@lanexc107p.fnmoc.navy.mil>

All,

I have figured out a bit more.  I can get the binary values from the service
but I think they come back as a single string.  How do I read that into an
array?  The code below will read the first number into the array and print
it out but how would I read the whole thing into an array...I would like to
skip the step of putting the raw binary numbers into a variable and instead
read it directly into the binvalues array.

I have tried things like  binvalues.read(rawData.read(4,size of array)) and
a few other things but none of them work.  I was hoping for a fromstream but
no luck no that either.
Thanks for any help.
<CODE>
binvalues = array.array('f')

rawData =
urllib2.urlopen("http://dsd1u:7003/GRID:U:NOGAPS:2005041800:global_360x181:a
ir_temp:ht_sfc:00020000:00000000:fcst_ops:0240")


binvalues.fromstring(rawData.read(4))  # 4 byte float

binvalues.byteswap()

print binvalues

</CODE>

-----Original Message-----
From: Kent Johnson
Cc: tutor@python.org
Sent: 4/18/05 1:10 PM
Subject: Re: [Tutor] Trying to d0 HTTP GET

Ertl, John wrote:
> All,
>
> I am trying to get some binary data from a web service.  None of the
tech
> guys are around so I am hoping you might be able to shed some light on
what
> might be happening.

I would think that
f = urllib.urlopen(...)
data = f.read()

would work. You could try urllib2.urlopen() and see if it is any better.

How big is the data you are expecting?

Kent

>
> Here is part of the email that explained what I needed to do.
>
> ----- clip ---
>
> If you can do an http "get" from Python, you'll be set.
> 
>
http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041512:global_360x181:max_wav_ht
:sur
> face:00000000:00000000:fcst_ops:0480
>
> It returns an http header like the following (if the grid exists),
> followed by the grid data in big-endian, IEEE format.
>
>          "HTTP/1.1 200 OK\r\n"
>          "Server: ISIS/4.0\r\n"
>          "Content-type: application/x-grid\r\n"
>          "Content-length: 261234\r\n\r\n"
>
> ----- end-----
>
> The grid data is in Binary.  How would I get to this?  I would imagine
that
> since f (the object) exists the call to the web service worked. Now I
need
> to read the grid...eventually I need to put it into a Numeric array
but not
> sure how to get just the grid from "f".
>
> As a simple starting point I tried. 
>
>
>>>>import urllib
>>>>f =
>
>
urllib.urlopen("http://dsd1u:7003/GRID:U:WW3_GLOBAL:2005041800:global_36
0x18
> 1:max_wav_ht:surface:00000000:00000000:fcst_ops:0240")
>
>>>>f.info()
>
> <httplib.HTTPMessage instance at 0xb9255f6c>
>
>>>>f.readlines()
>
>
> I tried read(), readLines() and some other stuff using scipy and
Numeric.
>
> The prompt has moved to the next line but nothing else has happened
for 30
> min or so (I have tried several times).  When I try to close IDLE it
says
> the program is still running.  How should I be getting this data is it
> trying to read the binary and that is why it is stalled? 
>
> Thanks,
>
> John Ertl
>
> _______________________________________________
> 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 dyoo at hkn.eecs.berkeley.edu  Tue Apr 19 19:18:11 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 19 19:18:19 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F12AF3993844D4165969338892A0@phx.gbl>
Message-ID: <Pine.LNX.4.44.0504191009500.2286-100000@hkn.eecs.berkeley.edu>



On Tue, 19 Apr 2005, Alberto Troiano wrote:

> Sorry I have Mysql-python 1.20
> that's the one I can not install
> I said MySQLdb because I'm still using it for windows
> I can't install mysql-python it gives me the error i described
>
> With mysql-python does the sintax change???????What should I import if
> not MySQLdb????????

hi Alberto

Same syntax, same author.  And same version number.  I think you guys are
talking about the same module.  *grin* I hope we are both talking about
the MySQL-Python module from SourceForge, here:

http://sourceforge.net/project/showfiles.php?group_id=22307&package_id=15775


Alberto, why are you using ./configure?  Are you trying to execute
Python's configure script?  If so, don't: third-party modules use a
different method of installation.  See:

    http://docs.python.org/inst/inst.html



Ideally, all you need to do is untar the source to MySQL-Python, and do
something like:

######
[dyoo@shoebox dyoo]$ cd MySQL-python-1.2.0
[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py build
######

The step 'python setup.py build' tells Python to try to build the third
party extension.  If you see problems here, please copy and paste exactly
what you see.


Otherwise, the last step:

######
[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py install
######

should finish the job --- you may need to have administrative privileges
on your machine to do this, as it tries to write files into the same place
as the Standard Library.

From kent37 at tds.net  Tue Apr 19 19:33:08 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 19 19:33:12 2005
Subject: FW: [Tutor] Trying to d0 HTTP GET
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C61A@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C61A@lanexc107p.fnmoc.navy.mil>
Message-ID: <426540D4.7010505@tds.net>

Ertl, John wrote:
> All,
> 
> I have figured out a bit more.  I can get the binary values from the service
> but I think they come back as a single string.  How do I read that into an
> array?  The code below will read the first number into the array and print
> it out but how would I read the whole thing into an array...I would like to
> skip the step of putting the raw binary numbers into a variable and instead
> read it directly into the binvalues array.
> 
> I have tried things like  binvalues.read(rawData.read(4,size of array)) and
> a few other things but none of them work.  I was hoping for a fromstream but
> no luck no that either.

Unless the data is huge you should probably just read it all into a string, then pass the string to 
binvalue like this:

binvalues = array.array('f')
rawData = urllib2.urlopen(...).read()

binvalues.fromstring(rawData)
binvalues.byteswap()

This is likely to be the fastest approach as all the looping happens internally to urllib2 and 
array. The only limitation is that both representations have to fit in memory at once.

Alternately you could wrap the rawData in a generator function which returns floats. Then pass the 
generator to binvalues.extend(). Something like this (untested):

import array, struct, urllib2

def generateFloats(rawDataStream):
   while True:
     s = rawData.read(4)
     if len(s) < 4: return
     f = struct.unpack('f', s) # prefix the 'f' with the correct byte-order character...
     yield f

binvalues = array.array('f')
rawDataStream = urllib2.urlopen(...)

binvalues.extend(generateFloats(rawDataStream))

Kent


> Thanks for any help.
> <CODE>
> binvalues = array.array('f')
> 
> rawData =
> urllib2.urlopen("http://dsd1u:7003/GRID:U:NOGAPS:2005041800:global_360x181:a
> ir_temp:ht_sfc:00020000:00000000:fcst_ops:0240")
> 
> 
> binvalues.fromstring(rawData.read(4))  # 4 byte float
> 
> binvalues.byteswap()
> 
> print binvalues
> 
> </CODE>

From dyoo at hkn.eecs.berkeley.edu  Tue Apr 19 19:34:49 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 19 19:34:53 2005
Subject: FW: [Tutor] Trying to d0 HTTP GET
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C61A@lanexc107p.fnmoc.navy.mil>
Message-ID: <Pine.LNX.4.44.0504191022530.2286-100000@hkn.eecs.berkeley.edu>



On Tue, 19 Apr 2005, Ertl, John wrote:

> I have figured out a bit more.  I can get the binary values from the
> service but I think they come back as a single string.  How do I read
> that into an array?

Hi John,


> The code below will read the first number into the array and print it
> out but how would I read the whole thing into an array...I would like to
> skip the step of putting the raw binary numbers into a variable and
> instead read it directly into the binvalues array.

Do you know how large the array of numbers will be?  Let's check
something.

######
>>> import struct
>>> struct.calcsize("f")
4
######

It looks like each float will be four bytes long, as expected.  Do you
remember if your web service provides these values in little-endian or
big-endian format?



You might be able to get away with just using the 'struct' module,

    http://www.python.org/doc/lib/module-struct.html

with its useful 'unpack' function():

#####
import urllib2
import struct

url = ("http://dsd1u:7003/GRID:U:NOGAPS:2005041800:global_360x181:" +
       "air_temp:ht_sfc:00020000:00000000:fcst_ops:0240")
rawdata = urllib2.urlopen(url).read()
numberOfValues = len(rawdata) / struct.calcsize("f")
values = struct.unpack("!%df" % numberOfValues,
                       rawData)
######

I'm assuming for the moment that the only data in rawdata are those
floats, and that the floats are in big-endian "network" byte order.

From john.ertl at fnmoc.navy.mil  Tue Apr 19 19:44:14 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Tue Apr 19 19:41:10 2005
Subject: FW: [Tutor] Trying to d0 HTTP GET
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C61B@lanexc107p.fnmoc.navy.mil>

Kent and Danny,

Thanks for the help.  The trick was to put the .read() at the end of the
urllib2 line.  It makes some sense now but man I hate it when it is that
simple and I just can't see it.

Thanks again for the great help.

John Ertl 

-----Original Message-----
From: Kent Johnson [mailto:kent37@tds.net]
Sent: Tuesday, April 19, 2005 10:33
Cc: tutor@python.org
Subject: Re: FW: [Tutor] Trying to d0 HTTP GET

Ertl, John wrote:
> All,
>
> I have figured out a bit more.  I can get the binary values from the
service
> but I think they come back as a single string.  How do I read that into an
> array?  The code below will read the first number into the array and print
> it out but how would I read the whole thing into an array...I would like
to
> skip the step of putting the raw binary numbers into a variable and
instead
> read it directly into the binvalues array.
>
> I have tried things like  binvalues.read(rawData.read(4,size of array))
and
> a few other things but none of them work.  I was hoping for a fromstream
but
> no luck no that either.

Unless the data is huge you should probably just read it all into a string,
then pass the string to
binvalue like this:

binvalues = array.array('f')
rawData = urllib2.urlopen(...).read()

binvalues.fromstring(rawData)
binvalues.byteswap()

This is likely to be the fastest approach as all the looping happens
internally to urllib2 and
array. The only limitation is that both representations have to fit in
memory at once.

Alternately you could wrap the rawData in a generator function which returns
floats. Then pass the
generator to binvalues.extend(). Something like this (untested):

import array, struct, urllib2

def generateFloats(rawDataStream):
   while True:
     s = rawData.read(4)
     if len(s) < 4: return
     f = struct.unpack('f', s) # prefix the 'f' with the correct byte-order
character...
     yield f

binvalues = array.array('f')
rawDataStream = urllib2.urlopen(...)

binvalues.extend(generateFloats(rawDataStream))

Kent


> Thanks for any help.
> <CODE>
> binvalues = array.array('f')
>
> rawData =
>
urllib2.urlopen("http://dsd1u:7003/GRID:U:NOGAPS:2005041800:global_360x181:a
> ir_temp:ht_sfc:00020000:00000000:fcst_ops:0240")
>
>
> binvalues.fromstring(rawData.read(4))  # 4 byte float
>
> binvalues.byteswap()
>
> print binvalues
>
> </CODE>

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From alan.gauld at freenet.co.uk  Tue Apr 19 19:50:49 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 19:50:21 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
Message-ID: <022801c54508$52db8420$728f8651@xp>

> I think in the OO world it is called Polymorphism,

Nope, its called overloading. Polymorphism is where you
send the same message to diferent types of object and
get different behaviour.

> where you have a single function name, but multiple definitions
> that are distinguished from one another by the number of arguments,
> type of arguments, and sometimes ( Smalltalk ) the return type
> of the function.

Actually the return type in Smalltalk is always an object
so its irrelevant, however what you say is true of
Objective C as an example.

> B. My first question was whether or not you can do this in Python
with the
> __init__ function. In C++ you can have multiple contructors for a
class,
> with the arguments deciding which contructor is called. Here is an
example:

The answer is no, but you can examoine the arguments at run time
and call any one of several helper functions from within init()
which achieves the same effect.

Python cannot easily support this feature because it relies on
binding of type to name but in Python names are simply keys in
a dictionary, the object asociated can be of any type and even
change type over time. THuds we must rely on runtime introspection
of the type of the object to decide which version of "init()"
we need.

HTH,

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

From tpc at csua.berkeley.edu  Tue Apr 19 19:59:38 2005
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Tue Apr 19 19:59:44 2005
Subject: [Tutor] inexplicable MySQLdb behavior, INSERT data doesn't appear
Message-ID: <20050419103240.T78720-100000@localhost.name>

hi all, while recently trying to insert some data into the following
table:

# stores unique course definitions
CREATE TABLE adminCourses (
ID TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
Code CHAR(6),
Title VARCHAR(55),
Units TINYINT UNSIGNED
) TYPE = InnoDB;

I got a 1L value when I ran the following:

cursor.execute("INSERT INTO adminCourses(ID, Code, Title, Units) VALUES
(NULL, 'EAT100', 'Josue', 30);")

indicating no errors.  Then when I cursor.execute("Select * from
adminCourses") I can see the datum, but when I go to MySQL shell and
"Select * from adminCourses;" there are 0 records !  If I then execute the
aforementioned INSERT statement while still in MySQL shell, and then the
SELECT statement, I will see the lone datum but the ID number will be
offset by how many times I executed the INSERT statement via MySQLdb
(e.g., if I cursor.execute the INSERT statement 5 times, then go to MySQL
shell to run the INSERT statement, when I do a "SELECT * from
adminCourses" the solo datum will appear prefixed by an ID number of 6).
Am I doing something wrong ?

From kent37 at tds.net  Tue Apr 19 20:19:08 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 19 20:19:11 2005
Subject: [Tutor] inexplicable MySQLdb behavior, INSERT data doesn't appear
In-Reply-To: <20050419103240.T78720-100000@localhost.name>
References: <20050419103240.T78720-100000@localhost.name>
Message-ID: <42654B9C.3030409@tds.net>

Sounds like you need to commit() the initial cursor.execute()

Kent

tpc@csua.berkeley.edu wrote:
> hi all, while recently trying to insert some data into the following
> table:
> 
> # stores unique course definitions
> CREATE TABLE adminCourses (
> ID TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
> Code CHAR(6),
> Title VARCHAR(55),
> Units TINYINT UNSIGNED
> ) TYPE = InnoDB;
> 
> I got a 1L value when I ran the following:
> 
> cursor.execute("INSERT INTO adminCourses(ID, Code, Title, Units) VALUES
> (NULL, 'EAT100', 'Josue', 30);")
> 
> indicating no errors.  Then when I cursor.execute("Select * from
> adminCourses") I can see the datum, but when I go to MySQL shell and
> "Select * from adminCourses;" there are 0 records !  If I then execute the
> aforementioned INSERT statement while still in MySQL shell, and then the
> SELECT statement, I will see the lone datum but the ID number will be
> offset by how many times I executed the INSERT statement via MySQLdb
> (e.g., if I cursor.execute the INSERT statement 5 times, then go to MySQL
> shell to run the INSERT statement, when I do a "SELECT * from
> adminCourses" the solo datum will appear prefixed by an ID number of 6).
> Am I doing something wrong ?
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From bvande at po-box.mcgill.ca  Tue Apr 19 20:29:49 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 19 20:31:21 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
Message-ID: <42654E1D.1030601@po-box.mcgill.ca>

Gooch, John said unto the world upon 2005-04-19 10:20:
> Brian, 
> 
> I think in the OO world it is called Polymorphism, where you have a single
> function name, but multiple definitions that are distinguished from one
> another by the number of arguments, type of arguments, and sometimes (
> Smalltalk ) the return type of the function.
> 
> Here are some example function declarations ( C++ style )
> boolean greaterThan( int A, int B );
> boolean greaterThan( char A, char B );
> boolean greaterThan( double A, double B );
> 
> All of these functions are called as "greaterThan( A,B )" and all of them
> return a boolean "true" or "false" value, but the compiler decides which one
> of the three functions above gets called depending on the data type of A and
> B. My first question was whether or not you can do this in Python with the
> __init__ function. In C++ you can have multiple contructors for a class,
> with the arguments deciding which contructor is called. Here is an example:
> 
> class Circle : Shape {
> public:
> 	Circle();//creates default circle object
> 
> 	Circle( int x, int y, float radius ); //creates circle object with
> specified x,y coordinates and radius
> };
> 
> 
> now, replace 'Circle' in the 'public:' area with '__init__' and you have a
> picture of what I would like to do in Python, but I don't know if the
> language support it or not. 
> 
> Thank you for answering the second part of the question, I will try that
> technique out.
> 

Hi John,

OK, I think I see what you meant.

First thing is, while I understand it was just an example, your 
greaterThan examples are handled differently in Python, I think. There 
are "special methods" for stipulating how the objects of a class 
behave when passed to the standard comparisons (like '>'). They are 
all methods with double leading and trailing underscores such as 
__gt__ I'm typing off line, but searching the docs for "special 
method" should get you there. (Also, if you have it, p.92 of Python in 
a Nutshell covers them.)

OK, but that was just your example :-)  Here is some ugly quick code 
which might show you how to meet you needs:

class JohnsMultiInitClass:
     def __init__(self, first, second):
         if type(first) == type(second) == str:
             self.string_init(first, second)
         if type(first) == type(second) == int:
             self.int_init(first, second)
     def string_init(self, first, second):
         # string init code here
     def int_init(self, first, second):
         # int init code here

That said, I'm not so sure this is a good thing. I'm no pro, still 
getting an handle on OOP, and dangerous only in Python. But, I suspect 
that this is not the Python way to do this sort of thing. (Perhaps 
people with C++ experience can weigh in to confirm or deny.)

Best,

Brian vdB

From marilyn at deliberate.com  Tue Apr 19 20:25:42 2005
From: marilyn at deliberate.com (Marilyn Davis)
Date: Tue Apr 19 20:34:25 2005
Subject: [Tutor] inexplicable MySQLdb behavior, INSERT data doesn't appear
In-Reply-To: <42654B9C.3030409@tds.net>
Message-ID: <Pine.LNX.4.44.0504191121100.18776-100000@Kuna>

On Tue, 19 Apr 2005, Kent Johnson wrote:

> Sounds like you need to commit() the initial cursor.execute()

Yes.  When we upgraded to 2.4, we had to add a commit(), so my own execute looks like:

self.cursor.execute(this,args)
did = self.connection.affected_rows()
self.connection.commit()
return did

Hope it helps.

Marilyn Davis

> 
> Kent
> 
> tpc@csua.berkeley.edu wrote:
> > hi all, while recently trying to insert some data into the following
> > table:
> > 
> > # stores unique course definitions
> > CREATE TABLE adminCourses (
> > ID TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
> > Code CHAR(6),
> > Title VARCHAR(55),
> > Units TINYINT UNSIGNED
> > ) TYPE = InnoDB;
> > 
> > I got a 1L value when I ran the following:
> > 
> > cursor.execute("INSERT INTO adminCourses(ID, Code, Title, Units) VALUES
> > (NULL, 'EAT100', 'Josue', 30);")
> > 
> > indicating no errors.  Then when I cursor.execute("Select * from
> > adminCourses") I can see the datum, but when I go to MySQL shell and
> > "Select * from adminCourses;" there are 0 records !  If I then execute the
> > aforementioned INSERT statement while still in MySQL shell, and then the
> > SELECT statement, I will see the lone datum but the ID number will be
> > offset by how many times I executed the INSERT statement via MySQLdb
> > (e.g., if I cursor.execute the INSERT statement 5 times, then go to MySQL
> > shell to run the INSERT statement, when I do a "SELECT * from
> > adminCourses" the solo datum will appear prefixed by an ID number of 6).
> > Am I doing something wrong ?
> > 
> > _______________________________________________
> > 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 dyoo at hkn.eecs.berkeley.edu  Tue Apr 19 20:39:20 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Apr 19 20:39:27 2005
Subject: [Tutor] inexplicable MySQLdb behavior, INSERT data doesn't appear
In-Reply-To: <20050419103240.T78720-100000@localhost.name>
Message-ID: <Pine.LNX.4.44.0504191130290.9580-100000@hkn.eecs.berkeley.edu>



On Tue, 19 Apr 2005 tpc@csua.berkeley.edu wrote:

> hi all, while recently trying to insert some data into the following
> table:
>
> # stores unique course definitions
> CREATE TABLE adminCourses (
> ID TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
> Code CHAR(6),
> Title VARCHAR(55),
> Units TINYINT UNSIGNED
> ) TYPE = InnoDB;
>
> I got a 1L value when I ran the following:
>
> cursor.execute("INSERT INTO adminCourses(ID, Code, Title, Units) VALUES
> (NULL, 'EAT100', 'Josue', 30);")

Hi Tpc,


Do you know if MySQLdb still continues to use AUTOCOMMIT mode, or has this
been changed in new releases of the module?  According to PEP 249:


    http://www.python.org/peps/pep-0249.html

Database modules that conform to the standard are required to keep from
doing autocommits:

"""
            Commit any pending transaction to the database. Note that
            if the database supports an auto-commit feature, this must
            be initially off. An interface method may be provided to
            turn it back on.
"""

But MySQL didn't have transactions for the longest time, so this never
really worked well until MySQL4 with InnoDB table support.


Now that MySQL is using transactions, it's possible that MySQLdb may have
autocommit off by default now.  In fact, it looks like it, as there's a
snippet of code in the driver now with the following:

######
        self._transactional = (self.server_capabilities &
                               CLIENT.TRANSACTIONS)
        if self._transactional:
            # PEP-249 requires autocommit to be initially off
            self.autocommit(0)
######


Ah, ok, so it does look like MySQL now doesn't autocommit by default.
That's new: I'll have to remember that.

Try doing a conn.commit() at the end of your database programs.



Best of wishes to you!

From albertito_g at hotmail.com  Tue Apr 19 20:57:42 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 19 20:57:46 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <Pine.LNX.4.44.0504191009500.2286-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-F15EFD7B7266053708EFC7E892A0@phx.gbl>

Thanks Danny

I will try to do that and let you know how it went
But one question thou, does it matter the location where I gunzip the 
distutil????????
If so where should I put it???????????????
NOTE: It's just to be sure that I'm understanding right the language 
(ENGLISH) of the link you attached

thanks again

regards

Alberto

>From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
>To: Alberto Troiano <albertito_g@hotmail.com>
>CC: Tutor <tutor@python.org>
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Tue, 19 Apr 2005 10:18:11 -0700 (PDT)
>
>
>
>On Tue, 19 Apr 2005, Alberto Troiano wrote:
>
> > Sorry I have Mysql-python 1.20
> > that's the one I can not install
> > I said MySQLdb because I'm still using it for windows
> > I can't install mysql-python it gives me the error i described
> >
> > With mysql-python does the sintax change???????What should I import if
> > not MySQLdb????????
>
>hi Alberto
>
>Same syntax, same author.  And same version number.  I think you guys are
>talking about the same module.  *grin* I hope we are both talking about
>the MySQL-Python module from SourceForge, here:
>
>http://sourceforge.net/project/showfiles.php?group_id=22307&package_id=15775
>
>
>Alberto, why are you using ./configure?  Are you trying to execute
>Python's configure script?  If so, don't: third-party modules use a
>different method of installation.  See:
>
>     http://docs.python.org/inst/inst.html
>
>
>
>Ideally, all you need to do is untar the source to MySQL-Python, and do
>something like:
>
>######
>[dyoo@shoebox dyoo]$ cd MySQL-python-1.2.0
>[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py build
>######
>
>The step 'python setup.py build' tells Python to try to build the third
>party extension.  If you see problems here, please copy and paste exactly
>what you see.
>
>
>Otherwise, the last step:
>
>######
>[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py install
>######
>
>should finish the job --- you may need to have administrative privileges
>on your machine to do this, as it tries to write files into the same place
>as the Standard Library.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From maxnoel_fr at yahoo.fr  Tue Apr 19 21:01:31 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Tue Apr 19 21:01:43 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F15EFD7B7266053708EFC7E892A0@phx.gbl>
References: <BAY106-F15EFD7B7266053708EFC7E892A0@phx.gbl>
Message-ID: <49227f92d8ed278a2f125d6d210bce03@yahoo.fr>


On Apr 19, 2005, at 19:57, Alberto Troiano wrote:

> Thanks Danny
>
> I will try to do that and let you know how it went
> But one question thou, does it matter the location where I gunzip the 
> distutil????????
> If so where should I put it???????????????
> NOTE: It's just to be sure that I'm understanding right the language 
> (ENGLISH) of the link you attached

	Wherever you want, it doesn't matter. When you run "python setup.py 
install", the module is installed in the Python standard library, so 
once you've done it, you can delete the files.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From albertito_g at hotmail.com  Tue Apr 19 21:07:16 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Tue Apr 19 21:07:20 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <49227f92d8ed278a2f125d6d210bce03@yahoo.fr>
Message-ID: <BAY106-F151BC60BE83A2954F3127D892A0@phx.gbl>

GOTCHA!!!!!

I let you know guys how it went

Bye for now

Alberto

>From: Max Noel <maxnoel_fr@yahoo.fr>
>To: "Alberto Troiano" <albertito_g@hotmail.com>
>CC: tutor@python.org, dyoo@hkn.eecs.berkeley.edu
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Tue, 19 Apr 2005 20:01:31 +0100
>
>
>On Apr 19, 2005, at 19:57, Alberto Troiano wrote:
>
>>Thanks Danny
>>
>>I will try to do that and let you know how it went
>>But one question thou, does it matter the location where I gunzip the 
>>distutil????????
>>If so where should I put it???????????????
>>NOTE: It's just to be sure that I'm understanding right the language 
>>(ENGLISH) of the link you attached
>
>	Wherever you want, it doesn't matter. When you run "python setup.py 
>install", the module is installed in the Python standard library, so once 
>you've done it, you can delete the files.
>
>-- Max
>maxnoel_fr at yahoo dot fr -- ICQ #85274019
>"Look at you hacker... A pathetic creature of meat and bone, panting and 
>sweating as you run through my corridors... How can you challenge a 
>perfect, immortal machine?"
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From alan.gauld at freenet.co.uk  Tue Apr 19 21:34:19 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 19 21:33:59 2005
Subject: [Tutor] Contructor Overloading and Function Tooktips
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
Message-ID: <024601c54516$c9104190$728f8651@xp>

> OK, but that was just your example :-)  Here is some ugly quick code
> which might show you how to meet you needs:
>
> class JohnsMultiInitClass:
>      def __init__(self, first, second):
>          if type(first) == type(second) == str:
>              self.string_init(first, second)
>          if type(first) == type(second) == int:
>              self.int_init(first, second)

> getting an handle on OOP, and dangerous only in Python. But, I
suspect
> that this is not the Python way to do this sort of thing. (Perhaps
> people with C++ experience can weigh in to confirm or deny.)

This is an acceptable way of doing it when needed, but one thing
to note about Python is that it is rarely needed - at least, much
less commonly than in C++/Java. The reason for this is that C++
is statically typed so you are limited in what you can do to the
parameters of a method based on it's type, in Python you can often
use the same method for a wide variety of types because the binding
is done at runtime. So long as the input argument responds to the
messages sent to it, it can be used.

Another way that multiple constructors etc can be simlified (and
this is true in C++ too, but for some reason not used as much) is
via default arguments. So you can do:

def foo(anInt = 1, aFloat = 2.0, aString= '3'): pass

foo()          #--> foo(1,2.0,'3')
foo(42)        #--> foo(42,2.0,'3')
foo(14,5.7)    #--> foo(14,5.7,'3')
foo(7,8.0,'b') #--> foo(7,8.0,'b')

So from the caller's perspective there are 4 possible signatures
but only one function definiton. As I said, you can do this in
C++ too but it's less commonly seen, at least in my experience.

Finally the Python mechanisms for multiple arguments can be used
and in particular the keywords technique can provide for multiple
input values/types.

So between all the various options you can do any of the
things C++/Java does and often with much less code!

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

From tim at johnsons-web.com  Tue Apr 19 22:22:39 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue Apr 19 22:18:19 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <024601c54516$c9104190$728f8651@xp>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
Message-ID: <20050419202239.GC6459@johnsons-web.com>

Hello Pythonmeisters:

Is it possible to dynamically compose a module name
for import?

Pointers to documentation or other discussions would
be sufficient at this time.

thanks
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
From 3dbernard at gmail.com  Tue Apr 19 22:36:08 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue Apr 19 22:36:11 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <20050419202239.GC6459@johnsons-web.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
Message-ID: <61d0e2b405041913363d236cc@mail.gmail.com>

Hi,

The one thing I would try, if I understand what you're after
correctly, would be to run a exec command with the module name.


modulename = 'myModule'
exec 'import ' + modulename

Then you can access the module names as any imported module.


Cheers
Bernard


On 4/19/05, Tim Johnson <tim@johnsons-web.com> wrote:
> Hello Pythonmeisters:
> 
> Is it possible to dynamically compose a module name
> for import?
> 
> Pointers to documentation or other discussions would
> be sufficient at this time.
> 
> thanks
> --
> Tim Johnson <tim@johnsons-web.com>
>       http://www.alaska-internet-solutions.com
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From maxnoel_fr at yahoo.fr  Tue Apr 19 22:38:46 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Tue Apr 19 22:39:21 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <20050419202239.GC6459@johnsons-web.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
Message-ID: <6291fbd4f8c57a81cde14250f6ac9b7a@yahoo.fr>


On Apr 19, 2005, at 21:22, Tim Johnson wrote:

> Hello Pythonmeisters:
>
> Is it possible to dynamically compose a module name
> for import?
>
> Pointers to documentation or other discussions would
> be sufficient at this time.
>
> thanks

	Ah, metaprogramming. I must admit I can't think of a way. Or rather, I  
did think of a few but they don't work:
- module isn't a built-in (yet importing a module and calling type on  
it returns <type 'module'>).
- eval("import os") raises a SyntaxError.



	However, the __import__ built-in function seems promising, although I  
have trouble seeing how it is used. Witness:

 >>> __import__("os")
<module 'os' from  
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/os.pyc'>
 >>> dir()
['__builtins__', '__doc__', '__name__']
 >>>

 >>> __import__("sys").version_info
(2, 3, 0, 'final', 0)


	So calling the function returns the module as an object, but it is not  
imported in the usual sense of the word. But you can use functions from  
it...

	Oh, wait, I get it. It's so obvious I wonder why I didn't see it  
before.

 >>> sys = __import__("sys")
 >>> sys.version_info
(2, 3, 0, 'final', 0)


	There you are. So yes, it can be done, and quite easily at that  
(although not as easily as in Ruby, IIRC, whose metaprogramming  
features truly frightened me last time I had a look at it).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge a  
perfect, immortal machine?"

From python.pan at gmail.com  Tue Apr 19 22:26:58 2005
From: python.pan at gmail.com (py pan)
Date: Tue Apr 19 23:01:51 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <20050419202239.GC6459@johnsons-web.com>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
Message-ID: <5af1b8bc050419132612bbdb06@mail.gmail.com>

__import__:  http://www.python.org/doc/2.4.1/lib/built-in-funcs.html
From count0.djd at gmail.com  Wed Apr 20 00:24:35 2005
From: count0.djd at gmail.com (David Driver)
Date: Wed Apr 20 00:24:38 2005
Subject: [Tutor] How to obfuscate a database password.
Message-ID: <22803ae205041915243d2436d1@mail.gmail.com>

Is there a convention for obfuscating database passwords? I think that
in the end there will be a script that boot-straps to zipped modules
but I don't think that that is secure enough. I was thinking about
asking  the database lists but I think that this is more of a general
question.
-- 

***********************************
See there, that wasn't so bad.
***********************************
From denise.hartley at gmail.com  Wed Apr 20 00:29:42 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 20 00:29:45 2005
Subject: [Tutor] crash - switching between text window and graphics/game
	window (high score)
Message-ID: <8daabe56050419152924c792d6@mail.gmail.com>

Ok. I got in the working code to have a high score list, and it even
saves/loads one now (!!).  The only problem is, clicking back from the
text window to the game window (only after you entered in your name to
go onto the high score list), closes the program. you dont get to say
y/n to another game, it just shuts down. i cant run a debugger on it,
because the error doesnt happen when I F5-run the game from the python
IDLE script, only when i have ran it by doubleclicking on it (which is
how you're supposed to run it. otherwise it doesnt shut down
properly). i really really REALLY want to keep the high score part of
my program, because i worked really hard to get this to work. but i
have to have this program running with NO crashes in like a week (it's
a birthday present, and the birthday is approaching fast!)

Here's the "end of game" code:

            #game over..
            if lives == 0:
### trying addscore

                def add_score():
 #                   high_scores = [(1000,"Denise"), (945,"Denise"),
  #                                 (883,"Denise"),(823,"Grant"),
   #                                (779,"Aaron"), (702,"Pete"),
    #                               (555,"Tom"), (443,"Tom"),
     #                              (442,"Robin"), (4,"Pete")]
                    high_scores = pickle.load(file("scores.pik"))
                    score = total_enemy_hits
                    if score > high_scores[-1][0]:
                        print "Ta da! You got", total_enemy_hits,
"Ranch Delivery Devices!"
                        name = read_string("You made the high score
list! What's your name? ")
                        user_score = (score,name)
                        high_scores.append(user_score)
                        high_scores.sort(reverse=True)
                        del high_scores[-1]
                        pickle.dump(high_scores, file("scores.pik", "w"))
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            prefix = 5*" "
                            print prefix,name,slip_amt,score
                    else:
                        print "Sorry, you only got", total_enemy_hits,
"Ranch Delivery Devices."
                        print "You didn't quite make the high score list!"
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            prefix = 5*" "
                            print prefix,name,slip_amt,score
                        print "Better luck next time!"

 #               pdb.set_trace()
                add_score()

                end.play()
                showGameOver(screen, background_image)                
                pygame.display.flip()
                

                answer = ""
                while not answer in ("y","n"):
                   for event in pygame.event.get():
                      if event.type == KEYDOWN:
                         if event.key == K_n:
                            answer = "n"
                         elif event.key == K_y:
                            answer = "y"
                if answer == "n":
                    running = 0
                else:
                    return 1
    
            #refresh the display
            pygame.event.pump()
            pygame.display.flip()

    #well, nice playing with you...
    screen = pygame.display.set_mode((640, 480))
    return 0


Can anyone tell me why it crashes? you click to the text window when
there's the "congrats, you made the high score list, enter your name"
prompt, enter your name and hit enter, and it displays the high
scores, with your name in it, just as it should. but then when you
click back to the game screen, poof! it all closes.  Of course if you
dont make the high score list, you can click to the text window and
click back to the game window and it operates like it should.

Any suggestions would be appreciated!!  Again, I'd like to have it do
all this score stuff in the game/graphics window, and then it wouldnt
have that crash at all. But I dont know how to do that.

Please help!

Thanks again :)

~Denise
From alan.gauld at freenet.co.uk  Wed Apr 20 00:52:00 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr 20 00:51:32 2005
Subject: [Tutor] Dynamically composing a module name
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com><42654E1D.1030601@po-box.mcgill.ca><024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
Message-ID: <025d01c54532$666d7d20$728f8651@xp>

> Is it possible to dynamically compose a module name
> for import?

Yes, there is a module somewhere that allows you to import a module 
programatically by passing the name as a string. Look for an import 
or module function or module in the docs...

> Pointers to documentation or other discussions would
> be sufficient at this time.

But this begs the question why? Apart from possible environment 
differences, like importing a different module depending on OS
(which can be easier done via an if/else construct anyway) why 
would you want to?

Curious,

Alan G.

From alan.gauld at freenet.co.uk  Wed Apr 20 00:56:57 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr 20 00:56:24 2005
Subject: [Tutor] How to obfuscate a database password.
References: <22803ae205041915243d2436d1@mail.gmail.com>
Message-ID: <026801c54533$171c81c0$728f8651@xp>

> Is there a convention for obfuscating database passwords? 

Depends what you mean. 

Do you mean encryption at the point of use? 
That depends on the database. 

Do you mean in your program?
That usually means unobfuscating it before use and its still 
vulnerable to interception.

Do you mean while stored in a config file or environment setting?
Thats possible either programmatically or via the OS encrypted 
file system...

I'm not sure what exactly you intend to do?

Alan G.
From tim at johnsons-web.com  Wed Apr 20 01:44:42 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed Apr 20 01:40:20 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <025d01c54532$666d7d20$728f8651@xp>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
	<025d01c54532$666d7d20$728f8651@xp>
Message-ID: <20050419234442.GD6459@johnsons-web.com>

* Alan Gauld <alan.gauld@freenet.co.uk> [050419 15:08]:
> > Is it possible to dynamically compose a module name
> > for import?
 
  Hi Alan:
  
> Yes, there is a module somewhere that allows you to import a module 
> programatically by passing the name as a string. Look for an import 
> or module function or module in the docs...
 
  Yes. Since I posted this, I tried the following:
  >>> X = __import__("xml")
  >>> help(X)
  ## seems to work kind of like "import foo as f"
  
> > Pointers to documentation or other discussions would
> > be sufficient at this time.
> 
> But this begs the question why? Apart from possible environment 
> differences, like importing a different module depending on OS
> (which can be easier done via an if/else construct anyway) why 
> would you want to?

  I'm just in the design phase of a large implementation where many
  modules - each having the same function and data member names - would
  be generated outmatically and a calling application would import such
  a module based on the name of the main application.

  This may not prove to be the pythonesque way of doing it, but
  am investigating python's particular features around this subject.

  Here's a little more detail;
  Let's say we have a series of executable scripts called
  form1.py, form2.py, form3.py and each import a function
  called 'setup()' from a common module called (!!) Common.py.

  Inside of the setup() function, a call to the cgi object determines
  the name of the calling application (form1,py ... etc.) and
  then imports another module (automatically generated from another
  process), always having the same members, composing that auto module
  name from the name of the calling application:  form1.py =>
  form1_extra.py......  And if I have to change the algorithm that
  determines the name of the module imported or the names of the
  members of the modules, I could just do it in two places:
  the setup() function and the application generating the auto modules
  (which isn't necessarily written in python).

  but like I said, I'm just thinking about this now, and am open to
  alternatives.

  Thanks Alan
  tim


-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 20 02:29:09 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 20 02:29:15 2005
Subject: [Tutor] How to obfuscate a database password.
In-Reply-To: <026801c54533$171c81c0$728f8651@xp>
Message-ID: <Pine.LNX.4.44.0504191719001.4869-100000@hkn.eecs.berkeley.edu>



> > Is there a convention for obfuscating database passwords?

Hi David,

Most people run passwords through some sort of hashing function.  That is,
databases almost never contain passwords in the clear, but instead store
the hashes of those passwords.

For example, I am almost positive that Amazon does not store its user's
passwords in the clear.  *grin*

Storing clear-text passwords would be terrible from a security point of
view, since some people, despite being warned, use the same password for
everything that they do.  And you can't trust the database provider not to
spill data every once in a while.

So hashing's probably the way to go.  Common hash functions include MD5 or
SHA-1:

    http://www.python.org/doc/lib/module-md5.html
    http://www.python.org/doc/lib/module-sha.html

Pick one.  *grin*


Avoid using a database-specific hash function, but use something standard
like MD5 or SHA-1, unless you really need to do something special.  In
particular, MySQL's documentation recommends against using its own
internal PASSWORD()  function, and recommends the other two hashing
functions, just because they warn that they're free to change the PASSWORD
implementation at any time:

    http://dev.mysql.com/doc/mysql/en/application-password-use.html

I assume the same kind of warning applies to any other database.


Best of wishes!

From maxnoel_fr at yahoo.fr  Wed Apr 20 02:41:19 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 20 02:41:24 2005
Subject: [Tutor] How to obfuscate a database password.
In-Reply-To: <Pine.LNX.4.44.0504191719001.4869-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504191719001.4869-100000@hkn.eecs.berkeley.edu>
Message-ID: <ffa6ed1a281ad48a151375b912a38a6f@yahoo.fr>


On Apr 20, 2005, at 01:29, Danny Yoo wrote:

>
>
>>> Is there a convention for obfuscating database passwords?
>
> Hi David,
>
> Most people run passwords through some sort of hashing function.  That 
> is,
> databases almost never contain passwords in the clear, but instead 
> store
> the hashes of those passwords.
>
> For example, I am almost positive that Amazon does not store its user's
> passwords in the clear.  *grin*

	The problem is, if I understood David's problem correctly, what he 
wants is a way to store a password to a database in his program (or a 
data file, or whatever), so that the program can access it without 
asking the user for a password.
	And as far as I know, there is no reliable way to do that. Since the 
program has to at some point decrypt the password, there are countless 
ways of intercepting it (including but not limited to reading the 
source code and sniffing the connection the program establishes to the 
DB).

> Storing clear-text passwords would be terrible from a security point of
> view, since some people, despite being warned, use the same password 
> for
> everything that they do.

	I think you can safely s/some/most/ on this one :D

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From tim at johnsons-web.com  Wed Apr 20 04:34:39 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed Apr 20 04:30:22 2005
Subject: [Tutor] Dynamically composing a module name
In-Reply-To: <025d01c54532$666d7d20$728f8651@xp>
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com>
	<42654E1D.1030601@po-box.mcgill.ca>
	<024601c54516$c9104190$728f8651@xp>
	<20050419202239.GC6459@johnsons-web.com>
	<025d01c54532$666d7d20$728f8651@xp>
Message-ID: <20050420023439.GG6459@johnsons-web.com>

Appreciate the replies. Also found this link:
http://diveintopython.org/functional_programming/dynamic_import.html
See Example 16.15.

:-) Very pythonesque! Methinks.
thanks
tj

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 20 05:05:06 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 20 05:05:08 2005
Subject: [Tutor] How to obfuscate a database password. (fwd)
Message-ID: <Pine.LNX.4.44.0504192005010.12510-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Tue, 19 Apr 2005 19:47:20 -0500
From: David Driver <count0.djd@gmail.com>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] How to obfuscate a database password.

I am not necessarily talking about passwords for users but about the
password that is used for connecting to the database. In a compiled
language you would have to look pretty hard in a dll to find where the
password had been encoded. As you point out there will be users inside
of the application. Their passwords will be hashed and stored in the
database. That is relatively easy to execute. But the password that
the application uses to connect to the database is going to be stored
somewhere in the code.

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 20 05:36:02 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 20 05:36:05 2005
Subject: [Tutor] How to obfuscate a database password.
In-Reply-To: <Pine.LNX.4.44.0504192005010.12510-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504192006190.12510-100000@hkn.eecs.berkeley.edu>



> I am not necessarily talking about passwords for users but about the
> password that is used for connecting to the database.

Hi David,

Ah, ok, I misunderstood the problem then.  Hmmm... I agree with the others
who have said that this is difficult.  *grin* Eventually, you'll need to
decrypt whatever you're using to talk to the database, and once it's
decrypted, it can be grabbed.

A common approach that I've seen is to separate that connection
username/password strings out into a separate file, out of the source
code.  One can then use the operating system's permissions system to
ensure that only authorized users can see the file.


I'm not sure if this approach will work for you.  Let me try to understand
the situation better: are there multiple clients who will talk to your
database, or is there just one central client to the database?  How much
do you plan to control?



> In a compiled language you would have to look pretty hard in a dll to
> find where the password had been encoded.

You may be underestimating your audience, and you may be overestimating
the obfuscation that compilation does: it's actually very easy to look at
strings that are encoded in binaries.

For example:

######
mumak:~ dyoo$ cat hello.c
#include <stdio.h>
int main(void) {
  printf("hello world");
}
mumak:~ dyoo$
mumak:~ dyoo$
mumak:~ dyoo$ gcc hello.c
mumak:~ dyoo$
mumak:~ dyoo$
mumak:~ dyoo$ strings a.out
__dyld_mod_term_funcs
__dyld_make_delayed_module_initializer_calls
The kernel support for the dynamic linker is not present to run this
program.
hello world
######

This is a quick and dirty example, but I hope it's clear that you can't
treat compilation as some magic scrambler.  Most compiled languages don't
do funky things to their string literals, and it's really easy to pull
them right out again.  There are dedicated tools to do code obfuscation,
but I don't believe they'd deter a determined attack.


Best of wishes!

From project5 at redrival.net  Wed Apr 20 08:06:02 2005
From: project5 at redrival.net (Andrei)
Date: Wed Apr 20 08:11:58 2005
Subject: [Tutor] Re: How to obfuscate a database password. (fwd)
References: <Pine.LNX.4.44.0504192005010.12510-100000@hkn.eecs.berkeley.edu>
Message-ID: <loom.20050420T075224-831@post.gmane.org>

> From: David Driver <count0.djd <at> gmail.com>
> I am not necessarily talking about passwords for users but about the
> password that is used for connecting to the database. In a compiled
> language you would have to look pretty hard in a dll to find where the
> password had been encoded. As you point out there will be users inside
> of the application. Their passwords will be hashed and stored in the
> database. That is relatively easy to execute. But the password that
> the application uses to connect to the database is going to be stored
> somewhere in the code.

Storing passwords in the exe/dll/pyc doesn't sound like a particularly secure
option whichever way you look at it. If you don't value the password of the DB
very much, you can always obsfucate it (zipping or converting to a list of
integers comes to mind, or you can be creative and devise something else -
though more obsfucation != more security). The effect this will have in stopping
a determined person will be pretty much zero, but at least it's not out there in
the open and a simple text search won't cause it to just show up.

Yours,

Andrei

From cyresse at gmail.com  Wed Apr 20 10:59:52 2005
From: cyresse at gmail.com (Liam Clarke)
Date: Wed Apr 20 10:59:56 2005
Subject: [Tutor] inexplicable MySQLdb behavior, INSERT data doesn't appear
In-Reply-To: <Pine.LNX.4.44.0504191130290.9580-100000@hkn.eecs.berkeley.edu>
References: <20050419103240.T78720-100000@localhost.name>
	<Pine.LNX.4.44.0504191130290.9580-100000@hkn.eecs.berkeley.edu>
Message-ID: <f2ff2d050420015911dba43@mail.gmail.com>

Seems a lot of wrappers are moving away from autocommit for performance 
reasons. 
pysqlite has removed it as of the alphra 2.0

On 4/20/05, Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
> 
> On Tue, 19 Apr 2005 tpc@csua.berkeley.edu wrote:
> 
> > hi all, while recently trying to insert some data into the following
> > table:
> >
> > # stores unique course definitions
> > CREATE TABLE adminCourses (
> > ID TINYINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
> > Code CHAR(6),
> > Title VARCHAR(55),
> > Units TINYINT UNSIGNED
> > ) TYPE = InnoDB;
> >
> > I got a 1L value when I ran the following:
> >
> > cursor.execute("INSERT INTO adminCourses(ID, Code, Title, Units) VALUES
> > (NULL, 'EAT100', 'Josue', 30);")
> 
> Hi Tpc,
> 
> Do you know if MySQLdb still continues to use AUTOCOMMIT mode, or has this
> been changed in new releases of the module? According to PEP 249:
> 
> http://www.python.org/peps/pep-0249.html
> 
> Database modules that conform to the standard are required to keep from
> doing autocommits:
> 
> """
> Commit any pending transaction to the database. Note that
> if the database supports an auto-commit feature, this must
> be initially off. An interface method may be provided to
> turn it back on.
> """
> 
> But MySQL didn't have transactions for the longest time, so this never
> really worked well until MySQL4 with InnoDB table support.
> 
> Now that MySQL is using transactions, it's possible that MySQLdb may have
> autocommit off by default now. In fact, it looks like it, as there's a
> snippet of code in the driver now with the following:
> 
> ######
> self._transactional = (self.server_capabilities &
> CLIENT.TRANSACTIONS)
> if self._transactional:
> # PEP-249 requires autocommit to be initially off
> self.autocommit(0)
> ######
> 
> Ah, ok, so it does look like MySQL now doesn't autocommit by default.
> That's new: I'll have to remember that.
> 
> Try doing a conn.commit() at the end of your database programs.
> 
> Best of wishes to you!
> 
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



-- 
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050420/6ca807a2/attachment.htm
From count0.djd at gmail.com  Wed Apr 20 15:58:55 2005
From: count0.djd at gmail.com (David Driver)
Date: Wed Apr 20 15:58:59 2005
Subject: [Tutor] How to obfuscate a database password.
In-Reply-To: <Pine.LNX.4.44.0504192006190.12510-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504192005010.12510-100000@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.44.0504192006190.12510-100000@hkn.eecs.berkeley.edu>
Message-ID: <22803ae205042006585cd28381@mail.gmail.com>

So I could do the folowing:
    Create a DB logon for each user that has permissions to just about
everything.
    Have them log on each time.
    This would require an application that they could manage their passwords.
    I already needed an application for managing permissions within
the application so I could just add a reset password to it, and adapt
it to using the database users for validation and keep my own tables
to track where the users can go in the app.


I guess that I was just thinking along the wrong lines for the design
of the login.
From cpu.crazy at gmail.com  Wed Apr 20 01:04:44 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed Apr 20 16:17:47 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
In-Reply-To: <01b101c54468$c6db1020$728f8651@xp>
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
	<01b101c54468$c6db1020$728f8651@xp>
Message-ID: <6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>


>Its not hard, but its not easy either to do it right.
>And given the profusion of installers already available
>ranging from free to expensive there really is little
>point in writing something that probably won't be as
>good as the already available alternative.
>
>Remember user expectation, if you write an installer you
>should also provide an uninstaller, and link it to the
>Control Panel Add/Remove applet. Its no coincidence that
>python uses a commercial (Wise) installer for the
>Windows distro...
>
> > This isn't a waste of your or my time is it?
>
>No, its a valid question even if the answer is that its probably a bad
>idea!
>
>Alan G.


My point is for practice and knowledge. Sure, I have Setup 2 Go (the paid 
version) and Install Creator (not paid)
Then again, how many free installers are there for linux?

I must get a book on Windows before I make a nice installer.

Thanks,
         Joe



From maxnoel_fr at yahoo.fr  Wed Apr 20 17:17:53 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 20 17:18:02 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
In-Reply-To: <6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
	<01b101c54468$c6db1020$728f8651@xp>
	<6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>
Message-ID: <13407195c8377d569c94837c179efbda@yahoo.fr>


On Apr 20, 2005, at 00:04, Joseph Quigley wrote:

> My point is for practice and knowledge. Sure, I have Setup 2 Go (the 
> paid version) and Install Creator (not paid)
> Then again, how many free installers are there for linux?

	emerge and apt-get come to mind. rpm is inferior (no dependency 
resolution) but still does a good job, and I hear autopackage isn't 
bad.
	Also, there was a project at some point that aimed at making Linux 
applications into self-contained "executable folders" (like .app 
bundles in Mac OS X). I don't remember the name, but I recall Rox-filer 
supports it.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From albertito_g at hotmail.com  Wed Apr 20 17:52:54 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 20 17:52:57 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F151BC60BE83A2954F3127D892A0@phx.gbl>
Message-ID: <BAY106-F16E2E74861D5CF583D576D892B0@phx.gbl>

Hey

Didn't work

I try the python2.3 setup.py build

I couldn't print the exact error because it's a lot of pages that says 
mostly the same

the final error says

error: mysql ended exit with status 1

I run the other command python2.3 setup.py install and the same error

What can I do
I'm desperate

Just in case I'm using MySQL 3.23 (Default MySQL Red Hat 9.0, but I don't 
see how that can affect the module)

Thanks in advanced

Alberto

>From: "Alberto Troiano" <albertito_g@hotmail.com>
>To: maxnoel_fr@yahoo.fr
>CC: tutor@python.org
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Tue, 19 Apr 2005 19:07:16 +0000
>
>GOTCHA!!!!!
>
>I let you know guys how it went
>
>Bye for now
>
>Alberto
>
>>From: Max Noel <maxnoel_fr@yahoo.fr>
>>To: "Alberto Troiano" <albertito_g@hotmail.com>
>>CC: tutor@python.org, dyoo@hkn.eecs.berkeley.edu
>>Subject: Re: [Tutor] TKinter and things over Linux
>>Date: Tue, 19 Apr 2005 20:01:31 +0100
>>
>>
>>On Apr 19, 2005, at 19:57, Alberto Troiano wrote:
>>
>>>Thanks Danny
>>>
>>>I will try to do that and let you know how it went
>>>But one question thou, does it matter the location where I gunzip the 
>>>distutil????????
>>>If so where should I put it???????????????
>>>NOTE: It's just to be sure that I'm understanding right the language 
>>>(ENGLISH) of the link you attached
>>
>>	Wherever you want, it doesn't matter. When you run "python setup.py 
>>install", the module is installed in the Python standard library, so once 
>>you've done it, you can delete the files.
>>
>>-- Max
>>maxnoel_fr at yahoo dot fr -- ICQ #85274019
>>"Look at you hacker... A pathetic creature of meat and bone, panting and 
>>sweating as you run through my corridors... How can you challenge a 
>>perfect, immortal machine?"
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>
>
>Gaucho
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From maxnoel_fr at yahoo.fr  Wed Apr 20 18:15:49 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 20 18:15:56 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F16E2E74861D5CF583D576D892B0@phx.gbl>
References: <BAY106-F16E2E74861D5CF583D576D892B0@phx.gbl>
Message-ID: <cddb064da1b0729560edf653226eafd6@yahoo.fr>


On Apr 20, 2005, at 16:52, Alberto Troiano wrote:

> Hey
>
> Didn't work
>
> I try the python2.3 setup.py build
>
> I couldn't print the exact error because it's a lot of pages that says 
> mostly the same
>
> the final error says
>
> error: mysql ended exit with status 1
>
> I run the other command python2.3 setup.py install and the same error
>
> What can I do
> I'm desperate
>
> Just in case I'm using MySQL 3.23 (Default MySQL Red Hat 9.0, but I 
> don't see how that can affect the module)

	Did you install the "software development" packages with your distro? 
If you didn't, install them.
	In order to install modules that aren't entirely written in Python 
(such as this one, I wager), you need a working C compiler and standard 
library.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From jsmith at medplus.com  Wed Apr 20 20:39:49 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Wed Apr 20 20:40:01 2005
Subject: [Tutor] A simple Perl to Python regex xlation question
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C033946AB@medexch1.medplus.com>

What's the quickest (and most Pythonic) way to do the following Perlism:
	$str = s/d+/d/;

(i.e. collapsing multiple occurrences of the letter 'd' to just one)

Thanks,
Jeff
From albertito_g at hotmail.com  Wed Apr 20 21:02:57 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 20 21:03:02 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <cddb064da1b0729560edf653226eafd6@yahoo.fr>
Message-ID: <BAY106-F3E16BBF83AA69C43BB079892B0@phx.gbl>

Could it be a problem wth gcc library????????????
and if so, gcc library is the C compiler or am I wrong in that?????????

The exact error is the following:

error: compiled 'gcc' failed with exit status 1

I'm reinstalling Red Hat 9.0 with the EVERYTHING option so there can be no 
problem

Thanks again

Alberto

>From: Max Noel <maxnoel_fr@yahoo.fr>
>To: "Alberto Troiano" <albertito_g@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Wed, 20 Apr 2005 17:15:49 +0100
>
>
>On Apr 20, 2005, at 16:52, Alberto Troiano wrote:
>
>>Hey
>>
>>Didn't work
>>
>>I try the python2.3 setup.py build
>>
>>I couldn't print the exact error because it's a lot of pages that says 
>>mostly the same
>>
>>the final error says
>>
>>error: mysql ended exit with status 1
>>
>>I run the other command python2.3 setup.py install and the same error
>>
>>What can I do
>>I'm desperate
>>
>>Just in case I'm using MySQL 3.23 (Default MySQL Red Hat 9.0, but I don't 
>>see how that can affect the module)
>
>	Did you install the "software development" packages with your distro? If 
>you didn't, install them.
>	In order to install modules that aren't entirely written in Python (such 
>as this one, I wager), you need a working C compiler and standard library.
>
>-- Max
>maxnoel_fr at yahoo dot fr -- ICQ #85274019
>"Look at you hacker... A pathetic creature of meat and bone, panting and 
>sweating as you run through my corridors... How can you challenge a 
>perfect, immortal machine?"
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From kent37 at tds.net  Wed Apr 20 21:07:28 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 20 21:07:31 2005
Subject: [Tutor] A simple Perl to Python regex xlation question
In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C033946AB@medexch1.medplus.com>
References: <C4C644CF4ADA9448904C3E8BACC4B97C033946AB@medexch1.medplus.com>
Message-ID: <4266A870.3060606@tds.net>

Smith, Jeff wrote:
> What's the quickest (and most Pythonic) way to do the following Perlism:
> 	$str = s/d+/d/;
> 
> (i.e. collapsing multiple occurrences of the letter 'd' to just one)

import re
s = re.sub('d+', 'd', s, 1)

if I understand the perl...this replaces just one occurance of d+. If you want to replace all 
occurances then use
s = re.sub('d+', 'd', s)

  >>> import re
  >>> s = 'dddaddddabcdeddd'
  >>> re.sub('d+', 'd', s, 1)
'daddddabcdeddd'
  >>> re.sub('d+', 'd', s)
'dadabcded'

Kent

From dyoo at hkn.eecs.berkeley.edu  Wed Apr 20 22:33:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 20 22:33:29 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F3E16BBF83AA69C43BB079892B0@phx.gbl>
Message-ID: <Pine.LNX.4.44.0504201314480.26907-100000@hkn.eecs.berkeley.edu>



> >>I couldn't print the exact error because it's a lot of pages that says
> >>mostly the same

Hi Alberto,

No, that's precisely the kind of wrong kind of attitude toward error
messages that's making this debugging much harder than it should be.


You may think that those error messages are mostly the same, but we REALLY
wanted to see that for ourselves.

Please don't interpret error messages for us: please let us make that
judgement for ourselves.  Again, I have to stress that we really like
seeing good error messages.  This may sound weird to you, but the error
message that comes out is usually much more descriptive than you might
realize.


> >>the final error says
> >>
> >>error: mysql ended exit with status 1

Right, but now we can't tell if it was a problem during compilation, or
linking, or any other kind of possibility.


In your next email, you mentioned:

> The exact error is the following:
>
> Error: compiled 'gcc' failed with exit status 1

which is equally uninformative.


All errors will eventually end up with saying something like "something
bad happened".  But what we need is "first cause": at what point do things
start to go horribly wrong?  And that's what the error log tells us.


If you had shown us the whole transcript of the error log, we'd have a
much better chance to give you exact answers on, at what stage, the
problem starts to emerge.  With what you're giving us now, we have no
clue.


If the error log is really that long, then zip it up, and put it as an
attachment.  But don't just omit it altogether.


Please also read:

    http://www.catb.org/~esr/faqs/smart-questions.html


Good luck to you.

From albertito_g at hotmail.com  Wed Apr 20 23:07:20 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 20 23:07:26 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe56050419152924c792d6@mail.gmail.com>
Message-ID: <BAY106-F25C49F1E45A2170291859D892B0@phx.gbl>

Hey

I'm curious

What extension are you using on your game???????????
is it .py???????????????

And what OS are you running the game???????????????

Another thing. I made a space ship game to learn Python. Is there a 
possibility that we exchange the games so we can know differents points of 
view????????

I'll wait your reply

Regards

Alberto


>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Python tutor <tutor@python.org>
>Subject: [Tutor] crash - switching between text window and 
>graphics/gamewindow (high score)
>Date: Tue, 19 Apr 2005 15:29:42 -0700
>
>Ok. I got in the working code to have a high score list, and it even
>saves/loads one now (!!).  The only problem is, clicking back from the
>text window to the game window (only after you entered in your name to
>go onto the high score list), closes the program. you dont get to say
>y/n to another game, it just shuts down. i cant run a debugger on it,
>because the error doesnt happen when I F5-run the game from the python
>IDLE script, only when i have ran it by doubleclicking on it (which is
>how you're supposed to run it. otherwise it doesnt shut down
>properly). i really really REALLY want to keep the high score part of
>my program, because i worked really hard to get this to work. but i
>have to have this program running with NO crashes in like a week (it's
>a birthday present, and the birthday is approaching fast!)
>
>Here's the "end of game" code:
>
>             #game over..
>             if lives == 0:
>### trying addscore
>
>                 def add_score():
>  #                   high_scores = [(1000,"Denise"), (945,"Denise"),
>   #                                 (883,"Denise"),(823,"Grant"),
>    #                                (779,"Aaron"), (702,"Pete"),
>     #                               (555,"Tom"), (443,"Tom"),
>      #                              (442,"Robin"), (4,"Pete")]
>                     high_scores = pickle.load(file("scores.pik"))
>                     score = total_enemy_hits
>                     if score > high_scores[-1][0]:
>                         print "Ta da! You got", total_enemy_hits,
>"Ranch Delivery Devices!"
>                         name = read_string("You made the high score
>list! What's your name? ")
>                         user_score = (score,name)
>                         high_scores.append(user_score)
>                         high_scores.sort(reverse=True)
>                         del high_scores[-1]
>                         pickle.dump(high_scores, file("scores.pik", "w"))
>                         for score, name in high_scores:
>                             slip = 30 - len(name)
>                             slip_amt = slip*" "
>                             prefix = 5*" "
>                             print prefix,name,slip_amt,score
>                     else:
>                         print "Sorry, you only got", total_enemy_hits,
>"Ranch Delivery Devices."
>                         print "You didn't quite make the high score list!"
>                         for score, name in high_scores:
>                             slip = 30 - len(name)
>                             slip_amt = slip*" "
>                             prefix = 5*" "
>                             print prefix,name,slip_amt,score
>                         print "Better luck next time!"
>
>  #               pdb.set_trace()
>                 add_score()
>
>                 end.play()
>                 showGameOver(screen, background_image)
>                 pygame.display.flip()
>
>
>                 answer = ""
>                 while not answer in ("y","n"):
>                    for event in pygame.event.get():
>                       if event.type == KEYDOWN:
>                          if event.key == K_n:
>                             answer = "n"
>                          elif event.key == K_y:
>                             answer = "y"
>                 if answer == "n":
>                     running = 0
>                 else:
>                     return 1
>
>             #refresh the display
>             pygame.event.pump()
>             pygame.display.flip()
>
>     #well, nice playing with you...
>     screen = pygame.display.set_mode((640, 480))
>     return 0
>
>
>Can anyone tell me why it crashes? you click to the text window when
>there's the "congrats, you made the high score list, enter your name"
>prompt, enter your name and hit enter, and it displays the high
>scores, with your name in it, just as it should. but then when you
>click back to the game screen, poof! it all closes.  Of course if you
>dont make the high score list, you can click to the text window and
>click back to the game window and it operates like it should.
>
>Any suggestions would be appreciated!!  Again, I'd like to have it do
>all this score stuff in the game/graphics window, and then it wouldnt
>have that crash at all. But I dont know how to do that.
>
>Please help!
>
>Thanks again :)
>
>~Denise
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From albertito_g at hotmail.com  Wed Apr 20 23:12:49 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 20 23:12:53 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <Pine.LNX.4.44.0504201314480.26907-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-F6D5AA2A9E26528B608C32892B0@phx.gbl>

You're so right and I apologize for my mistake

Do you or anybody knows where the error.log for this kind o things is?????

or how can I capture the output in a file???????????Cause is so damn long 
that I barely see the 10% of all the things its print out

I'll look up for the log and send it to you

Again, sorry for my ignorance and lack of info

Regards

Alberto

>From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
>To: Alberto Troiano <albertito_g@hotmail.com>
>CC: Tutor <tutor@python.org>
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Wed, 20 Apr 2005 13:33:15 -0700 (PDT)
>
>
>
> > >>I couldn't print the exact error because it's a lot of pages that says
> > >>mostly the same
>
>Hi Alberto,
>
>No, that's precisely the kind of wrong kind of attitude toward error
>messages that's making this debugging much harder than it should be.
>
>
>You may think that those error messages are mostly the same, but we REALLY
>wanted to see that for ourselves.
>
>Please don't interpret error messages for us: please let us make that
>judgement for ourselves.  Again, I have to stress that we really like
>seeing good error messages.  This may sound weird to you, but the error
>message that comes out is usually much more descriptive than you might
>realize.
>
>
> > >>the final error says
> > >>
> > >>error: mysql ended exit with status 1
>
>Right, but now we can't tell if it was a problem during compilation, or
>linking, or any other kind of possibility.
>
>
>In your next email, you mentioned:
>
> > The exact error is the following:
> >
> > Error: compiled 'gcc' failed with exit status 1
>
>which is equally uninformative.
>
>
>All errors will eventually end up with saying something like "something
>bad happened".  But what we need is "first cause": at what point do things
>start to go horribly wrong?  And that's what the error log tells us.
>
>
>If you had shown us the whole transcript of the error log, we'd have a
>much better chance to give you exact answers on, at what stage, the
>problem starts to emerge.  With what you're giving us now, we have no
>clue.
>
>
>If the error log is really that long, then zip it up, and put it as an
>attachment.  But don't just omit it altogether.
>
>
>Please also read:
>
>     http://www.catb.org/~esr/faqs/smart-questions.html
>
>
>Good luck to you.
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From denise.hartley at gmail.com  Wed Apr 20 23:15:13 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 20 23:15:15 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <BAY106-F25C49F1E45A2170291859D892B0@phx.gbl>
References: <8daabe56050419152924c792d6@mail.gmail.com>
	<BAY106-F25C49F1E45A2170291859D892B0@phx.gbl>
Message-ID: <8daabe560504201415684bc5e1@mail.gmail.com>

The play file does end in ".py".  I am running it on Windows.  You can
double-click the play file, and run it straight that way, which is
when the crash occurs.  If you right click the file, go to "edit in
IDLE", and hit F5 to run it, the crash does NOT happen. I'm not sure
why (but this is also why my debugging program won't tell me what's
wrong).

In fact, I wish the debugger *would* give me something, because then
I'd have a specific error, which would make researching the program on
google or in forum archives much easier! At the moment, I'm getting
nothing (or too much information about unrelated problems).

Thanks for any suggestions!

---------- Forwarded message ----------
From: Alberto Troiano <albertito_g@hotmail.com>
Date: Apr 20, 2005 2:07 PM
Subject: RE: [Tutor] crash - switching between text window and
graphics/gamewindow (high score)
To: denise.hartley@gmail.com
Cc: tutor@python.org


Hey

I'm curious

What extension are you using on your game???????????
is it .py???????????????

And what OS are you running the game???????????????

Another thing. I made a space ship game to learn Python. Is there a
possibility that we exchange the games so we can know differents points of
view????????

I'll wait your reply

Regards

Alberto

>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Python tutor <tutor@python.org>
>Subject: [Tutor] crash - switching between text window and
>graphics/gamewindow (high score)
>Date: Tue, 19 Apr 2005 15:29:42 -0700
>
>Ok. I got in the working code to have a high score list, and it even
>saves/loads one now (!!).  The only problem is, clicking back from the
>text window to the game window (only after you entered in your name to
>go onto the high score list), closes the program. you dont get to say
>y/n to another game, it just shuts down. i cant run a debugger on it,
>because the error doesnt happen when I F5-run the game from the python
>IDLE script, only when i have ran it by doubleclicking on it (which is
>how you're supposed to run it. otherwise it doesnt shut down
>properly). i really really REALLY want to keep the high score part of
>my program, because i worked really hard to get this to work. but i
>have to have this program running with NO crashes in like a week (it's
>a birthday present, and the birthday is approaching fast!)
>
>Here's the "end of game" code:
>
>             #game over..
>             if lives == 0:
>### trying addscore
>
>                 def add_score():
>  #                   high_scores = [(1000,"Denise"), (945,"Denise"),
>   #                                 (883,"Denise"),(823,"Grant"),
>    #                                (779,"Aaron"), (702,"Pete"),
>     #                               (555,"Tom"), (443,"Tom"),
>      #                              (442,"Robin"), (4,"Pete")]
>                     high_scores = pickle.load(file("scores.pik"))
>                     score = total_enemy_hits
>                     if score > high_scores[-1][0]:
>                         print "Ta da! You got", total_enemy_hits,
>"Ranch Delivery Devices!"
>                         name = read_string("You made the high score
>list! What's your name? ")
>                         user_score = (score,name)
>                         high_scores.append(user_score)
>                         high_scores.sort(reverse=True)
>                         del high_scores[-1]
>                         pickle.dump(high_scores, file("scores.pik", "w"))
>                         for score, name in high_scores:
>                             slip = 30 - len(name)
>                             slip_amt = slip*" "
>                             prefix = 5*" "
>                             print prefix,name,slip_amt,score
>                     else:
>                         print "Sorry, you only got", total_enemy_hits,
>"Ranch Delivery Devices."
>                         print "You didn't quite make the high score list!"
>                         for score, name in high_scores:
>                             slip = 30 - len(name)
>                             slip_amt = slip*" "
>                             prefix = 5*" "
>                             print prefix,name,slip_amt,score
>                         print "Better luck next time!"
>
>  #               pdb.set_trace()
>                 add_score()
>
>                 end.play()
>                 showGameOver(screen, background_image)
>                 pygame.display.flip()
>
>
>                 answer = ""
>                 while not answer in ("y","n"):
>                    for event in pygame.event.get():
>                       if event.type == KEYDOWN:
>                          if event.key == K_n:
>                             answer = "n"
>                          elif event.key == K_y:
>                             answer = "y"
>                 if answer == "n":
>                     running = 0
>                 else:
>                     return 1
>
>             #refresh the display
>             pygame.event.pump()
>             pygame.display.flip()
>
>     #well, nice playing with you...
>     screen = pygame.display.set_mode((640, 480))
>     return 0
>
>
>Can anyone tell me why it crashes? you click to the text window when
>there's the "congrats, you made the high score list, enter your name"
>prompt, enter your name and hit enter, and it displays the high
>scores, with your name in it, just as it should. but then when you
>click back to the game screen, poof! it all closes.  Of course if you
>dont make the high score list, you can click to the text window and
>click back to the game window and it operates like it should.
>
>Any suggestions would be appreciated!!  Again, I'd like to have it do
>all this score stuff in the game/graphics window, and then it wouldnt
>have that crash at all. But I dont know how to do that.
>
>Please help!
>
>Thanks again :)
>
>~Denise
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

Gaucho
From albertito_g at hotmail.com  Wed Apr 20 23:20:12 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 20 23:20:16 2005
Subject: [Tutor] crash - switching between text window
	andgraphics/gamewindow (high score)
In-Reply-To: <8daabe560504201415684bc5e1@mail.gmail.com>
Message-ID: <BAY106-F12203DB1678F285555C91C892B0@phx.gbl>

Hey Denise

That was fast

Try changing the extension to .pyw and tell me if this fix it

By the way you didn't say nothing about the game :D

Regards

Alberto
>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Python tutor <tutor@python.org>
>Subject: [Tutor] crash - switching between text window 
>andgraphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 14:15:13 -0700
>
>The play file does end in ".py".  I am running it on Windows.  You can
>double-click the play file, and run it straight that way, which is
>when the crash occurs.  If you right click the file, go to "edit in
>IDLE", and hit F5 to run it, the crash does NOT happen. I'm not sure
>why (but this is also why my debugging program won't tell me what's
>wrong).
>
>In fact, I wish the debugger *would* give me something, because then
>I'd have a specific error, which would make researching the program on
>google or in forum archives much easier! At the moment, I'm getting
>nothing (or too much information about unrelated problems).
>
>Thanks for any suggestions!
>
>---------- Forwarded message ----------
>From: Alberto Troiano <albertito_g@hotmail.com>
>Date: Apr 20, 2005 2:07 PM
>Subject: RE: [Tutor] crash - switching between text window and
>graphics/gamewindow (high score)
>To: denise.hartley@gmail.com
>Cc: tutor@python.org
>
>
>Hey
>
>I'm curious
>
>What extension are you using on your game???????????
>is it .py???????????????
>
>And what OS are you running the game???????????????
>
>Another thing. I made a space ship game to learn Python. Is there a
>possibility that we exchange the games so we can know differents points of
>view????????
>
>I'll wait your reply
>
>Regards
>
>Alberto
>
> >From: "D. Hartley" <denise.hartley@gmail.com>
> >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> >To: Python tutor <tutor@python.org>
> >Subject: [Tutor] crash - switching between text window and
> >graphics/gamewindow (high score)
> >Date: Tue, 19 Apr 2005 15:29:42 -0700
> >
> >Ok. I got in the working code to have a high score list, and it even
> >saves/loads one now (!!).  The only problem is, clicking back from the
> >text window to the game window (only after you entered in your name to
> >go onto the high score list), closes the program. you dont get to say
> >y/n to another game, it just shuts down. i cant run a debugger on it,
> >because the error doesnt happen when I F5-run the game from the python
> >IDLE script, only when i have ran it by doubleclicking on it (which is
> >how you're supposed to run it. otherwise it doesnt shut down
> >properly). i really really REALLY want to keep the high score part of
> >my program, because i worked really hard to get this to work. but i
> >have to have this program running with NO crashes in like a week (it's
> >a birthday present, and the birthday is approaching fast!)
> >
> >Here's the "end of game" code:
> >
> >             #game over..
> >             if lives == 0:
> >### trying addscore
> >
> >                 def add_score():
> >  #                   high_scores = [(1000,"Denise"), (945,"Denise"),
> >   #                                 (883,"Denise"),(823,"Grant"),
> >    #                                (779,"Aaron"), (702,"Pete"),
> >     #                               (555,"Tom"), (443,"Tom"),
> >      #                              (442,"Robin"), (4,"Pete")]
> >                     high_scores = pickle.load(file("scores.pik"))
> >                     score = total_enemy_hits
> >                     if score > high_scores[-1][0]:
> >                         print "Ta da! You got", total_enemy_hits,
> >"Ranch Delivery Devices!"
> >                         name = read_string("You made the high score
> >list! What's your name? ")
> >                         user_score = (score,name)
> >                         high_scores.append(user_score)
> >                         high_scores.sort(reverse=True)
> >                         del high_scores[-1]
> >                         pickle.dump(high_scores, file("scores.pik", 
>"w"))
> >                         for score, name in high_scores:
> >                             slip = 30 - len(name)
> >                             slip_amt = slip*" "
> >                             prefix = 5*" "
> >                             print prefix,name,slip_amt,score
> >                     else:
> >                         print "Sorry, you only got", total_enemy_hits,
> >"Ranch Delivery Devices."
> >                         print "You didn't quite make the high score 
>list!"
> >                         for score, name in high_scores:
> >                             slip = 30 - len(name)
> >                             slip_amt = slip*" "
> >                             prefix = 5*" "
> >                             print prefix,name,slip_amt,score
> >                         print "Better luck next time!"
> >
> >  #               pdb.set_trace()
> >                 add_score()
> >
> >                 end.play()
> >                 showGameOver(screen, background_image)
> >                 pygame.display.flip()
> >
> >
> >                 answer = ""
> >                 while not answer in ("y","n"):
> >                    for event in pygame.event.get():
> >                       if event.type == KEYDOWN:
> >                          if event.key == K_n:
> >                             answer = "n"
> >                          elif event.key == K_y:
> >                             answer = "y"
> >                 if answer == "n":
> >                     running = 0
> >                 else:
> >                     return 1
> >
> >             #refresh the display
> >             pygame.event.pump()
> >             pygame.display.flip()
> >
> >     #well, nice playing with you...
> >     screen = pygame.display.set_mode((640, 480))
> >     return 0
> >
> >
> >Can anyone tell me why it crashes? you click to the text window when
> >there's the "congrats, you made the high score list, enter your name"
> >prompt, enter your name and hit enter, and it displays the high
> >scores, with your name in it, just as it should. but then when you
> >click back to the game screen, poof! it all closes.  Of course if you
> >dont make the high score list, you can click to the text window and
> >click back to the game window and it operates like it should.
> >
> >Any suggestions would be appreciated!!  Again, I'd like to have it do
> >all this score stuff in the game/graphics window, and then it wouldnt
> >have that crash at all. But I dont know how to do that.
> >
> >Please help!
> >
> >Thanks again :)
> >
> >~Denise
> >_______________________________________________
> >Tutor maillist  -  Tutor@python.org
> >http://mail.python.org/mailman/listinfo/tutor
>
>Gaucho
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From denise.hartley at gmail.com  Wed Apr 20 23:25:32 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 20 23:25:37 2005
Subject: Fwd: [Tutor] crash - switching between text window
	andgraphics/gamewindow (high score)
In-Reply-To: <BAY106-F12203DB1678F285555C91C892B0@phx.gbl>
References: <8daabe560504201415684bc5e1@mail.gmail.com>
	<BAY106-F12203DB1678F285555C91C892B0@phx.gbl>
Message-ID: <8daabe5605042014254fe43c1d@mail.gmail.com>

Thanks for the suggestion.  The ".pyw" extension runs the game without
a text window at all, which actually is kind of nice.  However, there
were two problems:

a). the program still crashed out when i scored a score that would
have put me on the high score list

b). i cant see the high score list at all with this extension, since
there's no text window

Hope this is useful info?  Please let me know if I can test other
things out or provide more info that would make finding a fix easier!

Thanks!

---------- Forwarded message ----------
From: Alberto Troiano <albertito_g@hotmail.com>
Date: Apr 20, 2005 2:20 PM
Subject: RE: [Tutor] crash - switching between text window
andgraphics/gamewindow (high score)
To: denise.hartley@gmail.com
Cc: tutor@python.org


Hey Denise

That was fast

Try changing the extension to .pyw and tell me if this fix it

By the way you didn't say nothing about the game :D

Regards

Alberto
>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Python tutor <tutor@python.org>
>Subject: [Tutor] crash - switching between text window
>andgraphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 14:15:13 -0700
>
>The play file does end in ".py".  I am running it on Windows.  You can
>double-click the play file, and run it straight that way, which is
>when the crash occurs.  If you right click the file, go to "edit in
>IDLE", and hit F5 to run it, the crash does NOT happen. I'm not sure
>why (but this is also why my debugging program won't tell me what's
>wrong).
>
>In fact, I wish the debugger *would* give me something, because then
>I'd have a specific error, which would make researching the program on
>google or in forum archives much easier! At the moment, I'm getting
>nothing (or too much information about unrelated problems).
>
>Thanks for any suggestions!
>
>---------- Forwarded message ----------
>From: Alberto Troiano <albertito_g@hotmail.com>
>Date: Apr 20, 2005 2:07 PM
>Subject: RE: [Tutor] crash - switching between text window and
>graphics/gamewindow (high score)
>To: denise.hartley@gmail.com
>Cc: tutor@python.org
>
>
>Hey
>
>I'm curious
>
>What extension are you using on your game???????????
>is it .py???????????????
>
>And what OS are you running the game???????????????
>
>Another thing. I made a space ship game to learn Python. Is there a
>possibility that we exchange the games so we can know differents points of
>view????????
>
>I'll wait your reply
>
>Regards
>
>Alberto
>
> >From: "D. Hartley" <denise.hartley@gmail.com>
> >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> >To: Python tutor <tutor@python.org>
> >Subject: [Tutor] crash - switching between text window and
> >graphics/gamewindow (high score)
> >Date: Tue, 19 Apr 2005 15:29:42 -0700
> >
> >Ok. I got in the working code to have a high score list, and it even
> >saves/loads one now (!!).  The only problem is, clicking back from the
> >text window to the game window (only after you entered in your name to
> >go onto the high score list), closes the program. you dont get to say
> >y/n to another game, it just shuts down. i cant run a debugger on it,
> >because the error doesnt happen when I F5-run the game from the python
> >IDLE script, only when i have ran it by doubleclicking on it (which is
> >how you're supposed to run it. otherwise it doesnt shut down
> >properly). i really really REALLY want to keep the high score part of
> >my program, because i worked really hard to get this to work. but i
> >have to have this program running with NO crashes in like a week (it's
> >a birthday present, and the birthday is approaching fast!)
> >
> >Here's the "end of game" code:
> >
> >             #game over..
> >             if lives == 0:
> >### trying addscore
> >
> >                 def add_score():
> >  #                   high_scores = [(1000,"Denise"), (945,"Denise"),
> >   #                                 (883,"Denise"),(823,"Grant"),
> >    #                                (779,"Aaron"), (702,"Pete"),
> >     #                               (555,"Tom"), (443,"Tom"),
> >      #                              (442,"Robin"), (4,"Pete")]
> >                     high_scores = pickle.load(file("scores.pik"))
> >                     score = total_enemy_hits
> >                     if score > high_scores[-1][0]:
> >                         print "Ta da! You got", total_enemy_hits,
> >"Ranch Delivery Devices!"
> >                         name = read_string("You made the high score
> >list! What's your name? ")
> >                         user_score = (score,name)
> >                         high_scores.append(user_score)
> >                         high_scores.sort(reverse=True)
> >                         del high_scores[-1]
> >                         pickle.dump(high_scores, file("scores.pik",
>"w"))
> >                         for score, name in high_scores:
> >                             slip = 30 - len(name)
> >                             slip_amt = slip*" "
> >                             prefix = 5*" "
> >                             print prefix,name,slip_amt,score
> >                     else:
> >                         print "Sorry, you only got", total_enemy_hits,
> >"Ranch Delivery Devices."
> >                         print "You didn't quite make the high score
>list!"
> >                         for score, name in high_scores:
> >                             slip = 30 - len(name)
> >                             slip_amt = slip*" "
> >                             prefix = 5*" "
> >                             print prefix,name,slip_amt,score
> >                         print "Better luck next time!"
> >
> >  #               pdb.set_trace()
> >                 add_score()
> >
> >                 end.play()
> >                 showGameOver(screen, background_image)
> >                 pygame.display.flip()
> >
> >
> >                 answer = ""
> >                 while not answer in ("y","n"):
> >                    for event in pygame.event.get():
> >                       if event.type == KEYDOWN:
> >                          if event.key == K_n:
> >                             answer = "n"
> >                          elif event.key == K_y:
> >                             answer = "y"
> >                 if answer == "n":
> >                     running = 0
> >                 else:
> >                     return 1
> >
> >             #refresh the display
> >             pygame.event.pump()
> >             pygame.display.flip()
> >
> >     #well, nice playing with you...
> >     screen = pygame.display.set_mode((640, 480))
> >     return 0
> >
> >
> >Can anyone tell me why it crashes? you click to the text window when
> >there's the "congrats, you made the high score list, enter your name"
> >prompt, enter your name and hit enter, and it displays the high
> >scores, with your name in it, just as it should. but then when you
> >click back to the game screen, poof! it all closes.  Of course if you
> >dont make the high score list, you can click to the text window and
> >click back to the game window and it operates like it should.
> >
> >Any suggestions would be appreciated!!  Again, I'd like to have it do
> >all this score stuff in the game/graphics window, and then it wouldnt
> >have that crash at all. But I dont know how to do that.
> >
> >Please help!
> >
> >Thanks again :)
> >
> >~Denise
> >_______________________________________________
> >Tutor maillist  -  Tutor@python.org
> >http://mail.python.org/mailman/listinfo/tutor
>
>Gaucho
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

Gaucho
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 20 23:29:59 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 20 23:30:04 2005
Subject: [Tutor] TKinter and things over Linux [how to make a transcript]
In-Reply-To: <BAY106-F6D5AA2A9E26528B608C32892B0@phx.gbl>
Message-ID: <Pine.LNX.4.44.0504201413550.10799-101000@hkn.eecs.berkeley.edu>



On Wed, 20 Apr 2005, Alberto Troiano wrote:

> You're so right and I apologize for my mistake
>
> Do you or anybody knows where the error.log for this kind o things is?????
>
> or how can I capture the output in a file???????????Cause is so damn
> long that I barely see the 10% of all the things its print out


Hi Alberto,

On Unix, we can use a program called "script".  It's enormously useful.


Let's go through an example.  In my own copy of MySQL-python-1.2.0, I've
damaged my own setup.py: I've deliberately broken parts of the include
directory stuff to illicit a compile-time error.  This will show what kind
of errors we might expect to see from a missing MySQL setup.


Ok, let's start up the transcript.

######
[dyoo@shoebox dyoo]$ script
Script started, file is typescript
######


At this point, a file called 'typescript' is saved in the current working
directory.  It'll continue to record output until we 'exit'.

######
[dyoo@shoebox dyoo]$ cd MySQL-python-1.2.0
[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py build
running build
running build_py
running build_ext
building '_mysql' extension

... [output follows, as well as a LOT of error messages]

error: command 'gcc' failed with exit status 1
[dyoo@shoebox MySQL-python-1.2.0]$ exit
exit
Script done, file is typescript
######


Once things are done, I've 'exit'ed, and I have a nice 'typescript' which
records everything that I've done.



Let's do a quick inspection of that typescript:

######
[dyoo@shoebox dyoo]$ head -n 10 typescript
Script started on Wed Apr 20 14:15:02 2005
[dyoo@shoebox dyoo]$ cd MySQL-python-1.2.0
[dyoo@shoebox MySQL-python-1.2.0]$ python setup.py build
running build
running build_py
running build_ext
building '_mysql' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -fPIC -I/usr/include/python2.3
-c _mysql.c -o build/temp.linux-i686-2.3/_mysql.o
_mysql.c:41:19: mysql.h: No such file or directory
_mysql.c:42:26: mysqld_error.h: No such file or directory
######

This is an example of an error message log.  The whole file contains exact
information that we need to see to duplicate the error.  I'll attach a
gzipped copy of it, just so you understand what we'd like to get back.


I'm only showing the first few lines of the transcript, but it includes
invaluable information.  What's most valuable here is seeing what flags
are being passed to gcc.  That is, it is very interesting that we see
something like:

    gcc -pthread -fno-strict-aliasing -DNDEBUG -fPIC -I/usr/include/python2.3
        -c _mysql.c -o build/temp.linux-i686-2.3/_mysql.o

because, for those C hackers amongst us, this looks wrong, because there's
a missing reference to the MySQL include directory.  And our suspicions
are confirmed when we see that gcc has trouble finding header files.  In
this particular case, we'd figure out that something has happened so that
setup.py isn't including a '-I/usr/include/mysql' as part of the compiler
argument list.


This is exactly why a full transcript is so useful: we see how things are
really running through the system.  There are lots of silly little
details, but they're invaluable when we're tracing errors.


I hope this helps!
-------------- next part --------------
A non-text attachment was scrubbed...
Name: sample-typescript.gz
Type: application/octet-stream
Size: 2697 bytes
Desc: 
Url : http://mail.python.org/pipermail/tutor/attachments/20050420/2e589086/sample-typescript.obj
From bill at celestial.net  Wed Apr 20 23:35:35 2005
From: bill at celestial.net (Bill Campbell)
Date: Wed Apr 20 23:35:00 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <BAY106-F6D5AA2A9E26528B608C32892B0@phx.gbl>
References: <Pine.LNX.4.44.0504201314480.26907-100000@hkn.eecs.berkeley.edu>
	<BAY106-F6D5AA2A9E26528B608C32892B0@phx.gbl>
Message-ID: <20050420213535.GA46034@alexis.mi.celestial.com>

On Wed, Apr 20, 2005, Alberto Troiano wrote:
>You're so right and I apologize for my mistake
>
>Do you or anybody knows where the error.log for this kind o things is?????
>
>or how can I capture the output in a file???????????Cause is so damn long 
>that I barely see the 10% of all the things its print out

The following command will keep a copy of the output in the file
make.output (this doesn't work with csh).  The ``2>&1'' modem
noise joins standard error and standard output, and the ``tee''
program is a pipe fitting that puts its standard input into a
file, and to its own standard output.

	make 2>&1 | tee make.output

Bill
--
INTERNET:   bill@Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``If the personal freedoms guaranteed by the Constitution inhibit the
government's ability to govern the people, we should look to limit those
guarantees.''
   -President Bill Clinton, August 12, 1993
From prasad413in at gmail.com  Thu Apr 21 00:16:31 2005
From: prasad413in at gmail.com (Prasad Kotipalli)
Date: Thu Apr 21 00:16:45 2005
Subject: [Tutor] Help regarding optparse
Message-ID: <6ce40f75050420151618351af9@mail.gmail.com>

Hello
 I am a newbie to python, I have been working with getopt for parsing
command line options, but i came to know that optparse module is more
effecient. Can anyone suggest some ideas why it is powerful than
getopt.

Thanks
Prasad
From dyoo at hkn.eecs.berkeley.edu  Thu Apr 21 00:33:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 21 00:33:20 2005
Subject: [Tutor] Help regarding optparse
In-Reply-To: <6ce40f75050420151618351af9@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504201521580.31774-100000@hkn.eecs.berkeley.edu>



On Wed, 20 Apr 2005, Prasad Kotipalli wrote:

>  I am a newbie to python, I have been working with getopt for parsing
> command line options, but i came to know that optparse module is more
> effecient. Can anyone suggest some ideas why it is powerful than
> getopt.


Hi Prasad,

According to:

    http://www.python.org/doc/lib/module-optparse.html

the 'declarative' nature of optparse is what makes it nicer to work with
than getopt.


The documentation in optparse shows how to do things like assign value
converters for particular kinds of parameters.  For example, we can say
that we'd like to get an '-n' numeric argument.  In optparse, we'd be able
to declare that by saying:

    parser.add_option("-n", type="int", dest="num")

(taken from http://www.python.org/doc/lib/optparse-store-action.html)

It's "declarative" because we're saying that we expect the '-n' option to
be an int, but we don't really have to say how optparse will do that
checking.


We get a lot of stuff for free by letting optparse do the heavy lifint:
if someone tries to put something non-numeric for the '-n' argument,
optparse gives a good error message:

######
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-n", type="int", dest="num")
<optparse.Option instance at 0x402e556c>
>>> parser.parse_args(args=['-n', 'foobar'])
usage:  [options]

: error: option -n: invalid integer value: 'foobar'
######


In contrast, if we wanted to provide the same functionality with getopt:

    http://www.python.org/doc/lib/module-getopt.html

then we could probably do all of that, but it might be more painful, and
would involve manually coding the type tests.


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

From python at venix.com  Thu Apr 21 00:33:38 2005
From: python at venix.com (Lloyd Kvam)
Date: Thu Apr 21 00:34:59 2005
Subject: [Tutor] TKinter and things over Linux
Message-ID: <1114036418.26992.53.camel@laptop.venix.com>

Learning to install packages from source tar balls is useful knowledge.
However, most of the current Linux distributions have package managers
that greatly simply installing software.

apt-get and yum are available for Redhat style releases.  They will
download and install packages and figure out the dependency issues.
(yum is written in Python so this is slightly on topic.)  Sometimes the
hardest part is getting the package manager working on an old release
that did not include it.

Fedora 3 will generally prove easier to manage than Redhat 9 simply
because there are more people packaging code for the newer releases.
You'll be able to rely on yum to install software and keep the system
humming along.
	yum install MySQL-python
will determine which packages are needed, and download and install them.

-- 
Lloyd Kvam
Venix Corp

From albertito_g at hotmail.com  Thu Apr 21 00:57:54 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu Apr 21 00:57:58 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe5605042014225275cbf2@mail.gmail.com>
Message-ID: <BAY106-F1026D0EBC3D4C2507F78FD892B0@phx.gbl>

Hi

The thing is this

I get an error that says sort() has no arguments

Th error is in the sentence
high_score.sort(reverse=TRUE)

If you put just sort() it will work but the list will show from low to high 
and we don't want that 'cause if you make a high score it won't be able to 
know so you have to figure out another way to reverse the list

Regards

Alberto
>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Alberto Troiano <albertito_g@hotmail.com>
>Subject: Re: [Tutor] crash - switching between text window and 
>graphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 14:22:24 -0700
>
>Alberto,
>
>Thank you for replying! I sent answers to the general questions to the
>tutor list, so that hopefully the extra clarification might help
>someone else answer (I havent had much luck with this thread,
>unfortunately).  But I wanted to reply to you personally to send a
>copy of the game.  It's a "mod" of a game from pygame, but I've added
>a lot of stuff to it.  I'll send it as a zip file with two different
>"play" files - run the one simply called "play" to test out the game
>without the crash (oh, a side-note: the enemy ships will change
>graphics on levels 2 and 3, but they're not pretty - i just put those
>graphics in there as a place holder until i make their prettier
>replacements).  Anyway, the play file called "copy of play
>wscorelist2" is the copy with the scorelist that is crashing.  If you
>just want to see the *code*  you can look at either of those two
>files, but I thought you might want to play the actual game so I'm
>sending it all. Have fun :) Any comments/ideas/suggestions are very
>welcomed!! I'm having a couple friends test it out. But since I'm new
>I might not be able to take ALL of the suggestions before I have to
>have the game done next week, ha ha.
>
>Anyway thanks so much for replying, and for any help or suggestions
>you might have about the crash.
>
>~Denise
>
>P.S. if you dont have them, you'll need pygame and the livewires
>module, available at http://www.livewires.org.uk/python/lwpackage.html
>.  Thanks again!
>
>On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > Hey
> >
> > I'm curious
> >
> > What extension are you using on your game???????????
> > is it .py???????????????
> >
> > And what OS are you running the game???????????????
> >
> > Another thing. I made a space ship game to learn Python. Is there a
> > possibility that we exchange the games so we can know differents points 
>of
> > view????????
> >
> > I'll wait your reply
> >
> > Regards
> >
> > Alberto
> >
> > >From: "D. Hartley" <denise.hartley@gmail.com>
> > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > >To: Python tutor <tutor@python.org>
> > >Subject: [Tutor] crash - switching between text window and
> > >graphics/gamewindow (high score)
> > >Date: Tue, 19 Apr 2005 15:29:42 -0700
> > >
> > >Ok. I got in the working code to have a high score list, and it even
> > >saves/loads one now (!!).  The only problem is, clicking back from the
> > >text window to the game window (only after you entered in your name to
> > >go onto the high score list), closes the program. you dont get to say
> > >y/n to another game, it just shuts down. i cant run a debugger on it,
> > >because the error doesnt happen when I F5-run the game from the python
> > >IDLE script, only when i have ran it by doubleclicking on it (which is
> > >how you're supposed to run it. otherwise it doesnt shut down
> > >properly). i really really REALLY want to keep the high score part of
> > >my program, because i worked really hard to get this to work. but i
> > >have to have this program running with NO crashes in like a week (it's
> > >a birthday present, and the birthday is approaching fast!)
> > >
> > >Here's the "end of game" code:
> > >
> > >             #game over..
> > >             if lives == 0:
> > >### trying addscore
> > >
> > >                 def add_score():
> > >  #                   high_scores = [(1000,"Denise"), (945,"Denise"),
> > >   #                                 (883,"Denise"),(823,"Grant"),
> > >    #                                (779,"Aaron"), (702,"Pete"),
> > >     #                               (555,"Tom"), (443,"Tom"),
> > >      #                              (442,"Robin"), (4,"Pete")]
> > >                     high_scores = pickle.load(file("scores.pik"))
> > >                     score = total_enemy_hits
> > >                     if score > high_scores[-1][0]:
> > >                         print "Ta da! You got", total_enemy_hits,
> > >"Ranch Delivery Devices!"
> > >                         name = read_string("You made the high score
> > >list! What's your name? ")
> > >                         user_score = (score,name)
> > >                         high_scores.append(user_score)
> > >                         high_scores.sort(reverse=True)
> > >                         del high_scores[-1]
> > >                         pickle.dump(high_scores, file("scores.pik", 
>"w"))
> > >                         for score, name in high_scores:
> > >                             slip = 30 - len(name)
> > >                             slip_amt = slip*" "
> > >                             prefix = 5*" "
> > >                             print prefix,name,slip_amt,score
> > >                     else:
> > >                         print "Sorry, you only got", total_enemy_hits,
> > >"Ranch Delivery Devices."
> > >                         print "You didn't quite make the high score 
>list!"
> > >                         for score, name in high_scores:
> > >                             slip = 30 - len(name)
> > >                             slip_amt = slip*" "
> > >                             prefix = 5*" "
> > >                             print prefix,name,slip_amt,score
> > >                         print "Better luck next time!"
> > >
> > >  #               pdb.set_trace()
> > >                 add_score()
> > >
> > >                 end.play()
> > >                 showGameOver(screen, background_image)
> > >                 pygame.display.flip()
> > >
> > >
> > >                 answer = ""
> > >                 while not answer in ("y","n"):
> > >                    for event in pygame.event.get():
> > >                       if event.type == KEYDOWN:
> > >                          if event.key == K_n:
> > >                             answer = "n"
> > >                          elif event.key == K_y:
> > >                             answer = "y"
> > >                 if answer == "n":
> > >                     running = 0
> > >                 else:
> > >                     return 1
> > >
> > >             #refresh the display
> > >             pygame.event.pump()
> > >             pygame.display.flip()
> > >
> > >     #well, nice playing with you...
> > >     screen = pygame.display.set_mode((640, 480))
> > >     return 0
> > >
> > >
> > >Can anyone tell me why it crashes? you click to the text window when
> > >there's the "congrats, you made the high score list, enter your name"
> > >prompt, enter your name and hit enter, and it displays the high
> > >scores, with your name in it, just as it should. but then when you
> > >click back to the game screen, poof! it all closes.  Of course if you
> > >dont make the high score list, you can click to the text window and
> > >click back to the game window and it operates like it should.
> > >
> > >Any suggestions would be appreciated!!  Again, I'd like to have it do
> > >all this score stuff in the game/graphics window, and then it wouldnt
> > >have that crash at all. But I dont know how to do that.
> > >
> > >Please help!
> > >
> > >Thanks again :)
> > >
> > >~Denise
> > >_______________________________________________
> > >Tutor maillist  -  Tutor@python.org
> > >http://mail.python.org/mailman/listinfo/tutor
> >
> > Gaucho
> >
> >
><< zmine.zip >>


Gaucho


From maxnoel_fr at yahoo.fr  Thu Apr 21 01:10:48 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 21 01:14:44 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <BAY106-F1026D0EBC3D4C2507F78FD892B0@phx.gbl>
References: <BAY106-F1026D0EBC3D4C2507F78FD892B0@phx.gbl>
Message-ID: <89a7c8d08c919371675be5ebeeff0312@yahoo.fr>


On Apr 20, 2005, at 23:57, Alberto Troiano wrote:

> Hi
>
> The thing is this
>
> I get an error that says sort() has no arguments
>
> Th error is in the sentence
> high_score.sort(reverse=TRUE)
>
> If you put just sort() it will work but the list will show from low to 
> high and we don't want that 'cause if you make a high score it won't 
> be able to know so you have to figure out another way to reverse the 
> list
>
> Regards
>
> Alberto

	I seem to recall Denise is using Python 2.4, where as you're using a 
2.3 version. In Python 2.4, additional arguments were added to the 
list.sort() method: reverse, when set to True, sorts the list in 
reverse order, and key is a function which when applied to a member of 
the list, returns the element in function of which the list is to be 
sorted.
	So the error probably is elsewhere. Don't have time to take a look at 
it, though, sorry (50-page report due soon... I hate those :( ).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From maxnoel_fr at yahoo.fr  Thu Apr 21 01:26:29 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 21 01:26:36 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe5605042016194e9497e5@mail.gmail.com>
References: <BAY106-F1026D0EBC3D4C2507F78FD892B0@phx.gbl>
	<89a7c8d08c919371675be5ebeeff0312@yahoo.fr>
	<8daabe5605042016194e9497e5@mail.gmail.com>
Message-ID: <72ff4abe1ba1561ee5d6439d635693c7@yahoo.fr>


On Apr 21, 2005, at 00:19, D. Hartley wrote:

> Max -
>
> I thought it might be a version issue as well, thanks.  Also, good
> luck on your paper! 50 pages, whoo! Haven't done that since grad
> school, my condolences man.
>
> ~Denise :)

	Thanks... I'm almost done now, only a few more pages and all that will 
be left will be adding pictures and diagrams... /me fires up Rational 
Rose over Citrix.
	Anyway, I'll try to have a look at your program when I have some time 
(although being a 2.3 user I may not be of much use to you there). You 
should upload the whole of it somewhere, so that people can actually 
try to run it and see what goes wrong.

	Oh, and if all else fails, remember that your absolute best friend 
when it comes to debugging is the print statement. I haven't found a 
better way to trace the flow of a program yet.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From amonroe at columbus.rr.com  Thu Apr 21 01:53:21 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu Apr 21 01:54:22 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <1114036418.26992.53.camel@laptop.venix.com>
References: <1114036418.26992.53.camel@laptop.venix.com>
Message-ID: <183691066210.20050420195321@columbus.rr.com>


> apt-get and yum are available for Redhat style releases.  They will
> download and install packages and figure out the dependency issues.
> (yum is written in Python so this is slightly on topic.)

Gentoo's "emerge" system is also written in Python.

Alan

From jfouhy at paradise.net.nz  Thu Apr 21 02:05:31 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Thu Apr 21 02:05:35 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe560504201415684bc5e1@mail.gmail.com>
References: <8daabe56050419152924c792d6@mail.gmail.com>
	<BAY106-F25C49F1E45A2170291859D892B0@phx.gbl>
	<8daabe560504201415684bc5e1@mail.gmail.com>
Message-ID: <1114041930.4266ee4b001fb@www.paradise.net.nz>

Quoting "D. Hartley" <denise.hartley@gmail.com>:

> The play file does end in ".py". I am running it on Windows. You can
> double-click the play file, and run it straight that way, which is
> when the crash occurs. If you right click the file, go to "edit in
> IDLE", and hit F5 to run it, the crash does NOT happen. I'm not sure
> why (but this is also why my debugging program won't tell me what's
> wrong).

I haven't been following this thread, so apologies in advance if this is
something you've already done ---

Have you tried running the program from a command prompt?  To do this, go to
Start-->Run and type 'cmd'.  Then change to the directory with your script in it
('cd ' followed by the full directory path), and run the script by typing
'python ' followed by the script name.
(you may need to type something like 'c:\python24\python ' instead, if python is
not in your path)

The effect of this is that, when the program crashes, you will be left with a
window showing you (hopefully) some useful error messages.

-- 
John.
From denise.hartley at gmail.com  Thu Apr 21 02:45:00 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Thu Apr 21 02:45:04 2005
Subject: Fwd: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <1114041930.4266ee4b001fb@www.paradise.net.nz>
References: <8daabe56050419152924c792d6@mail.gmail.com>
	<BAY106-F25C49F1E45A2170291859D892B0@phx.gbl>
	<8daabe560504201415684bc5e1@mail.gmail.com>
	<1114041930.4266ee4b001fb@www.paradise.net.nz>
Message-ID: <8daabe5605042017457204a1dd@mail.gmail.com>

John,

Thank you for the suggestion to try the game from the command line. 
Unfortunately, when I scored high enough to make the high score list
and entered in my name (in the dos/command window, now), and clicked
back to the game screen, the game screen just closed/crashed, and the
command line returned to its pathname. No error messages,
unfortunately!  Was I supposed to be doing something else?

Thanks,
Denise

---------- Forwarded message ----------
From: jfouhy@paradise.net.nz <jfouhy@paradise.net.nz>
Date: Apr 20, 2005 5:05 PM
Subject: Re: [Tutor] crash - switching between text window and
graphics/gamewindow (high score)
To: tutor@python.org


I haven't been following this thread, so apologies in advance if this is
something you've already done ---

Have you tried running the program from a command prompt?  To do this, go to
Start-->Run and type 'cmd'.  Then change to the directory with your script in it
('cd ' followed by the full directory path), and run the script by typing
'python ' followed by the script name.
(you may need to type something like 'c:\python24\python ' instead, if python is
not in your path)

The effect of this is that, when the program crashes, you will be left with a
window showing you (hopefully) some useful error messages.

--
John.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From peterf at mac.com  Thu Apr 21 03:56:25 2005
From: peterf at mac.com (PFraterdeus)
Date: Thu Apr 21 04:05:38 2005
Subject: [Tutor] using a dictionary??
Message-ID: <loom.20050421T034952-897@post.gmane.org>

Here'a little py script for a plone page template...
I just want to translate the 'key' (organicnews) to a 'value' (Organics in the
News), for presentation purposes. (the key, of course, is in the URL request)


db = request.db

if db=="organicnews":  
 print "%s" % html_quote('Organics in the News')
elif db=="ovnews":
 print "%s" % html_quote('Our Stuff in the News')
elif db=="pressreleases":
 print "%s" % html_quote('Press Releases')
else:
 print "Unknown News Database!",
 print "%s" % db
return printed

This script works fine as is, no problem... BUT


I know there's a proper way to do this with a tuple, or something :)
For the three values, it's not a problem, but if I want to scale up to many, I
imagine the dictionary is the way to go...

Thanks for hints on a proper pythonesque and elegant syntax for this pattern!

Ciao
Peter



From kent37 at tds.net  Thu Apr 21 05:16:14 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 05:16:31 2005
Subject: [Tutor] Help regarding optparse
In-Reply-To: <6ce40f75050420151618351af9@mail.gmail.com>
References: <6ce40f75050420151618351af9@mail.gmail.com>
Message-ID: <42671AFE.2000505@tds.net>

Prasad Kotipalli wrote:
> Hello
>  I am a newbie to python, I have been working with getopt for parsing
> command line options, but i came to know that optparse module is more
> effecient. Can anyone suggest some ideas why it is powerful than
> getopt.

Another option I like is optionparse from this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844

To use optionparse you just write a usage string, optionparse will parse it to figure out what to do 
and return the options to you.

Kent

From kent37 at tds.net  Thu Apr 21 05:20:09 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 05:20:13 2005
Subject: [Tutor] using a dictionary??
In-Reply-To: <loom.20050421T034952-897@post.gmane.org>
References: <loom.20050421T034952-897@post.gmane.org>
Message-ID: <42671BE9.4090609@tds.net>

PFraterdeus wrote:
> Here'a little py script for a plone page template...
> I just want to translate the 'key' (organicnews) to a 'value' (Organics in the
> News), for presentation purposes. (the key, of course, is in the URL request)
> 
> 
> db = request.db
> 
> if db=="organicnews":  
>  print "%s" % html_quote('Organics in the News')
> elif db=="ovnews":
>  print "%s" % html_quote('Our Stuff in the News')
> elif db=="pressreleases":
>  print "%s" % html_quote('Press Releases')
> else:
>  print "Unknown News Database!",
>  print "%s" % db
> return printed
> 
> This script works fine as is, no problem... BUT
> 
> 
> I know there's a proper way to do this with a tuple, or something :)
> For the three values, it's not a problem, but if I want to scale up to many, I
> imagine the dictionary is the way to go...

Yes, something like

headlines = {
   "organicnews":'Organics in the News',
   "ovnews":'Our Stuff in the News',
   "pressreleases":'Press Releases',
}

db = request.db
head = headlines.get(db, "Unknown News Database!")
print "%s" % html_quote(head)

Kent

From bgailer at alum.rpi.edu  Thu Apr 21 05:22:14 2005
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu Apr 21 05:23:30 2005
Subject: [Tutor] using a dictionary??
In-Reply-To: <loom.20050421T034952-897@post.gmane.org>
References: <loom.20050421T034952-897@post.gmane.org>
Message-ID: <6.1.2.0.0.20050420201536.03a4eae8@pop.sbcglobal.yahoo.com>

At 06:56 PM 4/20/2005, PFraterdeus wrote:
>Here'a little py script for a plone page template...
>I just want to translate the 'key' (organicnews) to a 'value' (Organics in the
>News), for presentation purposes. (the key, of course, is in the URL request)
>
>
>db = request.db
>
>if db=="organicnews":
>  print "%s" % html_quote('Organics in the News')
>elif db=="ovnews":
>  print "%s" % html_quote('Our Stuff in the News')
>elif db=="pressreleases":
>  print "%s" % html_quote('Press Releases')
>else:
>  print "Unknown News Database!",
>  print "%s" % db
>return printed

Use a dictionary:

responses = {"organicnews": "Organics in the News'", "ovnews" : "'Our Stuff 
in the News'", "pressreleases" : "'Press Releases'"}
print html_quote(responses.get(db, "Unknown News Database! " + db))

BTW there is no benefit to print '%s' % blahblah. print blahblah does the 
same thing.

>[snip]
>I know there's a proper way to do this with a tuple, or something :)
>For the three values, it's not a problem, but if I want to scale up to many, I
>imagine the dictionary is the way to go...

Bob Gailer
mailto:bgailer@alum.rpi.edu
510 558 3275 home
720 938 2625 cell  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050420/072cda0d/attachment.html
From smichr at bigfoot.com  Thu Apr 21 06:15:35 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Thu Apr 21 06:16:44 2005
Subject: [Tutor] Weird import problem with PythonIDE on Mac (was 'import
	problem')
In-Reply-To: <fc337b05287044b9df6d8ef06d78b0e7@mac.com>
Message-ID: <027ED692-B21C-11D9-B60E-000393C0D100@bigfoot.com>


On Tuesday, Apr 19, 2005, Lee Cullens wrote:

> I assume you mean PythonIDE for Python 2.3 (I usually use 2.4 and 
> WingIDE).  Here it is (indents screwed up with var font):
>
> HTH,
> Lee C
>
>> import timeit
>> def y1():
>> 	print ?y1 executed?
>> def y2():
>> 	print ?y2 executed?
>> for f in [y1,y2]:
>> 	name = f.__name__
>> 	print name; f()
>> 	t=timeit.Timer(?%s()? % name, ?from __main__ import %s? % name)
>> 	print t.timeit(1)

I wrote this yesterday....
------------------
Well, how bizarre! Now I run the code again (after having restarted the 
PythonIDE) and now I can't get it to NOT work.  And it previously had 
not run for many tries.

I don't suppose this is some sort of quantum effect ;-)

Oh well, I'll keep my eyes open to see if this happens again.
------------------

And now today, the problem is back again :-(  What's going on? Here is 
a smaller code:

###
def y1():
	print 'y1 executed'
for f in [y1]:
	name = f.__name__
	f()
	s1 = '%s()' % name
	s2 = 'from __main__ import %s' % name
	t=timeit.Timer(s1, s2)
	print t.timeit(1)
###

Here is the full report from the traceback window {it's great to be 
able to cut and paste from that window, thanks Just}

'''
ImportError: cannot import name y1

Traceback (innermost last)

File "<Untitled Script 1>", line 10, in ?
File "timeit.py", line 158, in timeit
       return self.inner(it, self.timer)
File "<timeit-src>", line 3, in inner
'''

** If I click on the edit button it says that <timeit-src> cannot be 
found. Is this an error to pay attention to or is that an unrelated 
problem of trying to browse a (perhaps compiled) source file?


Here is what I've tried to reproduce the problem:

1) I have restarted the system (10.2.8) and run nothing but this script 
and still get the error.
2) removed my PythonStartup and sitecustomize.py codes after quitting; 
problem still persists
3) re-installed MacPython 2.3.3 after moving the old version's 
macPython 2.3.3 folder to the desktop
4) I have tried running the script in the add with and without the "run 
as __main__" option.

I DO NOT have the error show up when I run the script through the 
Terminal (i.e. %python timeitproblem.py).

I also DO NOT have the problem if I run the script with PyOXIDE.

As noted yesterday, there are some unknown steps that make the problem 
go away, though I do not know what these are yet.

Does anyone else have any insights?

/c

From ray007 at bluemail.ch  Thu Apr 21 11:07:04 2005
From: ray007 at bluemail.ch (ray007@bluemail.ch)
Date: Thu Apr 21 11:07:08 2005
Subject: [Tutor] GNUPLOT
Message-ID: <4262FED500020371@mssazhh-int.msg.bluewin.ch>

Hi 

Hoping that someone can help me here. I have been reading about gnuplot and
it's plotting functionality, so i decided to install this: I downloaded the
gnuplot windows function and then installed the gnuplot.py file using the
setut.py and install command all worked. I also installed the numeric python.

I start by a simple example below and then I get stuck...

>>> import Gnuplot, Gnuplot.funcutils
>>> from Numeric import *
>>> g = Gnuplot.Gnuplot()
>>> g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])


Traceback (most recent call last):
  File "<pyshell#3>", line 1, in -toplevel-
    g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 274, in
plot
    self.refresh()
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 215, in
refresh
    self(self.plotcmd + ' ' + string.join(plotcmds, ', '))
  File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 199, in
__call__
    self.gnuplot(s)
  File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py", line 125, in
__call__
    self.write(s + '\n')
IOError: [Errno 22] Invalid argument

Has someone experienced the same issue above if so did you manage to overcome
it?

Much appreciated if someone can help solve this issue for me.

Thanks

Ray

From kent37 at tds.net  Thu Apr 21 12:08:01 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 12:08:05 2005
Subject: [Tutor] Weird import problem with PythonIDE on Mac (was 'import
	problem')
In-Reply-To: <027ED692-B21C-11D9-B60E-000393C0D100@bigfoot.com>
References: <027ED692-B21C-11D9-B60E-000393C0D100@bigfoot.com>
Message-ID: <42677B81.5050808@tds.net>

Is it possible that the script is not running as __main__? Add
print __name__
to the script and see what it says...

Kent

Chris Smith wrote:
> 
> On Tuesday, Apr 19, 2005, Lee Cullens wrote:
> 
>> I assume you mean PythonIDE for Python 2.3 (I usually use 2.4 and 
>> WingIDE).  Here it is (indents screwed up with var font):
>>
>> HTH,
>> Lee C
>>
>>> import timeit
>>> def y1():
>>>     print ?y1 executed?
>>> def y2():
>>>     print ?y2 executed?
>>> for f in [y1,y2]:
>>>     name = f.__name__
>>>     print name; f()
>>>     t=timeit.Timer(?%s()? % name, ?from __main__ import %s? % name)
>>>     print t.timeit(1)
> 
> 
> I wrote this yesterday....
> ------------------
> Well, how bizarre! Now I run the code again (after having restarted the 
> PythonIDE) and now I can't get it to NOT work.  And it previously had 
> not run for many tries.
> 
> I don't suppose this is some sort of quantum effect ;-)
> 
> Oh well, I'll keep my eyes open to see if this happens again.
> ------------------
> 
> And now today, the problem is back again :-(  What's going on? Here is a 
> smaller code:
> 
> ###
> def y1():
>     print 'y1 executed'
> for f in [y1]:
>     name = f.__name__
>     f()
>     s1 = '%s()' % name
>     s2 = 'from __main__ import %s' % name
>     t=timeit.Timer(s1, s2)
>     print t.timeit(1)
> ###
> 
> Here is the full report from the traceback window {it's great to be able 
> to cut and paste from that window, thanks Just}
> 
> '''
> ImportError: cannot import name y1
> 
> Traceback (innermost last)
> 
> File "<Untitled Script 1>", line 10, in ?
> File "timeit.py", line 158, in timeit
>       return self.inner(it, self.timer)
> File "<timeit-src>", line 3, in inner
> '''
> 
> ** If I click on the edit button it says that <timeit-src> cannot be 
> found. Is this an error to pay attention to or is that an unrelated 
> problem of trying to browse a (perhaps compiled) source file?
> 
> 
> Here is what I've tried to reproduce the problem:
> 
> 1) I have restarted the system (10.2.8) and run nothing but this script 
> and still get the error.
> 2) removed my PythonStartup and sitecustomize.py codes after quitting; 
> problem still persists
> 3) re-installed MacPython 2.3.3 after moving the old version's macPython 
> 2.3.3 folder to the desktop
> 4) I have tried running the script in the add with and without the "run 
> as __main__" option.
> 
> I DO NOT have the error show up when I run the script through the 
> Terminal (i.e. %python timeitproblem.py).
> 
> I also DO NOT have the problem if I run the script with PyOXIDE.
> 
> As noted yesterday, there are some unknown steps that make the problem 
> go away, though I do not know what these are yet.
> 
> Does anyone else have any insights?
> 
> /c
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Thu Apr 21 12:29:39 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 12:29:46 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <4262FED500020371@mssazhh-int.msg.bluewin.ch>
References: <4262FED500020371@mssazhh-int.msg.bluewin.ch>
Message-ID: <42678093.4090102@tds.net>

Strange. This example works for me on Win2K with Python 2.4.

Kent

ray007@bluemail.ch wrote:
> Hi 
> 
> Hoping that someone can help me here. I have been reading about gnuplot and
> it's plotting functionality, so i decided to install this: I downloaded the
> gnuplot windows function and then installed the gnuplot.py file using the
> setut.py and install command all worked. I also installed the numeric python.
> 
> I start by a simple example below and then I get stuck...
> 
> 
>>>>import Gnuplot, Gnuplot.funcutils
>>>>from Numeric import *
>>>>g = Gnuplot.Gnuplot()
>>>>g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
> 
> 
> 
> Traceback (most recent call last):
>   File "<pyshell#3>", line 1, in -toplevel-
>     g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
>   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 274, in
> plot
>     self.refresh()
>   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 215, in
> refresh
>     self(self.plotcmd + ' ' + string.join(plotcmds, ', '))
>   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 199, in
> __call__
>     self.gnuplot(s)
>   File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py", line 125, in
> __call__
>     self.write(s + '\n')
> IOError: [Errno 22] Invalid argument
> 
> Has someone experienced the same issue above if so did you manage to overcome
> it?
> 
> Much appreciated if someone can help solve this issue for me.
> 
> Thanks
> 
> Ray
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From cpu.crazy at gmail.com  Thu Apr 21 08:00:00 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 21 14:31:06 2005
Subject: [Tutor] Error Raising (Joseph Q.)
Message-ID: <6.1.0.6.2.20050418145700.01f03318@pop.gmail.com>

(here I go again?)
Where could I find a nice long list of the errors I can raise? (I mean like 
EOF errors when some one doesn't fill in their name when they're supposed to).

Thanks,
Joe 

From kent37 at tds.net  Thu Apr 21 14:43:12 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 14:43:16 2005
Subject: [Tutor] Error Raising (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050418145700.01f03318@pop.gmail.com>
References: <6.1.0.6.2.20050418145700.01f03318@pop.gmail.com>
Message-ID: <42679FE0.8010006@tds.net>

Joseph Quigley wrote:
> (here I go again?)
> Where could I find a nice long list of the errors I can raise? (I mean 
> like EOF errors when some one doesn't fill in their name when they're 
> supposed to).

The standard (built-in) exceptions are documented here:
http://docs.python.org/lib/module-exceptions.html

If you don't find any that suit you, defining your own is as easy as

class MyException(Exception):
   pass

....
try:
   raise MyException
except MyException:
   ...

Kent

From albertito_g at hotmail.com  Thu Apr 21 15:21:00 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu Apr 21 15:21:05 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe5605042016102efd0ec5@mail.gmail.com>
Message-ID: <BAY106-F30595A95E3AC76E02004FD892C0@phx.gbl>

Hi

Sorry about that, I'm using Python 2.3.4 cause when Python 2.4 was released 
there wasn't libraries like MySQLdb and ReportLab (and I needed those)

I agree with Max, the problem is somewhere else but it'll take time (I don't 
have to do a report but I do have to finish a web-based system over Linux)

In the mean time only have to say that your game rocks!!
I'll send you mine next week

Regards

Alberto



<html><div><IMG height=12 src="http://graphics.hotmail.com/emvamp.gif" 
width=12>&nbsp;Gaucho</div></html>




>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Alberto Troiano <albertito_g@hotmail.com>
>Subject: Re: [Tutor] crash - switching between text window and 
>graphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 16:10:02 -0700
>
>Alberto,
>
>The sorting works just fine on mine (and on my friends' computers
>too).  sort CAN take no arguments, but it can also take three - key,
>cmp, and reverse.  Perhaps you have an older version of something?
>
>~Denise
>
>On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > Hi
> >
> > The thing is this
> >
> > I get an error that says sort() has no arguments
> >
> > Th error is in the sentence
> > high_score.sort(reverse=TRUE)
> >
> > If you put just sort() it will work but the list will show from low to 
>high
> > and we don't want that 'cause if you make a high score it won't be able 
>to
> > know so you have to figure out another way to reverse the list
> >
> > Regards
> >
> > Alberto
> > >From: "D. Hartley" <denise.hartley@gmail.com>
> > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > >To: Alberto Troiano <albertito_g@hotmail.com>
> > >Subject: Re: [Tutor] crash - switching between text window and
> > >graphics/gamewindow (high score)
> > >Date: Wed, 20 Apr 2005 14:22:24 -0700
> > >
> > >Alberto,
> > >
> > >Thank you for replying! I sent answers to the general questions to the
> > >tutor list, so that hopefully the extra clarification might help
> > >someone else answer (I havent had much luck with this thread,
> > >unfortunately).  But I wanted to reply to you personally to send a
> > >copy of the game.  It's a "mod" of a game from pygame, but I've added
> > >a lot of stuff to it.  I'll send it as a zip file with two different
> > >"play" files - run the one simply called "play" to test out the game
> > >without the crash (oh, a side-note: the enemy ships will change
> > >graphics on levels 2 and 3, but they're not pretty - i just put those
> > >graphics in there as a place holder until i make their prettier
> > >replacements).  Anyway, the play file called "copy of play
> > >wscorelist2" is the copy with the scorelist that is crashing.  If you
> > >just want to see the *code*  you can look at either of those two
> > >files, but I thought you might want to play the actual game so I'm
> > >sending it all. Have fun :) Any comments/ideas/suggestions are very
> > >welcomed!! I'm having a couple friends test it out. But since I'm new
> > >I might not be able to take ALL of the suggestions before I have to
> > >have the game done next week, ha ha.
> > >
> > >Anyway thanks so much for replying, and for any help or suggestions
> > >you might have about the crash.
> > >
> > >~Denise
> > >
> > >P.S. if you dont have them, you'll need pygame and the livewires
> > >module, available at http://www.livewires.org.uk/python/lwpackage.html
> > >.  Thanks again!
> > >
> > >On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > > > Hey
> > > >
> > > > I'm curious
> > > >
> > > > What extension are you using on your game???????????
> > > > is it .py???????????????
> > > >
> > > > And what OS are you running the game???????????????
> > > >
> > > > Another thing. I made a space ship game to learn Python. Is there a
> > > > possibility that we exchange the games so we can know differents 
>points
> > >of
> > > > view????????
> > > >
> > > > I'll wait your reply
> > > >
> > > > Regards
> > > >
> > > > Alberto
> > > >
> > > > >From: "D. Hartley" <denise.hartley@gmail.com>
> > > > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > > > >To: Python tutor <tutor@python.org>
> > > > >Subject: [Tutor] crash - switching between text window and
> > > > >graphics/gamewindow (high score)
> > > > >Date: Tue, 19 Apr 2005 15:29:42 -0700
> > > > >
> > > > >Ok. I got in the working code to have a high score list, and it 
>even
> > > > >saves/loads one now (!!).  The only problem is, clicking back from 
>the
> > > > >text window to the game window (only after you entered in your name 
>to
> > > > >go onto the high score list), closes the program. you dont get to 
>say
> > > > >y/n to another game, it just shuts down. i cant run a debugger on 
>it,
> > > > >because the error doesnt happen when I F5-run the game from the 
>python
> > > > >IDLE script, only when i have ran it by doubleclicking on it (which 
>is
> > > > >how you're supposed to run it. otherwise it doesnt shut down
> > > > >properly). i really really REALLY want to keep the high score part 
>of
> > > > >my program, because i worked really hard to get this to work. but i
> > > > >have to have this program running with NO crashes in like a week 
>(it's
> > > > >a birthday present, and the birthday is approaching fast!)
> > > > >
> > > > >Here's the "end of game" code:
> > > > >
> > > > >             #game over..
> > > > >             if lives == 0:
> > > > >### trying addscore
> > > > >
> > > > >                 def add_score():
> > > > >  #                   high_scores = [(1000,"Denise"), 
>(945,"Denise"),
> > > > >   #                                 (883,"Denise"),(823,"Grant"),
> > > > >    #                                (779,"Aaron"), (702,"Pete"),
> > > > >     #                               (555,"Tom"), (443,"Tom"),
> > > > >      #                              (442,"Robin"), (4,"Pete")]
> > > > >                     high_scores = pickle.load(file("scores.pik"))
> > > > >                     score = total_enemy_hits
> > > > >                     if score > high_scores[-1][0]:
> > > > >                         print "Ta da! You got", total_enemy_hits,
> > > > >"Ranch Delivery Devices!"
> > > > >                         name = read_string("You made the high 
>score
> > > > >list! What's your name? ")
> > > > >                         user_score = (score,name)
> > > > >                         high_scores.append(user_score)
> > > > >                         high_scores.sort(reverse=True)
> > > > >                         del high_scores[-1]
> > > > >                         pickle.dump(high_scores, 
>file("scores.pik",
> > >"w"))
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                     else:
> > > > >                         print "Sorry, you only got", 
>total_enemy_hits,
> > > > >"Ranch Delivery Devices."
> > > > >                         print "You didn't quite make the high 
>score
> > >list!"
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                         print "Better luck next time!"
> > > > >
> > > > >  #               pdb.set_trace()
> > > > >                 add_score()
> > > > >
> > > > >                 end.play()
> > > > >                 showGameOver(screen, background_image)
> > > > >                 pygame.display.flip()
> > > > >
> > > > >
> > > > >                 answer = ""
> > > > >                 while not answer in ("y","n"):
> > > > >                    for event in pygame.event.get():
> > > > >                       if event.type == KEYDOWN:
> > > > >                          if event.key == K_n:
> > > > >                             answer = "n"
> > > > >                          elif event.key == K_y:
> > > > >                             answer = "y"
> > > > >                 if answer == "n":
> > > > >                     running = 0
> > > > >                 else:
> > > > >                     return 1
> > > > >
> > > > >             #refresh the display
> > > > >             pygame.event.pump()
> > > > >             pygame.display.flip()
> > > > >
> > > > >     #well, nice playing with you...
> > > > >     screen = pygame.display.set_mode((640, 480))
> > > > >     return 0
> > > > >
> > > > >
> > > > >Can anyone tell me why it crashes? you click to the text window 
>when
> > > > >there's the "congrats, you made the high score list, enter your 
>name"
> > > > >prompt, enter your name and hit enter, and it displays the high
> > > > >scores, with your name in it, just as it should. but then when you
> > > > >click back to the game screen, poof! it all closes.  Of course if 
>you
> > > > >dont make the high score list, you can click to the text window and
> > > > >click back to the game window and it operates like it should.
> > > > >
> > > > >Any suggestions would be appreciated!!  Again, I'd like to have it 
>do
> > > > >all this score stuff in the game/graphics window, and then it 
>wouldnt
> > > > >have that crash at all. But I dont know how to do that.
> > > > >
> > > > >Please help!
> > > > >
> > > > >Thanks again :)
> > > > >
> > > > >~Denise
> > > > >_______________________________________________
> > > > >Tutor maillist  -  Tutor@python.org
> > > > >http://mail.python.org/mailman/listinfo/tutor
> > > >
> > > > Gaucho
> > > >
> > > >
> > ><< zmine.zip >>
> >
> > Gaucho
> >
> >


From albertito_g at hotmail.com  Thu Apr 21 15:21:08 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu Apr 21 15:21:14 2005
Subject: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <8daabe5605042016102efd0ec5@mail.gmail.com>
Message-ID: <BAY106-F36E5930E1E89BF850946DE892C0@phx.gbl>

Hi

Sorry about that, I'm using Python 2.3.4 cause when Python 2.4 was released 
there wasn't libraries like MySQLdb and ReportLab (and I needed those)

I agree with Max, the problem is somewhere else but it'll take time (I don't 
have to do a report but I do have to finish a web-based system over Linux)

In the mean time only have to say that your game rocks!!
I'll send you mine next week

Regards

Alberto



<html><div><IMG height=12 src="http://graphics.hotmail.com/emvamp.gif" 
width=12>&nbsp;Gaucho</div></html>




>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Alberto Troiano <albertito_g@hotmail.com>
>Subject: Re: [Tutor] crash - switching between text window and 
>graphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 16:10:02 -0700
>
>Alberto,
>
>The sorting works just fine on mine (and on my friends' computers
>too).  sort CAN take no arguments, but it can also take three - key,
>cmp, and reverse.  Perhaps you have an older version of something?
>
>~Denise
>
>On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > Hi
> >
> > The thing is this
> >
> > I get an error that says sort() has no arguments
> >
> > Th error is in the sentence
> > high_score.sort(reverse=TRUE)
> >
> > If you put just sort() it will work but the list will show from low to 
>high
> > and we don't want that 'cause if you make a high score it won't be able 
>to
> > know so you have to figure out another way to reverse the list
> >
> > Regards
> >
> > Alberto
> > >From: "D. Hartley" <denise.hartley@gmail.com>
> > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > >To: Alberto Troiano <albertito_g@hotmail.com>
> > >Subject: Re: [Tutor] crash - switching between text window and
> > >graphics/gamewindow (high score)
> > >Date: Wed, 20 Apr 2005 14:22:24 -0700
> > >
> > >Alberto,
> > >
> > >Thank you for replying! I sent answers to the general questions to the
> > >tutor list, so that hopefully the extra clarification might help
> > >someone else answer (I havent had much luck with this thread,
> > >unfortunately).  But I wanted to reply to you personally to send a
> > >copy of the game.  It's a "mod" of a game from pygame, but I've added
> > >a lot of stuff to it.  I'll send it as a zip file with two different
> > >"play" files - run the one simply called "play" to test out the game
> > >without the crash (oh, a side-note: the enemy ships will change
> > >graphics on levels 2 and 3, but they're not pretty - i just put those
> > >graphics in there as a place holder until i make their prettier
> > >replacements).  Anyway, the play file called "copy of play
> > >wscorelist2" is the copy with the scorelist that is crashing.  If you
> > >just want to see the *code*  you can look at either of those two
> > >files, but I thought you might want to play the actual game so I'm
> > >sending it all. Have fun :) Any comments/ideas/suggestions are very
> > >welcomed!! I'm having a couple friends test it out. But since I'm new
> > >I might not be able to take ALL of the suggestions before I have to
> > >have the game done next week, ha ha.
> > >
> > >Anyway thanks so much for replying, and for any help or suggestions
> > >you might have about the crash.
> > >
> > >~Denise
> > >
> > >P.S. if you dont have them, you'll need pygame and the livewires
> > >module, available at http://www.livewires.org.uk/python/lwpackage.html
> > >.  Thanks again!
> > >
> > >On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > > > Hey
> > > >
> > > > I'm curious
> > > >
> > > > What extension are you using on your game???????????
> > > > is it .py???????????????
> > > >
> > > > And what OS are you running the game???????????????
> > > >
> > > > Another thing. I made a space ship game to learn Python. Is there a
> > > > possibility that we exchange the games so we can know differents 
>points
> > >of
> > > > view????????
> > > >
> > > > I'll wait your reply
> > > >
> > > > Regards
> > > >
> > > > Alberto
> > > >
> > > > >From: "D. Hartley" <denise.hartley@gmail.com>
> > > > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > > > >To: Python tutor <tutor@python.org>
> > > > >Subject: [Tutor] crash - switching between text window and
> > > > >graphics/gamewindow (high score)
> > > > >Date: Tue, 19 Apr 2005 15:29:42 -0700
> > > > >
> > > > >Ok. I got in the working code to have a high score list, and it 
>even
> > > > >saves/loads one now (!!).  The only problem is, clicking back from 
>the
> > > > >text window to the game window (only after you entered in your name 
>to
> > > > >go onto the high score list), closes the program. you dont get to 
>say
> > > > >y/n to another game, it just shuts down. i cant run a debugger on 
>it,
> > > > >because the error doesnt happen when I F5-run the game from the 
>python
> > > > >IDLE script, only when i have ran it by doubleclicking on it (which 
>is
> > > > >how you're supposed to run it. otherwise it doesnt shut down
> > > > >properly). i really really REALLY want to keep the high score part 
>of
> > > > >my program, because i worked really hard to get this to work. but i
> > > > >have to have this program running with NO crashes in like a week 
>(it's
> > > > >a birthday present, and the birthday is approaching fast!)
> > > > >
> > > > >Here's the "end of game" code:
> > > > >
> > > > >             #game over..
> > > > >             if lives == 0:
> > > > >### trying addscore
> > > > >
> > > > >                 def add_score():
> > > > >  #                   high_scores = [(1000,"Denise"), 
>(945,"Denise"),
> > > > >   #                                 (883,"Denise"),(823,"Grant"),
> > > > >    #                                (779,"Aaron"), (702,"Pete"),
> > > > >     #                               (555,"Tom"), (443,"Tom"),
> > > > >      #                              (442,"Robin"), (4,"Pete")]
> > > > >                     high_scores = pickle.load(file("scores.pik"))
> > > > >                     score = total_enemy_hits
> > > > >                     if score > high_scores[-1][0]:
> > > > >                         print "Ta da! You got", total_enemy_hits,
> > > > >"Ranch Delivery Devices!"
> > > > >                         name = read_string("You made the high 
>score
> > > > >list! What's your name? ")
> > > > >                         user_score = (score,name)
> > > > >                         high_scores.append(user_score)
> > > > >                         high_scores.sort(reverse=True)
> > > > >                         del high_scores[-1]
> > > > >                         pickle.dump(high_scores, 
>file("scores.pik",
> > >"w"))
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                     else:
> > > > >                         print "Sorry, you only got", 
>total_enemy_hits,
> > > > >"Ranch Delivery Devices."
> > > > >                         print "You didn't quite make the high 
>score
> > >list!"
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                         print "Better luck next time!"
> > > > >
> > > > >  #               pdb.set_trace()
> > > > >                 add_score()
> > > > >
> > > > >                 end.play()
> > > > >                 showGameOver(screen, background_image)
> > > > >                 pygame.display.flip()
> > > > >
> > > > >
> > > > >                 answer = ""
> > > > >                 while not answer in ("y","n"):
> > > > >                    for event in pygame.event.get():
> > > > >                       if event.type == KEYDOWN:
> > > > >                          if event.key == K_n:
> > > > >                             answer = "n"
> > > > >                          elif event.key == K_y:
> > > > >                             answer = "y"
> > > > >                 if answer == "n":
> > > > >                     running = 0
> > > > >                 else:
> > > > >                     return 1
> > > > >
> > > > >             #refresh the display
> > > > >             pygame.event.pump()
> > > > >             pygame.display.flip()
> > > > >
> > > > >     #well, nice playing with you...
> > > > >     screen = pygame.display.set_mode((640, 480))
> > > > >     return 0
> > > > >
> > > > >
> > > > >Can anyone tell me why it crashes? you click to the text window 
>when
> > > > >there's the "congrats, you made the high score list, enter your 
>name"
> > > > >prompt, enter your name and hit enter, and it displays the high
> > > > >scores, with your name in it, just as it should. but then when you
> > > > >click back to the game screen, poof! it all closes.  Of course if 
>you
> > > > >dont make the high score list, you can click to the text window and
> > > > >click back to the game window and it operates like it should.
> > > > >
> > > > >Any suggestions would be appreciated!!  Again, I'd like to have it 
>do
> > > > >all this score stuff in the game/graphics window, and then it 
>wouldnt
> > > > >have that crash at all. But I dont know how to do that.
> > > > >
> > > > >Please help!
> > > > >
> > > > >Thanks again :)
> > > > >
> > > > >~Denise
> > > > >_______________________________________________
> > > > >Tutor maillist  -  Tutor@python.org
> > > > >http://mail.python.org/mailman/listinfo/tutor
> > > >
> > > > Gaucho
> > > >
> > > >
> > ><< zmine.zip >>
> >
> > Gaucho
> >
> >


From denise.hartley at gmail.com  Thu Apr 21 19:34:32 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Thu Apr 21 19:34:36 2005
Subject: Fwd: [Tutor] crash - switching between text window and
	graphics/gamewindow (high score)
In-Reply-To: <BAY106-F36E5930E1E89BF850946DE892C0@phx.gbl>
References: <8daabe5605042016102efd0ec5@mail.gmail.com>
	<BAY106-F36E5930E1E89BF850946DE892C0@phx.gbl>
Message-ID: <8daabe5605042110341fbe48c4@mail.gmail.com>

Thanks for the encouragement!!

I'm going to be completing some further updates today and hope to post
a url where anyone can get the whole game and try it out.  I made a
fall-back version where the game displays not a high score list
requiring input in the text window, but only keeps track of the one
highest score and displays that (i.e., no names = no user input into
the console window = no crash).  That way if I can't find an answer to
the crash problem by next Thursday (holy crap, only one week), I'll
still have a working game I can give to him.

I'll let you guys know if I find anything, and will post the url as
soon as the game is uploaded.  And let me know if any ideas come to
you about the crash!

Thanks,
Denise

---------- Forwarded message ----------
From: Alberto Troiano <albertito_g@hotmail.com>
Date: Apr 21, 2005 6:21 AM
Subject: Re: [Tutor] crash - switching between text window and
graphics/gamewindow (high score)
To: denise.hartley@gmail.com
Cc: tutor@python.org


Hi

Sorry about that, I'm using Python 2.3.4 cause when Python 2.4 was released
there wasn't libraries like MySQLdb and ReportLab (and I needed those)

I agree with Max, the problem is somewhere else but it'll take time (I don't
have to do a report but I do have to finish a web-based system over Linux)

In the mean time only have to say that your game rocks!!
I'll send you mine next week

Regards

Alberto

<html><div><IMG height=12 src="http://graphics.hotmail.com/emvamp.gif"
width=12>Gaucho</div></html>

>From: "D. Hartley" <denise.hartley@gmail.com>
>Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>To: Alberto Troiano <albertito_g@hotmail.com>
>Subject: Re: [Tutor] crash - switching between text window and
>graphics/gamewindow (high score)
>Date: Wed, 20 Apr 2005 16:10:02 -0700
>
>Alberto,
>
>The sorting works just fine on mine (and on my friends' computers
>too).  sort CAN take no arguments, but it can also take three - key,
>cmp, and reverse.  Perhaps you have an older version of something?
>
>~Denise
>
>On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > Hi
> >
> > The thing is this
> >
> > I get an error that says sort() has no arguments
> >
> > Th error is in the sentence
> > high_score.sort(reverse=TRUE)
> >
> > If you put just sort() it will work but the list will show from low to
>high
> > and we don't want that 'cause if you make a high score it won't be able
>to
> > know so you have to figure out another way to reverse the list
> >
> > Regards
> >
> > Alberto
> > >From: "D. Hartley" <denise.hartley@gmail.com>
> > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > >To: Alberto Troiano <albertito_g@hotmail.com>
> > >Subject: Re: [Tutor] crash - switching between text window and
> > >graphics/gamewindow (high score)
> > >Date: Wed, 20 Apr 2005 14:22:24 -0700
> > >
> > >Alberto,
> > >
> > >Thank you for replying! I sent answers to the general questions to the
> > >tutor list, so that hopefully the extra clarification might help
> > >someone else answer (I havent had much luck with this thread,
> > >unfortunately).  But I wanted to reply to you personally to send a
> > >copy of the game.  It's a "mod" of a game from pygame, but I've added
> > >a lot of stuff to it.  I'll send it as a zip file with two different
> > >"play" files - run the one simply called "play" to test out the game
> > >without the crash (oh, a side-note: the enemy ships will change
> > >graphics on levels 2 and 3, but they're not pretty - i just put those
> > >graphics in there as a place holder until i make their prettier
> > >replacements).  Anyway, the play file called "copy of play
> > >wscorelist2" is the copy with the scorelist that is crashing.  If you
> > >just want to see the *code*  you can look at either of those two
> > >files, but I thought you might want to play the actual game so I'm
> > >sending it all. Have fun :) Any comments/ideas/suggestions are very
> > >welcomed!! I'm having a couple friends test it out. But since I'm new
> > >I might not be able to take ALL of the suggestions before I have to
> > >have the game done next week, ha ha.
> > >
> > >Anyway thanks so much for replying, and for any help or suggestions
> > >you might have about the crash.
> > >
> > >~Denise
> > >
> > >P.S. if you dont have them, you'll need pygame and the livewires
> > >module, available at http://www.livewires.org.uk/python/lwpackage.html
> > >.  Thanks again!
> > >
> > >On 4/20/05, Alberto Troiano <albertito_g@hotmail.com> wrote:
> > > > Hey
> > > >
> > > > I'm curious
> > > >
> > > > What extension are you using on your game???????????
> > > > is it .py???????????????
> > > >
> > > > And what OS are you running the game???????????????
> > > >
> > > > Another thing. I made a space ship game to learn Python. Is there a
> > > > possibility that we exchange the games so we can know differents
>points
> > >of
> > > > view????????
> > > >
> > > > I'll wait your reply
> > > >
> > > > Regards
> > > >
> > > > Alberto
> > > >
> > > > >From: "D. Hartley" <denise.hartley@gmail.com>
> > > > >Reply-To: "D. Hartley" <denise.hartley@gmail.com>
> > > > >To: Python tutor <tutor@python.org>
> > > > >Subject: [Tutor] crash - switching between text window and
> > > > >graphics/gamewindow (high score)
> > > > >Date: Tue, 19 Apr 2005 15:29:42 -0700
> > > > >
> > > > >Ok. I got in the working code to have a high score list, and it
>even
> > > > >saves/loads one now (!!).  The only problem is, clicking back from
>the
> > > > >text window to the game window (only after you entered in your name
>to
> > > > >go onto the high score list), closes the program. you dont get to
>say
> > > > >y/n to another game, it just shuts down. i cant run a debugger on
>it,
> > > > >because the error doesnt happen when I F5-run the game from the
>python
> > > > >IDLE script, only when i have ran it by doubleclicking on it (which
>is
> > > > >how you're supposed to run it. otherwise it doesnt shut down
> > > > >properly). i really really REALLY want to keep the high score part
>of
> > > > >my program, because i worked really hard to get this to work. but i
> > > > >have to have this program running with NO crashes in like a week
>(it's
> > > > >a birthday present, and the birthday is approaching fast!)
> > > > >
> > > > >Here's the "end of game" code:
> > > > >
> > > > >             #game over..
> > > > >             if lives == 0:
> > > > >### trying addscore
> > > > >
> > > > >                 def add_score():
> > > > >  #                   high_scores = [(1000,"Denise"),
>(945,"Denise"),
> > > > >   #                                 (883,"Denise"),(823,"Grant"),
> > > > >    #                                (779,"Aaron"), (702,"Pete"),
> > > > >     #                               (555,"Tom"), (443,"Tom"),
> > > > >      #                              (442,"Robin"), (4,"Pete")]
> > > > >                     high_scores = pickle.load(file("scores.pik"))
> > > > >                     score = total_enemy_hits
> > > > >                     if score > high_scores[-1][0]:
> > > > >                         print "Ta da! You got", total_enemy_hits,
> > > > >"Ranch Delivery Devices!"
> > > > >                         name = read_string("You made the high
>score
> > > > >list! What's your name? ")
> > > > >                         user_score = (score,name)
> > > > >                         high_scores.append(user_score)
> > > > >                         high_scores.sort(reverse=True)
> > > > >                         del high_scores[-1]
> > > > >                         pickle.dump(high_scores,
>file("scores.pik",
> > >"w"))
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                     else:
> > > > >                         print "Sorry, you only got",
>total_enemy_hits,
> > > > >"Ranch Delivery Devices."
> > > > >                         print "You didn't quite make the high
>score
> > >list!"
> > > > >                         for score, name in high_scores:
> > > > >                             slip = 30 - len(name)
> > > > >                             slip_amt = slip*" "
> > > > >                             prefix = 5*" "
> > > > >                             print prefix,name,slip_amt,score
> > > > >                         print "Better luck next time!"
> > > > >
> > > > >  #               pdb.set_trace()
> > > > >                 add_score()
> > > > >
> > > > >                 end.play()
> > > > >                 showGameOver(screen, background_image)
> > > > >                 pygame.display.flip()
> > > > >
> > > > >
> > > > >                 answer = ""
> > > > >                 while not answer in ("y","n"):
> > > > >                    for event in pygame.event.get():
> > > > >                       if event.type == KEYDOWN:
> > > > >                          if event.key == K_n:
> > > > >                             answer = "n"
> > > > >                          elif event.key == K_y:
> > > > >                             answer = "y"
> > > > >                 if answer == "n":
> > > > >                     running = 0
> > > > >                 else:
> > > > >                     return 1
> > > > >
> > > > >             #refresh the display
> > > > >             pygame.event.pump()
> > > > >             pygame.display.flip()
> > > > >
> > > > >     #well, nice playing with you...
> > > > >     screen = pygame.display.set_mode((640, 480))
> > > > >     return 0
> > > > >
> > > > >
> > > > >Can anyone tell me why it crashes? you click to the text window
>when
> > > > >there's the "congrats, you made the high score list, enter your
>name"
> > > > >prompt, enter your name and hit enter, and it displays the high
> > > > >scores, with your name in it, just as it should. but then when you
> > > > >click back to the game screen, poof! it all closes.  Of course if
>you
> > > > >dont make the high score list, you can click to the text window and
> > > > >click back to the game window and it operates like it should.
> > > > >
> > > > >Any suggestions would be appreciated!!  Again, I'd like to have it
>do
> > > > >all this score stuff in the game/graphics window, and then it
>wouldnt
> > > > >have that crash at all. But I dont know how to do that.
> > > > >
> > > > >Please help!
> > > > >
> > > > >Thanks again :)
> > > > >
> > > > >~Denise
> > > > >_______________________________________________
> > > > >Tutor maillist  -  Tutor@python.org
> > > > >http://mail.python.org/mailman/listinfo/tutor
> > > >
> > > > Gaucho
> > > >
> > > >
> > ><< zmine.zip >>
> >
> > Gaucho
> >
> >
From python at jayloden.com  Thu Apr 21 20:27:32 2005
From: python at jayloden.com (Jay Loden)
Date: Thu Apr 21 20:39:54 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
In-Reply-To: <13407195c8377d569c94837c179efbda@yahoo.fr>
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
	<6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>
	<13407195c8377d569c94837c179efbda@yahoo.fr>
Message-ID: <200504211927.33690.python@jayloden.com>

Rpm does in fact have dependency resolution, and rpm-based distributions use a 
package manager that can download the dependencies and install them for you - 
urpmi on mandrake, yum or apt4rpm on Fedora and Redhat, Yast on Suse

I've used all of these, they are all rpm based, and they all install 
dependencies. If you use the raw "rpm" command, even that will tell you 
"missing dependecy foo".

That being said, apt-get on debian is still my favorite (for sheer number of 
available packages), but urpmi on mandrake or Yast on Suse are quite 
excellent.

-Jay

On Wednesday 20 April 2005 04:17 pm, Max Noel wrote:
emerge and apt-get come to mind. rpm is inferior (no dependency
> resolution) but still does a good job, and I hear autopackage isn't
> bad.
From john.ertl at fnmoc.navy.mil  Thu Apr 21 21:33:43 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Thu Apr 21 21:30:27 2005
Subject: [Tutor] trouble setting the environment
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C62A@lanexc107p.fnmoc.navy.mil>

All,

I have program and init I want to "source" a .ksh file to set some
environment variables and then use those variables in my program.

Is this possible? I vaguely remember something about the system env and the
interpreters env being separate after the interpreter starts up.

For instance if I have a .ksh file called envSet.ksh:

#!/bin/ksh

unset OPSBIN

export OPSBIN=/u/ops/bin 

---end --

Then 
 
>>> os.system(". envSet.ksh")
0
>>> os.getenv("OPSBIN")
>>>

What is the 0.  I know that I can set the env using Python but all of the
correct env are in the .ksh files maintained by others.  I would hate to
have to take the .ksh and tread each line and if it is an export turn that
into a python  os.environ statement.

Any ideas.

Thanks 

John 
       
From dyoo at hkn.eecs.berkeley.edu  Thu Apr 21 21:38:20 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 21 21:38:33 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <42678093.4090102@tds.net>
Message-ID: <Pine.LNX.4.44.0504211234230.11682-100000@hkn.eecs.berkeley.edu>



[Kent]
> Strange. This example works for me on Win2K with Python 2.4.


[Ray]
> > Hoping that someone can help me here. I have been reading about
> > gnuplot and it's plotting functionality, so i decided to install this:
> > I downloaded the gnuplot windows function and then installed the
> > gnuplot.py file using the setut.py and install command all worked. I
> > also installed the numeric python.

[some error text cut]

> > Traceback (most recent call last):
> >   File "<pyshell#3>", line 1, in -toplevel-
> >     g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
> >   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 274, in
> > plot
> >     self.refresh()
> >   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 215, in
> > refresh
> >     self(self.plotcmd + ' ' + string.join(plotcmds, ', '))
> >   File "C:\Python23\Lib\site-packages\Gnuplot\_Gnuplot.py", line 199, in
> > __call__
> >     self.gnuplot(s)
> >   File "C:\Python23\Lib\site-packages\Gnuplot\gp_win32.py", line 125, in
> > __call__
> >     self.write(s + '\n')
> > IOError: [Errno 22] Invalid argument
> >
> > Has someone experienced the same issue above if so did you manage to
> > overcome it?

Hi Ray,

Yeah, it looks like Joshua Pollack ran into this issue three years ago:

    http://mail.python.org/pipermail/tutor/2002-September/017579.html

I'm going through the archive now to see if he was able to resolve the
problem ok.

You might also want to bring this up on the gnuplot-py-users mailing list:
I'm sure that they'd definitely know what was going on:

    http://lists.sourceforge.net/lists/listinfo/gnuplot-py-users

In the meantime, I'll continue to do some hunting in the mail archive.
*grin*

Good luck to you!

From dyoo at hkn.eecs.berkeley.edu  Thu Apr 21 21:56:43 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Apr 21 21:56:57 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <Pine.LNX.4.44.0504211234230.11682-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504211241300.11682-100000@hkn.eecs.berkeley.edu>


> Yeah, it looks like Joshua Pollack ran into this issue three years ago:
>
>     http://mail.python.org/pipermail/tutor/2002-September/017579.html
>
> I'm going through the archive now to see if he was able to resolve the
> problem ok.

Hi Ray,

Yikes, it looks like someone never really answered Joshua when he brought
up that question.  Ugh.  Let's fix this now.


My best guess right now is that the module can't find the gnuplot command.

'gp_win32' uses the popen() command to try to connect to the underlying
gnuplot engine, and if it's given a command that it doesn't know about,
we'll get the same kind of errors that you're seeing:

#######
>>> import os
>>> test = os.popen("foobar", "w")
>>> sh: line 1: foobar: command not found

>>>
#######

It's a bit disappointing that Python doesn't raise an exception at this
point.  I wonder if that can be fixed.

Anyway, after this point, all bets are off, and even if 'test' is some
kind of object, it doesn't behave well at all:

#######
>>> test
<open file 'foobar', mode 'w' at 0x60a60>
>>> test.write("hello world")
>>> test.flush()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 32] Broken pipe
#######


I'm on a Unix system, so the exact error looks a bit different from yours,
but I think that the fundamental problem is the same: the module will emit
exceptions when it actually starts to try talking to gnuplot, rather than
at the point of initialization.

It makes for a slightly confusing error message situation, since the error
about not finding gnuplot should have been reported earlier.


By default, gp_win32.py tries to use the command 'pgnuplot.exe' as the
gnuplot command:

###### (Within gp_win32.py)
    gnuplot_command = r'pgnuplot.exe'
######

So check to see if you can access the command 'pgnuplot.exe' from your
command line from anywhere.  If not, then that's the problem, and you'll
probably want to put pgnuplot.exe in your PATH somewhere.  Either that, or
manually munge up gp_win32.py so that it explicitely points to the
pgnuplot.exe binary with its full path.



You might not have pgnuplot.exe if you're running an older version of
Gnuplot.  Do you know what version of Gnuplot you have?  If you have one
whose version is < 3.7.1, then you probably need to grab pgnuplot.exe from
the gnuplot FTP site here:

    ftp://ftp.gnuplot.info/pub/gnuplot/testing/windows-stdin.zip

(Taken from the README.txt in the Python gnuplot module.)

But since that file is just C source code, it might just be best to make
sure you're running the latest version of Gnuplot, since it should include
pgnuplot.exe now.


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

From cpu.crazy at gmail.com  Thu Apr 21 16:43:28 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 21 22:02:34 2005
Subject: [Tutor] Re: Error Raising
In-Reply-To: <20050421132114.EB2F91E4015@bag.python.org>
References: <20050421132114.EB2F91E4015@bag.python.org>
Message-ID: <6.1.0.6.2.20050421084030.01ef4720@pop.gmail.com>

Ahh. I really like the ability to make my own exceptions. This info will 
help alot.
Thanks,
         Joe
PS. Would the Tutorial included with IDLE be the same as the site's docs?


>The standard (built-in) exceptions are documented here:
>http://docs.python.org/lib/module-exceptions.html
>
>If you don't find any that suit you, defining your own is as easy as
>
>class MyException(Exception):
>    pass
>
>....
>try:
>    raise MyException
>except MyException:
>    ...
>
>Kent

From cpu.crazy at gmail.com  Thu Apr 21 16:43:28 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu Apr 21 22:02:36 2005
Subject: [Tutor] Re: Error Raising
In-Reply-To: <20050421132114.EB2F91E4015@bag.python.org>
References: <20050421132114.EB2F91E4015@bag.python.org>
Message-ID: <6.1.0.6.2.20050421084030.01ef4720@pop.gmail.com>

Ahh. I really like the ability to make my own exceptions. This info will 
help alot.
Thanks,
         Joe
PS. Would the Tutorial included with IDLE be the same as the site's docs?


>The standard (built-in) exceptions are documented here:
>http://docs.python.org/lib/module-exceptions.html
>
>If you don't find any that suit you, defining your own is as easy as
>
>class MyException(Exception):
>    pass
>
>....
>try:
>    raise MyException
>except MyException:
>    ...
>
>Kent

From kent37 at tds.net  Thu Apr 21 22:18:40 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 22:18:44 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <4262FED500021AD4@mssazhh-int.msg.bluewin.ch>
References: <4262FED500021AD4@mssazhh-int.msg.bluewin.ch>
Message-ID: <42680AA0.3030205@tds.net>

ray007@bluemail.ch wrote:
> Hi 
> 
> I have also now tried this on version 2.4 and w2k.....no luck. Anything special
> with installing gnuplot or just extracting it and running the .exe..

No, nothing special that I remember. This thread on c.l.python has a suggestion at the end that
might help:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/523e2e6af79281af/67f29c3f09058a10?rnum=2&hl=en#67f29c3f09058a10

This thread suggests to make sure the executable is in your PATH environment variable:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/bcc75878335bf571/49322acb8520f46f?hl=en#49322acb8520f46f

Actually they are both suggesting the same thing, that the exe is not being found.

Kent


From kent37 at tds.net  Thu Apr 21 22:20:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 22:20:36 2005
Subject: [Tutor] trouble setting the environment
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C62A@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C62A@lanexc107p.fnmoc.navy.mil>
Message-ID: <42680B0D.3040307@tds.net>

Ertl, John wrote:
> All,
> 
> I have program and init I want to "source" a .ksh file to set some
> environment variables and then use those variables in my program.
> 
> Is this possible? I vaguely remember something about the system env and the
> interpreters env being separate after the interpreter starts up.

What about making a shell file that sources your ksh file, then starts python?

Kent

> 
> For instance if I have a .ksh file called envSet.ksh:
> 
> #!/bin/ksh
> 
> unset OPSBIN
> 
> export OPSBIN=/u/ops/bin 
> 
> ---end --
> 
> Then 
>  
> 
>>>>os.system(". envSet.ksh")
> 
> 0
> 
>>>>os.getenv("OPSBIN")
>>>>
> 
> 
> What is the 0.  I know that I can set the env using Python but all of the
> correct env are in the .ksh files maintained by others.  I would hate to
> have to take the .ksh and tread each line and if it is an export turn that
> into a python  os.environ statement.
> 
> Any ideas.
> 
> Thanks 
> 
> John 
>        
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Thu Apr 21 22:22:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 22:22:29 2005
Subject: [Tutor] Re: Error Raising
In-Reply-To: <6.1.0.6.2.20050421084030.01ef4720@pop.gmail.com>
References: <20050421132114.EB2F91E4015@bag.python.org>
	<6.1.0.6.2.20050421084030.01ef4720@pop.gmail.com>
Message-ID: <42680B81.50201@tds.net>

Joseph Quigley wrote:
> PS. Would the Tutorial included with IDLE be the same as the site's docs?

Yes, I think so, though the site docs might be slightly newer, they are updated occasionally.

Kent

From john.ertl at fnmoc.navy.mil  Thu Apr 21 22:28:57 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Thu Apr 21 22:25:52 2005
Subject: [Tutor] trouble setting the environment
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C62D@lanexc107p.fnmoc.navy.mil>

Kent,

Good idea except that the environment that needs to be set depends on the
answers to some of the input that I get in the Python program.   Nothing is
ever easy here.

Thanks for the ideas.

John Ertl 

-----Original Message-----
From: Kent Johnson [mailto:kent37@tds.net]
Sent: Thursday, April 21, 2005 13:20
Cc: tutor@python.org
Subject: Re: [Tutor] trouble setting the environment

Ertl, John wrote:
> All,
>
> I have program and init I want to "source" a .ksh file to set some
> environment variables and then use those variables in my program.
>
> Is this possible? I vaguely remember something about the system env and
the
> interpreters env being separate after the interpreter starts up.

What about making a shell file that sources your ksh file, then starts
python?

Kent

>
> For instance if I have a .ksh file called envSet.ksh:
>
> #!/bin/ksh
>
> unset OPSBIN
>
> export OPSBIN=/u/ops/bin
>
> ---end --
>
> Then
> 
>
>>>>os.system(". envSet.ksh")
>
> 0
>
>>>>os.getenv("OPSBIN")
>>>>
>
>
> What is the 0.  I know that I can set the env using Python but all of the
> correct env are in the .ksh files maintained by others.  I would hate to
> have to take the .ksh and tread each line and if it is an export turn that
> into a python  os.environ statement.
>
> Any ideas.
>
> Thanks
>
> John
>       
> _______________________________________________
> 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 albertito_g at hotmail.com  Thu Apr 21 22:30:54 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu Apr 21 22:30:58 2005
Subject: [Tutor] TKinter and things over Linux
In-Reply-To: <183691066210.20050420195321@columbus.rr.com>
Message-ID: <BAY106-F131C5485CEC48FECEB2D0892C0@phx.gbl>

Hey all

Thanks for all your help. I solved the problem by installing ALL the 
packages of Red Hat 9.0 so basically I have 5 GB of OS in my HD haha :D

I must something you said about the development libraries but I really don't 
have time to find out which one so I install them all

Thanks again and sorry for the troubles I may had cause

Best regards

Alberto


>From: "R. Alan Monroe" <amonroe@columbus.rr.com>
>Reply-To: "R. Alan Monroe" <amonroe@columbus.rr.com>
>To: Tutor Python <tutor@python.org>
>Subject: Re: [Tutor] TKinter and things over Linux
>Date: Wed, 20 Apr 2005 19:53:21 -0400
>
>
> > apt-get and yum are available for Redhat style releases.  They will
> > download and install packages and figure out the dependency issues.
> > (yum is written in Python so this is slightly on topic.)
>
>Gentoo's "emerge" system is also written in Python.
>
>Alan
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From kent37 at tds.net  Thu Apr 21 22:49:15 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu Apr 21 22:49:19 2005
Subject: [Tutor] trouble setting the environment
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C62D@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C62D@lanexc107p.fnmoc.navy.mil>
Message-ID: <426811CB.2010205@tds.net>

Ertl, John wrote:
> Kent,
> 
> Good idea except that the environment that needs to be set depends on the
> answers to some of the input that I get in the Python program.   Nothing is
> ever easy here.

Maybe you could write a Python program that asks the questions, then spawns a shell task which sets 
the correct environment and runs another Python program that does the rest of the work?

Or, a ksh wrapper that sources the right program then outputs its environment to a .py file that you 
can import to get the config?

Just don't give me credit for the idea, I don't want to have anything to do with it :-)

Kent

> -----Original Message-----
> From: Kent Johnson [mailto:kent37@tds.net]
> Sent: Thursday, April 21, 2005 13:20
> Cc: tutor@python.org
> Subject: Re: [Tutor] trouble setting the environment
> 
> Ertl, John wrote:
> 
>>All,
>>
>>I have program and init I want to "source" a .ksh file to set some
>>environment variables and then use those variables in my program.
>>
>>Is this possible? I vaguely remember something about the system env and
> 
> the
> 
>>interpreters env being separate after the interpreter starts up.
> 
> 
> What about making a shell file that sources your ksh file, then starts
> python?
> 
> Kent
> 

From alan.gauld at freenet.co.uk  Thu Apr 21 22:58:17 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 22:57:15 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com>
	<01b101c54468$c6db1020$728f8651@xp>
	<6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>
Message-ID: <000e01c546b4$d80c75c0$728f8651@xp>

> Then again, how many free installers are there for linux?

The two most common are Red Hat's Package Manager (rpm) and 
the GNU apt-get system. But other distros also have install 
systems and so far as I know they are all free. But OTOH 
its also much easier to write a Unix installer since it 
simply involves copying files to some standard places 
and editing some plain text files.

There are some commercial installers that will target 
Windows and Linux from the same basic setup data. 
But I've never used them so can't comment on how 
well they work!

Alan G.


From john.ertl at fnmoc.navy.mil  Thu Apr 21 23:01:17 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Thu Apr 21 22:58:01 2005
Subject: [Tutor] trouble setting the environment
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C62E@lanexc107p.fnmoc.navy.mil>

Kent,

Like you allude ...a bit too much "what the heck is that" going on.  I will
give a few other things a try...I may just have to have the program run and
get the info then stop and have the user source the correct .ksh then run
another py program.  (basically the same thing but manually).

Thanks,

John Ertl  

-----Original Message-----
From: Kent Johnson [mailto:kent37@tds.net]
Sent: Thursday, April 21, 2005 13:49
Cc: tutor@python.org
Subject: Re: [Tutor] trouble setting the environment

Ertl, John wrote:
> Kent,
>
> Good idea except that the environment that needs to be set depends on the
> answers to some of the input that I get in the Python program.   Nothing
is
> ever easy here.

Maybe you could write a Python program that asks the questions, then spawns
a shell task which sets
the correct environment and runs another Python program that does the rest
of the work?

Or, a ksh wrapper that sources the right program then outputs its
environment to a .py file that you
can import to get the config?

Just don't give me credit for the idea, I don't want to have anything to do
with it :-)

Kent

> -----Original Message-----
> From: Kent Johnson [mailto:kent37@tds.net]
> Sent: Thursday, April 21, 2005 13:20
> Cc: tutor@python.org
> Subject: Re: [Tutor] trouble setting the environment
>
> Ertl, John wrote:
>
>>All,
>>
>>I have program and init I want to "source" a .ksh file to set some
>>environment variables and then use those variables in my program.
>>
>>Is this possible? I vaguely remember something about the system env and
>
> the
>
>>interpreters env being separate after the interpreter starts up.
>
>
> What about making a shell file that sources your ksh file, then starts
> python?
>
> Kent
>

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From alan.gauld at freenet.co.uk  Thu Apr 21 23:04:03 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 23:04:39 2005
Subject: [Tutor] Dynamically composing a module name
References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D2E3@riv-excha5.echostar.com><42654E1D.1030601@po-box.mcgill.ca><024601c54516$c9104190$728f8651@xp><20050419202239.GC6459@johnsons-web.com><025d01c54532$666d7d20$728f8651@xp>
	<20050419234442.GD6459@johnsons-web.com>
Message-ID: <002501c546b5$a6b8a1f0$728f8651@xp>

>   Inside of the setup() function, a call to the cgi object
determines
>   the name of the calling application (form1,py ... etc.) and
>   then imports another module (automatically generated from another
>   process), always having the same members, composing that auto
module
>   name from the name of the calling application:  form1.py =>
>   form1_extra.py......  And if I have to change the algorithm that
>   determines the name of the module imported or the names of the
>   members of the modules, I could just do it in two places:
>   the setup() function and the application generating the auto
modules
>   (which isn't necessarily written in python).

This sounds to me like a description of an object oriented design
using inheritance and polymorphism. An abstract class that defines
a standard set of methods that are called in a generic way which
may be substituted at runtime by any one of a number of subclasses
each implementing their own specialised version of the generic
behaviour.

The snag with importing at point of use is that importing a newly
created module is one of the slowest things you an do in Python - it
has to compile it and then read it and then execute it! If you
can load the moules in advance somehow (maybe in a thread?) there
might be significant gains...

Alan G.

From alan.gauld at freenet.co.uk  Thu Apr 21 23:10:06 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 23:11:21 2005
Subject: [Tutor] How to obfuscate a database password. (fwd)
References: <Pine.LNX.4.44.0504192005010.12510-100000@hkn.eecs.berkeley.edu>
Message-ID: <003001c546b6$7ea9b310$728f8651@xp>

> I am not necessarily talking about passwords for users but about the
> password that is used for connecting to the database. In a compiled
> language you would have to look pretty hard in a dll to find where
the
> password had been encoded.

IT would be insanely bad practice to embed the password in the code,
compiled or not. (And in fact its very easy to strip all the strings
out of a compiled executable - the strings command on unix does
exactly that...) BUt the real problem is that if the database gets
hacked the database administrator can't change the pasword unless
he can also edit the application source code and rebuild it!

It is normal practice to have the password stored in a text file
(that may be encrypted) and read it on startup of the program, or
better still to pass the login details(username and password) in
as startup command line parameters. That way the application
can access multiple databases etc, or different tablespaces in
the same instance etc etc. It's much more flexible and powerful
as well as being much more secure.

HTH,

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

From alan.gauld at freenet.co.uk  Thu Apr 21 23:13:01 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 23:12:03 2005
Subject: [Tutor] Installation Routines (Joseph Quigley)
References: <6.1.0.6.2.20050418145022.01ef14d8@pop.gmail.com><01b101c54468$c6db1020$728f8651@xp><6.1.0.6.2.20050419170110.01ed9a80@pop.gmail.com>
	<13407195c8377d569c94837c179efbda@yahoo.fr>
Message-ID: <004b01c546b6$e70083d0$728f8651@xp>

> Also, there was a project at some point that aimed at making Linux
> applications into self-contained "executable folders" (like .app
> bundles in Mac OS X). I don't remember the name, but I recall
Rox-filer
> supports it.

Tcl/Tk now comes in such a bundle, it makes installation a breeze
and you can carry it around on a USB memory stick. I love it.

Alan G.

From alan.gauld at freenet.co.uk  Thu Apr 21 23:19:06 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 23:18:31 2005
Subject: [Tutor] trouble setting the environment
References: <E338ADD616B66043824B9ABF5CA6EF2332C62A@lanexc107p.fnmoc.navy.mil>
Message-ID: <009401c546b7$c103fa30$728f8651@xp>

> Is this possible? I vaguely remember something about the system env
and the
> interpreters env being separate after the interpreter starts up.

When you execute another process it gets its own environment.
When it dies its environment dies with it. You can get round
this in your case by forking the child process and reading the
environment variables and writing them back via a pipe to the
original program - messy but it works!

> >>> os.system(". envSet.ksh")
> 0
> >>> os.getenv("OPSBIN")
> >>>
>
> What is the 0.

The return value from os.system(). It basically means the command
ran without errors. Not too useful normally. popen() is better
if you want to read the output (it basically does the fork/pipe
thing automagically for you) So if you popen a script that runs
your ksh file then prints the environment variables, you can read
them into your program...

HTH,

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

From alan.gauld at freenet.co.uk  Thu Apr 21 23:20:16 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 21 23:19:17 2005
Subject: [Tutor] Re: Error Raising
References: <20050421132114.EB2F91E4015@bag.python.org>
	<6.1.0.6.2.20050421084030.01ef4720@pop.gmail.com>
Message-ID: <009b01c546b7$ea3e7b50$728f8651@xp>

The tutorial is one of the documents, but you should have downloaded
all of the documentation for the current version, not just the tutor.

Alan G.

----- Original Message ----- 
From: "Joseph Quigley" <cpu.crazy@gmail.com>
To: <tutor@python.org>; <tutor@python.org>
Sent: Thursday, April 21, 2005 3:43 PM
Subject: [Tutor] Re: Error Raising


> Ahh. I really like the ability to make my own exceptions. This info
will
> help alot.
> Thanks,
>          Joe
> PS. Would the Tutorial included with IDLE be the same as the site's
docs?
>
>
> >The standard (built-in) exceptions are documented here:
> >http://docs.python.org/lib/module-exceptions.html
> >
> >If you don't find any that suit you, defining your own is as easy
as
> >
> >class MyException(Exception):
> >    pass
> >
> >....
> >try:
> >    raise MyException
> >except MyException:
> >    ...
> >
> >Kent
>
>
>

From dreamz93 at gmail.com  Thu Apr 21 23:30:05 2005
From: dreamz93 at gmail.com (dreamz93)
Date: Thu Apr 21 23:30:08 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <42680AA0.3030205@tds.net>
References: <4262FED500021AD4@mssazhh-int.msg.bluewin.ch>
	<42680AA0.3030205@tds.net>
Message-ID: <ae850ae2050421143073bd60b6@mail.gmail.com>

Hello,

I just ran into a similar problem. Here's what I found:

http://sourceforge.net/tracker/index.php?func=detail&aid=416091&group_id=17434&atid=217434

Just follow the instructions on the link and everything should work
fine. I think it has to do with emulating the unix pipe not being
available on windows, but I'm not sure. After I did this everything
worked fine.

Hope this works for you,
Chris

On 4/21/05, Kent Johnson <kent37@tds.net> wrote:
> ray007@bluemail.ch wrote:
> > Hi
> >
> > I have also now tried this on version 2.4 and w2k.....no luck. Anything special
> > with installing gnuplot or just extracting it and running the .exe..
> 
> No, nothing special that I remember. This thread on c.l.python has a suggestion at the end that
> might help:
> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/523e2e6af79281af/67f29c3f09058a10?rnum=2&hl=en#67f29c3f09058a10
> 
> This thread suggests to make sure the executable is in your PATH environment variable:
> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/bcc75878335bf571/49322acb8520f46f?hl=en#49322acb8520f46f
> 
> Actually they are both suggesting the same thing, that the exe is not being found.
> 
> Kent
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From ray007 at bluemail.ch  Fri Apr 22 05:14:17 2005
From: ray007 at bluemail.ch (ray007@bluemail.ch)
Date: Fri Apr 22 05:17:21 2005
Subject: [Tutor] GNUPLOT
In-Reply-To: <ae850ae2050421143073bd60b6@mail.gmail.com>
Message-ID: <4262FED5000274B7@mssazhh-int.msg.bluewin.ch>

Hi all

I thank you all who have particapted in solving/providing good feedback to
this GNUPLOT issue. I have managed to get this to work it was just simply
adding the following path to the gp_win32.py file under the site packages:

gnuplot_command = r'"C:\Program Files\gp373w32\pgnuplot.exe"'

many thanks

Ray

>-- Original-Nachricht --
>Date: Thu, 21 Apr 2005 14:30:05 -0700
>From: dreamz93 <dreamz93@gmail.com>
>To: tutor@python.org
>Subject: Re: [Tutor] GNUPLOT
>Reply-To: dreamz93 <dreamz93@gmail.com>
>
>
>Hello,
>
>I just ran into a similar problem. Here's what I found:
>
>http://sourceforge.net/tracker/index.php?func=detail&aid=416091&group_id=17434&atid=217434
>
>Just follow the instructions on the link and everything should work
>fine. I think it has to do with emulating the unix pipe not being
>available on windows, but I'm not sure. After I did this everything
>worked fine.
>
>Hope this works for you,
>Chris
>
>On 4/21/05, Kent Johnson <kent37@tds.net> wrote:
>> ray007@bluemail.ch wrote:
>> > Hi
>> >
>> > I have also now tried this on version 2.4 and w2k.....no luck. Anything
>special
>> > with installing gnuplot or just extracting it and running the .exe..
>> 
>> No, nothing special that I remember. This thread on c.l.python has a suggestion
>at the end that
>> might help:
>> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/523e2e6af79281af/67f29c3f09058a10?rnum=2&hl=en#67f29c3f09058a10
>> 
>> This thread suggests to make sure the executable is in your PATH environment
>variable:
>> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/bcc75878335bf571/49322acb8520f46f?hl=en#49322acb8520f46f
>> 
>> Actually they are both suggesting the same thing, that the exe is not
being
>found.
>> 
>> Kent
>> 
>> 
>> _______________________________________________
>> 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 smichr at bigfoot.com  Fri Apr 22 01:07:08 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 22 06:48:17 2005
Subject: [Tutor] Weird import problem with PythonIDE on Mac (was 'import
	problem')
In-Reply-To: <20050421132114.EB2F91E4015@bag.python.org>
Message-ID: <15D74868-B2BA-11D9-9F38-000393C0D100@bigfoot.com>

> From: Kent Johnson
> Is it possible that the script is not running as __main__? Add
> print __name__
> to the script and see what it says...
>
>

It says '__main__'.  Here is the end of the output after printing 
vars() if that helps:

'__file__': '/Users/csmith/Desktop/misc python/timeit eg.py',
't': <timeit.Timer instance at 0x1ed5dc8>,
'y1': <function y1 at 0x1eed4f0>,
'__name__': '__main__',
'y2': <function y2 at 0x1eed530>

/c

From smichr at bigfoot.com  Fri Apr 22 03:06:47 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 22 06:48:22 2005
Subject: [Tutor] Re: Weird import problem with PythonIDE on Mac (was 'import
	problem')
Message-ID: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>

###
def y1():
     pass
def foo():
     from __main__ import y1
     pass
foo()
###

Here is a version of the code, stripped of the timeit code.  The above 
segment exhibits the same symptoms as the previously submitted one.

Even though I am running this as "__main__" it behaves as though it is 
not __main__. i.e. if I run this with pyOxide without the 'run as 
__main__' option, it generates the same ImportError ('Can't import y1') 
as it does when run in the PythonIDE.

In the pythonIDE it generates the error whether the 'run as __main__' 
option is on or off. As a test of that option, I verified that the 
following code only runs when the __main__ option is on and it worked 
as expected:

###
if __name__=='__main__':
	print 'running as main'
###

/c

From bds at waywood.co.uk  Fri Apr 22 10:15:13 2005
From: bds at waywood.co.uk (Barnaby Scott)
Date: Fri Apr 22 10:16:51 2005
Subject: [Tutor] Is self.__init__() call bad style?
Message-ID: <000001c54713$693f1620$7c00a8c0@frankbruno>

I am working on a script at the moment, in which I seem to need to
re-initialise a class instance from within some of its methods. Before I go
too much further down this route - could anyone comment on whether the call
self.__init__() is in itself considered bad style or 'unpythonic'?

For instance, is it better to create a 'reset' method, which is called both
by __init__ and by the methods which are wanting to force a
re-initialisation?

I would be happy to post some of the code, but perhaps there is a general
consensus about this anyway?

Thanks

From kent37 at tds.net  Fri Apr 22 12:17:04 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 12:17:08 2005
Subject: [Tutor] Weird import problem with PythonIDE on Mac (was 'import
	problem')
In-Reply-To: <15D74868-B2BA-11D9-9F38-000393C0D100@bigfoot.com>
References: <15D74868-B2BA-11D9-9F38-000393C0D100@bigfoot.com>
Message-ID: <4268CF20.7060706@tds.net>

This looks like a bug in PythonIDE to me. I fired up my Mac and tried this in PythonIDE with Python 
2.3.3:

def f():
     print 'executed f'

code = '''
print 'name:', __name__
import __main__
print dir(__main__)
from __main__ import f
f()
'''

exec code in globals(), {}

It prints
name: __main__

then a dict with no 'f' in it, then an import error.

Maybe you should try mac-sig again?

Kent

Chris Smith wrote:
>> From: Kent Johnson
>> Is it possible that the script is not running as __main__? Add
>> print __name__
>> to the script and see what it says...
>>
>>
> 
> It says '__main__'.  Here is the end of the output after printing vars() 
> if that helps:
> 
> '__file__': '/Users/csmith/Desktop/misc python/timeit eg.py',
> 't': <timeit.Timer instance at 0x1ed5dc8>,
> 'y1': <function y1 at 0x1eed4f0>,
> '__name__': '__main__',
> 'y2': <function y2 at 0x1eed530>
> 
> /c
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Fri Apr 22 12:18:09 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 12:18:15 2005
Subject: [Tutor] Is self.__init__() call bad style?
In-Reply-To: <000001c54713$693f1620$7c00a8c0@frankbruno>
References: <000001c54713$693f1620$7c00a8c0@frankbruno>
Message-ID: <4268CF61.3030809@tds.net>

Barnaby Scott wrote:
> I am working on a script at the moment, in which I seem to need to
> re-initialise a class instance from within some of its methods. Before I go
> too much further down this route - could anyone comment on whether the call
> self.__init__() is in itself considered bad style or 'unpythonic'?
> 
> For instance, is it better to create a 'reset' method, which is called both
> by __init__ and by the methods which are wanting to force a
> re-initialisation?

Personally I would make a reset() method, the intent is clearer and it is less prone to breakage if 
for some reason you change __init__ later.

Kent

From smichr at bigfoot.com  Fri Apr 22 12:41:11 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Fri Apr 22 12:42:12 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Weird import problem with PythonIDE on
	Mac (was 'import problem')
In-Reply-To: <r01050400-1039-E758073EB30B11D99D53001124365170@[10.0.0.24]>
Message-ID: <0AE73573-B31B-11D9-9F38-000393C0D100@bigfoot.com>


On Friday, Apr 22, 2005, at 03:52 America/Chicago, Just van Rossum - 
just@letterror.com wrote:

> Importing __main__ is a very silly thing to do anyway, if you ask me.
>

All comments from you, Bob, and Jack have been *very* helpful.  I think 
I understand better what is going on.  What's got me scratching my head 
is that I thought it worked several at one time, but I must have been 
misunderstanding what script was actually being run. (?)

Anyway, as to importing from main, I was trying to learn to use the 
timeit module and wanted to be able to pass functions to it (rather 
than literal strings of code).  The init of timeit takes the strings 
you pass and creates a function that is exec'ed.

Do you have a suggestion as to what can I give a module so it has 
enough information to execute a function that resides in __main__? Here 
is a visual of what is going on:

------__main__
def y1():
   pass
import foo
foo.run(string_from_main) #what should I pass?

------external module, foo

def run(string_from_main):
	#
	exec(string_from_main) #y1 is run as if it were in __main__


/c

From work at infomaniak.ch  Fri Apr 22 13:44:28 2005
From: work at infomaniak.ch (Cedric BRINER)
Date: Fri Apr 22 12:51:43 2005
Subject: [Tutor] incomprehension in type of classes.
Message-ID: <20050422114428.GA7469@obs.unige.ch>

hello,

I have 2 questions. the first one is maybe not directly related to python (it's about eric3), and the second oneis about what the command `type' give back for two instances

in my python code I have changed some classes like the following

from (I):

class CYear:
   def __init__(self, year):
      self.__year=year
      print str(self.__year)             <<---(*)
      print 'dir of: '+str(dir(self))
      print 'type of: '+str(type(self))
   def __str__(self):
      return "we are in "+str(self.year)


to (IIOB):

class CYearDerived(int):
   def __init__(self, year):
      super(CYearDerived,self).__init__(year)
      self.__year=year
      print str(self.__year)            <<-----(*OB)
      print 'dir of: '+str( dir(self) )
      print 'type of: '+str(type(self))
   def __str__(self):
      return "we are in "+super(CYearDerived,self).__str__()



Question 1 (about eric3)
----------
with the change from I to II, when I debug the code, I don't see the self arborescence (that you find in Window Debug Browser>>Local Variables) which shows you the attributes of the class that you are currently debugging in.


Quesion 2
---------
why type of (CYear(2005))
<type 'instance'>

and type(CYearDerived)
<class '__main__.CYearDerived'>

doesn't give the same type ???

-- 

Cedric BRINER
From alan.gauld at freenet.co.uk  Fri Apr 22 13:02:47 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr 22 13:02:42 2005
Subject: [Tutor] Is self.__init__() call bad style?
References: <000001c54713$693f1620$7c00a8c0@frankbruno>
Message-ID: <001801c5472a$d4bf9110$dad48651@xp>


> I am working on a script at the moment, in which I seem to need to
> re-initialise a class instance from within some of its methods.
Before I go
> too much further down this route - could anyone comment on whether
the call
> self.__init__() is in itself considered bad style or 'unpythonic'?

NO its perfectly normal OOP style, in Python or otherwise.

> For instance, is it better to create a 'reset' method, which is
called both
> by __init__ and by the methods which are wanting to force a
> re-initialisation?

Some folks seem to prefer that technique (and it's necessary in
Java/C++
where the constructor cannot be called directly) but it adds very
little
benefit IMHO. init() is for initialisation and if you are sure you
want
to reset everything to default then why not use it.

Alan G.

From kent37 at tds.net  Fri Apr 22 14:07:18 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 14:07:20 2005
Subject: [Tutor] incomprehension in type of classes.
In-Reply-To: <20050422114428.GA7469@obs.unige.ch>
References: <20050422114428.GA7469@obs.unige.ch>
Message-ID: <4268E8F6.6020704@tds.net>

Cedric BRINER wrote:
> in my python code I have changed some classes like the following
> 
> from (I):
> 
> class CYear:
>    def __init__(self, year):
>       self.__year=year
>       print str(self.__year)             <<---(*)
>       print 'dir of: '+str(dir(self))
>       print 'type of: '+str(type(self))
>    def __str__(self):
>       return "we are in "+str(self.year)
> 
> 
> to (IIOB):
> 
> class CYearDerived(int):
>    def __init__(self, year):
>       super(CYearDerived,self).__init__(year)
>       self.__year=year
>       print str(self.__year)            <<-----(*OB)
>       print 'dir of: '+str( dir(self) )
>       print 'type of: '+str(type(self))
>    def __str__(self):
>       return "we are in "+super(CYearDerived,self).__str__()

> why type of (CYear(2005))
> <type 'instance'>
> 
> and type(CYearDerived)
> <class '__main__.CYearDerived'>
> 
> doesn't give the same type ???

It's a difference between new-style and old-style classes. CYear is an old-style class because it 
doesn't inherit from object. CYearDerived is a new-style class because it inherits from int which is 
a subtype of object:

  >>> class C: pass # old-style class
  ...
  >>> type(C())
<type 'instance'>
  >>> C().__class__
<class __main__.C at 0x008CE7B0>

  >>> class C2(object): pass # new-style class
  ...
  >>> type(C2())
<class '__main__.C2'>
  >>> C2().__class__
<class '__main__.C2'>

  >>> int.__bases__ # int inherits from object
(<type 'object'>,)

I'm not sure *why* there is this difference between the two types of classes, but there is...

By the way extending int does not work the way you have done it here. int is an immutable type so 
you have to initialize it in the __new__() method, not in __init__(). Read the details here:
http://www.python.org/2.2/descrintro.html#__new__

Kent

From kristian at zimmer428.net  Fri Apr 22 16:16:05 2005
From: kristian at zimmer428.net (Kristian Rink)
Date: Fri Apr 22 16:16:18 2005
Subject: [Tutor] SOAPPy - server and threading?
Message-ID: <20050422141605.C09EC384094@dd3334.kasserver.com>

Hi all;

just hope I'm not completely OT with this here; if so, I sincerely apologize... At the moment, I am trying to implement a small client/server system that communicate using SOAP, and for each client to connect to the SOAP server (via HTTP) I wanted to run a thread which exclusively is responsible to serve that very client.

My problem is: Currently I create a SOAPServer and make it available using serve_forever(). I want to put this into several threads, as well, but I read about having to manually send threads to sleep in Python to allow other threads to be processed within the "parent" process. serve_forever() in SOAPServer, anyhow, only terminates if the process is interrupted or killed.

So, do I have a chance to put a SOAPServer into threads in Python, or do I have to search for a solution other than SOAPPy?

TIA and bye,
Kris

From mhansen at cso.atmel.com  Fri Apr 22 16:04:26 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Fri Apr 22 16:16:40 2005
Subject: [Tutor] Pychecker
Message-ID: <4269046A.5090808@cso.atmel.com>

I had a frustrating time yesterday with a small Python program I wrote. I wasn't 
getting the results I expected, so I sprinkled print statements through it. I 
wasn't getting anywhere. I tossed it into Komodo to see if the background syntax 
checker would pick up something I was missing. I then stepped through it and 
finally noticed that I had messed up a variable name.

firstlist = [listItem[:12] for listItem in firstList]
      ^
when I meant

firstList = [listItem[:12] for listItem in firstList]
      ^
doh!

Later, I realized that I should have run it through Pychecker which would have 
picked it up immediately.

With that experience of learning the hard way, I'd recommend that you always run 
your code through Pychecker just after editing it and before running it.

In Perl, you can perl -c somehardtoreadperlprogram.pl that will just check the 
syntax. The above problem would have been caught in Perl since I always use 
strict. Is there a command line option in Python to do a Pychecker-like syntax 
check? I see a -t to check the tabs, but nothing to tell it to check the syntax 
but don't run it. If not, should Pychecker be part of the standard distribution? 
Am I missing something?

Mike

Go ahead and reply to me AND the list since I just get the digest.


From count0.djd at gmail.com  Fri Apr 22 16:30:03 2005
From: count0.djd at gmail.com (David Driver)
Date: Fri Apr 22 16:30:07 2005
Subject: [Tutor] Building application namespaces.
Message-ID: <22803ae2050422073061cfeed2@mail.gmail.com>

I have generally used python for tasks that are scripty and not
appish. I have found that I don't know the language very well even
though I have been scripting with it for about two years. To remedy
this I am in the process of laying out a mock up for an accounting
system (GL, AR, AP). This is the first time I have done modules inside
packages and I am confused about namespaces.

What I have is a folder structure that looks like this:
root
++ Common
++ AP
++ AR
++ GL

Each subfolder looks like:
++ Common
++++ __init__.py
++++ sobjs.py (this contains sqlobjects for the domain)
++++ validators.py (contains formencode validators for the sqlobjects
for the domain)
++++ exceptions.py
++++ folder: view (this will be templates)
++++ folder: search (this will contain controllers for lookups)
++++ folder: transact (this will contain controllers for creating transactions)
++++ folder: maintain (contains folders for maintaining domain objects
(ie customer maintenance or anything that isn't a busness transaction)

In the __init__ file I import sobjs, exceptions, validators and I will
eventually check to see that the user is supposed to be in that
domain.

You may laready see what the problem is. When I import Common from the
script running in the root folder and it runs init all of themodules
in the  domain (common, GL) package that get imported by __init__have
no ancesters in their name spaces (is that the correct term?). What I
wanted was root/common/sobjs.py as common.sobjs not just sobjs.

Am I totally confused here?

Is there some place that I could go that has better doccumentation on
settig up namespaces for large python projects?

Thanks tutors!

-- 

***********************************
See there, that wasn't so bad.
***********************************
From kent37 at tds.net  Fri Apr 22 16:53:52 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 16:53:55 2005
Subject: [Tutor] SOAPPy - server and threading?
In-Reply-To: <20050422141605.C09EC384094@dd3334.kasserver.com>
References: <20050422141605.C09EC384094@dd3334.kasserver.com>
Message-ID: <42691000.1060706@tds.net>



Kristian Rink wrote:
> HAt the moment, I
am trying to implement a small client/server system that communicate using SOAP, and for each client
to connect to the SOAP server (via HTTP) I wanted to run a thread which exclusively is responsible
to serve that very client.
> 
> My problem is: Currently I create a SOAPServer and make it available using serve_forever(). I
> want
to put this into several threads, as well

If you want each request to be handled in its own thread, use ThreadingSOAPServer instead of 
SOAPServer. If you want to dedicate a thread to each client, I think you will have to run multiple 
SOAPServer instances. Each one will need its own port as well.

Kent

From kent37 at tds.net  Fri Apr 22 16:59:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 16:59:44 2005
Subject: [Tutor] Building application namespaces.
In-Reply-To: <22803ae2050422073061cfeed2@mail.gmail.com>
References: <22803ae2050422073061cfeed2@mail.gmail.com>
Message-ID: <4269115D.1060500@tds.net>

David Driver wrote:
> I have generally used python for tasks that are scripty and not
> appish. I have found that I don't know the language very well even
> though I have been scripting with it for about two years. To remedy
> this I am in the process of laying out a mock up for an accounting
> system (GL, AR, AP). This is the first time I have done modules inside
> packages and I am confused about namespaces.
> 
> What I have is a folder structure that looks like this:
> root
> ++ Common
> ++ AP
> ++ AR
> ++ GL
> 
> Each subfolder looks like:
> ++ Common
> ++++ __init__.py
> ++++ sobjs.py (this contains sqlobjects for the domain)
> ++++ validators.py (contains formencode validators for the sqlobjects
> for the domain)
> ++++ exceptions.py
> ++++ folder: view (this will be templates)
> ++++ folder: search (this will contain controllers for lookups)
> ++++ folder: transact (this will contain controllers for creating transactions)
> ++++ folder: maintain (contains folders for maintaining domain objects
> (ie customer maintenance or anything that isn't a busness transaction)
> 
> In the __init__ file I import sobjs, exceptions, validators and I will
> eventually check to see that the user is supposed to be in that
> domain.
> 
> You may laready see what the problem is. When I import Common from the
> script running in the root folder and it runs init all of themodules
> in the  domain (common, GL) package that get imported by __init__have
> no ancesters in their name spaces (is that the correct term?). What I
> wanted was root/common/sobjs.py as common.sobjs not just sobjs.

If I understand the setup correctly it should work. How are you importing Common? If you say
import Common
you should be able to refer to Common.sobjs. If you say
from Common import *
then sobjs will be imported into the main module namespace.

Kent

From maxnoel_fr at yahoo.fr  Fri Apr 22 17:00:23 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 22 17:00:35 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Weird import problem with PythonIDE
	on Mac (was 'import problem')
In-Reply-To: <0AE73573-B31B-11D9-9F38-000393C0D100@bigfoot.com>
References: <0AE73573-B31B-11D9-9F38-000393C0D100@bigfoot.com>
Message-ID: <2d467e1207737ca240b98741d3045b9c@yahoo.fr>


On Apr 22, 2005, at 11:41, Chris Smith wrote:

> Do you have a suggestion as to what can I give a module so it has 
> enough information to execute a function that resides in __main__? 
> Here is a visual of what is going on:
>
> ------__main__
> def y1():
>   pass
> import foo
> foo.run(string_from_main) #what should I pass?
>
> ------external module, foo
>
> def run(string_from_main):
> 	#
> 	exec(string_from_main) #y1 is run as if it were in __main__
>
>
> /c

	Python makes it easy to do because functions (and classes) are 
objects. Here:

# in __main__
def y1():
     pass
import foo
foo.run(y1)


# in foo
def run(functionFromMain):
     functionFromMain()


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From gsaha at imsa.edu  Fri Apr 22 18:55:38 2005
From: gsaha at imsa.edu (Gautam Saha)
Date: Fri Apr 22 18:55:38 2005
Subject: [Tutor] Tracking URL in browser location bar
Message-ID: <42692C8A.7080804@imsa.edu>

Hi:

A newbie here..I was wondering if python can help me to track the URL in
browser (IE6+, FF, Mozilla) location bar.

What I want is to get each URL from the the browser location bar, as 
user clicks from
links to link  in the web (or types an URL) and store it in  a flat file 
and flag some how
the entry page url for all my clicks.
If I open a new page (via a bookmark or type the url) it will then flag 
the 1st page again
and keep a record of all the pages I visits afterwards (so that I can 
create a tree).

1.Can it be done easily?
2. Can it be done for each browser (mainly IE6+, FF, Mozilla) ?

Primarily the program will be sitting in the user's PC (Windows based) 
and keep everything
locally. It would be ideal if it is platform and browser independent.

I really have no clue if we can do this. Any help in the right direction 
or  a general discussion
on a solution is greatly appreciated.

Thanks,

Gautam


From peterf at mac.com  Thu Apr 21 05:50:57 2005
From: peterf at mac.com (Peter Fraterdeus)
Date: Fri Apr 22 20:14:22 2005
Subject: [Tutor] using a dictionary??
In-Reply-To: <6.1.2.0.0.20050420201536.03a4eae8@pop.sbcglobal.yahoo.com>
References: <loom.20050421T034952-897@post.gmane.org>
	<6.1.2.0.0.20050420201536.03a4eae8@pop.sbcglobal.yahoo.com>
Message-ID: <p0621022dbe8cd255b3f0@[192.168.2.35]>


>At 06:56 PM 4/20/2005, PFraterdeus wrote:
>...
>Use a dictionary:
>
>responses = {"organicnews": "Organics in the News'", "ovnews" : 
>"'Our Stuff in the News'", "pressreleases" : "'Press Releases'"}
>print html_quote(responses.get(db, "Unknown News Database! " + db))

Hi Bob
I read this as using the 'get' method on the responses dictionary, yes?
'get' takes a key and returns a matched value, or the 'no match' 
parameter following?

I will give that a try.
Many thanks!
PF


>BTW there is no benefit to print '%s' % blahblah. print blahblah 
>does the same thing.

Ah, right. It's the degenerate case of 'sprint' formatting, eh?


>>[snip]
>>I know there's a proper way to do this with a tuple, or something :)
>>For the three values, it's not a problem, but if I want to scale up 
>>to many, I
>>imagine the dictionary is the way to go...
>>
>Bob Gailer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050420/c090ecde/attachment-0001.htm
From ghenry at suretecsystems.com  Thu Apr 21 16:20:35 2005
From: ghenry at suretecsystems.com (Gavin Henry)
Date: Fri Apr 22 20:14:26 2005
Subject: [Tutor] A simple Perl to Python regex xlation question
In-Reply-To: <4266A870.3060606@tds.net>
References: <C4C644CF4ADA9448904C3E8BACC4B97C033946AB@medexch1.medplus.com>
	<4266A870.3060606@tds.net>
Message-ID: <200504211520.35422.ghenry@suretecsystems.com>

On Wednesday 20 Apr 2005 20:07, Kent Johnson wrote:
> Smith, Jeff wrote:
> > What's the quickest (and most Pythonic) way to do the following Perlism:
> > 	$str = s/d+/d/;
> >
> > (i.e. collapsing multiple occurrences of the letter 'd' to just one)
>
> import re
> s = re.sub('d+', 'd', s, 1)
>
> if I understand the perl...this replaces just one occurance of d+.

It means one or more of d.

> If you 
> want to replace all occurances then use
> s = re.sub('d+', 'd', s)
>
>   >>> import re
>   >>> s = 'dddaddddabcdeddd'
>   >>> re.sub('d+', 'd', s, 1)
>
> 'daddddabcdeddd'
>
>   >>> re.sub('d+', 'd', s)
>
> 'dadabcded'
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Kind Regards,

Gavin Henry.

Open Source. Open Solutions(tm).

http://www.suretecsystems.com/
From bob at redivi.com  Fri Apr 22 07:21:22 2005
From: bob at redivi.com (Bob Ippolito)
Date: Fri Apr 22 20:14:29 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Re: Weird import problem with PythonIDE
	on Mac (was 'import problem')
In-Reply-To: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>
References: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>
Message-ID: <69019775ddec78595d1aef38394f20a3@redivi.com>


On Apr 21, 2005, at 9:06 PM, Chris Smith wrote:

> ###
> def y1():
>     pass
> def foo():
>     from __main__ import y1
>     pass
> foo()
> ###
>
> Here is a version of the code, stripped of the timeit code.  The above 
> segment exhibits the same symptoms as the previously submitted one.
>
> Even though I am running this as "__main__" it behaves as though it is 
> not __main__. i.e. if I run this with pyOxide without the 'run as 
> __main__' option, it generates the same ImportError ('Can't import 
> y1') as it does when run in the PythonIDE.
>
> In the pythonIDE it generates the error whether the 'run as __main__' 
> option is on or off. As a test of that option, I verified that the 
> following code only runs when the __main__ option is on and it worked 
> as expected:

The issue probably lies with the fact that (definitely) PythonIDE and 
(probably) PyOXIDE have the dumbest possible implementation of an 
interactive interpreter.  They use the *same interpreter* that runs the 
IDE itself.  Since the module namespace is flat, there can only be one 
__main__, and it belongs to the IDE.  This is the least of the issues 
you will experience when using such an interpreter.

Wing and IDLE don't have this problem, last I checked.  Other than 
that, I have no idea which IDEs are stupid and which are not.

-bob

From Jack.Jansen at cwi.nl  Fri Apr 22 10:31:11 2005
From: Jack.Jansen at cwi.nl (Jack Jansen)
Date: Fri Apr 22 20:14:32 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Re: Weird import problem with PythonIDE
	on Mac (was 'import problem')
In-Reply-To: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>
References: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>
Message-ID: <3d415fdeb32d3619ac81ad0bc8ad6e18@cwi.nl>


On 22 Apr 2005, at 03:06, Chris Smith wrote:

> ###
> def y1():
>     pass
> def foo():
>     from __main__ import y1
>     pass
> foo()
> ###
>
> Here is a version of the code, stripped of the timeit code.  The above 
> segment exhibits the same symptoms as the previously submitted one.
>
> Even though I am running this as "__main__" it behaves as though it is 
> not __main__. i.e. if I run this with pyOxide without the 'run as 
> __main__' option, it generates the same ImportError ('Can't import 
> y1') as it does when run in the PythonIDE.
>
> In the pythonIDE it generates the error whether the 'run as __main__' 
> option is on or off. As a test of that option, I verified that the 
> following code only runs when the __main__ option is on and it worked 
> as expected:
>
> ###
> if __name__=='__main__':
> 	print 'running as main'
> ###

As always, reading the source provides the answer.

If you look in PyEdit.py, method Editor.execstring(), you'll see that 
the only thing "run as __main__" does is set the module name to 
"__main__". It does *not* change the globals dictionary to __main__.

I'm not sure about the reasoning behind this, I think Just wanted to 
make sure that if you had two edit windows open both with "run as 
__main__" selected they didn't influence each other. On the other hand 
I can imageine that if you do that, open two windows in __main__ mode, 
the behaviour you want is exactly that.

Just?
--
Jack Jansen, <Jack.Jansen@cwi.nl>, http://www.cwi.nl/~jack
If I can't dance I don't want to be part of your revolution -- Emma 
Goldman

From just at letterror.com  Fri Apr 22 10:52:47 2005
From: just at letterror.com (Just van Rossum)
Date: Fri Apr 22 20:14:34 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Re: Weird import problem with PythonIDE
	on Mac (was 'import problem')
In-Reply-To: <3d415fdeb32d3619ac81ad0bc8ad6e18@cwi.nl>
Message-ID: <r01050400-1039-E758073EB30B11D99D53001124365170@[10.0.0.24]>

Jack Jansen wrote:

> As always, reading the source provides the answer.
> 
> If you look in PyEdit.py, method Editor.execstring(), you'll see that 
> the only thing "run as __main__" does is set the module name to 
> "__main__". It does *not* change the globals dictionary to __main__.
> 
> I'm not sure about the reasoning behind this, I think Just wanted to 
> make sure that if you had two edit windows open both with "run as 
> __main__" selected they didn't influence each other. On the other hand 
> I can imageine that if you do that, open two windows in __main__ mode, 
> the behaviour you want is exactly that.

It largely as Bob wrote: you can't do this sanely if the script runs in
the same process as the IDE. And what you said: I don't want __main__
scripts to share a namespace. The "Run as __main__" feature is intended
to support the if __name__ == "__main__" idiom, nothing else. Importing
__main__ is a very silly thing to do anyway, if you ask me.

Just
From gandreas at gandreas.com  Fri Apr 22 15:03:25 2005
From: gandreas at gandreas.com (gandreas@gandreas.com)
Date: Fri Apr 22 20:14:37 2005
Subject: [Tutor] Re: [Pythonmac-SIG] Re: Weird import problem with PythonIDE
	on Mac (was 'import problem')
In-Reply-To: <69019775ddec78595d1aef38394f20a3@redivi.com>
References: <CD1675C1-B2CA-11D9-9F38-000393C0D100@bigfoot.com>
	<69019775ddec78595d1aef38394f20a3@redivi.com>
Message-ID: <db17ccaa06a96587bf152211a29dd3fd@gandreas.com>


On Apr 22, 2005, at 12:21 AM, Bob Ippolito wrote:

>
> On Apr 21, 2005, at 9:06 PM, Chris Smith wrote:
>
>> ###
>> def y1():
>>     pass
>> def foo():
>>     from __main__ import y1
>>     pass
>> foo()
>> ###
>>
>> Here is a version of the code, stripped of the timeit code.  The 
>> above segment exhibits the same symptoms as the previously submitted 
>> one.
>>
>> Even though I am running this as "__main__" it behaves as though it 
>> is not __main__. i.e. if I run this with pyOxide without the 'run as 
>> __main__' option, it generates the same ImportError ('Can't import 
>> y1') as it does when run in the PythonIDE.
>>
>> In the pythonIDE it generates the error whether the 'run as __main__' 
>> option is on or off. As a test of that option, I verified that the 
>> following code only runs when the __main__ option is on and it worked 
>> as expected:
>
> The issue probably lies with the fact that (definitely) PythonIDE and 
> (probably) PyOXIDE have the dumbest possible implementation of an 
> interactive interpreter.  They use the *same interpreter* that runs 
> the IDE itself.  Since the module namespace is flat, there can only be 
> one __main__, and it belongs to the IDE.  This is the least of the 
> issues you will experience when using such an interpreter.
>


PyOXIDE has the option of running as an internal interpreter or an 
external interpreter.  Running internally allows for more interactive 
development since you can spawn interactive interpreters that run in 
the same name space (so you can work with the results of executing), 
and the environment is then persistent between runs.  You can also run 
a script internally "as __main__" or not (i.e, have the module name set 
to "__main__" so the 'if __name__=="__main__"' works).

If you run externally, you, of course, get __main__, but you can't 
easily investigate the result environment (unless you enable debugging 
and put a breakpoint at the last line of code, at which point you can 
show a console interpreter which executes (remotely) in that 
environment).

Both modes support full debugging capabilities, though the "internal" 
version is faster (and a little more flexible) since it doesn't need to 
do all the rpc/object proxy stuff...


Glenn Andreas????????????????????? gandreas@gandreas.com?
  <http://www.gandreas.com/> oh my!
quadrium | build, mutate, evolve | images, textures, backgrounds, art

From count0.djd at gmail.com  Fri Apr 22 20:36:49 2005
From: count0.djd at gmail.com (David Driver)
Date: Fri Apr 22 20:36:55 2005
Subject: [Tutor] Building application namespaces.
Message-ID: <22803ae205042211366acfd4b2@mail.gmail.com>

In the root script I import Common. Inside of Common's __init__.py I
import the basic domain modules. Is this correct?


>If I understand the setup correctly it should work. How are you
importing Common? If you say
>import Common
>you should be able to refer to Common.sobjs. If you say
>from Common import *
>then sobjs will be imported into the main module namespace.
>
>Kent
-- 

***********************************
See there, that wasn't so bad.
***********************************
From dyoo at hkn.eecs.berkeley.edu  Fri Apr 22 20:38:09 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 22 20:40:52 2005
Subject: [Tutor] Pychecker
In-Reply-To: <4269046A.5090808@cso.atmel.com>
Message-ID: <Pine.LNX.4.44.0504221125020.27766-100000@hkn.eecs.berkeley.edu>


> In Perl, you can perl -c somehardtoreadperlprogram.pl that will just
> check the syntax. The above problem would have been caught in Perl since
> I always use strict. Is there a command line option in Python to do a
> Pychecker-like syntax check?

Hi Mike,

Unfortunately, no, because there are some really funky things that one can
do in Python that you can't do easily in Perl.  For example, Python allows
one to inject new names into existing modules:

######
>>> import StringIO
>>> StringIO.foo = 'bar'
######


Python uses a "late binding" module for name lookup, where the variable
lookup happens as late as it can.

There are some places where something like this has been useful.  For
example, it's sometimes been useful to replace the standard file objects
systemwide by doing this:

######
>>> import sys
>>> import StringIO
>>> import sys
>>> sys.stderr = StringIO.StringIO()
>>> blah
>>> print sys.stderr.getvalue()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'blah' is not defined
######

which is sorta cool.  But it also makes it possible to completely break
encapsulation --- Parnas would not be happy.


Python's late binding does make typos a bit maddening, since those become
runtime errors rather than compile-time ones.  PyChecker uses a model
that's a bit more strict than Python's, and that's how it catches things
like typos.


> I see a -t to check the tabs, but nothing to tell it to check the syntax
> but don't run it. If not, should Pychecker be part of the standard
> distribution?  Am I missing something?

You may want to talk with the PyChecker developers to see what their
future plans are.

    http://pychecker.sourceforge.net/


Best of wishes!

From dyoo at hkn.eecs.berkeley.edu  Fri Apr 22 20:44:07 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 22 20:44:11 2005
Subject: [Tutor] Tracking URL in browser location bar
In-Reply-To: <42692C8A.7080804@imsa.edu>
Message-ID: <Pine.LNX.4.44.0504221139010.27766-100000@hkn.eecs.berkeley.edu>



On Fri, 22 Apr 2005, Gautam Saha wrote:

> A newbie here..I was wondering if python can help me to track the URL in
> browser (IE6+, FF, Mozilla) location bar.
>
> What I want is to get each URL from the the browser location bar, as
> user clicks from links to link in the web (or types an URL) and store it
> in a flat file and flag some how the entry page url for all my clicks.
> If I open a new page (via a bookmark or type the url) it will then flag
> the 1st page again and keep a record of all the pages I visits
> afterwards (so that I can create a tree).
>
> 1.Can it be done easily?
> 2. Can it be done for each browser (mainly IE6+, FF, Mozilla) ?


Hi Gautam,

Yes, but it involves work: the most direct solution I can see is to write
a "web proxy".  The web proxy would be responsible for watching web
requests and saving those URLs to disk.  So, instead of:

         Browser  <===========>   WWW

we would have:

         Browser  <======>  Proxy <======> WWW


I did a quick Google search: you may find the PPS project useful:

    http://www.suttree.com/code/pps/

as they're doing something very similar.

From dyoo at hkn.eecs.berkeley.edu  Fri Apr 22 20:47:46 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 22 20:47:56 2005
Subject: [Tutor] Pychecker
In-Reply-To: <Pine.LNX.4.44.0504221125020.27766-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0504221144390.27766-100000@hkn.eecs.berkeley.edu>



On Fri, 22 Apr 2005, Danny Yoo wrote:

>
> > In Perl, you can perl -c somehardtoreadperlprogram.pl that will just
> > check the syntax. The above problem would have been caught in Perl
> > since I always use strict. Is there a command line option in Python to
> > do a Pychecker-like syntax check?
>
> Hi Mike,
>
> Unfortunately, no, because there are some really funky things that one
> can do in Python that you can't do easily in Perl.


Yikes.  I should correct myself before I get someone angry at me. You can
do this sort of late-binding stuff in Perl too, and in many other
languages.  (Java's reflection mechanism is another kind of late-binding
mechanism, for example.)

But Python makes it extraordinarly easy --- perhaps too much so.  *grin*

From kent37 at tds.net  Fri Apr 22 21:04:03 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 21:04:10 2005
Subject: [Tutor] Building application namespaces.
In-Reply-To: <22803ae205042211366acfd4b2@mail.gmail.com>
References: <22803ae205042211366acfd4b2@mail.gmail.com>
Message-ID: <42694AA3.3090602@tds.net>

OK, here is a brief, working example.

In my working directory I have the file test.py containing:

# test.py
import mypackage

c=mypackage.MyClass()
c.foo()


In the mypackage directory I have __init__.py and MyClass.py containing:

# __init__.py
from MyClass import MyClass

# MyClass.py
class MyClass:
     def foo(self):
         print 'MyClass.foo() here!'

Running test.py prints 'MyClass.foo() here!' as desired.

Kent

David Driver wrote:
> In the root script I import Common. Inside of Common's __init__.py I
> import the basic domain modules. Is this correct?
> 
> 
> 
>>If I understand the setup correctly it should work. How are you
> 
> importing Common? If you say
> 
>>import Common
>>you should be able to refer to Common.sobjs. If you say
> 
>>from Common import *
> 
>>then sobjs will be imported into the main module namespace.
>>
>>Kent

From kent37 at tds.net  Fri Apr 22 21:07:35 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 21:07:38 2005
Subject: [Tutor] Tracking URL in browser location bar
In-Reply-To: <42692C8A.7080804@imsa.edu>
References: <42692C8A.7080804@imsa.edu>
Message-ID: <42694B77.5080708@tds.net>

Gautam Saha wrote:
> Hi:
> 
> A newbie here..I was wondering if python can help me to track the URL in
> browser (IE6+, FF, Mozilla) location bar.

You might find some hints here:
http://wwwsearch.sourceforge.net/bits/GeneralFAQ.html

Kent

From cpu.crazy at gmail.com  Fri Apr 22 02:15:51 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri Apr 22 21:15:58 2005
Subject: [Tutor] CLS? (Joseph Quigley)
Message-ID: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>

In QBASIC there was the command "CLS"
this wiped the screen and "started printing letters to the screen at the 
top " of the console window.

Is there any such command in Python? Would a Python cook book have this (I 
have pay-by-the-minute dial-up Internet so I can't go online for long)?

Thanks in advance,
  Joe

From cpu.crazy at gmail.com  Fri Apr 22 21:45:05 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri Apr 22 21:58:54 2005
Subject: [Tutor] Re: Installation Routines (Joseph Quigley) (Jay Loden)
In-Reply-To: <20050421200234.33AA31E4002@bag.python.org>
References: <20050421200234.33AA31E4002@bag.python.org>
Message-ID: <6.1.0.6.2.20050422134319.01eeff20@pop.gmail.com>

Interesting. So several distros use rpms? I though only red hat used 'em.


>Rpm does in fact have dependency resolution, and rpm-based distributions 
>use a
>package manager that can download the dependencies and install them for you -
>urpmi on mandrake, yum or apt4rpm on Fedora and Redhat, Yast on Suse
>
>I've used all of these, they are all rpm based, and they all install
>dependencies. If you use the raw "rpm" command, even that will tell you
>"missing dependecy foo".
>
>That being said, apt-get on debian is still my favorite (for sheer number of
>available packages), but urpmi on mandrake or Yast on Suse are quite
>excellent.
>
>-Jay
>
>On Wednesday 20 April 2005 04:17 pm, Max Noel wrote:
>emerge and apt-get come to mind. rpm is inferior (no dependency
> > resolution) but still does a good job, and I hear autopackage isn't
> > bad.

From prasad413in at gmail.com  Fri Apr 22 22:09:53 2005
From: prasad413in at gmail.com (Prasad Kotipalli)
Date: Fri Apr 22 22:09:56 2005
Subject: [Tutor] Newbie Question:Regarding Command line Parsing and Run Unix
	Shell Command
Message-ID: <6ce40f750504221309d8079db@mail.gmail.com>

Hello evryone

     I am a newbie to python. I have a makefile which i can compile in
UNIX/LINUX, But i
I am planning to write a python script which actually does what my
MAKEFILE does. The make file is

#Makefile and some scripts to give output
#numbers
#Change till sign #END
var1:=564-574
a1 = 23
b1 = 678
kxm = ixm_7.gh
out = c$(var1)_s.gh
imageim
#END
#other files
file1 = sec$(b1).jk
file2 = sgf$(a1)
file3 = p$(b1).gh
prg3scriptfile = prg3_produce.xx
findoutdir = Dir:~/home/
x=67
#work
evrything: prg1 script2 prg3 script4
withoutprg1: script2 prg3 script4
prg1:
        s$(ca)$(d) .

script2: Makefile
       ./script2 -i '$(file2)' -o '$(file1)' -a $(x) -n

prg3:
        : > $(prg3scriptfile)
>>  $(prg3scriptfile)

        prg3 $(prg3scriptfile)
        rm $(prg3scriptfile)
script4:
        ./script4 $(kxm) $(file2)  $(out)  $(var1)

I want to write a python script to replace this Makefile.
I Have tried using getopt/optparse for parsing command line options
How to Run  Unix shell command from python.

My Task is

Myprg.py a1 b1 kxm out

Kindly suggest me some ideas/comments.

I started writing the code
I started writing the script.. I have gone through documentation for
getopt

import string, getopt, sys
def usage():
    print '''myscript.py -- uses getopt to recognize options
Options: -n  -- No
         -t  -- T
         -h  -- help
         -i  -- i
         -o  -- Output:filename'''
    sys.exit(1)
def main():
    print "SYS ARGV: ", ",".join(sys.argv)
# Define the Options
Options = {
        'n:': 'Number=',
        't:': 'T',
        'h' : 'help',
        'i' : 'i',
        'o' : 'Output_file',
    }
shortOpts = ''.join(Options.keys())
longOpts  = Options.values()

try:
        (opts, args) = getopt.getopt(argv[1:], shortOpts, longOpts)
except getopt.error, msg:
        print "Unrecognized argument or option"
    # end try

for (opt, arg) in opts:

        if opt in ('-n', '--Number'):
            print '-n is the Number', Number
            sys.exit()

        elif opt in ('-t', '--T'):
            print '-t is the T', T
            sys.exit()

        elif opt in ('-h', '--help'):
            usage()
            print " "
            sys.exit()

        elif opt in ('-i', '--i'):
            print " I", i

        elif opt  in ('-o', '--Output Filename'):
            print "Output", Output
        # end if
       # end for

            print "OPTS: ", ",".join([repr(o) for o in opts])
            print "ARGS: ", ",".join(args)

if __name__ == "__main__":
    main()

with the above code, I am planning to do command line parsing. But how
to run unix shell command? DO i have to use os Module/  import command?

How should i proceed further, to
 import commands
 commands.getstatusoutput('ls /bin/ls')

Please suggest me some ideas how to proceed further

Thanks
koid wayne
From project5 at redrival.net  Fri Apr 22 23:08:48 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr 22 23:09:48 2005
Subject: [Tutor] Re: CLS? (Joseph Quigley)
References: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>
Message-ID: <1xnpo9h3lw9me.1403kc6ozx33x$.dlg@40tude.net>

Joseph Quigley wrote on Thu, 21 Apr 2005 18:15:51 -0600:
> In QBASIC there was the command "CLS"
> this wiped the screen and "started printing letters to the screen at the 
> top " of the console window.

With a quick Google, it does indeed appear to be in the cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65257
(look under >>> Platform Testing <<<).

For Windows this is:

import os
os.system('cls')

It's actually just sending the cls command to the dos box it's running on,
it's not built-in (hence the need for platform-specific code in the recipe
above).

> Is there any such command in Python? Would a Python cook book have this (I 
> have pay-by-the-minute dial-up Internet so I can't go online for long)?

I'm tempted to say that if you need cls, you've got the wrong interface for
your application :). Command line apps which wipe out the command line
history are bad. You might prefer making a GUI or a web application
instead.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From kent37 at tds.net  Fri Apr 22 23:10:13 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri Apr 22 23:10:20 2005
Subject: [Tutor] CLS? (Joseph Quigley)
In-Reply-To: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>
References: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>
Message-ID: <42696835.7030005@tds.net>

Joseph Quigley wrote:
> In QBASIC there was the command "CLS"
> this wiped the screen and "started printing letters to the screen at the 
> top " of the console window.

On Windows you can
import os
os.system('cls')

Kent

From project5 at redrival.net  Fri Apr 22 23:10:25 2005
From: project5 at redrival.net (Andrei)
Date: Fri Apr 22 23:16:27 2005
Subject: [Tutor] Re: Installation Routines (Joseph Quigley) (Jay Loden)
References: <20050421200234.33AA31E4002@bag.python.org>
	<6.1.0.6.2.20050422134319.01eeff20@pop.gmail.com>
Message-ID: <enzp7aux39sm$.1ab7yljx0oypw$.dlg@40tude.net>

Joseph Quigley wrote on Fri, 22 Apr 2005 13:45:05 -0600:

> Interesting. So several distros use rpms? I though only red hat used 'em.

Yeah, including some major ones like Mandrake and Suse.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

From mhansen at cso.atmel.com  Fri Apr 22 23:16:42 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Fri Apr 22 23:16:36 2005
Subject: [Tutor] Pychecker
In-Reply-To: <Pine.LNX.4.44.0504221144390.27766-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504221144390.27766-100000@hkn.eecs.berkeley.edu>
Message-ID: <426969BA.1050702@cso.atmel.com>

Thanks Danny.

I'll make sure I use pychecker so I don't shoot myself in the foot with not so 
easy to catch typos in variable names and syntax blunders.

I might check with the pychecker devs to see if there's any effort to get it put 
into the standard distribution. I think it's too handy to not have it in the 
standard distribution.

Mike

Danny Yoo wrote:
> 
> On Fri, 22 Apr 2005, Danny Yoo wrote:
> 
> 
>>>In Perl, you can perl -c somehardtoreadperlprogram.pl that will just
>>>check the syntax. The above problem would have been caught in Perl
>>>since I always use strict. Is there a command line option in Python to
>>>do a Pychecker-like syntax check?
>>
>>Hi Mike,
>>
>>Unfortunately, no, because there are some really funky things that one
>>can do in Python that you can't do easily in Perl.
> 
> 
> 
> Yikes.  I should correct myself before I get someone angry at me. You can
> do this sort of late-binding stuff in Perl too, and in many other
> languages.  (Java's reflection mechanism is another kind of late-binding
> mechanism, for example.)
> 
> But Python makes it extraordinarly easy --- perhaps too much so.  *grin*
> 
From maxnoel_fr at yahoo.fr  Sat Apr 23 01:19:31 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr 23 01:19:36 2005
Subject: [Tutor] Newbie Question:Regarding Command line Parsing and Run
	Unix Shell Command
In-Reply-To: <6ce40f750504221309d8079db@mail.gmail.com>
References: <6ce40f750504221309d8079db@mail.gmail.com>
Message-ID: <e5ae199e3adf592e1493342233d9d3d8@yahoo.fr>


On Apr 22, 2005, at 21:09, Prasad Kotipalli wrote:

> Hello evryone
>
>      I am a newbie to python. I have a makefile which i can compile in
> UNIX/LINUX, But i
> I am planning to write a python script which actually does what my
> MAKEFILE does.

	Then what you want is SCons (http://www.scons.org/). Haven't had the 
occasion to use it yet, but it seems like an instance of Best Thing 
Ever(TM).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From alan.gauld at freenet.co.uk  Sat Apr 23 01:28:19 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 23 01:28:00 2005
Subject: [Tutor] CLS? (Joseph Quigley)
References: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>
Message-ID: <005701c54792$f85a6c40$dad48651@xp>


> In QBASIC there was the command "CLS"
> this wiped the screen and "started printing letters to the screen at
the
> top " of the console window.

This was possible because QBASIC knew what kind of screen it was
working with, Python can't tell that reliably since it runs on
many operating systems.

The best way is probably to use the os.system() call to clear the
screen via the OS. Thus on DOS its

os.system('CLS')

on Linux

os.system('clear')

Failing that you can write a cls function:

def cls():
   print '\n' * 100

HTH,

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

From magoldfish at gmail.com  Sat Apr 23 04:02:56 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Sat Apr 23 04:02:59 2005
Subject: [Tutor] iterator question for a toy class
Message-ID: <5e183f3d0504221902e0f414e@mail.gmail.com>

I'm trying to understand custom iterators in Python, and created the
following toy class for sequence comparison, which seems to work:

class Foo(object):
   """A toy class to experiment with __eq__ and __iter__"""
   def __init__(self, listA, listB):
      self.head, self.tail = listA, listB
   def __iter__(self):
      return iter(self.head[:]+self.tail[:])
   def __eq__(self, other):
      """Foo instances are equal if their respective subsequences,
      head, tail, are in the same order"""
      diff = [i for i, j in zip(self, other) if i != j]
      return len(diff) == 0

>>> f1 = Foo( [1,2], ['a','b','c'] )
>>> f2 = Foo( [1,2], ['a','b','c'] )
>>> f3 = Foo( [1,2], ['a','b','d'] )
>>> f1 == f2, f1 == f3
(True, False)


I'm not really sure if I'm implementing iter() correctly, for
instance: should I make copies of the sublists?  Should I try to
implement my own next() method?

Advice, comments, and links to good tutorial web pages on iterators
are appreciated!

Thanks,
Marcus
From magoldfish at gmail.com  Sat Apr 23 05:15:57 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Sat Apr 23 05:16:00 2005
Subject: [Tutor] Tracking URL in browser location bar
In-Reply-To: <42694B77.5080708@tds.net>
References: <42692C8A.7080804@imsa.edu> <42694B77.5080708@tds.net>
Message-ID: <5e183f3d05042220155cd1b04b@mail.gmail.com>

> > A newbie here..I was wondering if python can help me to track the URL in
> > browser (IE6+, FF, Mozilla) location bar.
I think browser helper objects may also be useful.  ASPN has a thread at:

http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/2263094

Marcus
From rmkrauter at yahoo.com  Sat Apr 23 07:36:04 2005
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Sat Apr 23 07:36:59 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <5e183f3d0504221902e0f414e@mail.gmail.com>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>
Message-ID: <4269DEC4.2010400@yahoo.com>

Marcus Goldfish wrote:
> I'm trying to understand custom iterators in Python, and created the
> following toy class for sequence comparison, which seems to work:
> 
> class Foo(object):
>    """A toy class to experiment with __eq__ and __iter__"""
>    def __init__(self, listA, listB):
>       self.head, self.tail = listA, listB
>    def __iter__(self):
>       return iter(self.head[:]+self.tail[:])
>    def __eq__(self, other):
>       """Foo instances are equal if their respective subsequences,
>       head, tail, are in the same order"""
>       diff = [i for i, j in zip(self, other) if i != j]
>       return len(diff) == 0
> 
> 
>>>>f1 = Foo( [1,2], ['a','b','c'] )
>>>>f2 = Foo( [1,2], ['a','b','c'] )
>>>>f3 = Foo( [1,2], ['a','b','d'] )
>>>>f1 == f2, f1 == f3
> 
> (True, False)
> 
> 
> I'm not really sure if I'm implementing iter() correctly, for
> instance: should I make copies of the sublists?  Should I try to
> implement my own next() method?
> 
> Advice, comments, and links to good tutorial web pages on iterators
> are appreciated!
> 

Hi Marcus,

Here are some points I noticed -

1) I would probably change your __eq__ method to something like this:

def __eq__(self,other):
        return (self.head,self.tail) == (other.head,other.tail)

2) Or, if you really want your __eq__ method to use the iterator 
returned by __iter__(),

def __eq__(self, other):
     for i, j in map(None,self, other):
         if i != j:
             return False
     return True

One reason this might be a little better than your version is that using 
zip() as you have, f1 = Foo( [1,2], ['a','b','c']) and f2 = Foo( [1,2], 
['a','b','c','q'] ) would compare equal. Another reason is that this 
version returns False as soon as it figures out the lists are not equal.

3) It's not a big deal, but instead of what you have in __iter__(), I 
might import itertools and then write something like

def __iter__(self):
     return itertools.chain(self.head,self.tail)

4) In this specific case, if you want to use the iterator returned by 
__iter__ in your __eq__ method, I think you should avoid using a next(). 
Here's a silly example why:

class Foo2(object):
    def __init__(self, listA,listB):
       self.head,self.tail = listA,listB
       self._current = -1
       self._cache = None

    def _fill_cache(self):
        """save some state"""
        if not self._cache:
            self._cache = self.head + self.tail

    def __iter__(self):
        """the iterator is the iterable object itself"""
        return self

    def next(self):
        """make the object an iterator"""
        self._fill_cache()
        self._current += 1

        if self._current >= len(self._cache):
            raise StopIteration

        return self._cache[self._current]

    def __eq__(self, other):
        for i, j in map(None,self, other):
            if i != j:
                return False
        return True

if __name__ == '__main__':
     f1 = Foo2( [1,2], ['a','b','c'])
     f2 = Foo2( [1,2], ['a','b','c'])
     f3 = Foo2( [1,2], ['a','b','d'])
     print f1 == f2, f1 == f3, f1 == f3 # notice the output here



Good luck.

Rich


From work at infomaniak.ch  Sat Apr 23 11:46:50 2005
From: work at infomaniak.ch (Cedric BRINER)
Date: Sat Apr 23 10:53:38 2005
Subject: [Tutor] incomprehension in type of classes.
In-Reply-To: <4268E8F6.6020704@tds.net>
References: <20050422114428.GA7469@obs.unige.ch> <4268E8F6.6020704@tds.net>
Message-ID: <20050423094650.GB7469@obs.unige.ch>

> >from (I):
> >
> >class CYear:
> >   def __init__(self, year):
> >      self.__year=year
> >      print str(self.__year)             <<---(*)
> >      print 'dir of: '+str(dir(self))
> >      print 'type of: '+str(type(self))
> >   def __str__(self):
> >      return "we are in "+str(self.year)
> >
> >
> >to (IIOB):
> >
> >class CYearDerived(int):
> >   def __init__(self, year):
> >      super(CYearDerived,self).__init__(year)
> >      self.__year=year
> >      print str(self.__year)            <<-----(*OB)
> >      print 'dir of: '+str( dir(self) )
> >      print 'type of: '+str(type(self))
> >   def __str__(self):
> >      return "we are in "+super(CYearDerived,self).__str__()
> 
> >why type of (CYear(2005))
> ><type 'instance'>
> >
> >and type(CYearDerived)
> ><class '__main__.CYearDerived'>
> >
> >doesn't give the same type ???
> 
> It's a difference between new-style and old-style classes. CYear is an 
> old-style class because it doesn't inherit from object. CYearDerived is a 
> new-style class because it inherits from int which is a subtype of object:
> 
>  >>> class C: pass # old-style class
>  ...
>  >>> type(C())
> <type 'instance'>
>  >>> C().__class__
> <class __main__.C at 0x008CE7B0>
> 
>  >>> class C2(object): pass # new-style class
>  ...
>  >>> type(C2())
> <class '__main__.C2'>
>  >>> C2().__class__
> <class '__main__.C2'>
> 
>  >>> int.__bases__ # int inherits from object
> (<type 'object'>,)
> 
> I'm not sure *why* there is this difference between the two types of 
> classes, but there is...
aaaaah... I din't know that there was two kinds of classes. So you mean that, now the new style object should be like: class A(object): pass

>>> class A: pass
...
>>> class B(object): pass
...
>>> a=A()
>>> b=B()

I see that dir (b) compare to dir(a) provides more stuff. So the new style of a class, is not only about syntax but also about properties ???

ok, I'll try to find more about this !

> By the way extending int does not work the way you have done it here. int 
> is an immutable type so you have to initialize it in the __new__() method, 
> not in __init__(). Read the details here:
> http://www.python.org/2.2/descrintro.html#__new__
this link is very usefull

thanks

Cedric BRINER
From kent37 at tds.net  Sat Apr 23 13:04:37 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 13:04:41 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <4269DEC4.2010400@yahoo.com>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>
	<4269DEC4.2010400@yahoo.com>
Message-ID: <426A2BC5.4070004@tds.net>

Rich Krauter wrote:
> 2) Or, if you really want your __eq__ method to use the iterator 
> returned by __iter__(),
> 
> def __eq__(self, other):
>     for i, j in map(None,self, other):
>         if i != j:
>             return False
>     return True

That's not right either, it will compare Foo([None], []) == Foo([], []) for example.

Kent

From kent37 at tds.net  Sat Apr 23 13:09:10 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 13:09:13 2005
Subject: [Tutor] incomprehension in type of classes.
In-Reply-To: <20050423094650.GB7469@obs.unige.ch>
References: <20050422114428.GA7469@obs.unige.ch> <4268E8F6.6020704@tds.net>
	<20050423094650.GB7469@obs.unige.ch>
Message-ID: <426A2CD6.6060100@tds.net>

Cedric BRINER wrote:
>>I'm not sure *why* there is this difference between the two types of 
>>classes, but there is...
> 
> aaaaah... I din't know that there was two kinds of classes. So you mean that, now the new style
object should be like: class A(object): pass

Yes, this is the recommended way to define a class since Python 2.2.

> ok, I'll try to find more about this !

This document
http://www.python.org/2.2/descrintro.html
and the two PEPs it links to are the best source of information on new-style classes. Another good 
summary is here:
http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html

Kent

From kristian at zimmer428.net  Sat Apr 23 14:36:43 2005
From: kristian at zimmer428.net (Kristian Rink)
Date: Sat Apr 23 14:35:48 2005
Subject: [Tutor] SOAPPy - server and threading?
In-Reply-To: <42691000.1060706@tds.net>
References: <20050422141605.C09EC384094@dd3334.kasserver.com>
	<42691000.1060706@tds.net>
Message-ID: <20050423143643.38317f0f@kassiopeia.zimmer428.net>


Hi Kent;

On Fri, 22 Apr 2005 10:53:52 -0400
Kent Johnson <kent37@tds.net> wrote:

> If you want each request to be handled in its own thread, use
> ThreadingSOAPServer instead of SOAPServer. If you want to dedicate a
> thread to each client, I think you will have to run multiple

Thanks for pointing me the way here... Actually, my current idea is to
run a "master server" which the clients connect to and, while
connecting, get returned a local port number where their "responsible"
SOAP server thread is listening. Anyhow, do you have a short example or
documentation link handy on how to get ThreadedSOAPServer running?
SOAPpy documentation same as googling for it sadly weren't very
extensive on that... :/

Thanks and bye,
Kris
From jeannot18 at hotmail.com  Sat Apr 23 14:58:13 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Sat Apr 23 14:58:17 2005
Subject: [Tutor] Help with this script
Message-ID: <BAY20-F708AA180AEF4F554D8346B32E0@phx.gbl>

Hi guys, I am back from my hols.

Jacob S gave me this little exercise to do a little while ago.

1) Make a program to compute the areas of several figures. Make it display a 
menu on startup,         ask for a choice, and then compute the area of the 
figure chosen by asking for dimensions.

2) Make another script similiar to #1 using volumes instead of areas

I have decided to merge the 2 scripts. First I should have a menu asking me 
if I want to compute areas or volumes. Then depending on the choice it 
should display the relevant menu. My first menu comes on but if I select "b" 
or "c" the script does not run. The error message points out that 
"print_options()" or "print_options_2()" are not defined. Could somebody 
point me into the right direction, thanks.

---------------------------------------------------------------------------------------------
#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume

##First ask the user what he wants to do
running = True

def area_rect():
        length = input("Length: ")
        width = input ("Width: ")
        print "The area is: ",length*width

def area_circ():
        radius = input("What is the radius?: ")
        print "The area is approximately: ", 3.14159*(radius**2)

def area_squ():
        side = input ("What is the length of one side?: ")
        print "The area is: ", side*side

def area_tgle():
        base = input ("What is the base of the triangle?: ")
        heigth = input ("What is the heigth of the triangle?: ")
        print "The area is: ",base*heigth/2

def vol_sph():
        radius = input("What is the radius?: ")
        print "The volume is: ", (4*3.14159*radius**3)/3

def vol_cube():
        side = input("Side: ")
        print "The volume is: ",side**3

def vol_box():
        width = input ("What is the width of the box?: ")
        length = input ("What is the length of the box?: ")
        depth = input ("What is the depth of the box?: ")
        print "The volume is: ", width*length*depth

def vol_cone():
        radius = input ("What is the radiux of the base of the cone?: ")
        heigth = input ("What is the heigth of the cone?: ")
        print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)


def task_options():
        print "---------------------------------------"
        print "Options:"
        print "a. Print options: "
        print "b. Do you want to calculate areas?: "
        print "c. Do you want to calculate volumes?: "
        print "d. Quit the programme"
        print "---------------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print task_options()
        elif choice == 'b':
            print print_options()
        elif choice == 'c':
            print print_options_2()
        elif choice == 'd':
            running = False
print task_options()


def print_options():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate circle area"
        print "c. calculate square area"
        print "d. calculate rectangle area"
        print "e. calculate triangle area"
        print "f. quit the programme"
        print "------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print_options()
        elif choice == 'b':
            area_circ()
        elif choice == 'c':
            area_squ()
        elif choice == 'd':
            area_rect()
        elif choice == 'e':
            area_tgle()
        elif choice == 'f':
                print_options()
#Call starting menu
print_options()

def print_options_2():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate the volume of a sphere"
        print "c. calculate the volume of a cube"
        print "d. calculate the volume of a box"
        print "e. calculate the volume of a cone"
        print "f. quit the programme"
        print "------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print_options()
        elif choice == 'b':
            vol_sph()
        elif choice == 'c':
            vol_cube()
        elif choice == 'd':
            vol_box()
        elif choice == 'e':
            vol_cone()
        elif choice == 'e':
            print_options()
#Call starting menu
print_options()
-------------------------------------------------------------------------------------------------------------------------------

JC


From kent37 at tds.net  Sat Apr 23 15:14:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 15:14:30 2005
Subject: [Tutor] SOAPPy - server and threading?
In-Reply-To: <20050423143643.38317f0f@kassiopeia.zimmer428.net>
References: <20050422141605.C09EC384094@dd3334.kasserver.com>	<42691000.1060706@tds.net>
	<20050423143643.38317f0f@kassiopeia.zimmer428.net>
Message-ID: <426A4A31.70709@tds.net>

Kristian Rink wrote:
> Hi Kent;
> 
> On Fri, 22 Apr 2005 10:53:52 -0400
> Kent Johnson <kent37@tds.net> wrote:
> 
> 
>>If you want each request to be handled in its own thread, use
>>ThreadingSOAPServer instead of SOAPServer. If you want to dedicate a
>>thread to each client, I think you will have to run multiple
> 
> 
> Thanks for pointing me the way here... Actually, my current idea is to
> run a "master server" which the clients connect to and, while
> connecting, get returned a local port number where their "responsible"
> SOAP server thread is listening.

Yes, that is the usual way of running a threaded server and that is what ThreadedSOAPServer will do.

  Anyhow, do you have a short example or
> documentation link handy on how to get ThreadedSOAPServer running?
> SOAPpy documentation same as googling for it sadly weren't very
> extensive on that... :/

Just change SOAPServer to ThreadedSOAPServer everywhere you use it.

I should say I haven't actually done this, I just looked at the source for SOAPpy/Server.py. It has
class SOAPServer(SOAPServerBase, SocketServer.TCPServer):
   ...

and

class ThreadingSOAPServer(SOAPServerBase, SocketServer.ThreadingTCPServer):
   ...

so the only difference between the two is that ThreadingSOAPServer is based on ThreadingTCPServer 
which has the behaviour you want. For more details see the docs and source for the SocketServer module.

Kent

From kent37 at tds.net  Sat Apr 23 15:19:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 15:19:34 2005
Subject: [Tutor] Help with this script
In-Reply-To: <BAY20-F708AA180AEF4F554D8346B32E0@phx.gbl>
References: <BAY20-F708AA180AEF4F554D8346B32E0@phx.gbl>
Message-ID: <426A4B5D.9020607@tds.net>

John Carmona wrote:
> I have decided to merge the 2 scripts. First I should have a menu asking 
> me if I want to compute areas or volumes. Then depending on the choice 
> it should display the relevant menu. My first menu comes on but if I 
> select "b" or "c" the script does not run. The error message points out 
> that "print_options()" or "print_options_2()" are not defined. Could 
> somebody point me into the right direction, thanks.

The problem is that you are calling task_options() before print_options() and print_options_2() are 
defined.

A good practice is to put all your function definitions first in the file, then put the main code 
that calls them at the end. So you would have
def task_options():
   ...

def print_options():
   ...

def print_options_2():
   ...

Then start the main program by calling
task_options()

Kent

From rmkrauter at yahoo.com  Sat Apr 23 15:30:33 2005
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Sat Apr 23 15:31:28 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <426A2BC5.4070004@tds.net>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>	<4269DEC4.2010400@yahoo.com>
	<426A2BC5.4070004@tds.net>
Message-ID: <426A4DF9.90203@yahoo.com>

Kent Johnson wrote:
> Rich Krauter wrote:
> 
>> 2) Or, if you really want your __eq__ method to use the iterator 
>> returned by __iter__(),
>>
>> def __eq__(self, other):
>>     for i, j in map(None,self, other):
>>         if i != j:
>>             return False
>>     return True
> 
> 
> That's not right either, it will compare Foo([None], []) == Foo([], []) 
> for example.

Kent,
Yikes, I should have seen that. Thanks for pointing out the error.

Rich
From jeannot18 at hotmail.com  Sat Apr 23 16:44:48 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Sat Apr 23 16:44:52 2005
Subject: [Tutor] Re Help with this script
Message-ID: <BAY20-F27D0083E2C4C67491C320EB32E0@phx.gbl>

Thanks Kent, it is working now. Is this what you meant in your reply? 
Because if I set up the main code at the end of the script I was still 
getting an error message.

Also, what do I need to use if for example I want my code to rerun once I 
have computed let's say a volume. Right now the execution of the script 
gives me "None" at the end.

Thanks
JC

----------------------------------------------------------------------------------------------------------
#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume

##First ask the user what he wants to do
running = True

def area_rect():
        length = input("Length: ")
        width = input ("Width: ")
        print "The area is: ",length*width

def area_circ():
        radius = input("What is the radius?: ")
        print "The area is approximately: ", 3.14159*(radius**2)

def area_squ():
        side = input ("What is the length of one side?: ")
        print "The area is: ", side*side

def area_tgle():
        base = input ("What is the base of the triangle?: ")
        heigth = input ("What is the heigth of the triangle?: ")
        print "The area is: ",base*heigth/2

def vol_sph():
        radius = input("What is the radius?: ")
        print "The volume is: ", (4*3.14159*radius**3)/3

def vol_cube():
        side = input("Side: ")
        print "The volume is: ",side**3

def vol_box():
        width = input ("What is the width of the box?: ")
        length = input ("What is the length of the box?: ")
        depth = input ("What is the depth of the box?: ")
        print "The volume is: ", width*length*depth

def vol_cone():
        radius = input ("What is the radiux of the base of the cone?: ")
        heigth = input ("What is the heigth of the cone?: ")
        print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)


def task_options():
        print "---------------------------------------"
        print "Options:"
        print "a. Print options: "
        print "b. Do you want to calculate areas?: "
        print "c. Do you want to calculate volumes?: "
        print "d. Quit the programme"
        print "---------------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print task_options()
        elif choice == 'b':
            print print_options()
        elif choice == 'c':
            print print_options_2()
        elif choice == 'd':
            running = False

def print_options():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate circle area"
        print "c. calculate square area"
        print "d. calculate rectangle area"
        print "e. calculate triangle area"
        print "f. quit the programme"
        print "------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print_options()
        elif choice == 'b':
            area_circ()
        elif choice == 'c':
            area_squ()
        elif choice == 'd':
            area_rect()
        elif choice == 'e':
            area_tgle()
        elif choice == 'f':
            print_options()

def print_options_2():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate the volume of a sphere"
        print "c. calculate the volume of a cube"
        print "d. calculate the volume of a box"
        print "e. calculate the volume of a cone"
        print "f. quit the programme"
        print "------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print_options()
        elif choice == 'b':
            vol_sph()
        elif choice == 'c':
            vol_cube()
        elif choice == 'd':
            vol_box()
        elif choice == 'e':
            vol_cone()
        elif choice == 'e':
            print_options()

#Call starting menu
print task_options()




----------------------------------------------------------------------------------------------------------


From maxnoel_fr at yahoo.fr  Sat Apr 23 17:36:56 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr 23 17:37:02 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <BAY20-F27D0083E2C4C67491C320EB32E0@phx.gbl>
References: <BAY20-F27D0083E2C4C67491C320EB32E0@phx.gbl>
Message-ID: <17aa15b5f1ec355b4c3678e075712db7@yahoo.fr>


On Apr 23, 2005, at 15:44, John Carmona wrote:

> Thanks Kent, it is working now. Is this what you meant in your reply? 
> Because if I set up the main code at the end of the script I was still 
> getting an error message.
>
> Also, what do I need to use if for example I want my code to rerun 
> once I have computed let's say a volume. Right now the execution of 
> the script gives me "None" at the end.
>
> Thanks
> JC

	Here's an example of a script that will print "Yo." until you answer 
"n" or "no" (in any capitalization) to it. It should help you do what 
you want.


#!/usr/bin/env python

while True:
     print "yo."
     onceMore = raw_input("Once more?").strip().lower()
     if "no".startswith(onceMore):
         break


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From kent37 at tds.net  Sat Apr 23 17:50:02 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 17:50:17 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <BAY20-F27D0083E2C4C67491C320EB32E0@phx.gbl>
References: <BAY20-F27D0083E2C4C67491C320EB32E0@phx.gbl>
Message-ID: <426A6EAA.8080009@tds.net>

John Carmona wrote:
> Thanks Kent, it is working now. Is this what you meant in your reply? 
> Because if I set up the main code at the end of the script I was still 
> getting an error message.

Yes, that's what I meant, though you just need
task_options()
rather than
print task_options()

When you say print task_options() you are asking the program to call task_options() and print the 
value returned. task_options() doesn't return a value, it does all the printing, etc. itself. So 
Python uses the default return value which is None. That's why the program prints "None" at the end.

> 
> Also, what do I need to use if for example I want my code to rerun once 
> I have computed let's say a volume. Right now the execution of the 
> script gives me "None" at the end.

You have to put a loop somewhere. Perhaps in task_options () you could have a loop that repeatedly 
asks for input and processes it. Since you are doing this as a learning exercise I won't show you 
how; give it a try and ask again if you have trouble.

You can find a little about while loops here:
http://docs.python.org/tut/node5.html

Kent

From netnews at linuxscope.com  Sat Apr 23 18:09:37 2005
From: netnews at linuxscope.com (Paul Tader)
Date: Sat Apr 23 18:10:35 2005
Subject: [Tutor] Python and Web Pages?
Message-ID: <426A7341.5070207@linuxscope.com>

I have a couple programs/scripts that I want to write that need to be 
web-based.  Can Python (and a little HTML) accomplish this?  Or are 
other languages like PHP, or Perl better suited?


A little more detail:

One project is to make a web page that users login to with a name and 
password, choose from a list of "canned" directory structure (ie. how 
many subdirectories, top-level name, maybe permissions, etc), hit a "GO" 
button and then the directories are made.

Another example is a web-based form that users interface with a mySQL 
database.  Simple additions/changes/deletions.  Basic stuff.


Thanks,
Paul



From kent37 at tds.net  Sat Apr 23 18:31:44 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 18:31:47 2005
Subject: [Tutor] Python and Web Pages?
In-Reply-To: <426A7341.5070207@linuxscope.com>
References: <426A7341.5070207@linuxscope.com>
Message-ID: <426A7870.7050001@tds.net>

Paul Tader wrote:
> I have a couple programs/scripts that I want to write that need to be 
> web-based.  Can Python (and a little HTML) accomplish this?  Or are 
> other languages like PHP, or Perl better suited?

Yes, Python can do this nicely. You can write CGI programs in Python or use one of the many web 
frameworks available. See
http://www.python.org/topics/web/
http://www.python.org/moin/WebProgramming
for some starting points; you probably want to write a CGI.

> One project is to make a web page that users login to with a name and 
> password, choose from a list of "canned" directory structure (ie. how 
> many subdirectories, top-level name, maybe permissions, etc), hit a "GO" 
> button and then the directories are made.

If you mean to make the directories on the user's machine, I don't think this is possible with just 
HTML and a browser. You could do it with a signed Java applet. If you mean to make the directories 
on the server then yes, you can do this.

> 
> Another example is a web-based form that users interface with a mySQL 
> database.  Simple additions/changes/deletions.  Basic stuff.

Yes, you can do this in Python.

Kent

From python at jayloden.com  Sat Apr 23 18:48:54 2005
From: python at jayloden.com (Jay Loden)
Date: Sat Apr 23 18:49:53 2005
Subject: [Tutor] Python and Web Pages?
In-Reply-To: <426A7341.5070207@linuxscope.com>
References: <426A7341.5070207@linuxscope.com>
Message-ID: <200504231748.55179.python@jayloden.com>

I use both Python and PHP on my website to do a variety of tasks.  Some things 
PHP can do much easier than Python, but if you're doing simple things like 
form handling, Python will do nicely.  

If you're comfortable with Python, use it.  I find Python much easier to work 
with than PHP for a lot of things, but PHP works better with dynamic content 
within html, so I use each one where it's easiest. However, if you're not 
familiar with PHP, then I definitely wouldn't go out and learn PHP for this; 
just stick with Python because you'll get it done faster when you're 
comfortable.

-Jay

On Saturday 23 April 2005 05:09 pm, Paul Tader wrote:
> I have a couple programs/scripts that I want to write that need to be
> web-based.  Can Python (and a little HTML) accomplish this?  Or are
> other languages like PHP, or Perl better suited?
>
>
> A little more detail:
>
> One project is to make a web page that users login to with a name and
> password, choose from a list of "canned" directory structure (ie. how
> many subdirectories, top-level name, maybe permissions, etc), hit a "GO"
> button and then the directories are made.
>
> Another example is a web-based form that users interface with a mySQL
> database.  Simple additions/changes/deletions.  Basic stuff.
>
>
> Thanks,
> Paul
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From bvande at po-box.mcgill.ca  Sat Apr 23 18:19:20 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sat Apr 23 19:24:07 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
Message-ID: <426A7588.5030404@po-box.mcgill.ca>

Hi all,

I am wondering about the Pythonic way to handle the problem of 
ostriches, emus, and penguins. (I cannot recall from where I got the 
example.)

Here's what I mean:

class Bird(object):
     def fly(self):
         # flying logic here
     def lay(self):
         # egg-laying logic here
     # more bird methods

class Ostrich(Bird):
     # ostriches can't fly, so what to do?

I've explored a number of solutions; here they are with what I see as 
to cons and problems:


The simplest thing is to emulate the ostrich and pretend the problem 
doesn't exist. But, putting one's head in the sand looks likely to 
cause troubles in that this route break encapsulation, requiring 
callers to know enough not to call the fly method of an ostrich. So, 
that's no good.


class Ostrich(Bird):
     def fly(self):
         pass

seems only marginally better, in that it gives the external appearance 
of flight, whereas what is needed is a "Hey, I don't fly" signal.


The next thought was to over-ride Ostrich.fly as
     def fly(self):
          raise NotImplementedError

That seems better, but also a bit confusing; the way I understand it, 
NotImplementedError is, in the first instance, for abstract classes or 
for marking work in progress. But Ostrich.fly doesn't fit either case.


That makes me think to define a custom exception, say

class OstrichError(NotImplementedError):
     '''A custom exception for cases of the "Ostrich problem".

     Intended to be raised by methods in a subclass over-riding methods
     of the parent which don't make sense for the subclass to actually
     implement.'''
     def __init__(self):
         NotImplementedError.__init__(self)

But, since the problem isn't one that my penetrating genius 
discovered, I am inclined to think that were this the ideal solution, 
there'd be a (better named) exception class builtin to Python already.


A complicated class hierarchy like

class Bird(object):
     # bird logic

class FlyingBird(Bird):
     def fly(self):
         # flying logic here

class FlightlessBird(Bird):
     # any particularly flightless logic here

class Ostrich(FlightlessBird):
     # ostrich logic

seems an invitation to difficulty. My analogy will soon break, but 
some birds build nests and sing, others, no so much, etc. Flat is soon 
to give way to deeply nested.


I also tried to delete the inherited Bird.fly method within 
Ostrich.__init__, but

class Ostrich(Bird):
     def __init__(self):
         del self.__dict__['fly']

raises a KeyError, whereas

     def __init__(self):
         del Ostrich.__dict__['fly']

raises:
TypeError: object does not support item deletion


Do I have the syntax of the last approach wrong? Or is there no way to 
remove a method from a class? If the latter, what to do about 
flightless fowl?

Thanks and best,

Brian vdB

From magoldfish at gmail.com  Sat Apr 23 19:47:31 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Sat Apr 23 19:47:33 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <426A2B77.3030604@tds.net>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>
	<426A2B77.3030604@tds.net>
Message-ID: <5e183f3d05042310474fd04896@mail.gmail.com>

> - As Rich pointed out, making Foo into it's own iterator by adding a next()
> method is not a good idea. A simple way to define your own iterator is to
I see that an iterator is conceptually distinct from the container
object it iterates over, but I am confused that both the iterator and
container implement __iter__() to support the iterator protocol.  In
my original Foo implementation, __iter__() returned a list, which
supports the iterator protocol, so it "just worked" (albeit not for
all cases, and not efficiently).  In general, though, how would I
implement my own iterator (not using generator functions)?  Would I
have to have a FooIterator class?  What would FooIterator.__iter__()
return?

> make __iter__() into a generator function like
... so gfs look much easier!  This is the first concrete use for gf's
I've found in my code so far, and it rocks-- is it always possible to
implement an iterator using gfs?  Is there a performance issue to be
aware of when using gfs?

> you want. A simple definition for __eq__() that finds these unequal would be
>   def __eq__(self, other):
>     return self.head == other.head and self.tail == other.tail
Ok, I like the modified __eq__(), but now I want my Foo class to store
the head and tail lists as private attributes (self.__head,
self.__tail).  Is it pythonic to modify the __eq__() method to:

   def __eq__(self, other):
      return self.__head == other._Foo__head and self.__tail == other._Foo__tail

or is this too restrictive (e.g., perhaps I wish to compare a Foo and
Bar class as correlated list sequences.  It is likely that
other._Foo__head will fail for a Bar).

> - If you define __eq__() you should also define __ne__(). Alteratively you can
... because it seems that Foo1 != Foo2 will fail otherwise.  Why is that?

Thanks (you too, Rich) for the very helpful comments!
Marcus
From kent37 at tds.net  Sat Apr 23 19:58:59 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 19:59:03 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <426A7588.5030404@po-box.mcgill.ca>
References: <426A7588.5030404@po-box.mcgill.ca>
Message-ID: <426A8CE3.7070804@tds.net>

Brian,

I think you have done a great job of demonstrating that design has to be evaluated in the light of 
requirements. There are probably scenarios where each of these solutions makes sense. Without 
knowing how it is to be used, there is no way to pick the 'right' one.

For example in a bird simulation it might be fine to have Ostrich.fly() do nothing. Possibly the 
version that throws an exception would be useful there also. The class hierarchy with FlyingBird is 
maybe more 'correct' but I don't know that it would be any easier to use in practice.

If you make Ostrich.fly() raise AttributeError it will look to the caller like it is not 
implemented...NotImplementedError seems appropriate as well. If you want to define your own 
exception it can be as simple as
class FlightlessBirdException(Exception):
   pass

Kent

Brian van den Broek wrote:
> Hi all,
> 
> I am wondering about the Pythonic way to handle the problem of 
> ostriches, emus, and penguins. (I cannot recall from where I got the 
> example.)
> 
> Here's what I mean:
> 
> class Bird(object):
>     def fly(self):
>         # flying logic here
>     def lay(self):
>         # egg-laying logic here
>     # more bird methods
> 
> class Ostrich(Bird):
>     # ostriches can't fly, so what to do?
> 
> I've explored a number of solutions; here they are with what I see as to 
> cons and problems:
> 
> 
> The simplest thing is to emulate the ostrich and pretend the problem 
> doesn't exist. But, putting one's head in the sand looks likely to cause 
> troubles in that this route break encapsulation, requiring callers to 
> know enough not to call the fly method of an ostrich. So, that's no good.
> 
> 
> class Ostrich(Bird):
>     def fly(self):
>         pass
> 
> seems only marginally better, in that it gives the external appearance 
> of flight, whereas what is needed is a "Hey, I don't fly" signal.
> 
> 
> The next thought was to over-ride Ostrich.fly as
>     def fly(self):
>          raise NotImplementedError
> 
> That seems better, but also a bit confusing; the way I understand it, 
> NotImplementedError is, in the first instance, for abstract classes or 
> for marking work in progress. But Ostrich.fly doesn't fit either case.
> 
> 
> That makes me think to define a custom exception, say
> 
> class OstrichError(NotImplementedError):
>     '''A custom exception for cases of the "Ostrich problem".
> 
>     Intended to be raised by methods in a subclass over-riding methods
>     of the parent which don't make sense for the subclass to actually
>     implement.'''
>     def __init__(self):
>         NotImplementedError.__init__(self)
> 
> But, since the problem isn't one that my penetrating genius discovered, 
> I am inclined to think that were this the ideal solution, there'd be a 
> (better named) exception class builtin to Python already.
> 
> 
> A complicated class hierarchy like
> 
> class Bird(object):
>     # bird logic
> 
> class FlyingBird(Bird):
>     def fly(self):
>         # flying logic here
> 
> class FlightlessBird(Bird):
>     # any particularly flightless logic here
> 
> class Ostrich(FlightlessBird):
>     # ostrich logic
> 
> seems an invitation to difficulty. My analogy will soon break, but some 
> birds build nests and sing, others, no so much, etc. Flat is soon to 
> give way to deeply nested.
> 
> 
> I also tried to delete the inherited Bird.fly method within 
> Ostrich.__init__, but
> 
> class Ostrich(Bird):
>     def __init__(self):
>         del self.__dict__['fly']
> 
> raises a KeyError, whereas
> 
>     def __init__(self):
>         del Ostrich.__dict__['fly']
> 
> raises:
> TypeError: object does not support item deletion
> 
> 
> Do I have the syntax of the last approach wrong? Or is there no way to 
> remove a method from a class? If the latter, what to do about flightless 
> fowl?
> 
> Thanks and best,
> 
> Brian vdB
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Sat Apr 23 20:01:53 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 20:01:59 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <5e183f3d0504221902e0f414e@mail.gmail.com>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>
Message-ID: <426A8D91.1010502@tds.net>

Sending to the list, originally this went just to Marcus...

Marcus Goldfish wrote:
> I'm trying to understand custom iterators in Python, and created the
> following toy class for sequence comparison, which seems to work:
> 
> class Foo(object):
>    """A toy class to experiment with __eq__ and __iter__"""
>    def __init__(self, listA, listB):
>       self.head, self.tail = listA, listB
>    def __iter__(self):
>       return iter(self.head[:]+self.tail[:])
>    def __eq__(self, other):
>       """Foo instances are equal if their respective subsequences,
>       head, tail, are in the same order"""
>       diff = [i for i, j in zip(self, other) if i != j]
>       return len(diff) == 0
> 
> I'm not really sure if I'm implementing iter() correctly, for
> instance: should I make copies of the sublists?  Should I try to
> implement my own next() method?

A few comments:
- A semantic point - you haven't created a custom iterator, you have created a class that is
iterable. The actual iterator is the standard list iterator.

- You actually copy head and tail twice in __iter__ - once explicitly with [:] and once with + which
makes a new list. Neither copy is needed.

- As Rich pointed out, making Foo into it's own iterator by adding a next() method is not a good
idea. A simple way to define your own iterator is to make __iter__() into a generator function like
this:
   def __iter__(self):
     for i in self.head:
       yield i
     for i in self.tail:
       yield i

- __eq__() will say that Foo([1,2], [3,4]) == [1,2,3,4] which may not be what you want. If not then
put in a test for isinstance(other, Foo)

- __eq__() will say that Foo([1], [2]) == Foo([1, 2], []) which may not be what you want. A simple
definition for __eq__() that finds these unequal would be
   def __eq__(self, other):
     return self.head == other.head and self.tail == other.tail

- If you define __eq__() you should also define __ne__(). Alteratively you can define __cmp__().

Reference on iterators:
http://docs.python.org/lib/typeiter.html

Reference on __eq__():
http://docs.python.org/ref/customization.html

Kent


From rmkrauter at yahoo.com  Sat Apr 23 20:11:29 2005
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Sat Apr 23 20:12:24 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <426A7588.5030404@po-box.mcgill.ca>
References: <426A7588.5030404@po-box.mcgill.ca>
Message-ID: <426A8FD1.6050201@yahoo.com>

Brian van den Broek wrote:
> Hi all,
> 
> I am wondering about the Pythonic way to handle the problem of 
> ostriches, emus, and penguins. (I cannot recall from where I got the 
> example.)
> 
> Here's what I mean:
> 
> class Bird(object):
>     def fly(self):
>         # flying logic here
>     def lay(self):
>         # egg-laying logic here
>     # more bird methods
> 
> class Ostrich(Bird):
>     # ostriches can't fly, so what to do?
> 
> I've explored a number of solutions; here they are with what I see as to 
> cons and problems:
> 
> 
> The simplest thing is to emulate the ostrich and pretend the problem 
> doesn't exist. But, putting one's head in the sand looks likely to cause 
> troubles in that this route break encapsulation, requiring callers to 
> know enough not to call the fly method of an ostrich. So, that's no good.
> 
> 
> class Ostrich(Bird):
>     def fly(self):
>         pass
> 
> seems only marginally better, in that it gives the external appearance 
> of flight, whereas what is needed is a "Hey, I don't fly" signal.
> 
> 
> The next thought was to over-ride Ostrich.fly as
>     def fly(self):
>          raise NotImplementedError
> 
> That seems better, but also a bit confusing; the way I understand it, 
> NotImplementedError is, in the first instance, for abstract classes or 
> for marking work in progress. But Ostrich.fly doesn't fit either case.
> 
> 
> That makes me think to define a custom exception, say
> 
> class OstrichError(NotImplementedError):
>     '''A custom exception for cases of the "Ostrich problem".
> 
>     Intended to be raised by methods in a subclass over-riding methods
>     of the parent which don't make sense for the subclass to actually
>     implement.'''
>     def __init__(self):
>         NotImplementedError.__init__(self)
> 
> But, since the problem isn't one that my penetrating genius discovered, 
> I am inclined to think that were this the ideal solution, there'd be a 
> (better named) exception class builtin to Python already.
> 
> 
> A complicated class hierarchy like
> 
> class Bird(object):
>     # bird logic
> 
> class FlyingBird(Bird):
>     def fly(self):
>         # flying logic here
> 
> class FlightlessBird(Bird):
>     # any particularly flightless logic here
> 
> class Ostrich(FlightlessBird):
>     # ostrich logic
> 
> seems an invitation to difficulty. My analogy will soon break, but some 
> birds build nests and sing, others, no so much, etc. Flat is soon to 
> give way to deeply nested.
> 
> 
> I also tried to delete the inherited Bird.fly method within 
> Ostrich.__init__, but
> 
> class Ostrich(Bird):
>     def __init__(self):
>         del self.__dict__['fly']
> 
> raises a KeyError, whereas
> 
>     def __init__(self):
>         del Ostrich.__dict__['fly']
> 
> raises:
> TypeError: object does not support item deletion
> 
> 
> Do I have the syntax of the last approach wrong? Or is there no way to 
> remove a method from a class? If the latter, what to do about flightless 
> fowl?
> 
> Thanks and best,
> 
> Brian vdB
> 


Brian,

I've seen the strategy pattern used in this kind of scenario. Your 
strategies can be encapulated classes, and methods within the Bird 
classes delegate to the strategy classes - so you achieve desired 
behavior though composition, rather than inheritance.

Here's a quick example (which doesn't really address any of your 
questions and probably has its own problems):

class CantFly(object):
     def fly(self):
         print "I can't fly"

class CanFly(object):
     def fly(self):
         print "I can fly"

class Bird(object):
     def __init__(self,flightBehavior):
         self.flightBehavior = flightBehavior

     def fly(self):
         self.flightBehavior.fly()

b1 = Bird(CantFly())
b2 = Bird(CanFly())

for b in (b1,b2):
     b.fly()

Good luck.

Rich
From kent37 at tds.net  Sat Apr 23 20:18:53 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat Apr 23 20:18:58 2005
Subject: [Tutor] iterator question for a toy class
In-Reply-To: <5e183f3d05042310474fd04896@mail.gmail.com>
References: <5e183f3d0504221902e0f414e@mail.gmail.com>	
	<426A2B77.3030604@tds.net>
	<5e183f3d05042310474fd04896@mail.gmail.com>
Message-ID: <426A918D.101@tds.net>

Marcus Goldfish wrote:
> I see that an iterator is conceptually distinct from the container
> object it iterates over, but I am confused that both the iterator and
> container implement __iter__() to support the iterator protocol.

I think this is to simplify the Python runtime. 'for i in c' will work if c is an iterable container 
or an actual iterator. In either case the runtime can just call c.__iter__() and get an iterator.

   In
> my original Foo implementation, __iter__() returned a list, which
> supports the iterator protocol, so it "just worked" (albeit not for
> all cases, and not efficiently).  

Actually your Foo.__iter__() returned an iterator over a list. You called iter() on a list, which 
returns an iterator.

In general, though, how would I
> implement my own iterator (not using generator functions)?  Would I
> have to have a FooIterator class?  

Yes, that would be the simplest way.

What would FooIterator.__iter__()
> return?

self.

Here's an attempt at Foo.__iter__() that creates a custom iterator object...no, actually, it is so 
awkward I'm not going to bother. FooIterator has to keep a lot of state - the current list being 
indexed and the current index. Use a generator function!

>>make __iter__() into a generator function like
> 
> ... so gfs look much easier!  This is the first concrete use for gf's
> I've found in my code so far, and it rocks-- is it always possible to
> implement an iterator using gfs?  

Yes, at least there are no restriction I know of. Maybe some strange case where it doesn't make 
sense. The docs say, "Python's generators provide a convenient way to implement the iterator 
protocol. If a container object's __iter__() method is implemented as a generator, it will 
automatically return an iterator object (technically, a generator object) supplying the __iter__() 
and next() methods."

Is there a performance issue to be
> aware of when using gfs?

Not that I know of. Try it and see. It wouldn't surprise me to find that gfs are faster; generally 
the more you use builtin stuff the faster your code will run.

>>you want. A simple definition for __eq__() that finds these unequal would be
>>  def __eq__(self, other):
>>    return self.head == other.head and self.tail == other.tail
> 
> Ok, I like the modified __eq__(), but now I want my Foo class to store
> the head and tail lists as private attributes (self.__head,
> self.__tail).  Is it pythonic to modify the __eq__() method to:
> 
>    def __eq__(self, other):
>       return self.__head == other._Foo__head and self.__tail == other._Foo__tail

You just need other.__head

> or is this too restrictive (e.g., perhaps I wish to compare a Foo and
> Bar class as correlated list sequences.  It is likely that
> other._Foo__head will fail for a Bar).

It depends on how you want to use Foo. Since it is a toy you can make it do whatever you want.

>>- If you define __eq__() you should also define __ne__(). Alteratively you can
> 
> ... because it seems that Foo1 != Foo2 will fail otherwise.  Why is that?

Because Python doesn't assume that __eq__() and __ne__() are inverses. See
http://docs.python.org/ref/customization.html

Kent

From alan.gauld at freenet.co.uk  Sat Apr 23 21:02:45 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 23 21:02:13 2005
Subject: [Tutor] CLS? (Joseph Quigley)
References: <6.1.0.6.2.20050421181106.01efa008@pop.gmail.com>
	<005701c54792$f85a6c40$dad48651@xp>
	<6.1.0.6.2.20050423082001.01f11a00@pop.gmail.com>
Message-ID: <009501c54837$091290e0$dad48651@xp>

> Drat. I do like the \n * 100 though but that really wasn't what I
was
> getting at. Do you know what the command is for Mac

The problem is that it depends not just on the OS.

MacOS X is Unix and that can support zillions of different terminal
types each with their own control codes. These are mapped to a
standard set in a database called (depending on your Unix version!)
terminfo or termcap (cap=capability) and manipulated by a utility
called tty. The difficulty is that not all terminals support all
capabilities so you have to call stty to first find out if the
capability exists, then use stty again to set it. - Altogether
far too messy for most mortals.

The more common route on Unix is to use the curses library which
provides a windowing toolkit for a dumb terminal. The default
window is the whole screeen and curses allows you to position the
cursor at any point on screen, clear the screen(Or any rectangular
section of it) and so on.

Try man terminfo for the full story, and man curses if you want
to go down that route. Programs like vi and top are written using
curses.

> considering not clearing the screen. What a hassle.

As someone else said thats actually the right approach on a Unix box.
Consider that some folks might be using an old paper teletype where
the text just prints onto paper which scrolls off the top. What
happens
with my print '\n'*100 there? - they get a lot of white paper!

Now on DOS MIcrosoft used a thing called the ANSI terminal which is
a kind of virtual terminal standard that a lot of terminal
manufacturers
could support in addition to their own standards. It was pretty dumb
but by adopting a standard QBASIC et al could implement screen
controlls
in assembler so they were both fast and reliable. But it only workled
because the PC only supported that one standard.

The joys of multi platform computing! :-)

Alan G.

From alan.gauld at freenet.co.uk  Sat Apr 23 21:06:43 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 23 21:06:13 2005
Subject: [Tutor] Help with this script
References: <BAY20-F708AA180AEF4F554D8346B32E0@phx.gbl>
Message-ID: <00a701c54837$96d66000$dad48651@xp>

> should display the relevant menu. My first menu comes on but if I
select "b"
> or "c" the script does not run. The error message points out that
> "print_options()" or "print_options_2()" are not defined. Could
somebody
> point me into the right direction, thanks.

Thats because you define them after you call task_options().
So when task_options runs you haven't defined the functions
it is trying to call.

Put the code that actually calls your functions at the very end of the
script.


>
> --------------------------------------------------------------------
-------------------------
> #By J Carmona
> #Programme that compute volumes or surfaces
> ##First menu is for the calculation of area
> ##Second menu is for the calculation of volume
>
> ##First ask the user what he wants to do
> running = True
>
> def area_rect():
>         length = input("Length: ")
>         width = input ("Width: ")
>         print "The area is: ",length*width
>
> def area_circ():
>         radius = input("What is the radius?: ")
>         print "The area is approximately: ", 3.14159*(radius**2)
>
> def area_squ():
>         side = input ("What is the length of one side?: ")
>         print "The area is: ", side*side
>
> def area_tgle():
>         base = input ("What is the base of the triangle?: ")
>         heigth = input ("What is the heigth of the triangle?: ")
>         print "The area is: ",base*heigth/2
>
> def vol_sph():
>         radius = input("What is the radius?: ")
>         print "The volume is: ", (4*3.14159*radius**3)/3
>
> def vol_cube():
>         side = input("Side: ")
>         print "The volume is: ",side**3
>
> def vol_box():
>         width = input ("What is the width of the box?: ")
>         length = input ("What is the length of the box?: ")
>         depth = input ("What is the depth of the box?: ")
>         print "The volume is: ", width*length*depth
>
> def vol_cone():
>         radius = input ("What is the radiux of the base of the
cone?: ")
>         heigth = input ("What is the heigth of the cone?: ")
>         print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)
>
>
> def task_options():
>         print "---------------------------------------"
>         print "Options:"
>         print "a. Print options: "
>         print "b. Do you want to calculate areas?: "
>         print "c. Do you want to calculate volumes?: "
>         print "d. Quit the programme"
>         print "---------------------------------------"
>         choice = raw_input("Choose an option: ")
>         if choice == 'a':
>             print task_options()
>         elif choice == 'b':
>             print print_options()
>         elif choice == 'c':
>             print print_options_2()
>         elif choice == 'd':
>             running = False
> print task_options()
>
>
> def print_options():
>         print "------------------------------"
>         print "Options:"
>         print "a. print options"
>         print "b. calculate circle area"
>         print "c. calculate square area"
>         print "d. calculate rectangle area"
>         print "e. calculate triangle area"
>         print "f. quit the programme"
>         print "------------------------------"
>         choice = raw_input("Choose an option: ")
>         if choice == 'a':
>             print_options()
>         elif choice == 'b':
>             area_circ()
>         elif choice == 'c':
>             area_squ()
>         elif choice == 'd':
>             area_rect()
>         elif choice == 'e':
>             area_tgle()
>         elif choice == 'f':
>                 print_options()
> #Call starting menu
> print_options()
>
> def print_options_2():
>         print "------------------------------"
>         print "Options:"
>         print "a. print options"
>         print "b. calculate the volume of a sphere"
>         print "c. calculate the volume of a cube"
>         print "d. calculate the volume of a box"
>         print "e. calculate the volume of a cone"
>         print "f. quit the programme"
>         print "------------------------------"
>         choice = raw_input("Choose an option: ")
>         if choice == 'a':
>             print_options()
>         elif choice == 'b':
>             vol_sph()
>         elif choice == 'c':
>             vol_cube()
>         elif choice == 'd':
>             vol_box()
>         elif choice == 'e':
>             vol_cone()
>         elif choice == 'e':
>             print_options()
> #Call starting menu
> print_options()
> --------------------------------------------------------------------
-----------------------------------------------------------
>
> JC
>
>
>
>

From alan.gauld at freenet.co.uk  Sat Apr 23 21:18:30 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 23 21:18:07 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
References: <426A7588.5030404@po-box.mcgill.ca>
Message-ID: <00bc01c54839$3c3c07b0$dad48651@xp>

> I am wondering about the Pythonic way to handle the problem of
> ostriches, emus, and penguins. (I cannot recall from where I got the
> example.)

Its not really a Python issue its one of several similar conundrums in
OOP in any language.

My solution for this one:

class Bird()...

class FlightlessBird(BIrd):...

class FlyingBird(Bird):...

class Ostritch(FlightlessBird):...

class Emu(FlighlessBird):...

class Seagull(FlyingBird):...

etc.

But it gets complicated when you get more exceptions and you wind up
with
an explosion of classes. So in general there is a design pattermn that
helps out called a decorator(I hope thats the right one...).

The other approach(which I prefer) is to use a concept called a Mixin
(as mixing in flavours in an ice cream parlour - it was introduced in
the Lisp OO Language Flavors...). Mixins are little classes that
define
behaviour in a generic way. You then use multiple inheritance to
create the mix you need:

class Bird....

class Flight:.... # used for birds or planes or rockets...

class Nesting:....

class TreeDweller....

class HouseDweller...

class Swallow(Bird, Flight, HouseDweller, Nesting)....

class  Ostritch(Bird)....

class Owl(Bird,Flight, Nesting, TreeDweller)...

and so on.

But this only works well in languages that support dynamic
binding, and multiple inheritance - like Python!

But as I said similar problems exist and there is no simple answer.
You pick the one with least pain for your situation. (A common
example is where do Square and Rectangle sit in a heirarchy of
shapes?....)

HTH

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


From bvande at po-box.mcgill.ca  Sat Apr 23 23:39:49 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sat Apr 23 23:42:26 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <00bc01c54839$3c3c07b0$dad48651@xp>
References: <426A7588.5030404@po-box.mcgill.ca>
	<00bc01c54839$3c3c07b0$dad48651@xp>
Message-ID: <426AC0A5.1040102@po-box.mcgill.ca>

Alan Gauld said unto the world upon 2005-04-23 15:18:
>>I am wondering about the Pythonic way to handle the problem of
>>ostriches, emus, and penguins. (I cannot recall from where I got the
>>example.)
> 
> 
> Its not really a Python issue its one of several similar conundrums in
> OOP in any language.


Thanks Alan, Kent, and Rich for the replies.

Since posting I retraced my steps and found where I came across the 
example: an OK book Object-Oriented Thought Process, The, Second 
Edition By Matt Weisfeld that I read on safari 
<http://safari.oreilly.com/0672326116/copyrightpg>. Weisfled points 
out the ostrich problem has often been cited by those who say "don't 
inherit, compose".

Alan's second solution (the mixin approach), seems to go in that 
direction. (I'm not attributing endorsement of "don't inherit" to any 
of the respondents!) In spirit, if not details, Rich's Strategy 
Pattern suggestion seems to point in that direction, too.

Any of these solutions (or the alternatives in my original post) seem 
likely to be messy in some contexts. I take Kent and Alan's points  to 
that effect.


I do remain a bit surprised that there seems to be no way to implement 
what I naively thought would be the obvious solution -- to remove an 
inherited method from the instance's dictionary.

Anyway, thanks again to all,

Brian vdB

From tktucker at gmail.com  Sun Apr 24 03:43:05 2005
From: tktucker at gmail.com (Tom Tucker)
Date: Sun Apr 24 03:43:09 2005
Subject: [Tutor] Does Python have anything like Perls format output?
Message-ID: <2a278ffe0504231843448ea8f7@mail.gmail.com>

Good evening!  Does Python have a print function similar to Perl
format output (example below)?

Thanks

Tom

        format STDOUT =
        @<<<<< @>>>> @<<<<<<<<<<<<<<<<<<< $@######.## $@######.##
        $code, $date,$descript, 	       $amt,       $balance
From dyoo at hkn.eecs.berkeley.edu  Sun Apr 24 03:54:24 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Apr 24 03:54:29 2005
Subject: [Tutor] Does Python have anything like Perls format output?
In-Reply-To: <2a278ffe0504231843448ea8f7@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504231847070.31437-100000@hkn.eecs.berkeley.edu>



On Sat, 23 Apr 2005, Tom Tucker wrote:

> Good evening!  Does Python have a print function similar to Perl
> format output (example below)?

Hi Tom,

Not exactly, but we can get something close, by using the String
Formatting operators.

    http://www.python.org/doc/current/lib/typesseq-strings.html

The example above might be written as:

######
code = "hi"
date = "0420"
descript = "a test of formatting"
amt = 3.14
balance = 2.71
text = """
%-5s %4s %-19s %5.2f %5.2f
""" % (code, date, descript, amt, balance)
print text
######

If you have more questions, please feel free to bring them to the group.

From dyoo at hkn.eecs.berkeley.edu  Sun Apr 24 04:16:41 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Apr 24 04:16:49 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <426AC0A5.1040102@po-box.mcgill.ca>
Message-ID: <Pine.LNX.4.44.0504231854490.31437-100000@hkn.eecs.berkeley.edu>



> I do remain a bit surprised that there seems to be no way to implement
> what I naively thought would be the obvious solution -- to remove an
> inherited method from the instance's dictionary.


Hi Brian,

If we're trying to do this, we probably don't want to "inherit" from a
parent.  A subclass child is supposed to have, at the very least, the same
public methods as its parent.  For example, if we have a:

######
class Account:
    def __init__(self, amount):
        self.amount = amount

    def withdraw(self, x):
        assert x > 0
        self.amount = self.amount - x

    def report(self):
        print "You have ", self.amount, "dollars"
#######


And we'd like to reuse this, but for something that doesn't report itself,
we shouldn't use inheritance:

#######
class SecretAccount(Account):
    def report(self):
        pass
#######


This SecretAccount is now pretending to be an account that doesn't have a
usable report() method.

#######
>>> Account(5).report()
You have  5 dollars
>>> SecretAccount(5).report()
>>>
#######



But we can get into trouble again, if, later on, Account is expanded to
have a few more additional functions:

######
class Account:  ## version 2
    # [same as before]
    def htmlReport(self):
        print ("<html><body><p>You have %d dollars</p></body></html" %
                self.amount)
######

And now, suddenly, SecretAccount again has a method that shows information
that it probably doesn't want out in the open.


The issue that that SecretAccount is really not trying to be an "Account":
it's just trying to reuse its functionality.  Instead of doing things with
inheritance, we're probably looking for delegation:

#######
class SecretAccount:
    def __init__(self, amount):
        self.account = Account(amount)
    def withdraw(self, x):
        self.account.withdraw(x)
#######

And now we're more isolated from changes to the Account class.


There are some more Pythonic idioms to make delegation easier to code.
And the example above is hideously toyish.  *grin*

But I hope the idea's a little clearer: inheritance ties the subclass down
to at least what the superclass has promised, and in many cases, that's
not what we want.


Best of wishes!

From polatel at gmail.com  Sun Apr 24 08:15:37 2005
From: polatel at gmail.com (Ali Polatel)
Date: Sun Apr 24 08:15:40 2005
Subject: [Tutor] Bandwidth Tester
Message-ID: <3c51d51805042323155503b194@mail.gmail.com>

   Hi Tutors,
   How can i write a simple bandwidth tester with Python?
   Regards,
From bvande at po-box.mcgill.ca  Sun Apr 24 08:27:11 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Sun Apr 24 08:28:17 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <Pine.LNX.4.44.0504231854490.31437-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0504231854490.31437-100000@hkn.eecs.berkeley.edu>
Message-ID: <426B3C3F.7090305@po-box.mcgill.ca>

Danny Yoo said unto the world upon 2005-04-23 22:16:
> 
>>I do remain a bit surprised that there seems to be no way to implement
>>what I naively thought would be the obvious solution -- to remove an
>>inherited method from the instance's dictionary.
> 
> 
> 
> Hi Brian,
> 
> If we're trying to do this, we probably don't want to "inherit" from a
> parent.  A subclass child is supposed to have, at the very least, the same
> public methods as its parent.  For example, if we have a:


<SNIP e.g. of an account class with report method and a subclass 
SecretAccount which overrides the report method to do nothing>


> But we can get into trouble again, if, later on, Account is expanded to
> have a few more additional functions:
> 
> ######
> class Account:  ## version 2
>     # [same as before]
>     def htmlReport(self):
>         print ("<html><body><p>You have %d dollars</p></body></html" %
>                 self.amount)
> ######
> 
> And now, suddenly, SecretAccount again has a method that shows information
> that it probably doesn't want out in the open.
> 
> 
> The issue that that SecretAccount is really not trying to be an "Account":
> it's just trying to reuse its functionality.  Instead of doing things with
> inheritance, we're probably looking for delegation:
> 
> #######
> class SecretAccount:
>     def __init__(self, amount):
>         self.account = Account(amount)
>     def withdraw(self, x):
>         self.account.withdraw(x)
> #######
> 
> And now we're more isolated from changes to the Account class.
> 
> 
> There are some more Pythonic idioms to make delegation easier to code.
> And the example above is hideously toyish.  *grin*
> 
> But I hope the idea's a little clearer: inheritance ties the subclass down
> to at least what the superclass has promised, and in many cases, that's
> not what we want.


Thanks Danny, that's really helpful.

I still think the "delete an inherited method" approach could be 
useful in some cases, but your example certainly shows it would come 
with its own sack of troubles, too. Given that it would take a 
language change, and wouldn't be less troubled than any of the other 
available approaches, I can now happily agree that it wouldn't be 
worth it.

Best to all,

Brian vdB

From alan.gauld at freenet.co.uk  Sun Apr 24 09:48:01 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun Apr 24 09:47:26 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
References: <426A7588.5030404@po-box.mcgill.ca><00bc01c54839$3c3c07b0$dad48651@xp>
	<426AC0A5.1040102@po-box.mcgill.ca>
Message-ID: <00d201c548a1$f22babd0$dad48651@xp>

> I do remain a bit surprised that there seems to be no way to
implement
> what I naively thought would be the obvious solution -- to remove an
> inherited method from the instance's dictionary.

You can, as Kent said, override the method to do nothing. Some
languages,
like Eifell offer better support for that than others.

But there is a danger in removing methods too. By doing so you break
one of the fundamental principles of inheritence:
that everywhere that you use the superclass you can use the sub class.

If you remove the fly() method from your subclass of birds code like
this will break:

birds = [ aSwallow, anOstrich, anEmu, anEagle]

for bird in birds:
   bird.fly()

Whereas if you simply make fly a null method you can still call it
but nothing happens - a lot safer...

But conceptually the problem (and it is common) is that bird has a
fly() method when not all birds can fly - the object model is broken
at a high level of abstraction.

HTH,

Alan G.


From alan.gauld at freenet.co.uk  Sun Apr 24 09:54:03 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun Apr 24 09:55:31 2005
Subject: [Tutor] Does Python have anything like Perls format output?
References: <2a278ffe0504231843448ea8f7@mail.gmail.com>
Message-ID: <00d701c548a2$c9116770$dad48651@xp>

> Good evening!  Does Python have a print function similar to Perl
> format output (example below)?
>        format STDOUT =
>        @<<<<< @>>>> @<<<<<<<<<<<<<<<<<<< $@######.## $@######.##
>        $code, $date,$descript,        $amt,       $balance

This should be in a FAQ somewhere because it comes up a lot!

There is no direct equivalent but very similar effects are achieved 
using triple quoted format strings with named parameters:

format = '''
%-5(code)s %4(date)s %-20(descript)s $%9.2(amt)f $%9.2(balance)f'''

Then when you print the string provide the builtin local variables 
dictionary as the feeder for the variable substitution.

PS. 
The above string may not be exactly the same as your example 
- my Perl memory is fading fast...

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  Sun Apr 24 10:49:36 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Apr 24 10:49:40 2005
Subject: [Tutor] Bandwidth Tester
In-Reply-To: <3c51d51805042323155503b194@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504240136420.32457-100000@hkn.eecs.berkeley.edu>



On Sun, 24 Apr 2005, Ali Polatel wrote:

> How can i write a simple bandwidth tester with Python?

Hi Ali,

A really rough sketch would be:


###### Really rough pseudocode
def bandwidthTest():
    Record the current time (use time.time())
    Choose some resource that you can download, and download it
    Record the current time again.
######

By this time, you should have some file that has been downloaded, and
you'll know how long it took you to get that file: this is enough
information to get a rough bandwidth calculation.


To make it robust, you'll probably want to do this on several resources on
the web, and on ones that are reliably fast, and then average the results.
You might also have to take into account things like bad connections, or
perhaps servers going down.  So the real world makes things a little
messy.


If you'd like a real example of one that's in production use, see:

    http://mozmonkey.com/bandwidthtest/

It's the bandwidth tester used by the Firefox project.  The source code is
in Javascript, and can be extracted by using 'jar' to unpack the .XPI
file.

The source code in 'chrome/tester.js' doesn't look too particularly
daunting: the basic idea is the one sketched up above, with some special
cases to make sure silly things like Divide-by-zero don't happen.  And
it's slightly ugly because the interface / status-report code is mixed in
with the algorithm, but oh well.  *grin*

Best of wishes!

From jeannot18 at hotmail.com  Sun Apr 24 12:27:37 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Sun Apr 24 12:27:41 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <426A6EAA.8080009@tds.net>
Message-ID: <BAY20-F216C34B5351ABEBF09B8F1B32F0@phx.gbl>

Thanks for the help Kent, Noel and Alan. Here is my final script (it seems 
to be working ok but sometimes if I select "quit the programme", I need to 
enter that option 2 or 3 times before it works, is this a bug (I am running 
Win XP), please feel free to comment if you thing that something could be 
improved. Time to do the next exercise.
JC

------------------------------------------------------------------------------------
#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume

##First ask the user what he wants to do
running = True

def area_rect():
        length = input("Length: ")
        width = input ("Width: ")
        print "The area is: ",length*width

def area_circ():
        radius = input("What is the radius?: ")
        print "The area is approximately: ", 3.14159*(radius**2)

def area_squ():
        side = input ("What is the length of one side?: ")
        print "The area is: ", side*side

def area_tgle():
        base = input ("What is the base of the triangle?: ")
        heigth = input ("What is the heigth of the triangle?: ")
        print "The area is: ",base*heigth/2

def vol_sph():
        radius = input("What is the radius?: ")
        print "The volume is: ", (4*3.14159*radius**3)/3

def vol_cube():
        side = input("Side: ")
        print "The volume is: ",side**3

def vol_box():
        width = input ("What is the width of the box?: ")
        length = input ("What is the length of the box?: ")
        depth = input ("What is the depth of the box?: ")
        print "The volume is: ", width*length*depth

def vol_cone():
        radius = input ("What is the radiux of the base of the cone?: ")
        heigth = input ("What is the heigth of the cone?: ")
        print "The volume is: ", 0.3333*3.144159*(radius**2)*heigth


def task_options():
        print "---------------------------------------"
        print "Options:"
        print "a. Print options: "
        print "b. Do you want to calculate areas?: "
        print "c. Do you want to calculate volumes?: "
        print "d. Quit the programme"
        print "---------------------------------------"
        choice = raw_input("Choose an option: ")
        if choice == 'a':
            print task_options()
        elif choice == 'b':
            print print_options()
        elif choice == 'c':
            print print_options_2()
        elif choice == 'd':
            running = False

def print_options():
        print_options
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate circle area"
        print "c. calculate square area"
        print "d. calculate rectangle area"
        print "e. calculate triangle area"
        print "f. quit the programme"
        print "------------------------------"
        while 1:
            choice = raw_input("Choose an option: ")
            if choice == 'a':
                print_options()
            elif choice == 'b':
                area_circ()
            elif choice == 'c':
                area_squ()
            elif choice == 'd':
                area_rect()
            elif choice == 'e':
                area_tgle()
            if choice == 'f': break

def print_options_2():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "b. calculate the volume of a sphere"
        print "c. calculate the volume of a cube"
        print "d. calculate the volume of a box"
        print "e. calculate the volume of a cone"
        print "f. quit the programme"
        print "------------------------------"
        while 1:
            choice = raw_input("Choose an option: ")
            if choice == 'a':
                print_options()
            elif choice == 'b':
                vol_sph()
            elif choice == 'c':
                vol_cube()
            elif choice == 'd':
                vol_box()
            elif choice == 'e':
                vol_cone()
            elif choice == 'e':
                print_options()
            if choice == 'f': break

#Call starting menu
task_options()

------------------------------------------------------------------------------------


From logesh at iafrica.com  Sun Apr 24 12:46:00 2005
From: logesh at iafrica.com (Logesh Pillay)
Date: Sun Apr 24 12:48:04 2005
Subject: [Tutor] variable scope in nested functions
Message-ID: <426B78E8.7040007@iafrica.com>

Hello list

I am having trouble with a variable to act as a counter in a nested 
recursive function which will only occasionally find an answer.  
Something like a static variable in C.

Why does this sort of thing not work?

def foo (n):
    counter = 0
    def choose (i):
       if (solution found):
          counter += 1
          print counter, (solution)
       else choose (i+1)
    choose (1)

I get an error message that counter is referenced before being declared.

Declaring counter as global does not help either

Incidentally how does one nest comments in python.  I want to comment 
out part of a line.  Is it just Kate my editor which won't allow it

Thanks
Logesh



From kent37 at tds.net  Sun Apr 24 14:04:57 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 24 14:05:02 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
In-Reply-To: <426AC0A5.1040102@po-box.mcgill.ca>
References: <426A7588.5030404@po-box.mcgill.ca>	<00bc01c54839$3c3c07b0$dad48651@xp>
	<426AC0A5.1040102@po-box.mcgill.ca>
Message-ID: <426B8B69.6000603@tds.net>

Brian van den Broek wrote:
> I do remain a bit surprised that there seems to be no way to implement 
> what I naively thought would be the obvious solution -- to remove an 
> inherited method from the instance's dictionary.

The thing is, the inherited method is never *in* the instance's dictionary. It's not in the 
instance's class's dictionary either. It only lives one place, in the base class's dictionary. So it 
is not possible to remove it from the derived class - it is not there.

  >>> class Base(object):
  ...   def p(self):
  ...     print 'Base.p()'
  ...

dir() shows attributes of Base and also of its base classes:
  >>> dir(Base)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', 
'__module__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__str__', '__weakref__', 'p']

Not all of these items are in Base.__dict__, some are inherited from object. For example 
__getattribute__ is an attribute of object:
  >>> print Base.__dict__
{'__dict__': <attribute '__dict__' of 'Base' objects>, 'p': <function p at 0x008D6D30>, 
'__module__': '__main__', '__weakref__': <attribute '__weakref
__' of 'Base' objects>, '__doc__': None}

If we derive from Base, we can see more of the same:
  >>> class Derived(Base):
  ...   def q(self):
  ...     print 'Derived.q()'
  ...
  >>> dir(Derived)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', 
'__module__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__str__', '__weakref__', 'p', 'q']

  >>> print Derived.__dict__
{'q': <function q at 0x008D6E30>, '__module__': '__main__', '__doc__': None}

There is no 'p' in Derived.__dict__.

So to 'remove' a method from Derived, you can't actually delete it from anywhere, you have to make 
it look like it is deleted.

One way to do this I have already suggested - make the Derived method raise AttributeError. This is 
the same exception you would get if it hadn't been defined and I think it will give a pretty 
convincing simulation.

Another way to do this would be to override Derived.__getattribute__() to watch for access to the 
derived method and raise AttributeError there.

Either one of these approaches should give a pretty good simulation of removing the attribute, 
though it still shows up if you dir(Derived). There doesn't seem to be a way to change that - I 
looked at the implementation of dir() (merge_class_dict() in object.c is the important part) and it 
doesn't have any hooks to customize it that I can see.

Whether you actually should do any of this is another question, I'll let my previous answer stand on 
that.

Kent

From count0.djd at gmail.com  Sun Apr 24 16:23:20 2005
From: count0.djd at gmail.com (David Driver)
Date: Sun Apr 24 16:23:25 2005
Subject: [Tutor] Name spaces again
Message-ID: <22803ae20504240723c1bdb98@mail.gmail.com>

I have read the essay at
<http://www.python.org/doc/essays/packages.html> and I am still having
problems understanding what I need to do. Here is the structure that I
am looking at:

Root folder
	StartHere.py
	Common folder
		__init__.py
		sobj.py
		exceptions.py
		validators.py
		View folder (keeps cheetah and sxl templates)
		Search folder (will be namespace for lookup operations)
		Maintain folder (for creating and altering base domain objects)
		Transact folder (namespace for creating transaction operations)
	AR folder
		__init__.py
		sobj.py
		exceptions.py
		validators.py
		View folder 
		Search folder 
		Maintain folder
		Transact folder
	AP folder
		__init__.py
		sobj.py
		exceptions.py
		validators.py
		View folder 
		Search folder 
		Maintain folder
		Transact folder
	GL folder
		__init__.py
		sobj.py
		exceptions.py
		validators.py
		View folder 
		Search folder 
		Maintain folder
		Transact folder

StartHere.py contains:
	import Common
	import AR
	import AP

Each subpackage __init__.py contains:
	import exceptions
	import validators
	import sobjs
	import Maintain
	import Transact
	import Search
	import View


In AR.sobjs I have a class that is inherited from
Common.sobjs.baseDomObj. When I run StartHere.py Common imports just
fine. It starts to import AR and AR. __init__.py imports AR.sobjs.py
and it throws the following error:

Traceback (most recent call last):
  File "C:\foo\doinit\starthere.py", line 3, in ?
    import AR
  File "C:\foo\doinit\AR\__init__.py", line 3, in ?
    import sobjs
  File "C:\foo\doinit\AR\sobjs.py", line 1, in ?
    class custAddress(Common.address):
NameError: name 'Common' is not defined

Do I need to import Common in each sub package to have access to it?
Does it consume more memory? What about Sub Sub packages? shouldn't
you be able to Import DateTime in StartHere and have all sub
modules/packages that are imported into StartHere.py use it? Am I
making a big deal out of nothing?

This entire project is more or less of a mock up of a project. I am
just trying to learn more about python and I am basing it on the VB
based accounting package I currently maintain. It isn't that I would
normally organize an app this way if I were building a new one.

-- 

***********************************
See there, that wasn't so bad.
***********************************
From alan.gauld at freenet.co.uk  Sun Apr 24 17:48:49 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun Apr 24 17:48:01 2005
Subject: [Tutor] Bandwidth Tester
References: <3c51d51805042323155503b194@mail.gmail.com>
Message-ID: <00f301c548e5$1c5a2e70$dad48651@xp>

>    How can i write a simple bandwidth tester with Python?

It's very simple in concept: just download a fixed quantity 
of data and measure how long it took. Unfortunately, like 
many concepts measuring true Bandwidth is much more complex 
than that!

The simple approach only works if:
1) You are the only user of the link
2) You are the only user of the server at the other end
3) The remote server has 'infinite' capacity to deliver data.
4) The receiving computer has infinite capacity to receive data.
5) The data you receive is much bigger than the network 
   protocol overhead
6) The data you receive is all delivered in a single packet

If you can meet all of the above (or get near enough) then 
a simple approach will work. Otherwise you need to take 
account of queuing effects, both in the link and in the 
server, packet delays and network overheads. One way of 
achieveing resonable results is to repeat the process 
several times and take an average. Another thing to 
consider is taking a few ping samples and subtracting 
the ping time (multiplied by the number of packets) 
from the total.

However, many people when they refer to Bandwidth really 
mean the available data throughput which is much easier 
to measure. The simple approach combined with averaging is
usually adequate for that (but still beware of factor 2 
in the list above).

Finally, these techniques will only give a figure for the 
throughput of the end to end link, not the bandwidth of 
your ISP connection. To achieve that you need to ensure 
you download the data from a server on the same LAN as 
your network server! If you try using a remote server the 
congestion on a link between the USA and Europe, say, 
could easily become a dominant factor for the duration 
of your measures but on another occasion be non affecting. 
To get round that you need to take your samples at 
widely different times of day and day of week/month....

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
From gmanbauer at gmail.com  Sun Apr 24 19:04:15 2005
From: gmanbauer at gmail.com (Gavin Bauer)
Date: Sun Apr 24 19:04:19 2005
Subject: [Tutor] "saving"?
Message-ID: <fbc3a181050424100418b4a675@mail.gmail.com>

I've decided it would be cool to make a flashcard program. You would
start by entering all of the cards and their answers, then it would
ask you them in random order, with ones you get right coming up less
often, and ones you consistantly get wrong coming up more often.
However, I don't want to start this project unless I  could actually
make it useful. This means one thing: saving. I would need some way of
saving a "set" of flash cards such as "english vocab test" or "french
irregular verbs". The main purpose of this program (other than
learning more python) would be to actually help me study for a test,
so I would need to be able to save the information somehow. Any ideas?
From maxnoel_fr at yahoo.fr  Sun Apr 24 19:40:58 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sun Apr 24 19:41:05 2005
Subject: [Tutor] "saving"?
In-Reply-To: <fbc3a181050424100418b4a675@mail.gmail.com>
References: <fbc3a181050424100418b4a675@mail.gmail.com>
Message-ID: <e93033594803fc869c1e98ae64c45d29@yahoo.fr>


On Apr 24, 2005, at 18:04, Gavin Bauer wrote:

> I've decided it would be cool to make a flashcard program. You would
> start by entering all of the cards and their answers, then it would
> ask you them in random order, with ones you get right coming up less
> often, and ones you consistantly get wrong coming up more often.
> However, I don't want to start this project unless I  could actually
> make it useful. This means one thing: saving. I would need some way of
> saving a "set" of flash cards such as "english vocab test" or "french
> irregular verbs". The main purpose of this program (other than
> learning more python) would be to actually help me study for a test,
> so I would need to be able to save the information somehow. Any ideas?

	The shelve module seems to be what you're looking for.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From kent37 at tds.net  Sun Apr 24 21:29:07 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun Apr 24 21:29:15 2005
Subject: [Tutor] "saving"?
In-Reply-To: <e93033594803fc869c1e98ae64c45d29@yahoo.fr>
References: <fbc3a181050424100418b4a675@mail.gmail.com>
	<e93033594803fc869c1e98ae64c45d29@yahoo.fr>
Message-ID: <426BF383.3000401@tds.net>

Max Noel wrote:
> 
> On Apr 24, 2005, at 18:04, Gavin Bauer wrote:
>> make it useful. This means one thing: saving. I would need some way of
>> saving a "set" of flash cards such as "english vocab test" or "french
>> irregular verbs". The main purpose of this program (other than
>> learning more python) would be to actually help me study for a test,
>> so I would need to be able to save the information somehow. Any ideas?
> 
> 
>     The shelve module seems to be what you're looking for.

Or the pickle module.

Kent

From kent37 at tds.net  Mon Apr 25 00:02:11 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 25 00:02:18 2005
Subject: [Tutor] variable scope in nested functions
In-Reply-To: <426B78E8.7040007@iafrica.com>
References: <426B78E8.7040007@iafrica.com>
Message-ID: <426C1763.6010301@tds.net>

Logesh Pillay wrote:
> Hello list
> 
> I am having trouble with a variable to act as a counter in a nested 
> recursive function which will only occasionally find an answer.  
> Something like a static variable in C.
> 
> Why does this sort of thing not work?
> 
> def foo (n):
>    counter = 0
>    def choose (i):
>       if (solution found):
>          counter += 1
>          print counter, (solution)
>       else choose (i+1)
>    choose (1)
> 
> I get an error message that counter is referenced before being declared.

This is a limitation of Python's nested scopes. You can't assign to a variable in an enclosing 
scope. One way to work around this is to use a mutable value like a list in the enclosing scope:
def foo (n):
    counter = [0]
    def choose (i):
       if (solution found):
          counter[0] += 1
          print counter[0], (solution)
       else choose (i+1)
    choose (1)

You could also write a counter class:
class foo:
    def __init__ (n):
       self.counter = 0
    def choose (self, i):
       if (solution found):
          self.counter += 1
          print self.counter, (solution)
       else self.choose (i+1)

foo().choose (1)

I would suggest separating the counter from the solution checking though.

> 
> Declaring counter as global does not help either

No, then it just looks for counter in the global (module) namespace so it still doesn't find it.

> 
> Incidentally how does one nest comments in python.  I want to comment 
> out part of a line.  Is it just Kate my editor which won't allow it

Use # to comment out to the end of a line. There is no way to comment out the middle of a line (like 
you could do in C or Java with /* stuff */)

Kent

From kent37 at tds.net  Mon Apr 25 00:05:45 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 25 00:05:50 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <BAY20-F216C34B5351ABEBF09B8F1B32F0@phx.gbl>
References: <BAY20-F216C34B5351ABEBF09B8F1B32F0@phx.gbl>
Message-ID: <426C1839.5000209@tds.net>

John Carmona wrote:
> Thanks for the help Kent, Noel and Alan. Here is my final script (it 
> seems to be working ok but sometimes if I select "quit the programme", I 
> need to enter that option 2 or 3 times before it works, is this a bug

Try this program. Choose option a a few times, then choose f enough times to exit. See if you can 
figure out what is going on.

def print_options():
        print "------------------------------"
        print "Options:"
        print "a. print options"
        print "f. quit the programme"
        print "------------------------------"
        while 1:
            choice = raw_input("Choose an option: ")
            if choice == 'a':
                print 'About to call print_options'
                print_options()
                print 'Finished calling print_options'
            if choice == 'f': break

print_options()

Kent

From kent37 at tds.net  Mon Apr 25 00:11:54 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 25 00:11:59 2005
Subject: [Tutor] Name spaces again
In-Reply-To: <22803ae20504240723c1bdb98@mail.gmail.com>
References: <22803ae20504240723c1bdb98@mail.gmail.com>
Message-ID: <426C19AA.1020909@tds.net>

David Driver wrote:
> I have read the essay at
> <http://www.python.org/doc/essays/packages.html> and I am still having
> problems understanding what I need to do. 

> In AR.sobjs I have a class that is inherited from
> Common.sobjs.baseDomObj. When I run StartHere.py Common imports just
> fine. It starts to import AR and AR. __init__.py imports AR.sobjs.py
> and it throws the following error:
> 
> Traceback (most recent call last):
>   File "C:\foo\doinit\starthere.py", line 3, in ?
>     import AR
>   File "C:\foo\doinit\AR\__init__.py", line 3, in ?
>     import sobjs
>   File "C:\foo\doinit\AR\sobjs.py", line 1, in ?
>     class custAddress(Common.address):
> NameError: name 'Common' is not defined
> 
> Do I need to import Common in each sub package to have access to it?

Yes, you have to import Common in any module that references Common.

> Does it consume more memory?

No, not a significant amount. The module itself is only loaded once; each client module keeps a 
reference to the loaded module, so it is just the cost of a name.

  What about Sub Sub packages? shouldn't
> you be able to Import DateTime in StartHere and have all sub
> modules/packages that are imported into StartHere.py use it?

No, that's not the way it works. There is no truly global namespace in Python, you have to import 
the names you need into the modules that need them. (OK, there is one global namespace but you 
generally shouldn't change it.)

  Am I
> making a big deal out of nothing?

Maybe - are you making a big deal out of it? :-)

Kent

From jeffpeery at yahoo.com  Mon Apr 25 07:40:54 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Mon Apr 25 07:40:58 2005
Subject: [Tutor] py2exe
In-Reply-To: 6667
Message-ID: <20050425054054.24153.qmail@web30511.mail.mud.yahoo.com>

I am using python 2.3.4. thanks.
 
Jeff

Greg Hasseler <ghasseler@gmail.com> wrote:
Hi Jeff. I can't tell if you sent the last email to just me or me and
the list, but make sure to send it to the list (don't just hit reply).

Also, what version of wxPython are you using?

On 4/21/05, Jeff Peery wrote:
> 
> OK, thanks again. I attached my code. I if anyone has an idea as to why the
> executable fails after running py2exe please let me know. thanks for the
> help! 
> 
> Jeff
> 
> Greg Hasseler wrote: 
> If the application was named test.exe, I find that they are typically
> named test.exe.log then or similar.
> 
> On 4/19/05, Jeff Peery wrote:
> > Ok, thanks again Greg. Although I didn't see a log file, where would it
> > appear and what would the name be... just in case I missed it. thanks. 
> > 
> > Jeff
> > 
> > Greg Hasseler wrote: 
> > I meant to send my first reply the list..oops. If it doesn't leave any
> > log file then I would suggest maybe sending the program source code
> > itself to the list so that others can review it for potential error.
> > 
> > 
> > On 4/18/05, Jeff Peery wrote:
> > > Hi Greg, thanks for the help. the program does not launch, it crashes
> > > immediately, and I did not see a log file. I also ran py2exe several
> times
> > > over and always the same result. the program runs great in regular
> python
> > > mode. any ideas? thanks. 
> > > 
> > > Jeff
> > > 
> > > Greg Hasseler wrote: 
> > > Does the application launch at all or does it just immediately crash?
> > > Look and see if there are any logs available. You may also consider
> > > running py2exe again.
> > > 
> > > On 4/15/05, Jeff Peery wrote:
> > > > 
> > > ! > hello, I am using py2exe. for most of my applications it has been
> > great.
> > > > although this last one I built and when I try to execute it I get an
> > > error: 
> > > > 
> > > > RunTime Error: this application has requested the runtime to terminate
> > in
> > > an
> > > > unusual way. please contact the applications support team for more
> info.
> > > > 
> > > > does anyone know what this means? thanks. 
> > > > 
> > > > Jeff 
> > > > 
> > > > 
> > > > _______________________________________________
> > > > Tutor maillist - Tutor@python.org
> > > > http://mail.python.org/mailman/listinfo/tutor
> > > > 
> > > > 
> > > >
> > >
> > 
> > _______________________________________________
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> > 
> >
> 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050424/4c9994ad/attachment.htm
From smichr at bigfoot.com  Mon Apr 25 15:18:08 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Mon Apr 25 15:19:06 2005
Subject: [Tutor] Re: Weird import problem with PythonIDE on Mac (was 'import
	problem')
In-Reply-To: <2d467e1207737ca240b98741d3045b9c@yahoo.fr>
Message-ID: <774F538A-B58C-11D9-BB74-000393C0D100@bigfoot.com>


On Friday, Apr 22, 2005, at 10:00 America/Chicago, Max Noel wrote:

>
>> Do you have a suggestion as to what can I give a module so it has 
>> enough information to execute a function that resides in __main__? 
>> Here is a visual of what is going on:
>>
>> ------__main__
>> def y1():
>>   pass
>> import foo
>> foo.run(string_from_main) #what should I pass?
>>
>> ------external module, foo
>>
>> def run(string_from_main):
>> 	#
>> 	exec(string_from_main) #y1 is run as if it were in __main__
>>
>>
>> /c
>
> 	Python makes it easy to do because functions (and classes) are 
> objects. Here:
>
> # in __main__
> def y1():
>     pass
> import foo
> foo.run(y1)
>
>
> # in foo
> def run(functionFromMain):
>     functionFromMain()
>

Yes, I know about this, but this is not the problem.  The problem is 
knowing what *strings* to pass to the timeit module so it can access a 
function that is written in one's __main__. Basically, the timeit 
module uses a template to construct a function which is (in the timeit 
module) compiled and then executed.  You get to send two strings: an 
initialization string that is run once and the code string that appears 
in a loop.  Here, for example, is the function that is reconstructed 
and run without success (in mac's pythonIDE:

###
def inner(_it, _timer):
     from __main__ import y1  # I supplied this
     _t0 = _timer()
     for _i in _it:
         y1()                 # and I supplied this
     _t1 = _timer()
     return _t1 - _t0
###

The way the IDE works, this import fails.  There are two ways I have 
found around the problem:

1) wrap the functions of __main__ into a triple quoted string and then 
parsing it apart and sending it to timeit (not too elegant/pythonic):

### brute force passing of function to timeit
funcs='''

def y1():
	print 'y1 executed'
	
def y2():
	print 'y2 executed'
'''

for f in funcs.split('def'):
     f = f.strip()
     if not f:
	continue
     name = f.split('(')[0]
     t=timeit.Timer('def '+f)
     print name,t.timeit(1)
###

2) the other approach is to add an additional argument to the timeit 
__init__ that accepts globals() from the calling program:

###
     def __init__(self, stmt="pass", setup="pass", timer=default_timer, 
glbls = globals):
         """Constructor.  See class doc string."""          # changed 
here - -^
         self.timer = timer
         stmt = reindent(stmt, 8)
         setup = reindent(setup, 4)
         src = template % {'stmt': stmt, 'setup': setup}
         self.src = src # Save for traceback display
         code = compile(src, dummy_src_name, "exec")
         ns = {}
         exec code in glbls, ns                              # and here
         self.inner = ns["inner"]
###

Then __main__ can send functions like this:

###
def y1():
	print 'y1 executed'
def y2():
	print 'y2 executed'
for f in [y1,y2]:
     func = f.__name__
     t=timeit.Timer(stmt = "%s()" % func, glbls = globals())
     print func, t.timeit(1)
###

{If you read to here, thanks.  Is there a better way to accomplish this 
with the current timeit module without modifying timeit?  i.e. is there 
another way to pass the needed information as a string that timeit's 
created function can execute?}

/c

From smichr at bigfoot.com  Mon Apr 25 15:18:23 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Mon Apr 25 15:19:19 2005
Subject: [Tutor] CLS?
In-Reply-To: <20050424014310.8FACF1E400E@bag.python.org>
Message-ID: <7FE70E8D-B58C-11D9-BB74-000393C0D100@bigfoot.com>

I have this in my misc library.  It was my last attempt at unifying the 
cls function snippets that I got when I asked about this question some 
time ago (check the ASPN tutor archives for 'cls').  After adding 
"darwin" to the test for the system (instead of just 'mac') I got it to 
work from a script written and executed in pythonIDE for 2.3.3.  Does 
it work for you in your context?  (Note: it ends with the "white paper" 
method if all else fails.)

###
#--------------------------
def isInteractive():
     """Returns 1 if we're running in an interpreter window, and false
     otherwise.    This is a variation of what
     pydoc.help() tries.     If it doesn't work it might be because the
     None, 1, "?" is occuring on a different line.  One might consider
     the following approach instead:

     for li in inspect.stack():
     if li[1:4] == (None, 1, "?"):
         return 1

     """
     #return inspect.stack()[2][1:4] == (None, 1, "?")
     # the line above will enable the math if called on the 1st line of 
a script

     #return inspect.stack()[3][1].find("PyInteractive")<>0
     # but if this encounters a None at that position it will not be able
     # to use the find function.     SO...let's just look through the 
whole stack
     import inspect
     return str([x[1] for x in inspect.stack()]).find("PyInteractive")>-1

#--------------------------
def cls():
     """A function to clear the output window."""
     import sys,os
     if sys.platform in ['mac', 'darwin']:
         if isInteractive():
             import PyConsole
             PyConsole.console.clearbuffer()
             print
         else:
             print #in case the window is not open yet
             sys.stdout.clearbuffer()
     else:
         try:
             os.system('cls')
         except:
             try:
                 os.system('clear')
             except:
                 try:
                     print
                     sys.stdout.write(os.popen("clear").read())
                 except:
                     print '\n'*80
###

From jsmith at medplus.com  Mon Apr 25 15:33:00 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Mon Apr 25 15:33:32 2005
Subject: [Tutor] design questions: pythonic approach to ostriches
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C0339486A@medexch1.medplus.com>

This is an excellent observation and points to the real problem with the
original question.  The problem is that the base class has more features
than some of the classes that will be dervied from it which is usually
just plain wrong.

Think about it in the abstract.  The Bird class makes the statement: all
birds fly.  Then you want to turn around and define a Bird that doesn't.
Even doing

def fly:
	pass

makes no sense since what you've really done is to re-defined what 'fly'
means for this bird.  Again in the abstract:  all birds fly and for some
birds that will mean that they don't.

The only sensible solution to this that will cause the least confusion
from a maintenance stanpoint and allow for the largest possible reuse is
multiple inheritance for languages that support it.  

Jeff

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Alan Gauld
Sent: Sunday, April 24, 2005 3:48 AM
To: Brian van den Broek; Tutor
Subject: Re: [Tutor] design questions: pythonic approach to ostriches


> I do remain a bit surprised that there seems to be no way to
implement
> what I naively thought would be the obvious solution -- to remove an 
> inherited method from the instance's dictionary.

You can, as Kent said, override the method to do nothing. Some
languages, like Eifell offer better support for that than others.

But there is a danger in removing methods too. By doing so you break one
of the fundamental principles of inheritence: that everywhere that you
use the superclass you can use the sub class.

If you remove the fly() method from your subclass of birds code like
this will break:

birds = [ aSwallow, anOstrich, anEmu, anEagle]

for bird in birds:
   bird.fly()

Whereas if you simply make fly a null method you can still call it but
nothing happens - a lot safer...

But conceptually the problem (and it is common) is that bird has a
fly() method when not all birds can fly - the object model is broken at
a high level of abstraction.

HTH,

Alan G.


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From jeannot18 at hotmail.com  Mon Apr 25 16:36:41 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Mon Apr 25 16:36:44 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <426C1839.5000209@tds.net>
Message-ID: <BAY20-F192D9BC221EBFA5F889A4EB3200@phx.gbl>

Thanks Kent, as far as I can see I get the same problem that on my script, i 
need to enter "f" 3 to 4 times before I exit the programme. Hmmm, why, I 
can't see it really, i thought that the fact to have the "break" command 
would terminate the script straight away. If I enter "f" first then the 
programme ends.  What am i missing?

JC

John Carmona wrote:

	 	Thanks for the help Kent, Noel and Alan. Here is my final script (it 
seems to be working ok but sometimes if I select "quit the programme", I 
need to enter that option 2 or 3 times before it works, is this a bug


Try this program. Choose option a a few times, then choose f enough times to 
exit. See if you can figure out what is going on.

def print_options():
       print "------------------------------"
       print "Options:"
       print "a. print options"
       print "f. quit the programme"
       print "------------------------------"
       while 1:
           choice = raw_input("Choose an option: ")
           if choice == 'a':
               print 'About to call print_options'
               print_options()
               print 'Finished calling print_options'
           if choice == 'f': break

print_options()

Kent


From jeffpeery at yahoo.com  Mon Apr 25 17:24:35 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Mon Apr 25 17:24:40 2005
Subject: [Tutor] py2exe
In-Reply-To: 6667
Message-ID: <20050425152435.52009.qmail@web30512.mail.mud.yahoo.com>

Skipped content of type multipart/alternative-------------- next part --------------
A non-text attachment was scrubbed...
Name: python.zip
Type: application/x-zip-compressed
Size: 15574 bytes
Desc: python.zip
Url : http://mail.python.org/pipermail/tutor/attachments/20050425/4fd879af/python-0001.bin
From andre.roberge at gmail.com  Mon Apr 25 18:03:11 2005
From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=)
Date: Mon Apr 25 18:04:57 2005
Subject: [Tutor] Highlighting instructions: pedagogical preferences
Message-ID: <d4j416$rs3$1@sea.gmane.org>

I'm writing a program "interpreter" which has two windows: a program 
editing window and a program output window.

The interpreter can either step through the program automatically, at a 
slow pace, or step through the program one instruction at a time, as the 
user "clicks" on a "step button".

The instructions being executed are highlighted one by one.

Question: should the highlighted instruction be the one that has just 
been executed, or the one that is about to be executed (when the user 
clicks on the step button, for example)?

At present, I have implemented the second method.  I'm wondering if 
that's the best choice.

Any ideas?

Andr?

P.S.  Btw, this program is part of a python tutorial I am writing - 
hence the relevance to this list :-)

From maxnoel_fr at yahoo.fr  Mon Apr 25 18:20:44 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Mon Apr 25 18:20:51 2005
Subject: [Tutor] Highlighting instructions: pedagogical preferences
In-Reply-To: <d4j416$rs3$1@sea.gmane.org>
References: <d4j416$rs3$1@sea.gmane.org>
Message-ID: <f270681c5c6d1c0610648f5793b51572@yahoo.fr>


On Apr 25, 2005, at 17:03, Andr? Roberge wrote:

> I'm writing a program "interpreter" which has two windows: a program 
> editing window and a program output window.
>
> The interpreter can either step through the program automatically, at 
> a slow pace, or step through the program one instruction at a time, as 
> the user "clicks" on a "step button".
>
> The instructions being executed are highlighted one by one.
>
> Question: should the highlighted instruction be the one that has just 
> been executed, or the one that is about to be executed (when the user 
> clicks on the step button, for example)?

	That probably isn't what you're asking for, but my vote would go to 
"both". In different colors/tones, of course (for example, highlight in 
blue the instruction that is about to be executed, and in grey the one 
that has just been).
	Lacking that, highlighting the instruction about to be executed makes 
more sense to me.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From john.ertl at fnmoc.navy.mil  Mon Apr 25 19:24:08 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Mon Apr 25 19:20:46 2005
Subject: [Tutor] using TK to view an image and then close the window
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C636@lanexc107p.fnmoc.navy.mil>

All,

I have been struggling with being able to view an image and most things have
not worked for one reason or another so I am trying to fall back on a way I
used to do it in PERL.  Use TK to show the image.  I do not know TKInter but
I have two scripts one that gets a list of images and anouther that displays
them using Tkinter.   This is basically how I would like to use it...I am
going to be using PIL to manipulate the image (and show() does not work) so
I just want a quick view to see how it looks.  I can get the image to show
up and minimize and maximize but I can not get the window to close and then
display the next image.  

I have tired several things but no luck. 

Any help on getting the TK window to shutdown cleanly would be appreciated.
Thanks

John Ertl 

<code> # this is supposed to display an image in a TK window but the close
(X) does not work.
import Image
import Tkinter,ImageTk

def TKview(img,mainTitle="image"):
        
        app = Tkinter.Tk()
        app.withdraw()

        top = Tkinter.Toplevel(app,visual="truecolor",colormap="new")
        top.title(mainTitle)
        top.protocol("WM_DELETE_WINDOW", quit)
        top.bind("<q>",quit)
        top.bind("<Q>",quit)

        canvas = Tkinter.Canvas(top)
        canvas.pack()

        p = ImageTk.PhotoImage(img)

        canvas['width'] = img.size[0]
        canvas['height'] = img.size[1]

        canvas.create_image(0,0,anchor='nw',image=p)

        top.mainloop()

def quit(event=None):
        top.destroy()
        top.quit()
</CODE>

<CODE># this code gets the images opens them and calls the TK code above to
display them

import glob
import thread
import Image

import TKviewTest # the module to view the images

       
gifList = glob.glob("./*.gif")
print gifList
for image in gifList:
       image = image[2:] # glob leaves ./ in file name

       newIm    = Image.open(image)

       TK = TKviewTest
       thread.start_new_thread(TK.TKview(newIm,mainTitle="image"))

</CODE>
From john.ertl at fnmoc.navy.mil  Mon Apr 25 19:52:03 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Mon Apr 25 19:48:43 2005
Subject: [Tutor] RE: using TK to view an image and then close the window
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C639@lanexc107p.fnmoc.navy.mil>

I forgot to mention that I am running on a Linux system if that makes any
difference for the TK part.

Thanks, 

John Ertl 

-----Original Message-----
From: Ertl, John 
Sent: Monday, April 25, 2005 10:24
To: tutor@python.org
Subject: using TK to view an image and then close the window

All,

I have been struggling with being able to view an image and most things have
not worked for one reason or another so I am trying to fall back on a way I
used to do it in PERL.  Use TK to show the image.  I do not know TKInter but
I have two scripts one that gets a list of images and anouther that displays
them using Tkinter.   This is basically how I would like to use it...I am
going to be using PIL to manipulate the image (and show() does not work) so
I just want a quick view to see how it looks.  I can get the image to show
up and minimize and maximize but I can not get the window to close and then
display the next image. 

I have tired several things but no luck.

Any help on getting the TK window to shutdown cleanly would be appreciated.
Thanks

John Ertl

<code> # this is supposed to display an image in a TK window but the close
(X) does not work.
import Image
import Tkinter,ImageTk

def TKview(img,mainTitle="image"):
       
        app = Tkinter.Tk()
        app.withdraw()

        top = Tkinter.Toplevel(app,visual="truecolor",colormap="new")
        top.title(mainTitle)
        top.protocol("WM_DELETE_WINDOW", quit)
        top.bind("<q>",quit)
        top.bind("<Q>",quit)

        canvas = Tkinter.Canvas(top)
        canvas.pack()

        p = ImageTk.PhotoImage(img)

        canvas['width'] = img.size[0]
        canvas['height'] = img.size[1]

        canvas.create_image(0,0,anchor='nw',image=p)

        top.mainloop()

def quit(event=None):
        top.destroy()
        top.quit()
</CODE>

<CODE># this code gets the images opens them and calls the TK code above to
display them

import glob
import thread
import Image

import TKviewTest # the module to view the images

      
gifList = glob.glob("./*.gif")
print gifList
for image in gifList:
       image = image[2:] # glob leaves ./ in file name

       newIm    = Image.open(image)

       TK = TKviewTest
       thread.start_new_thread(TK.TKview(newIm,mainTitle="image"))

</CODE>
From kent37 at tds.net  Mon Apr 25 19:49:50 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 25 19:49:55 2005
Subject: [Tutor] Highlighting instructions: pedagogical preferences
In-Reply-To: <d4j416$rs3$1@sea.gmane.org>
References: <d4j416$rs3$1@sea.gmane.org>
Message-ID: <426D2DBE.7030101@tds.net>

Andr? Roberge wrote:
> I'm writing a program "interpreter" which has two windows: a program 
> editing window and a program output window.
> 
> The interpreter can either step through the program automatically, at a 
> slow pace, or step through the program one instruction at a time, as the 
> user "clicks" on a "step button".
> 
> The instructions being executed are highlighted one by one.
> 
> Question: should the highlighted instruction be the one that has just 
> been executed, or the one that is about to be executed (when the user 
> clicks on the step button, for example)?
> 
> At present, I have implemented the second method.  I'm wondering if 
> that's the best choice.

The second choice is typical for debuggers.

Kent

From alan.gauld at freenet.co.uk  Mon Apr 25 20:08:34 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 25 20:08:24 2005
Subject: [Tutor] Re Help with this script
References: <BAY20-F192D9BC221EBFA5F889A4EB3200@phx.gbl>
Message-ID: <002401c549c1$cd091f10$43ce8651@xp>

> can't see it really, i thought that the fact to have the "break"
command
> would terminate the script straight away.

break terminates the current loop, which is inside your print_options
function. print_options is called from inside print_options.

Research the term "recursion" and see if you can see where the problem
lies.
(Try my online tutor for one explanation...)

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


If I enter "f" first then the
> programme ends.  What am i missing?
>
> JC
>
> John Carmona wrote:
>
> Thanks for the help Kent, Noel and Alan. Here is my final script (it
> seems to be working ok but sometimes if I select "quit the
programme", I
> need to enter that option 2 or 3 times before it works, is this a
bug
>
>
> Try this program. Choose option a a few times, then choose f enough
times to
> exit. See if you can figure out what is going on.
>
> def print_options():
>        print "------------------------------"
>        print "Options:"
>        print "a. print options"
>        print "f. quit the programme"
>        print "------------------------------"
>        while 1:
>            choice = raw_input("Choose an option: ")
>            if choice == 'a':
>                print 'About to call print_options'
>                print_options()
>                print 'Finished calling print_options'
>            if choice == 'f': break
>
> print_options()
>
> Kent
>
>
>
>

From gltewalt at yahoo.com  Mon Apr 25 20:22:07 2005
From: gltewalt at yahoo.com (Greg T)
Date: Mon Apr 25 20:22:10 2005
Subject: [Tutor] Re: design questions: pythonic appraoch to ostriches
In-Reply-To: <20050425152445.9885D1E400E@bag.python.org>
Message-ID: <20050425182207.25499.qmail@web52909.mail.yahoo.com>

Greetings.
Any comments made by me will certainly not be the
'pythonic' way to do things, but I would like to
make a few comments on the subject, and possibly
weave in a few questions of my own.
(I took a brief detour into Common Lisp after joining
this list, not too long ago. Thanks Mr. Gauld.)

>This is an excellent observation and points to the
>real problem with 
>the
>original question.  The problem is that the base
class >has more 
>features
>than some of the classes that will be dervied from it
>which is usually
>just plain wrong.

I agree with that satement.
My understanding is to move from the highest level
of abstraction to the detailed, or idividually
specific.

>Think about it in the abstract.  The Bird class makes
>the statement: 
>all
>birds fly.  Then you want to turn around and define a
>Bird that 
>doesn't.
>Even doing

>def fly:
>	pass

>makes no sense since what you've really done is to
>re-defined what 
>'fly'
>means for this bird. 

Personally, I see nothing wrong with redefining a
method in a subclass. From my limited dealings with
multiple inheritance, it seems to me the less you have
to deal with it, the better off you are.
I think my general view would be to cut out any excess
complexity unless its absolutely necessary.
Ostiches did fly at one point in time, and I'm pretty
sure all birds did. (though I'd have to reseach that
to be sure)

What do you all think about dealing with 'all birds
fly, but not these' based on an attribute?
Mass, or weight might be one factor...
Ostiches are too large to fly. (at least with their
current wing size)

>Again in the abstract:  all >birds fly and for 
>some
>birds that will mean that they don't.

>The only sensible solution to this that will cause
the >least confusion
>from a maintenance stanpoint and allow for the
largest >possible reuse 
>is
>multiple inheritance for languages that support it.  

I disagree, but then I come from the ruby language
which has an interesting take on MI.
Attributes and methods without the full complexity
of MI.
(though I'm certainly not an expert in ruby)

>Jeff


>Behalf Of Alan Gauld
>Sent: Sunday, April 24, 2005 3:48 AM
>To: Brian van den Broek; Tutor
>Subject: Re: [Tutor] design questions: pythonic
>approach to ostriches


> I do remain a bit surprised that there seems to be
no >way to
>implement
> what I naively thought would be the obvious solution
-- to remove an 
> inherited method from the instance's dictionary.

>You can, as Kent said, override the method to do
>nothing. Some
>languages, like Eifell offer better support for that
>than others.

What would be the harm in having the fly() ethod in
ostrich perform a different action?
"Im flapping my wings to no avail, but I'm running
quite fast"

>But there is a danger in removing methods too. By
>doing so you break 
>one
>of the fundamental principles of inheritence: that
>everywhere that you
>use the superclass you can use the sub class.

>If you remove the fly() method from your subclass of
>birds code like
>this will break:

>birds = [ aSwallow, anOstrich, anEmu, anEagle]

>for bird in birds:
>   bird.fly()

Where I come from, it wold look in the super class
for the fly() method when it wasnt found in ostrich,
and then you would have an action that wasnt right.
Ostriches dont fly.

>Whereas if you simply make fly a null method you can
>still call it but
>nothing happens - a lot safer...

>But conceptually the problem (and it is common) is
>that bird has a
>fly() method when not all birds can fly - the object
>model is broken at
>a high level of abstraction.

What about subclassing bird with FlightlessBird?


As I learn more about the python way, I will be able
to
contribute something more usefull and intelligent.

I hope it was ok to post my general thoughts about it
here...

--Greg



>HTH,

>Alan G.

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
From jsmith at medplus.com  Mon Apr 25 21:10:40 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Mon Apr 25 21:10:44 2005
Subject: [Tutor] Re: design questions: pythonic appraoch to ostriches
Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C03394902@medexch1.medplus.com>

From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Greg T
>>Think about it in the abstract.  The Bird class makes
>>the statement:
>>all
>>birds fly.  Then you want to turn around and define a
>>Bird that 
>>doesn't.
>>Even doing
>>
>>def fly:
>>	pass
>>
>>makes no sense since what you've really done is to
>>re-defined what
>>'fly'
>>means for this bird. 

>Personally, I see nothing wrong with redefining a
>method in a subclass. From my limited dealings with
>multiple inheritance, it seems to me the less you have
>to deal with it, the better off you are.

Arguably this is an extreme case but the problem here is that the method
was redefined to be diametrically opposed to its usual meaning.  Kind of
like derving a class from list and re-defining reverse to return the
original list rather than the reversed one.  Sure there may be some
obscure reasons to do this or some valid sub-class to derive from list
where this might make sense, but that's clearly not the intent of the
original problem.


>What do you all think about dealing with 'all birds
>fly, but not these' based on an attribute?
>Mass, or weight might be one factor...
>Ostiches are too large to fly. (at least with their
>current wing size)

I'd still disagree because it starts with a statement about the class
that is false: all bird fly.  That's an incorrect statement about the
base class and is the direct cause of the problems with the dervied
classes.  



>>Again in the abstract:  all >birds fly and for
>>some
>>birds that will mean that they don't.
>>
>>The only sensible solution to this that will cause
>>the least confusion
>>from a maintenance stanpoint and allow for the
>>largest possible reuse 
>>is
>>multiple inheritance for languages that support it.

>I disagree, but then I come from the ruby language
>which has an interesting take on MI.
>Attributes and methods without the full complexity
>of MI.
>(though I'm certainly not an expert in ruby)

Well, in retrospect I did overstate the case that it is the "only
sensible solution."  I could conceive of a class where there were a
number of possible attributes that a member of that class could have and
then maybe you would have a factory which would generate the proper
subclass with the correct collection of attributes.  And I agree that a
profussion of classes may not be the best from a maintenance standpoint.
But that's often the trade-off in OO class design...a profusion of
classes that makes logical sense for the problem you are solving or
something that you can actually maintain :-)

Jeff
From logesh at iafrica.com  Mon Apr 25 21:30:17 2005
From: logesh at iafrica.com (Logesh Pillay)
Date: Mon Apr 25 21:30:34 2005
Subject: [Tutor] variable scope in nested functions
Message-ID: <426D4549.8000005@iafrica.com>

Thanks Kent for your reply.
You said

>This is a limitation of Python's nested scopes. You can't assign to a variable in an enclosing 
>scope. One way to work around this is to use a mutable value like a list in the enclosing scope:
>def foo (n):
>    counter = [0]
>    def choose (i):
>       if (solution found):
>          counter[0] += 1
>          print counter[0], (solution)
>       else choose (i+1)
>    choose (1)
>
I can't help thinking that this is a little unsatisfactory and suggests 
(with all due respect)  an unfinished quality to Python.

Consider a program I've just translated into python from my version in C.

def erdos(n):                                             #Explores 
Erdos theorem that any
    found, r, s = False, 1, [0]*1000            #integer can be 
expressed as +-1.1
    def choose (d, k):                                  #+-2.2...+-r.r 
for some r and some
        for i in -1, 1:                                       
#combinations of +'s and -'s
            s[d] = i
            if d < r:
                choose (d+1, k - i*d*d)
            elif k == i*d*d:
                found = True
                printout ()
    def printout ():
        print n, '=',
        for i in range (1, r+1):
            if s[i] == 1:
                print '+', i,'.',i,
            else:
                print '-',i,'.',i,
        print '\n'
    while not found:
        choose(1, n)
        r += 1

The program is supposed to return to the python prompt as soon as it 
finds solution(s) at the smallest width r.

I entered it exactly as it is expecting the same sort of error message 
for the boolean variable 'found'.  There was none.  Instead python 
simply fails to perform 'found = True' in choose() and it just keeps 
running (incidentally demonstrating the other part of this Erdos theorem 
that the no. can be  so  expressed  in an infinite number of ways).  
Why  the inconsistency  in handling enclosing scope variables of type 
'int' and 'bool'?  Also, it can't be desirable that the interpreter 
effectively ignores a line of code without warning.

Logesh
From alan.gauld at freenet.co.uk  Mon Apr 25 21:37:29 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 25 21:37:23 2005
Subject: [Tutor] Highlighting instructions: pedagogical preferences
References: <d4j416$rs3$1@sea.gmane.org>
Message-ID: <003701c549ce$3a64eab0$43ce8651@xp>

> Question: should the highlighted instruction be the one that has
just
> been executed, or the one that is about to be executed (when the
user
> clicks on the step button, for example)?

Its conventional to take the second option - it allows the student
to examine the highlighted line before it operates. The alternative
could be confusing if, for example you jump into a function.

> P.S.  Btw, this program is part of a python tutorial I am writing -
> hence the relevance to this list :-)

I thought about trying to use JavaScript to do  the same in my web
tutor but gave up because browser support was too patchy. But I do
think it's a good idea. Have you seen the Tcl tutor that you can
download, it has 3 levels and is very good IMHO.

Alan G.

From alan.gauld at freenet.co.uk  Mon Apr 25 21:48:41 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon Apr 25 21:48:31 2005
Subject: [Tutor] Re: design questions: pythonic appraoch to ostriches
References: <20050425182207.25499.qmail@web52909.mail.yahoo.com>
Message-ID: <004001c549cf$c8a32480$43ce8651@xp>

> (I took a brief detour into Common Lisp after joining
> this list, not too long ago. Thanks Mr. Gauld.)

YOu are welcome, everyone should at least dabble 
in Lisp if only because it teaches you so much about 
the fundamentals of programming.

> method in a subclass. From my limited dealings with
> multiple inheritance, it seems to me the less you have
> to deal with it, the better off you are.

If the language is designed to support it(and I don't 
mean the way C++ does it!) then it can work. But in 
general MI can create its own unique form of torture 
as you play hunt the method...

> >But there is a danger in removing methods too. By
> 
> Where I come from, it wold look in the super class
> for the fly() method when it wasnt found in ostrich,

THats not removing the methjod, thats simply not implementing it.
The OP was suggesting actually removing the method from the 
classes look-up chain. Languages like Eiffel allow you to do this
in a controlled way but that still doen't mean its a good idea!

> What about subclassing bird with FlightlessBird?

YEs thats a valid option if there is a limited set of BIrd types, 
the danger is that the nu,mber of different types of Bird can 
explode exponentially if you aren't careful.

For example take just 3 cases
- BIrds that fly/don't
- Birds that nest/don't
- Birds that migrate/don't

Now you need subclasses for each of those, plus any combination:

Fly + Migrate + Nest
Fly + Don't Migrate + Nest
Fly + Migrate + Don't Nest
Fly + Don't Migrate + Don't Nest.

In fact for N special cases you need 2**N subclasses... Thats a 
lot of classes before you even get near an instance...

> I hope it was ok to post my general thoughts about it
> here...

Of course, thats what a forum is for! :-)

Alan G.

From andre.roberge at gmail.com  Mon Apr 25 22:17:41 2005
From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=)
Date: Mon Apr 25 22:19:23 2005
Subject: [Tutor] Re: Highlighting instructions: pedagogical preferences
In-Reply-To: <003701c549ce$3a64eab0$43ce8651@xp>
References: <d4j416$rs3$1@sea.gmane.org> <003701c549ce$3a64eab0$43ce8651@xp>
Message-ID: <d4jiv7$j2o$1@sea.gmane.org>

Alan Gauld  wrote:  (and Kent Johnson agrees :-)
[snip]
> Its conventional to take the second option - it allows the student
> to examine the highlighted line before it operates. The alternative
> could be confusing if, for example you jump into a function.
> 
[snip]
> think it's a good idea. Have you seen the Tcl tutor that you can
> download, it has 3 levels and is very good IMHO.
> 
> Alan G.
> 
Thanks for the pointer.  I just downloaded it.  It does look good.

However, I'll stick to Python for now :-)

Andr?

From andre.roberge at gmail.com  Mon Apr 25 22:27:28 2005
From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=)
Date: Mon Apr 25 22:29:33 2005
Subject: [Tutor] Re: variable scope in nested functions: SOLUTION :-)
In-Reply-To: <426D4549.8000005@iafrica.com>
References: <426D4549.8000005@iafrica.com>
Message-ID: <d4jjhi$l77$1@sea.gmane.org>

Logesh Pillay wrote:
[snip]
> 
> Consider a program I've just translated into python from my version in C.
> 
> def erdos(n):                                          

      global found       # added line

>    found, r, s = False, 1, [0]*1000            
>    def choose (d, k):      

          global found   # added line

>        for i in -1, 1:                                       
>            s[d] = i
>            if d < r:
>                choose (d+1, k - i*d*d)
>            elif k == i*d*d:
>                found = True
>                printout ()
>    def printout ():
>        print n, '=',
>        for i in range (1, r+1):
>            if s[i] == 1:
>                print '+', i,'.',i,
>            else:
>                print '-',i,'.',i,
>        print '\n'
>    while not found:
>        choose(1, n)
>        r += 1
> 
> The program is supposed to return to the python prompt as soon as it 
> finds solution(s) at the smallest width r.
> 
> I entered it exactly as it is expecting the same sort of error message 
> for the boolean variable 'found'.  There was none.  Instead python 
> simply fails to perform 'found = True' in choose() and it just keeps 
> running (incidentally demonstrating the other part of this Erdos theorem 
> that the no. can be  so  expressed  in an infinite number of ways).  
> Why  the inconsistency  in handling enclosing scope variables of type 
> 'int' and 'bool'?  Also, it can't be desirable that the interpreter 
> effectively ignores a line of code without warning.
> 
> Logesh
> _______________________________________________

Just add two global statements as written above and it will work just as 
you would have expected it to!

Andr?

From klappnase at freenet.de  Mon Apr 25 22:42:53 2005
From: klappnase at freenet.de (Michael Lange)
Date: Mon Apr 25 22:39:01 2005
Subject: [Tutor] using TK to view an image and then close the window
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C636@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C636@lanexc107p.fnmoc.navy.mil>
Message-ID: <20050425224253.65de38b1.klappnase@freenet.de>

On Mon, 25 Apr 2005 10:24:08 -0700
"Ertl, John" <john.ertl@fnmoc.navy.mil> wrote:


Hi John,

> I can get the image to show
> up and minimize and maximize but I can not get the window to close and then
> display the next image.  
> 
> I have tired several things but no luck. 
> 
> Any help on getting the TK window to shutdown cleanly would be appreciated.
> Thanks
> 
> John Ertl 
> 
> <code> # this is supposed to display an image in a TK window but the close
> (X) does not work.
> import Image
> import Tkinter,ImageTk
> 
> def TKview(img,mainTitle="image"):
>         
>         app = Tkinter.Tk()
>         app.withdraw()
> 
>         top = Tkinter.Toplevel(app,visual="truecolor",colormap="new")
>         top.title(mainTitle)
>         top.protocol("WM_DELETE_WINDOW", quit)
>         top.bind("<q>",quit)
>         top.bind("<Q>",quit)
> 
>         canvas = Tkinter.Canvas(top)
>         canvas.pack()
> 
>         p = ImageTk.PhotoImage(img)
> 
>         canvas['width'] = img.size[0]
>         canvas['height'] = img.size[1]
> 
>         canvas.create_image(0,0,anchor='nw',image=p)
> 
>         top.mainloop()
> 
> def quit(event=None):
>         top.destroy()
>         top.quit()
> </CODE>

If that's all of the code, "top" is created as a local variable inside your TKview() function,
so your quit() function doesn't know about it.
Second, I don't see much use for using a second Toplevel window at all, why not just pack the
canvas onto the main Tk() window?


> 
> <CODE># this code gets the images opens them and calls the TK code above to
> display them
> 
> import glob
> import thread
> import Image
> 
> import TKviewTest # the module to view the images
> 
>        
> gifList = glob.glob("./*.gif")
> print gifList
> for image in gifList:
>        image = image[2:] # glob leaves ./ in file name
> 
>        newIm    = Image.open(image)
> 
>        TK = TKviewTest
>        thread.start_new_thread(TK.TKview(newIm,mainTitle="image"))
> 
> </CODE>

I hope this helps

Michael

From kent37 at tds.net  Mon Apr 25 22:51:31 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon Apr 25 22:51:38 2005
Subject: [Tutor] variable scope in nested functions
In-Reply-To: <426D4549.8000005@iafrica.com>
References: <426D4549.8000005@iafrica.com>
Message-ID: <426D5853.8040405@tds.net>

Logesh Pillay wrote:
> Thanks Kent for your reply.
> You said
> 
>> This is a limitation of Python's nested scopes. You can't assign to a 
>> variable in an enclosing scope. One way to work around this is to use 
>> a mutable value like a list in the enclosing scope:
>> def foo (n):
>>    counter = [0]
>>    def choose (i):
>>       if (solution found):
>>          counter[0] += 1
>>          print counter[0], (solution)
>>       else choose (i+1)
>>    choose (1)
>>
> I can't help thinking that this is a little unsatisfactory and suggests 
> (with all due respect)  an unfinished quality to Python.

Well, you are not alone in that opinion. It is a limitation of Python nested scopes though I 
personally have never had a problem with it. Python is good but not perfect and it certainly doesn't 
contain every feature ever desired.

> Consider a program I've just translated into python from my version in C.
> 
> def erdos(n):                                             #Explores 
> Erdos theorem that any
>    found, r, s = False, 1, [0]*1000            #integer can be expressed 
> as +-1.1
>    def choose (d, k):                                  #+-2.2...+-r.r 
> for some r and some
>        for i in -1, 1:                                       
> #combinations of +'s and -'s
>            s[d] = i
>            if d < r:
>                choose (d+1, k - i*d*d)
>            elif k == i*d*d:
>                found = True
>                printout ()
>    def printout ():
>        print n, '=',
>        for i in range (1, r+1):
>            if s[i] == 1:
>                print '+', i,'.',i,
>            else:
>                print '-',i,'.',i,
>        print '\n'
>    while not found:
>        choose(1, n)
>        r += 1
> 
> The program is supposed to return to the python prompt as soon as it 
> finds solution(s) at the smallest width r.
> 
> I entered it exactly as it is expecting the same sort of error message 
> for the boolean variable 'found'.  There was none.  Instead python 
> simply fails to perform 'found = True' in choose() and it just keeps 

No, it doesn't ignore it, it creates a variable 'found' in the local scope of choose(), just as if 
you assigned to any other name.

> running (incidentally demonstrating the other part of this Erdos theorem 
> that the no. can be  so  expressed  in an infinite number of ways).  
> Why  the inconsistency  in handling enclosing scope variables of type 
> 'int' and 'bool'?  

It's not inconsistent. You can't bind a new value to a name in an enclosing (non-global) scope. 
Period. You can access and mutate the values of names in enclosing scopes. So
   found = True
binds a value to the name in the local scope. If found were defined as
   found = [False]
in erdos(), then in choose() you could say
   found[0] = True
This is mutating the value of found, not rebinding found.

Also, it can't be desirable that the interpreter
> effectively ignores a line of code without warning.

It didn't ignore it, it just didn't do what you expected.

Here is a version that works using a list to hold the value of found in the enclosing scope:
def erdos(n):                                             #Explores Erdos theorem that any
    found, r, s = [False], 1, [0]*1000            #integer can be expressed as +-1.1
    def choose (d, k):                                  #+-2.2...+-r.r for some r and some
        for i in -1, 1:                                       #combinations of +'s and -'s
            s[d] = i
            if d < r:
                choose (d+1, k - i*d*d)
            elif k == i*d*d:
                found[0] = True
                printout ()
    def printout ():
        print n, '=',
        for i in range (1, r+1):
            if s[i] == 1:
                print '+', i,'.',i,
            else:
                print '-',i,'.',i,
        print '\n'
    while not found[0]:
        choose(1, n)
        r += 1


Here is a version that uses a generator function to create the lists of +- and corresponding sums:

def gen_sum(n):
     ''' Generator for +-1*1 +- 2*2 +- ...+- n*n.
         Yields pairs of (sum, [list of +-1])
     '''
     if n<=0:
         yield (0, [])
         return

     for i in -1, 1:
         for sum, signs in gen_sum(n-1):
             yield sum + i*n*n, signs + [i]


def printout(n, signs):
        print n, '=',
        for i, sign in enumerate(signs):
            j = i+1
            if sign == 1:
                print '+', j,'*',j,
            else:
                print '-',j,'*',j,
        print '\n'


def erdos(n):
     r = 1
     while True:
         for sum, signs in gen_sum(r):
             if sum == n:
                 printout(n, signs)
                 return
         r += 1

Kent

From jfouhy at paradise.net.nz  Tue Apr 26 01:18:46 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Tue Apr 26 01:18:50 2005
Subject: [Tutor] using TK to view an image and then close the window
In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C636@lanexc107p.fnmoc.navy.mil>
References: <E338ADD616B66043824B9ABF5CA6EF2332C636@lanexc107p.fnmoc.navy.mil>
Message-ID: <1114471126.426d7ad6954ba@www.paradise.net.nz>

Quoting "Ertl, John" <john.ertl@fnmoc.navy.mil>:

>  top = Tkinter.Toplevel(app,visual="truecolor",colormap="new")
>  top.title(mainTitle)
>  top.protocol("WM_DELETE_WINDOW", quit)
>  top.bind("<q>",quit)
>  top.bind("<Q>",quit)

In addition to Michael's comments, to bind to a keypress, you just do (eg)
widget.bind("q", f).

-- 
John.
From bvande at po-box.mcgill.ca  Tue Apr 26 00:36:00 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 26 02:38:53 2005
Subject: [Tutor] properties and subclasses
Message-ID: <426D70D0.3000409@po-box.mcgill.ca>

Hi all,

I'm trying to get a hang of properties. It isn't quite clear to me
what is the best way to make properties differ in subclasses. Some
code snips to show what I've tried:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(prop_set)
... 	
>>> class AA(A):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by AA's method"
... 	
>>> aa = AA()
>>> aa.my_property
"I was set by A's method"

OK, so the naive approach didn't work -- I wanted aa.my_property to be
"I was set by AA's method".


So, the next thought was to change A's my_property assignment:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(self.prop_set)
...
Traceback (most recent call last):
...
NameError: name 'self' is not defined

OK, that worked less well, still :-)


I can get what I want this way:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(prop_set)
...
>>> class AA(A):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by AA's method"
... 	my_property = property(prop_set)
...
>>> aa = AA()
>>> aa.my_property
"I was set by AA's method"

But the reduplication of the prop_set definition and the my_property
assignment line seem to go against the grain of OOP to me.


The best I have manged to date is:

>>> class B(object):
... 	def __init__(self): pass
... 	def prop_set(self): return self.property_setter()
... 	def property_setter(self): return "I was set by a B method"
... 	my_property = property(prop_set)
...
>>> class BB(B):
... 	def __init__(self): pass
... 	def property_setter(self): return "I was set by a BB method"
...
>>> b=B()
>>> b.my_property
'I was set by a B method'
>>> bb=BB()
>>> bb.my_property
'I was set by a BB method'
>>>

Is that the cleanest way available? The indirection doesn't bother me
too much, but it feels like it might have bothered Guido et. al. 
enough that I worry I am missing a better approach.

Further, are my desired indicative of a misunderstanding of the role
of properties?

I'd aimed to make a separate post explaining why this matters to me 
and asking for alternative solutions, but the draft I have yet to 
finish is rather more dense than this post. So, I will leave off 
unless respondents think it matters to the current enquiry.

Thanks and best to all,

Brian vdB


From chumpytown at gmail.com  Tue Apr 26 06:27:02 2005
From: chumpytown at gmail.com (chumpy town)
Date: Tue Apr 26 06:27:07 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
Message-ID: <82b2500905042521276bbe0e46@mail.gmail.com>

Hello all,
I am trying to convert from bash to python for scripting.  What is the
simplest & cleanest way to do the following in python:

#!/bin/bash
for i in `seq 1 1000`
  do
  my-other-script &
done
wait
echo "all done"

I at first tried os.system("my-other-script &") and os.wait() but this
caused os.wait() to throw an exception and say no child processes. 
Alternatively, I know I can use os.fork(), os.exec() and os.wait() but
this seems cumbersome.  As a second alternative, os.spawnlp() and
os.wait() works, but I need to additionally redirect the spawned
process' stdout to the spawnee's stdout, etc. - again an extra step.

Experienced python programmers, what's the best thing to do here?  Thanks a lot!

-david
From pierre.barbier at cirad.fr  Tue Apr 26 09:34:24 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue Apr 26 09:33:50 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
In-Reply-To: <82b2500905042521276bbe0e46@mail.gmail.com>
References: <82b2500905042521276bbe0e46@mail.gmail.com>
Message-ID: <426DEF00.2030501@cirad.fr>

I do not understand why you don't want the so simple fork/exec pattern !
In UNIX programming this is the way to go ...

I cannot think of anything simpler than that :

for i in xrange( 10 ):
   pid = os.fork()
   if not pid:
     os.execv( "/bin/echo", [ "echo", "toto" ] )
try:
   while True:
     os.wait()
except OSError:
   pass
print "all done"

I fear that python programming is a little less process-oriented than 
shells ... but then, it is just normal for an all-purpose language (or 
at least an all-purpose wanna-be language ;) ).

Pierre

chumpy town a ?crit :
> Hello all,
> I am trying to convert from bash to python for scripting.  What is the
> simplest & cleanest way to do the following in python:
> 
> #!/bin/bash
> for i in `seq 1 1000`
>   do
>   my-other-script &
> done
> wait
> echo "all done"
> 
> I at first tried os.system("my-other-script &") and os.wait() but this
> caused os.wait() to throw an exception and say no child processes. 
> Alternatively, I know I can use os.fork(), os.exec() and os.wait() but
> this seems cumbersome.  As a second alternative, os.spawnlp() and
> os.wait() works, but I need to additionally redirect the spawned
> process' stdout to the spawnee's stdout, etc. - again an extra step.
> 
> Experienced python programmers, what's the best thing to do here?  Thanks a lot!
> 
> -david
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68
From kent37 at tds.net  Tue Apr 26 12:24:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 26 12:24:47 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <426D70D0.3000409@po-box.mcgill.ca>
References: <426D70D0.3000409@po-box.mcgill.ca>
Message-ID: <426E16EA.7090300@tds.net>

Brian van den Broek wrote:
> Hi all,
> 
> I'm trying to get a hang of properties. It isn't quite clear to me
> what is the best way to make properties differ in subclasses. Some
> code snips to show what I've tried:
> 
> I can get what I want this way:
> 
>>>> class A(object):
> 
> ...     def __init__(self): pass
> ...     def prop_set(self): return "I was set by A's method"
> ...     my_property = property(prop_set)
> ...
> 
>>>> class AA(A):
> 
> ...     def __init__(self): pass
> ...     def prop_set(self): return "I was set by AA's method"
> ...     my_property = property(prop_set)
> ...
> 
>>>> aa = AA()
>>>> aa.my_property
> 
> "I was set by AA's method"
> 
> But the reduplication of the prop_set definition and the my_property
> assignment line seem to go against the grain of OOP to me.

That is the simplest way to do it. Your indirection approach is also valid. These two threads have 
some discussion and other solutions but IMO the cures are worse than the disease:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/8c96e856c8966c67/6594dfecff4a3744?q=subclass+property&rnum=6&hl=en#6594dfecff4a3744
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/95b9b8df2fa0ad3/a4e8896bd9074f23?q=subclass+property&rnum=2&hl=en#a4e8896bd9074f23

Kent

From kent37 at tds.net  Tue Apr 26 12:32:30 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 26 12:32:34 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
In-Reply-To: <82b2500905042521276bbe0e46@mail.gmail.com>
References: <82b2500905042521276bbe0e46@mail.gmail.com>
Message-ID: <426E18BE.1060705@tds.net>

chumpy town wrote:
> Hello all,
> I am trying to convert from bash to python for scripting.  What is the
> simplest & cleanest way to do the following in python:
> 
> #!/bin/bash
> for i in `seq 1 1000`
>   do
>   my-other-script &
> done
> wait
> echo "all done"

You might like the subprocess module - something like this (untested!):

from subprocess import Popen
procs = [ Popen("my-other-script") for i in range(1000) ]
for p in procs:
   p.wait()

Kent

From kristian at zimmer428.net  Tue Apr 26 13:49:21 2005
From: kristian at zimmer428.net (Kristian Rink)
Date: Tue Apr 26 13:49:25 2005
Subject: [Tutor] custom package structure?
Message-ID: <20050426114921.867E74BB87@dd3334.kasserver.com>

Hi all;

currently I am trying to get some structure into my Python / SOAP project now that the threading issue is gone (thanks lots, Kent!); so I created a package structure and __init__.py files according to [1], so my project tree looks somewhat like this:

$PROJECTROOT
/start.py
/Server
/Server/Core/
/Server/Core/__init__.py
/Server/Core/DMServer.py
..
/Server/Generic/
/Server/Generic/__init__.py
/Server/Generic/DBLink.py
..

$PROJECTROOT is exported to PYTHONPATH and also shows up in sys.path. Now, the following is about to happen:

start.py (which is the launcher for the server) basically does an

..
from Server.Core import DMServer
..

which works. Anyhow, DMServer.py contains 

.
from Server.Generic import DBLink
.


which doesn't work. This is sort of confusing me since, according to what I read in the Python it should be possible to access modules from inside a package using this way. Am I mistaking in any essential point? Do I have to explicitely tell Python in which paths to look for modules within every single module? Is there a better way to   permanently include a path into Python's "import" search than to export PYTHONPATH each time before starting the application?

Thanks and bye,
Kris






[1]http://docs.python.org/tut/node8.html

From kent37 at tds.net  Tue Apr 26 14:31:13 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 26 14:31:17 2005
Subject: [Tutor] custom package structure?
In-Reply-To: <20050426114921.867E74BB87@dd3334.kasserver.com>
References: <20050426114921.867E74BB87@dd3334.kasserver.com>
Message-ID: <426E3491.5080308@tds.net>

Kristian Rink wrote:
> Hi all;
> 
> currently I am trying to get some structure into my Python / SOAP project now that the threading issue is gone (thanks lots, Kent!); so I created a package structure and __init__.py files according to [1], so my project tree looks somewhat like this:
> 
> $PROJECTROOT
> /start.py
> /Server
> /Server/Core/
> /Server/Core/__init__.py
> /Server/Core/DMServer.py
> ..
> /Server/Generic/
> /Server/Generic/__init__.py
> /Server/Generic/DBLink.py
> ..
> 

Do you have a /Server/__init__.py? I think you must or you wouldn't be able to import DMServer but 
you don't show it above...

> $PROJECTROOT is exported to PYTHONPATH and also shows up in sys.path. Now, the following is about
> to happen:
> 
> start.py (which is the launcher for the server) basically does an
> 
> .. from Server.Core import DMServer ..
> 
> which works. Anyhow, DMServer.py contains
> 
> . from Server.Generic import DBLink .
> 
> 
> which doesn't work. This is sort of confusing me since, according to what I read in the Python it
> should be possible to access modules from inside a package using this way. Am I mistaking in any
> essential point? 

No, everything above looks fine. Please post the exact error message you are getting (copy / paste 
the whole thing including the stack trace).

One problem I have seen in Jython (not sure if CPython does the same thing) is that errors in an 
imported module can show up as a failure to import the importing module. In other words if something 
that DBLink imports fails to load, it could cause an import error on DBLink. The way to track this 
down is to try to import the modules from the interpreter prompt. For example try
  >>> from Server.Generic import DBLink
if this gives you an import error on some other module then try to import that module directly, and 
so on until you find the actual root error.

> Do I have to explicitely tell Python in which paths to look for modules within
every single module?

No

> Is there a better way to permanently include a path into Python's "import"
search than to export PYTHONPATH each time before starting the application?

There are alternatives, not necessarily better. These both make your project available to any Python 
application:
- Put all your project files into Lib/site-packages
- Put a .pth file containing the path to your project into site-packages
http://docs.python.org/lib/module-site.html

Kent

From bvande at po-box.mcgill.ca  Tue Apr 26 16:29:48 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Tue Apr 26 16:43:26 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <426E16EA.7090300@tds.net>
References: <426D70D0.3000409@po-box.mcgill.ca> <426E16EA.7090300@tds.net>
Message-ID: <426E505C.2020006@po-box.mcgill.ca>

Kent Johnson said unto the world upon 2005-04-26 06:24:
> Brian van den Broek wrote:
> 
>> Hi all,
>>
>> I'm trying to get a hang of properties. It isn't quite clear to me
>> what is the best way to make properties differ in subclasses. Some
>> code snips to show what I've tried:
>>
>> I can get what I want this way:
>>
>>>>> class A(object):
>>
>>
>> ...     def __init__(self): pass
>> ...     def prop_set(self): return "I was set by A's method"
>> ...     my_property = property(prop_set)
>> ...
>>
>>>>> class AA(A):
>>
>>
>> ...     def __init__(self): pass
>> ...     def prop_set(self): return "I was set by AA's method"
>> ...     my_property = property(prop_set)
>> ...
>>
>>>>> aa = AA()
>>>>> aa.my_property
>>
>>
>> "I was set by AA's method"
>>
>> But the reduplication of the prop_set definition and the my_property
>> assignment line seem to go against the grain of OOP to me.
> 
> 
> That is the simplest way to do it. Your indirection approach is also 
> valid. These two threads have some discussion and other solutions but 
> IMO the cures are worse than the disease:
> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/8c96e856c8966c67/6594dfecff4a3744?q=subclass+property&rnum=6&hl=en#6594dfecff4a3744 
> 
> http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/95b9b8df2fa0ad3/a4e8896bd9074f23?q=subclass+property&rnum=2&hl=en#a4e8896bd9074f23 
> 
> 
> Kent

Thanks, Kent.

I think I will go with the indirection way, then.

I had found the first thread you linked. I see what you mean about the 
  cure -- my general belief is that *I* am unlikely to have problems 
for which meta-classes are really the best solution :-)

Thanks for the links and the advice.

Best to all,

Brian vdB

From kristian at zimmer428.net  Tue Apr 26 18:56:04 2005
From: kristian at zimmer428.net (Kristian Rink)
Date: Tue Apr 26 18:54:58 2005
Subject: [Tutor] custom package structure?
In-Reply-To: <426E3491.5080308@tds.net>
References: <20050426114921.867E74BB87@dd3334.kasserver.com>
	<426E3491.5080308@tds.net>
Message-ID: <20050426185604.5c108fee@kassiopeia.zimmer428.net>


Hi Kent;

...and thanks loads for your mail. Once again it helped me pretty much
figuring out what my mistake was like.


On Tue, 26 Apr 2005 08:31:13 -0400
Kent Johnson <kent37@tds.net> wrote:

> No, everything above looks fine. Please post the exact error message
> you are getting (copy / paste the whole thing including the stack
> trace).

Actually, I did quite a mistake which I just discovered after reading
through your reply and my initial mail: My structure is not

> /start.py
> /Server
> /Server/Core/
> /Server/Core/__init__.py
> /Server/Core/DMServer.py
...

but actually

/start.py
/DMServer
/DMServer/__init__.py
/DMServer/Core
/DMServer/Core/DMServer.py
...

After changing the toplevel package name from DMServer to Server,
avoiding having it named DMServer (like the mail class), everything
works fine, and I'm starting to get a clue why this naming got me
trapped in here. :)

Anyhow, thanks a lot for enlightening me.
Cheers & take care,
Kris
From john.ertl at fnmoc.navy.mil  Tue Apr 26 19:02:34 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Tue Apr 26 18:59:15 2005
Subject: [Tutor] using TK to view an image and then close the window
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C645@lanexc107p.fnmoc.navy.mil>

Michael,

Thanks for the understanding and help,  It works kind of.  I was getting
this error with one of my iterations of the code as well.   Do you know what
might be causing this?  Since your code also produced this I figured Oh-Well
and I just put in a try and this at least keeps the error from printing to
the screen.  I will keep trying...a guick google gave me an idea but not
sure.  

Thanks again for the help

Traceback (most recent call last):
  File "./eraseLauncher.py", line 19, in ?
    TK.TKview(newIm,mainTitle="image")
  File "/gpfs3/home/ertlj/BATCH/meteogram/new/test/TKviewTest.py", line 22,
in TKview
    canvas.create_image(0,0,anchor='nw',image=p)
  File "/home/ertlj/ertljVersion/lib/python2.4/lib-tk/Tkinter.py", line
2086, in create_image
    return self._create('image', args, kw)
  File "/home/ertlj/ertljVersion/lib/python2.4/lib-tk/Tkinter.py", line
2075, in _create
    return getint(self.tk.call(
_tkinter.TclError: image "pyimage2" doesn't exist

-----Original Message-----
From: Michael Lange [mailto:klappnase@freenet.de]
Sent: Tuesday, April 26, 2005 01:58
To: Ertl, John
Subject: Re: [Tutor] using TK to view an image and then close the window

On Mon, 25 Apr 2005 14:09:17 -0700
"Ertl, John" <john.ertl@fnmoc.navy.mil> wrote:

> Michael,
>
> I got the TK code from an old post...I really do not know much about how
it
> is supposed to work.  I just thought I seamed so close that it should be
> simple to fix.  I was trying to use self and what not but I still could
not
> get the window to close down.  I guess I will just have to learn a bit
more
> about Tkinter.
>
> Thanks,
>
> John Ertl
>
John,

you are right, it was quite close. It just could be done a little simpler,
like this:

def TKview(img,mainTitle="image"):
       
        top = Tkinter.Tk()

        top.protocol("WM_DELETE_WINDOW", top.quit)# not really necessary if
you don't want to do any cleanup on exit
        top.bind("<q>",lambda event : top.quit)# use lambda here to catch
the event that gets passed by bind()
 
        canvas = Tkinter.Canvas(top)
        canvas.pack()

        p = ImageTk.PhotoImage(img)

        canvas['width'] = img.size[0]
        canvas['height'] = img.size[1]

        canvas.create_image(0,0,anchor='nw',image=p)

        top.mainloop()

I didn't test this, but I think it should do pretty much the same as you
expected from the code you posted.

Calling top.destroy() is not really necessary, because python should do this
for you when you quit
the mainloop. However it seems to be "cleaner" to call destroy() explicitely
with a construction like
this (pseudo code):

top = Tkinter.Tk()
top.protocol("WM_DELETE_WINDOW", top.quit)
top.mainloop()
top.destroy()

Using the protocol() method is necessary here, because otherwise clicking
the "Close" button in the window's title bar
would destroy the window, so calling top.destroy() would raise an error.
The last line of this code is only reached, after the mainloop was
interrupted by calling quit() .
What's nice about this construction is, that you can put some
cleanup-on-exit stuff before top.destroy()
that's performed automatically when the window is closed; in a more complex
application with several modules it's
also nice that you can use any (child) Tk widget's quit() method to stop the
mainloop, so
it's not necessary to have a reference to the main Tk() instance in every
module.

Best regards

Michael
From jeremiah.rushton at gmail.com  Tue Apr 26 19:33:34 2005
From: jeremiah.rushton at gmail.com (Jeremiah Rushton)
Date: Tue Apr 26 19:33:39 2005
Subject: [Tutor] Tkinter and Animation
Message-ID: <be96a66f050426103343beef2f@mail.gmail.com>

In a program that I'm writing in Tkinter, I wanted to know how to animate 
objects. I have three buttons in the beginnig, all in the center. I wanted 
to know how to, when the user clicks one of them, make them small and move 
to a top corner and then have a text box appear where they were.

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050426/e5721579/attachment.htm
From chumpytown at gmail.com  Tue Apr 26 19:49:43 2005
From: chumpytown at gmail.com (chumpy town)
Date: Tue Apr 26 19:49:48 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
In-Reply-To: <426E18BE.1060705@tds.net>
References: <82b2500905042521276bbe0e46@mail.gmail.com>
	<426E18BE.1060705@tds.net>
Message-ID: <82b2500905042610493271bdb7@mail.gmail.com>

Thanks Pierre & Kent.  The subprocess.Popen worked beautifully.

-david

On 4/26/05, Kent Johnson <kent37@tds.net> wrote:
> chumpy town wrote:
> > Hello all,
> > I am trying to convert from bash to python for scripting.  What is the
> > simplest & cleanest way to do the following in python:
> >
> > #!/bin/bash
> > for i in `seq 1 1000`
> >   do
> >   my-other-script &
> > done
> > wait
> > echo "all done"
> 
> You might like the subprocess module - something like this (untested!):
> 
> from subprocess import Popen
> procs = [ Popen("my-other-script") for i in range(1000) ]
> for p in procs:
>    p.wait()
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From alan.gauld at freenet.co.uk  Tue Apr 26 22:39:25 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 26 22:39:51 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
References: <82b2500905042521276bbe0e46@mail.gmail.com>
Message-ID: <007101c54aa0$09542760$43ce8651@xp>

> #!/bin/bash
> for i in `seq 1 1000`
>  do
>  my-other-script &
> done
> wait
> echo "all done"
>
> ...Alternatively, I know I can use os.fork(), os.exec() 
> and os.wait() but this seems cumbersome.  

Bash is optimised for process control, in that it excels. 
For general purpose programming it is both very slow and 
somewhat clunky. Python by contrast is optimised for 
general purpose programming, which means when it comes 
to process control it can be a little clunky.

I suspect fork/exec/wait is your best solution. The only 
real alternative would be to code the process work in python 
and call those functions in separate threads - much more 
efficient but also much more work!

There ain't no perfect language!

Alan G.
From alan.gauld at freenet.co.uk  Tue Apr 26 22:58:12 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 26 22:57:45 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
References: <82b2500905042521276bbe0e46@mail.gmail.com>
	<426E18BE.1060705@tds.net>
Message-ID: <008501c54aa2$a9701720$43ce8651@xp>

> You might like the subprocess module - something like this
(untested!):

Yikes, even more batteries. When did that appear, I've never seen
it before! - Aha! Its 2.4 that's why I havemn't seen it, as ever I
am one release behind the bleeding edge on 2.3...

> from subprocess import Popen
> procs = [ Popen("my-other-script") for i in range(1000) ]
> for p in procs:
>    p.wait()

p.wait will be called for each process in the list so its not quite
the same as a single os.wait but then that might be what's wanted!

Alan G.

From alan.gauld at freenet.co.uk  Tue Apr 26 23:01:27 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue Apr 26 23:02:14 2005
Subject: [Tutor] properties and subclasses
References: <426D70D0.3000409@po-box.mcgill.ca> <426E16EA.7090300@tds.net>
	<426E505C.2020006@po-box.mcgill.ca>
Message-ID: <008a01c54aa3$1de356d0$43ce8651@xp>

> I had found the first thread you linked. I see what you mean about
the
>   cure -- my general belief is that *I* am unlikely to have problems
> for which meta-classes are really the best solution :-)

Once you get used to them meta-classes are very useful. In fact I have
never built an industrial size OO system yet that did not use meta
classes somewhere in the design...

And if you program in OO in Smalltalk, CLOS or Objective C its hard to
escape them. They really aren't that difficult once you wrap your head
around the concept. OTOH I've never actually got round to trying to
use them in Python yet... :-)

Alan G.



From kent37 at tds.net  Tue Apr 26 23:30:54 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue Apr 26 23:31:00 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
In-Reply-To: <008501c54aa2$a9701720$43ce8651@xp>
References: <82b2500905042521276bbe0e46@mail.gmail.com>
	<426E18BE.1060705@tds.net> <008501c54aa2$a9701720$43ce8651@xp>
Message-ID: <426EB30E.4090406@tds.net>

Alan Gauld wrote:
>>from subprocess import Popen
>>procs = [ Popen("my-other-script") for i in range(1000) ]
>>for p in procs:
>>   p.wait()
> 
> 
> p.wait will be called for each process in the list so its not quite
> the same as a single os.wait but then that might be what's wanted!

I'm not sure but from the docs it sounds like os.wait() would be called once for each child also, as 
it returns "a tuple containing [a child process'] pid and exit status indication".

Kent

From jeannot18 at hotmail.com  Wed Apr 27 00:23:25 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Wed Apr 27 00:23:29 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <002401c549c1$cd091f10$43ce8651@xp>
Message-ID: <BAY20-F1365393D8D6FE23EF6116DB3210@phx.gbl>

Hi Alan, sorry for not replying sooner I am right in the middle of setting 
up a network at home. Thanks for your email.

OK the situation is that I haven't still found out what the answer is, I 
have noticed in the other hand that if I select the option "a" let's say 4 
times, I need to enter the option "f" 4 times. I am curious to know what the 
solution is. I have read your chapter on recursion but that did not clear 
anything.

As soon as i get a minute I will look again.

Thanks
JC


From alan.gauld at freenet.co.uk  Wed Apr 27 00:51:35 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr 27 00:51:05 2005
Subject: [Tutor] Re Help with this script
References: <BAY20-F1365393D8D6FE23EF6116DB3210@phx.gbl>
Message-ID: <009101c54ab2$801c2750$43ce8651@xp>

> OK the situation is that I haven't still found out what the answer
is, I
> have noticed in the other hand that if I select the option "a" let's
say 4
> times, I need to enter the option "f" 4 times. I am curious to know
what the
> solution is. I have read your chapter on recursion but that did not
clear
> anything.

OK, basically the problem is that you have unintentionally created
a recursive function. Every time you call it you create a new copy
of the function. When you exit the function you wind up back in
the previous copy. So as many times as you call the function you
have to exit it the same number of times to get back to the top
of your program.

Have a think about it, and see if that makes sense.

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

From denise.hartley at gmail.com  Wed Apr 27 00:57:39 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 27 00:57:47 2005
Subject: [Tutor] font/text in pygame
Message-ID: <8daabe56050426155749f851f2@mail.gmail.com>

So with pygames, if I want to display text on the graphics window, I
can set the font and size and so on, and set what I want my text to
be.  But if I wanted python to grab that text from a list, say, how
would I do that? I can do it in the print command, as follows:

                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            prefix = 5*" "
                            print prefix,name,slip_amt,score

(slip et al. is spacing stuff - not the prettiest code to do it, but it works)

But in any case, font/text will only take strings - i cant pass in a
list, or an index to an item in a list (which is, in this case, a
tuple), and since the items in the list will be changed and updated
obviously i cant just type in the items as strings myself.

any ideas? does this question even make sense the way it's worded?
It's a last-ditch effort to get my high score list onto the graphics
window before i have to abandon it :)

Thanks!
~Denise
From maxnoel_fr at yahoo.fr  Wed Apr 27 01:17:11 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 27 01:17:19 2005
Subject: [Tutor] font/text in pygame
In-Reply-To: <8daabe56050426155749f851f2@mail.gmail.com>
References: <8daabe56050426155749f851f2@mail.gmail.com>
Message-ID: <61a0dbf9464d89ec0cceafb261225608@yahoo.fr>


On Apr 26, 2005, at 23:57, D. Hartley wrote:

> But in any case, font/text will only take strings - i cant pass in a
> list, or an index to an item in a list (which is, in this case, a
> tuple), and since the items in the list will be changed and updated
> obviously i cant just type in the items as strings myself.
>
> any ideas? does this question even make sense the way it's worded?
> It's a last-ditch effort to get my high score list onto the graphics
> window before i have to abandon it :)

	The idea, of course, is to convert the things you want to display to 
strings. You may be interested in the following things:

- the str() function -- converts anything it's passed into a string. 
str(1) returns "1". str((2, 3, 4)) returns "(2, 3, 4)".
- Basic string concatenation -- use the + operator. Example: "a" + "b" 
returns "ab".
- the string.join method -- joins a list or tuple of strings. Example: 
'xx'.join(["foo", "bar", "baz"]) returns "fooxxbarxxbaz".
- string formatting. You ever programmed in C? It's basically the same 
thing as printf, only better. Example:
"Hi, my name is %s. I am %s years old. I come from %s." % ("Max", 21, 
"France")
returns "Hi, my name is Max. I am 21 years old. I come from France."

	By using some of these (string formatting and str() come to mind), you 
should be able to do what you want.

Hope that helps,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From jfouhy at paradise.net.nz  Wed Apr 27 01:22:40 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Wed Apr 27 01:36:40 2005
Subject: [Tutor] Tkinter and Animation
In-Reply-To: <be96a66f050426103343beef2f@mail.gmail.com>
References: <be96a66f050426103343beef2f@mail.gmail.com>
Message-ID: <1114557760.426ecd4052229@www.paradise.net.nz>

Quoting Jeremiah Rushton <jeremiah.rushton@gmail.com>:

> In a program that I'm writing in Tkinter, I wanted to know how to
> animate objects. I have three buttons in the beginnig, all in the 
> center. I wanted to know how to, when the user clicks one of them,
> make them small and move to a top corner and then have a text box 
> appear where they were.

Do you actually want to _animate_ them (ie: have the buttons visually shrink and
move across the screen), or do you just want them to vanish and appear in the
new place?

In Tkinter, placing an object on the screen (using grid or pack) is distinct
from creating the object.  You can use .grid_forget() or .pack_forget() to
ungrid or unpack an object, so that it is not displayed, but it still exists. 
And/or you can just recall grid/pack with different arguments.

eg:

>>> from Tkinter import *
>>> tk = Tk()
>>> b = Button(tk, text='Make')
>>> current = [0]
>>> def make():
...  c = current[0]
...  Label(tk, text='Entry %d' % c).grid(row=c, column=0)
...  Entry(tk).grid(row=c, column=1)
...  b.grid(row=c+1, column=1)
...  current[0] = c + 1
...
>>> b.config(command=make)
>>> b.grid(row=0, column=1)

-- 
John.
From maxnoel_fr at yahoo.fr  Wed Apr 27 02:47:42 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 27 02:47:47 2005
Subject: Fwd: [Tutor] font/text in pygame
Message-ID: <9ce3b9fdfe51fcd9b4ff83f5cb79e778@yahoo.fr>

[Forwarding to the list. Please use "Reply to all", not "Reply", if you 
want your reply to a message to go to the list]

Begin forwarded message:

> From: "D. Hartley" <denise.hartley@gmail.com>
> Date: April 27, 2005 01:36:26 BST
> To: Max Noel <maxnoel_fr@yahoo.fr>
> Subject: Re: [Tutor] font/text in pygame
> Reply-To: "D. Hartley" <denise.hartley@gmail.com>
>
> Max,
>
> Thank you for your helpful answer.  I am particularly interested in 
> this part:
>
>> string formatting. You ever programmed in C? It's basically >the same
>> thing as printf, only better. Example:
>> "Hi, my name is %s. I am %s years old. I come from %s." >% ("Max", 21,
>> "France")
>> returns "Hi, my name is Max. I am 21 years old. I come >from France."
>
> I haven't programmed in C (python is my first language!), but I *have*
> done something like this before, only with the print command:
>
> def displaybalance():
>     for score, name in mylist:
>         slip = 30 - len(name)
>         slip_amt = slip*" "
>         print "%s%s%s" % (name,slip_amt,score)
>
> (I did this with the print command to make sure it would produce what
> I wanted, three strings for the three sample scores I put in this
> dummy list).
>
> So I went and found some sample code to just create a graphics window
> I could try out my new stuff in, and I inserted it as follows. The
> only problem is, it's printing all three lines right on top of each
> other! The newline command wont work (i'm not printing), and I tried
> to do something like text.pos = text.pos + 20 for the y, but no matter
> where I put it in the loop, it was in the wrong place (cant reference
> it before I create "text", can't make a function out of the whole text
> part outside of the main loop....etc).
>
> I know at this point it's just an indentation
> problem/where-it-goes-in-the-loop problem. But I've tried and retried
> it a hundred times and I cant seem to get it to work.  But if I can
> make it work on this sample, maybe I can insert it into my program.
> (Then the only thing I'll have to do is get user input for the new
> name, which I'll worry about second, if I can get this first part to
> work).
>
> I know it's a lot to ask, but can you find the error here, how to make
> these lines print one under the other and not on top of each other?
>
> Ideally I want it to print several lines:
>
> (1)   High Scores
> (2)   Denise                         23   (etc., one for each %s item)
>
> Here's the sample render-font-onto-pygame-window code:
>
> import pygame
> from pygame.locals import *
>
> def main():
> 	# Initialise screen
> 	pygame.init()
> 	screen = pygame.display.set_mode((640, 480))
> 	pygame.display.set_caption('Basic Pygame program')
>
> 	# Fill background
> 	background = pygame.Surface(screen.get_size())
> 	background = background.convert()
> 	background.fill((250, 250, 250))
>
> 	# Display some text
> 	for score, name in mylist:
>             slip = 30 - len(name)
>             slip_amt = slip*" "
>             font = pygame.font.Font(None, 25)
>             text = font.render("%s%s%s" % (name,slip_amt,score), 1,
> (10, 10, 10))
>             textpos = text.get_rect()
>             textpos.centerx = background.get_rect().centerx
>             textpos.centery = 270
>             background.blit(text, textpos)
>
> 	
> 	# Blit everything to the screen
> 	screen.blit(background, (0, 0))
> 	pygame.display.flip()
>
> 	# Event loop
> 	while 1:
> 		for event in pygame.event.get():
> 			if event.type == QUIT:
> 				return
>
> 		screen.blit(background, (0, 0))
> 		pygame.display.flip()
> 		
>
> if __name__ == '__main__': main()
>
> Thanks, Max!!
>
> ~Denise
>
> On 4/26/05, Max Noel <maxnoel_fr@yahoo.fr> wrote:
>>
>> On Apr 26, 2005, at 23:57, D. Hartley wrote:
>>
>>> But in any case, font/text will only take strings - i cant pass in a
>>> list, or an index to an item in a list (which is, in this case, a
>>> tuple), and since the items in the list will be changed and updated
>>> obviously i cant just type in the items as strings myself.
>>>
>>> any ideas? does this question even make sense the way it's worded?
>>> It's a last-ditch effort to get my high score list onto the graphics
>>> window before i have to abandon it :)
>>
>>        The idea, of course, is to convert the things you want to 
>> display to
>> strings. You may be interested in the following things:
>>
>> - the str() function -- converts anything it's passed into a string.
>> str(1) returns "1". str((2, 3, 4)) returns "(2, 3, 4)".
>> - Basic string concatenation -- use the + operator. Example: "a" + "b"
>> returns "ab".
>> - the string.join method -- joins a list or tuple of strings. Example:
>> 'xx'.join(["foo", "bar", "baz"]) returns "fooxxbarxxbaz".
>> - string formatting. You ever programmed in C? It's basically the same
>> thing as printf, only better. Example:
>> "Hi, my name is %s. I am %s years old. I come from %s." % ("Max", 21,
>> "France")
>> returns "Hi, my name is Max. I am 21 years old. I come from France."
>>
>>        By using some of these (string formatting and str() come to 
>> mind), you
>> should be able to do what you want.
>>
>> Hope that helps,
>> -- Max
>> maxnoel_fr at yahoo dot fr -- ICQ #85274019
>> "Look at you hacker... A pathetic creature of meat and bone, panting
>> and sweating as you run through my corridors... How can you challenge 
>> a
>> perfect, immortal machine?"
>>
>>
>
>
-- 
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From maxnoel_fr at yahoo.fr  Wed Apr 27 02:59:39 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 27 02:59:48 2005
Subject: [Tutor] font/text in pygame
In-Reply-To: <8daabe5605042617365bc2a830@mail.gmail.com>
References: <8daabe56050426155749f851f2@mail.gmail.com>
	<61a0dbf9464d89ec0cceafb261225608@yahoo.fr>
	<8daabe5605042617365bc2a830@mail.gmail.com>
Message-ID: <170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>


On Apr 27, 2005, at 01:36, D. Hartley wrote:

> I haven't programmed in C (python is my first language!), but I *have*
> done something like this before, only with the print command:
>
> def displaybalance():
>     for score, name in mylist:
>         slip = 30 - len(name)
>         slip_amt = slip*" "
>         print "%s%s%s" % (name,slip_amt,score)
>
> (I did this with the print command to make sure it would produce what
> I wanted, three strings for the three sample scores I put in this
> dummy list).

	Yup, you did that. And actually, what happened was that string 
formatting was first used to create a string, and then this string was 
sent to the print command, which displayed it. Your last line is 
equivalent to:

foo = "%s%s%s" % (name,slip_amt,score)
print foo

	The only "magic" thing you can only do with print is the "print a, b, 
c" syntax.

> So I went and found some sample code to just create a graphics window
> I could try out my new stuff in, and I inserted it as follows. The
> only problem is, it's printing all three lines right on top of each
> other! The newline command wont work (i'm not printing), and I tried
> to do something like text.pos = text.pos + 20 for the y, but no matter
> where I put it in the loop, it was in the wrong place (cant reference
> it before I create "text", can't make a function out of the whole text
> part outside of the main loop....etc).
>
> I know at this point it's just an indentation
> problem/where-it-goes-in-the-loop problem. But I've tried and retried
> it a hundred times and I cant seem to get it to work.  But if I can
> make it work on this sample, maybe I can insert it into my program.
> (Then the only thing I'll have to do is get user input for the new
> name, which I'll worry about second, if I can get this first part to
> work).
>
> I know it's a lot to ask, but can you find the error here, how to make
> these lines print one under the other and not on top of each other?
>
> Ideally I want it to print several lines:
>
> (1)   High Scores
> (2)   Denise                         23   (etc., one for each %s item)
>
> Here's the sample render-font-onto-pygame-window code:
>

[SNIP some code]

> 	# Display some text
> 	for score, name in mylist:
>             slip = 30 - len(name)
>             slip_amt = slip*" "
>             font = pygame.font.Font(None, 25)
>             text = font.render("%s%s%s" % (name,slip_amt,score), 1,
> (10, 10, 10))
>             textpos = text.get_rect()
>             textpos.centerx = background.get_rect().centerx
>             textpos.centery = 270
			^^^^^^^^^^^^^^^^^^^^^

	This, I believe, is the line you have to modify. All your text goes to 
the same place because you affect it the same position. (text.centery, 
text.centerx) is where the "text" object is rendered on the screen. The 
renderer doesn't know (nor should even care) about the text you may 
have rendered earlier.
	Therefore, you need to render each line of text at a unique position. 
Ideally, the second line should be below the first, etc.

	So that means textpos.centery must be slightly different for each line 
of text you create. Let's say, 270 for the first one, 300 for the 
second one, etc.

	You could start by modifying your for loop so that it reads like this:

for score, name, posY in mylist, range(270, 540, 30):

	The rest shouldn't be hard to figure out. ;)

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From denise.hartley at gmail.com  Wed Apr 27 03:27:47 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 27 03:27:53 2005
Subject: [Tutor] font/text in pygame
In-Reply-To: <170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>
References: <8daabe56050426155749f851f2@mail.gmail.com>
	<61a0dbf9464d89ec0cceafb261225608@yahoo.fr>
	<8daabe5605042617365bc2a830@mail.gmail.com>
	<170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>
Message-ID: <8daabe56050426182762a36a59@mail.gmail.com>

Max (et al.):

I tried to do it that way ("score, name, posY" etc) and it told me
"too many values to unpack".  But I did get it to work the following
way:


# Display some text
        x, y = 230, 270
	for score, name in mylist:
            slip = 30 - len(name)
            slip_amt = slip*" "
            font = pygame.font.Font(None, 25)
            text = font.render("%s%s%s" % (name,slip_amt,score), 1,
(10, 10, 10, 0))
            background.blit(text, (x,y))
            y += text.get_height()

I'd rather have it centered on the x (x = 230 is the beginning (left
end) of the string, and my strings are different lengths, so I'd
rather have it centered), but I was just thrilled to get it working in
the first place.   So if anyone knows something quick I can add to
that code to make it centerx rather than beginning x, that'd be great.
But it does at least work for now.

But then I tried to import this (working!) code into my game, and even
tho it executes the function within which it's contained BEFORE
waiting for the "y/n another game" response, it's not displaying the
score then (I just managed to glimpse it in the second after I hit n,
the score flashed on right before the window closed. So I know it's in
there and works! Just not at the right time.)

The code goes like this:

          if lives == 0:
### trying addscore
                gameover.play()
                showGameOver(screen, background_image)                
                pygame.display.flip()                

                def add_score():
                    high_scores = pickle.load(file("scores.pik"))
                    score = total_enemy_hits
                    if score > high_scores[-1][0]:
                        print "Ta da! You got", total_enemy_hits,
"Ranch Delivery Devices!"
                        name = read_string("You made the high score
list! What's your name? ")
                        user_score = (score,name)
                        high_scores.append(user_score)
                        high_scores.sort(reverse=True)
                        del high_scores[-1]
                        pickle.dump(high_scores, file("scores.pik", "w"))
                        x, y = 230, 270
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            font = pygame.font.Font(None, 25)
                            text = font.render("%s%s%s" %
(name,slip_amt,score), 1, (255, 255, 255, 0))
                            screen.blit(text, (x,y))
                            y += text.get_height()
                    else:
                        print "Sorry, you only got", total_enemy_hits,
"Ranch Delivery Devices."
                        print "You didn't quite make the high score list!"
                        x, y = 230, 270
                        for score, name in high_scores:
                            slip = 30 - len(name)
                            slip_amt = slip*" "
                            font = pygame.font.Font(None, 25)
                            text = font.render("%s%s%s" %
(name,slip_amt,score), 1, (255, 255, 255, 0))
                            screen.blit(text, (x,y))
                            y += text.get_height()
                        print "Better luck next time!"

#                pdb.set_trace()
                add_score()

                answer = ""
                while not answer in ("y","n"):
                   for event in pygame.event.get():
                      if event.type == KEYDOWN:
                         if event.key == K_n:
                            answer = "n"
                         elif event.key == K_y:
                            answer = "y"
                if answer == "n":
                    running = 0
                else:
                    return 1

    
            #refresh the display
            pygame.event.pump()
            pygame.display.flip()

    #well, nice playing with you...
    screen = pygame.display.set_mode((640, 480))
    return 0


See, it seems to me that I define and execute the add_score function
BEFORE the "do you want to play again" bit. But it doesnt display
until AFTER you hit that key, at which point the game goes onto the
next thing (i.e., either refreshes and starts the game over, or closes
the window).  Like I said I know it's in there, because I saw it flash
on after I hit the n key, right before the window closes.  I tried
moving the showgameover/flip, commenting out the different
flip/pump/etc commands (these are a little out of my league,
experience-wise), and tried rearranging things as best I could. (And
yes, I know defining the add_score function right there is probably
not elegant, but if I dont do it that way I get other errors).  Am I
missing something glaringly obvious? If I define and use the add_score
function before the keystroke commands, why is it displaying after?

Thanks...

~Denise
From denise.hartley at gmail.com  Wed Apr 27 03:31:19 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 27 03:31:23 2005
Subject: [Tutor] font/text in pygame
In-Reply-To: <8daabe56050426182762a36a59@mail.gmail.com>
References: <8daabe56050426155749f851f2@mail.gmail.com>
	<61a0dbf9464d89ec0cceafb261225608@yahoo.fr>
	<8daabe5605042617365bc2a830@mail.gmail.com>
	<170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>
	<8daabe56050426182762a36a59@mail.gmail.com>
Message-ID: <8daabe5605042618317e8cfa75@mail.gmail.com>

P.S.  I should also add that the "print" commands embedded within the
add_score function ARE displaying at the appropriate time (i.e.,
before I have to hit y/n).  Of course they're in the text/console
window, but it does tell me that it's executing that add_score
function at the right point in time.

So why is it waiting until after the y/n keystroke to display the text
I'm rendering on the game window?
From bvande at po-box.mcgill.ca  Wed Apr 27 03:51:57 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Wed Apr 27 03:52:32 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <008a01c54aa3$1de356d0$43ce8651@xp>
References: <426D70D0.3000409@po-box.mcgill.ca> <426E16EA.7090300@tds.net>
	<426E505C.2020006@po-box.mcgill.ca>
	<008a01c54aa3$1de356d0$43ce8651@xp>
Message-ID: <426EF03D.5080403@po-box.mcgill.ca>

Alan Gauld said unto the world upon 2005-04-26 17:01:
>>I had found the first thread you linked. I see what you mean about
> 
> the
> 
>>  cure -- my general belief is that *I* am unlikely to have problems
>>for which meta-classes are really the best solution :-)
> 
> 
> Once you get used to them meta-classes are very useful. In fact I have
> never built an industrial size OO system yet that did not use meta
> classes somewhere in the design...
> 
> And if you program in OO in Smalltalk, CLOS or Objective C its hard to
> escape them. They really aren't that difficult once you wrap your head
> around the concept. OTOH I've never actually got round to trying to
> use them in Python yet... :-)
> 
> Alan G.


Hi Alan,

thanks for the reply.

I can see why they'd be useful. But, as my OO code is at best cottage 
industry size ;-) I've yet to find I needed them. The couple of times 
I've been tempted to work out the details of using them for a real 
case of my own I recalled Eric Raymond's comment:

Why Python? | Linux Journal
"This kind of thing is called metaclass hacking and is generally 
considered fearsomely esoteric--deep black magic. "
http://www.linuxjournal.com/article/3882

and decided to think harder to see if I could find another way. So 
far, that's worked :-)

But, thanks for the encouragement to take them on.

Best,

Brian vdB
From maxnoel_fr at yahoo.fr  Wed Apr 27 04:05:21 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Wed Apr 27 04:05:29 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <008a01c54aa3$1de356d0$43ce8651@xp>
References: <426D70D0.3000409@po-box.mcgill.ca> <426E16EA.7090300@tds.net>
	<426E505C.2020006@po-box.mcgill.ca>
	<008a01c54aa3$1de356d0$43ce8651@xp>
Message-ID: <6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>


On Apr 26, 2005, at 22:01, Alan Gauld wrote:

>> I had found the first thread you linked. I see what you mean about
> the
>>   cure -- my general belief is that *I* am unlikely to have problems
>> for which meta-classes are really the best solution :-)
>
> Once you get used to them meta-classes are very useful. In fact I have
> never built an industrial size OO system yet that did not use meta
> classes somewhere in the design...

	Speaking of that, would you happen to know a good 
tutorial/introduction to metaclasses in Python?

-- Max
"Metaclass is an instance of one of its own subclasses." It's not just 
black magic, it's *recursive* black magic! :D

From kent37 at tds.net  Wed Apr 27 05:45:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 27 05:45:48 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>
References: <426D70D0.3000409@po-box.mcgill.ca>
	<426E16EA.7090300@tds.net>	<426E505C.2020006@po-box.mcgill.ca>	<008a01c54aa3$1de356d0$43ce8651@xp>
	<6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>
Message-ID: <426F0AE6.1070902@tds.net>

Max Noel wrote:
>     Speaking of that, would you happen to know a good 
> tutorial/introduction to metaclasses in Python?

You could try Guido's essay:
http://www.python.org/2.2/descrintro.html#metaclasses

Kent

From apantomimehorse at gmail.com  Wed Apr 27 08:59:42 2005
From: apantomimehorse at gmail.com (brian will)
Date: Wed Apr 27 08:59:44 2005
Subject: [Tutor] tuple/list assignment in 'for-in'
Message-ID: <80de89630504262359bc40ee4@mail.gmail.com>

Hi there,

I can't explain my experience with what I like to call 'parallel
assignment' (tuple/list assignment) inside 'for-in' loops and list
comprehensions:

1)
>>> [f + g for f, g in (1, 2), (3, 4)]
[3, 7]

2)
>>> x = 'ab'
>>> y = 'cd'
>>> [f + g for f, g in x, y]
['ab', 'cd']

3)
>>> f, g = '123', '456'
>>> f
'123'
>>> g
'456'

4)
>>> [f + g for f, g in '123', '456']
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in -toplevel-
    [f + g for f, g in '123', '456']
ValueError: too many values to unpack

So why does it accept references to strings but not string literals?
The third example works with a tuple assignment of string literals but
not in the for-in? Any good reason for this, or is it just a quirk?

Thanks,

--Brian Will
From alan.gauld at freenet.co.uk  Wed Apr 27 09:24:58 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr 27 09:24:23 2005
Subject: [Tutor] properties and subclasses
References: <426D70D0.3000409@po-box.mcgill.ca> <426E16EA.7090300@tds.net>
	<426E505C.2020006@po-box.mcgill.ca>
	<008a01c54aa3$1de356d0$43ce8651@xp>
	<6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>
Message-ID: <009801c54afa$3887caf0$43ce8651@xp>

> > Once you get used to them meta-classes are very useful. In fact I
have
> > never built an industrial size OO system yet that did not use meta
> > classes somewhere in the design...
>
> Speaking of that, would you happen to know a good
> tutorial/introduction to metaclasses in Python?


Nope, but it sounds like a fun thing to do! :-)
Maybe I'll put that next on my worklist, as soon
as I finish writing up databases...

The only thing I've read on Python metaclasses is the paper
Guido wrote when they were introduced and it's hardly a
simple tutorial...

There is a pair of articles by the normally excellent
David Mertz here:

http://www-106.ibm.com/developerworks/linux/library/l-pymeta.html

Alan G

From alan.gauld at freenet.co.uk  Wed Apr 27 09:34:39 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Wed Apr 27 09:34:10 2005
Subject: [Tutor] python's bash wait and ampersand equivalent?
References: <82b2500905042521276bbe0e46@mail.gmail.com><426E18BE.1060705@tds.net>
	<008501c54aa2$a9701720$43ce8651@xp> <426EB30E.4090406@tds.net>
Message-ID: <00b101c54afb$92298b10$43ce8651@xp>

> I'm not sure but from the docs it sounds like os.wait() would 
> be called once for each child also, as 

If you don't specify a pid os.wait should return as soon as *any* 
child process terminates. Which is why it returns the pid - to tell 
you which child died...

At least that's what I'd expect based on using the C version.

Alan G.

From exogen at gmail.com  Wed Apr 27 10:10:21 2005
From: exogen at gmail.com (Brian Beck)
Date: Wed Apr 27 10:12:03 2005
Subject: [Tutor] Re: tuple/list assignment in 'for-in'
In-Reply-To: <80de89630504262359bc40ee4@mail.gmail.com>
References: <80de89630504262359bc40ee4@mail.gmail.com>
Message-ID: <d4nh38$18n$1@sea.gmane.org>

brian will wrote:
> Hi there,
> 
> I can't explain my experience with what I like to call 'parallel
> assignment' (tuple/list assignment) inside 'for-in' loops and list
> comprehensions:

You're probably confused about what's being assigned to what inside the
comprehension. Maybe this will clear it up:

> 1)
> 
>>>>[f + g for f, g in (1, 2), (3, 4)]
> 
> [3, 7]

[(1, 2), (3, 4)] is your 'source' list, so the first time f = 1 and g =
2, then f = 3 and g = 4. I'm guessing you have no problem with the
output given.

> 2)
> 
>>>>x = 'ab'
>>>>y = 'cd'
>>>>[f + g for f, g in x, y]
> 
> ['ab', 'cd']

[x, y] is your 'source' list. For x, f = 'a' and g = 'b'. For y, f = 'c'
and g = 'd'.

> 3)
> 
>>>>f, g = '123', '456'
>>>>[f + g for f, g in '123', '456']
> 
> Traceback (most recent call last):
>   File "<pyshell#55>", line 1, in -toplevel-
>     [f + g for f, g in '123', '456']
> ValueError: too many values to unpack

Here you're in trouble because the strings are the wrong length. Your
second example worked, whether intentionally or by coincidence, because
the strings were both 2 characters long, and you were unpacking them
into two variables. Here you're trying to unpack 3 items ('1', '2', '3',
 then '4', '5', '6') into 2 variables, which doesn't work.

--
Brian Beck
Adventurer of the First Order

From kent37 at tds.net  Wed Apr 27 12:25:37 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed Apr 27 12:25:44 2005
Subject: [Tutor] properties and subclasses
In-Reply-To: <6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>
References: <426D70D0.3000409@po-box.mcgill.ca>
	<426E16EA.7090300@tds.net>	<426E505C.2020006@po-box.mcgill.ca>	<008a01c54aa3$1de356d0$43ce8651@xp>
	<6b44f11fd5f4e633ebbac95fd3665789@yahoo.fr>
Message-ID: <426F68A1.4070301@tds.net>

Max Noel wrote:
>     Speaking of that, would you happen to know a good 
> tutorial/introduction to metaclasses in Python?

Here is an example that bills itself as "The Simplest Possible Metaclass":
http://orbtech.com/blog/simplemetaclass

The new Python Cookbook (the printed one) has a chapter on Descriptors, Decorators and Metaclasses. 
It has some simple examples of metaclasses. I haven't read it yet but the first Cookbook was 
excellent and I expect this one to be also.

BTW the new Cookbook features a recipe by none other than yours truly and Danny Yoo! It happens to 
be in the sample chapter online - check out recipe 3.2 at 
http://www.oreilly.com/catalog/pythoncook2/chapter/index.html

Kent

From apantomimehorse at gmail.com  Wed Apr 27 12:47:00 2005
From: apantomimehorse at gmail.com (brian will)
Date: Wed Apr 27 12:47:03 2005
Subject: [Tutor] Re: tuple/list assignment in 'for-in'
Message-ID: <80de89630504270347580947a3@mail.gmail.com>

Thanks. I realized this mistake right before you replied. Yup, the
coincidence of my test cases threw me there.

By the way, what's a good way to reply to specific subjects and
quoting when using the mailing list through g-mail here?
From jeremiah.rushton at gmail.com  Wed Apr 27 18:35:47 2005
From: jeremiah.rushton at gmail.com (Jeremiah Rushton)
Date: Wed Apr 27 18:35:56 2005
Subject: [Tutor] Re: Tkinter and Animation
Message-ID: <be96a66f050427093546ecbedd@mail.gmail.com>

>> In a program that I'm writing in Tkinter, I wanted to know how to
>> animate objects. I have three buttons in the beginnig, all in the
>> center. I wanted to know how to, when the user clicks one of them,
>> make them small and move to a top corner and then have a text box
>> appear where they were.
>
>Do you actually want to _animate_ them (ie: have the buttons visually 
shrink and
>move across the screen), or do you just want them to vanish and appear in 
the
>new place?
>
>In Tkinter, placing an object on the screen (using grid or pack) is 
distinct
>from creating the object. You can use .grid_forget() or .pack_forget() to
>ungrid or unpack an object, so that it is not displayed, but it still 
exists.
>And/or you can just recall grid/pack with different arguments.
>
>eg:
>
>>>> from Tkinter import *
>>>> tk = Tk()
>>>> b = Button(tk, text='Make')
>>>> current = [0]
>>>> def make():
>... c = current[0]
>... Label(tk, text='Entry %d' % c).grid(row=c, column=0)
>... Entry(tk).grid(row=c, column=1)
>... b.grid(row=c+1, column=1)
>... current[0] = c + 1
>...
>>>> b.config(command=make)
>>>> b.grid(row=0, column=1)
>
>--
>John.

I wanted them to visually shrink and visually move to a corner on the frame. 
I did not know how to do it the way you explained, thanks for that. But is 
there any way to do it visually?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050427/e9dec92b/attachment.htm
From klappnase at freenet.de  Wed Apr 27 22:46:42 2005
From: klappnase at freenet.de (Michael Lange)
Date: Wed Apr 27 22:42:42 2005
Subject: [Tutor] Re: Tkinter and Animation
In-Reply-To: <be96a66f050427093546ecbedd@mail.gmail.com>
References: <be96a66f050427093546ecbedd@mail.gmail.com>
Message-ID: <20050427224642.3e0c5d97.klappnase@freenet.de>

On Wed, 27 Apr 2005 09:35:47 -0700
Jeremiah Rushton <jeremiah.rushton@gmail.com> wrote:

> 
> I wanted them to visually shrink and visually move to a corner on the frame. 
> I did not know how to do it the way you explained, thanks for that. But is 
> there any way to do it visually?
> 

I guess so, if you use the "place" geometry manager. With place() you can determine
things like x- and y-coordinates on the parent widget and relative width / height,
so if you start a loop that moves the button 2 pixels up and one pixel to the left
every 50ms for example it might come close to the kind of animation you want.
It's probably tricky, but I think it's possible.

Best regards

Michael
From tktucker at gmail.com  Wed Apr 27 22:52:57 2005
From: tktucker at gmail.com (Tom Tucker)
Date: Wed Apr 27 22:52:59 2005
Subject: [Tutor] Is it possible to load variable into a regex string?
Message-ID: <2a278ffe05042713523a748b7c@mail.gmail.com>

Hello all! I am trying to pass a variable to my re.compile string (see
broken example below). Is something like this possible?  Thanks!

regexstring = 'H\sb'
textstring = 'BLAH blah'
match = re.compile((%s) % (regexstring))  # ?
if match.search(line):
          print "I found it!"


Tom
From dyoo at hkn.eecs.berkeley.edu  Wed Apr 27 23:14:00 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Apr 27 23:14:10 2005
Subject: [Tutor] Is it possible to load variable into a regex string?
In-Reply-To: <2a278ffe05042713523a748b7c@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0504271408490.27573-100000@hkn.eecs.berkeley.edu>



On Wed, 27 Apr 2005, Tom Tucker wrote:

> Hello all! I am trying to pass a variable to my re.compile string (see
> broken example below). Is something like this possible?  Thanks!
>
> regexstring = 'H\sb'
> textstring = 'BLAH blah'
> match = re.compile((%s) % (regexstring))  # ?

Hi Tom,

Ah, I think I see what you're trying to do.  I think you were trying to
do:

    match = re.compile("%s" % (regexstring))

which uses string formatting to pull the 'regexstring' in, and then passes
the result off to re.compile().



But it might be better to just directly compile the regex string, without
the intermediate string formatting:

    match = re.compile(regexstring)

Does that make sense?



One other note: your regex string definition:

> regexstring = 'H\sb'

might need a slight adjustment, since you want to maintain that backslash
in the string literal.  Try:

    regexstring = r'H\sb'


The leading "r' in front of the string literal tells Python not to treat
internal backslashes as the escape character.  This "raw mode" is
especially useful for regular expressions, which use literal backslashes
heavily as metacharacters.

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

From denise.hartley at gmail.com  Wed Apr 27 23:14:34 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Wed Apr 27 23:14:42 2005
Subject: [Tutor] Is there an InputBox function in pygame/python?
In-Reply-To: <8daabe560504271413128e978a@mail.gmail.com>
References: <8daabe560504271413128e978a@mail.gmail.com>
Message-ID: <8daabe5605042714142867dd48@mail.gmail.com>

I am trying to create a box on the graphics window which asks a user
for their name.  My research led me to the "InputBox" function, which
is said to "get user input, allowing backspace etc shown in a box in
the middle of the screen" (but ignores the shift key?).  I found
several pages that refer to it, and one example on google, but it
seems very cryptic to me, and I can't find any other help materials.
I tried help(InputBox), tried to use the function itself, tried to
search for it in the documentation on python.org, and tried to google
it (InputBox, Python).  I got a half-million websites talking about
VBS and other versions of InputBox, and can't find one (besides the
cryptic one) for python.  Does this function exist? Or is it called
something else?  Can someone point me to an
explanation/definition/simple example?  Like I said, I am just trying
to ask for a user name, it is nothing more (or less!) complicated than
that.

Thanks for any pointers you might have!
From albertito_g at hotmail.com  Wed Apr 27 23:35:43 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed Apr 27 23:35:47 2005
Subject: [Tutor] Help with daemon
Message-ID: <BAY106-F8B9E46B2EB4626DFF119E89220@phx.gbl>

Hi everyone

Again disturbing the peace of the TUTOR :D

I'm making an application to check every few seconds for photos uploaded via 
ftp

The users will program their upload time via web page (made in php). The 
time is saved in a MySQL database so I will check for all the created users 
if they are in record time. I'm applying a security politic that when the 
users are in record time then the ftp will let them write and erase, but 
when they aren't the ftp only will let them read.

Here is my problem. Imagine 100 users and lets say that User A connects at 
9:00 and User B will connect at 9:10. When I first check at 9:00 User A is 
in record time so he can send photos but User B does not. The program will 
have to check for all 100 users and will hardly reach for another check at 
9:10 and it will loss transfer time. The OS is linux and the version of 
Python is 2.2.3.

The question is, how can I make the application to manage a process for each 
user the database find, so only one process will attend one user and I think 
it will be fast enough to cover the record time.

I don't know if my approach is right, I'm new with multithreading and I will 
appreciate the help.

I'm gonna give you an example:

The program will check for new users and to check record time every 10 
seconds. But first the program will have to finish the checking process that 
started before so it won't be 10 seconds right?
Unless I have one process for each user to check the database at the same 
time is checking other users

Thanks for the help and I hope this is clear (and not long) enough for you 
to help me

Regards

Alberto


From maxnoel_fr at yahoo.fr  Thu Apr 28 00:38:00 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Thu Apr 28 00:41:51 2005
Subject: [Tutor] Help with daemon
In-Reply-To: <BAY106-F8B9E46B2EB4626DFF119E89220@phx.gbl>
References: <BAY106-F8B9E46B2EB4626DFF119E89220@phx.gbl>
Message-ID: <2ee178fe156c9bbe2cb356f8495e57f5@yahoo.fr>


On Apr 27, 2005, at 22:35, Alberto Troiano wrote:

> I'm gonna give you an example:
>
> The program will check for new users and to check record time every 10 
> seconds. But first the program will have to finish the checking 
> process that started before so it won't be 10 seconds right?
> Unless I have one process for each user to check the database at the 
> same time is checking other users

	This sounds like it'd be better done as a cron job (man cron for more 
info).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From keridee at jayco.net  Thu Apr 28 01:48:49 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu Apr 28 01:48:13 2005
Subject: [Tutor] crash - switching between text window
	andgraphics/gamewindow (high score)
References: <8daabe56050419152924c792d6@mail.gmail.com><BAY106-F25C49F1E45A2170291859D892B0@phx.gbl><8daabe560504201415684bc5e1@mail.gmail.com>
	<1114041930.4266ee4b001fb@www.paradise.net.nz>
Message-ID: <004801c54b83$c07e7880$d95328cf@JSLAPTOP>

> I haven't been following this thread, so apologies in advance if this is
> something you've already done ---
>
> Have you tried running the program from a command prompt?  To do this, go 
> to
> Start-->Run and type 'cmd'.  Then change to the directory with your script 
> in it
> ('cd ' followed by the full directory path), and run the script by typing
> 'python ' followed by the script name.
> (you may need to type something like 'c:\python24\python ' instead, if 
> python is
> not in your path)
>
> The effect of this is that, when the program crashes, you will be left 
> with a
> window showing you (hopefully) some useful error messages.

I tend to look at cool new ways of automation.  For this particular 
inventive idea, I said, how can I make this do what I want?  In the 
documentation somewhere, it tells you that if you add an -i extension to the 
python command, it will end with an interpreter so you can explore the 
current environment.  i.e. all of your variables set in the program won't be 
erased, and you can print them, manipulate them, etc.

So I said to myself, "That's brilliant, let's make it easier to use from the 
Windows environment."
Using the file associations found in folder options--you can get to folder 
options through control panel--you can go to the py extension listed under 
the tab "file types"  If you click on the advanced button, you can copy the 
command for open, paste it to a new function called say, "Run, end with 
interpreter" or something that makes sense to you, and add the -i extension 
in the command.  Then you make the necessary closings of the dialog boxes, 
the display refreshes automatically, and you can right click on a py file to 
see the new command labeled with your equivalent of "Run, end with 
interpreter"  This is cool, because you can click on it, and it acts like 
IDLE without it.

Okay, I'm done and I'll shut up now.
Jacob 

From keridee at jayco.net  Thu Apr 28 02:37:58 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu Apr 28 02:37:57 2005
Subject: [Tutor] font/text in pygame
References: <8daabe56050426155749f851f2@mail.gmail.com><61a0dbf9464d89ec0cceafb261225608@yahoo.fr><8daabe5605042617365bc2a830@mail.gmail.com>
	<170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>
Message-ID: <007e01c54b8a$ae64aa50$d95328cf@JSLAPTOP>

>> def displaybalance():
>>     for score, name in mylist:
>>         slip = 30 - len(name)
>>         slip_amt = slip*" "
>>         print "%s%s%s" % (name,slip_amt,score)
>>
>> (I did this with the print command to make sure it would produce what
>> I wanted, three strings for the three sample scores I put in this
>> dummy list).
>
> Yup, you did that. And actually, what happened was that string formatting 
> was first used to create a string, and then this string was sent to the 
> print command, which displayed it. Your last line is equivalent to:
>
> foo = "%s%s%s" % (name,slip_amt,score)
> print foo
>
> The only "magic" thing you can only do with print is the "print a, b, c" 
> syntax.

Uck.

Try this.

for score, name in mylist:
    name = name.ljust(30)
    print "%s%s" % (name,score)

Or, if you prefer...

print "\n".join("%-30s%s"%(name,score) for name,score in mylist)

If you don't have python 2.4

print "\n".join([---]) # with the hyphens replaced with the above 
comprehension


Oh, and there is another cool thing you can do with print.
First off, print uses sys.stdout, so if you change it, print changes where 
it prints.
Second, if you use the syntax print >>output,item0,item1,item2
you can redirect manually where things are printed to. output has to be an 
object which has a write method.

i.e.

a = open("myfile.txt","w")

b = "This is the string I want to print out."
print >>a,b
a.close()

gives you a file in the current directory with the filename "myfile.txt" 
with the contents "This is the string I want to print out."

Okay, I'm done again,
Jacob 

From denise.hartley at gmail.com  Thu Apr 28 02:45:33 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Thu Apr 28 02:45:36 2005
Subject: [Tutor] font/text in pygame
In-Reply-To: <007e01c54b8a$ae64aa50$d95328cf@JSLAPTOP>
References: <8daabe56050426155749f851f2@mail.gmail.com>
	<61a0dbf9464d89ec0cceafb261225608@yahoo.fr>
	<8daabe5605042617365bc2a830@mail.gmail.com>
	<170ada857abaa17ea9a8520cf2b7b021@yahoo.fr>
	<007e01c54b8a$ae64aa50$d95328cf@JSLAPTOP>
Message-ID: <8daabe56050427174563e0dcf1@mail.gmail.com>

Jacob (et al):

Unfortunately at this point I'm rendering the text, not printing it
(using text = font.render).  So I need to know if there is a hard
character or something I can type, since 50*" " (space) isnt lining
them up right.

Thanks!
~Denise

On 4/27/05, Jacob S. <keridee@jayco.net> wrote:
> >> def displaybalance():
> >>     for score, name in mylist:
> >>         slip = 30 - len(name)
> >>         slip_amt = slip*" "
> >>         print "%s%s%s" % (name,slip_amt,score)
> >>
> >> (I did this with the print command to make sure it would produce what
> >> I wanted, three strings for the three sample scores I put in this
> >> dummy list).
> >
> > Yup, you did that. And actually, what happened was that string formatting
> > was first used to create a string, and then this string was sent to the
> > print command, which displayed it. Your last line is equivalent to:
> >
> > foo = "%s%s%s" % (name,slip_amt,score)
> > print foo
> >
> > The only "magic" thing you can only do with print is the "print a, b, c"
> > syntax.
> 
> Uck.
> 
> Try this.
> 
> for score, name in mylist:
>    name = name.ljust(30)
>    print "%s%s" % (name,score)
> 
> Or, if you prefer...
> 
> print "\n".join("%-30s%s"%(name,score) for name,score in mylist)
> 
> If you don't have python 2.4
> 
> print "\n".join([---]) # with the hyphens replaced with the above
> comprehension
> 
> Oh, and there is another cool thing you can do with print.
> First off, print uses sys.stdout, so if you change it, print changes where
> it prints.
> Second, if you use the syntax print >>output,item0,item1,item2
> you can redirect manually where things are printed to. output has to be an
> object which has a write method.
> 
> i.e.
> 
> a = open("myfile.txt","w")
> 
> b = "This is the string I want to print out."
> print >>a,b
> a.close()
> 
> gives you a file in the current directory with the filename "myfile.txt"
> with the contents "This is the string I want to print out."
> 
> Okay, I'm done again,
> Jacob
> 
>
From jeannot18 at hotmail.com  Thu Apr 28 03:18:47 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Thu Apr 28 03:18:51 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <009101c54ab2$801c2750$43ce8651@xp>
Message-ID: <BAY20-F17D3FCADB30691C5C37CA5B3230@phx.gbl>

OK Alan, I thing I have seen the light!!. Here is the script that Kent and 
you asked me to look at modified:

-------------------------------------------------------------------------
def print_options():
       print "------------------------------"
       print "Options:"
       print "a. print options"
       print "f. quit the programme"
       print "------------------------------"

print_options()
choice = 0
while choice != 'f':
    print
    choice = raw_input("Choose an option: ")
    if choice == 'a':
        print "Here we go again"
        print_options()
    if choice == 'f': break

print_options()
-------------------------------------------------------------------------
Is it that if you use "while 1:" you create a recursive function? Hope I am 
right.

Thanks
JC

--------------------------------------------------------------------------------------------
PREVIOUS EMAIL

OK the situation is that I haven't still found out what the answer
is, I
>have noticed in the other hand that if I select the option "a" let's
say 4
>times, I need to enter the option "f" 4 times. I am curious to know
what the
>solution is. I have read your chapter on recursion but that did not
clear
>anything.

OK, basically the problem is that you have unintentionally created
a recursive function. Every time you call it you create a new copy
of the function. When you exit the function you wind up back in
the previous copy. So as many times as you call the function you
have to exit it the same number of times to get back to the top
of your program.

Have a think about it, and see if that makes sense.

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


From jeremiah.rushton at gmail.com  Thu Apr 28 04:31:06 2005
From: jeremiah.rushton at gmail.com (Jeremiah Rushton)
Date: Thu Apr 28 04:31:13 2005
Subject: [Tutor] Re: Re: Re: Tkinter and Animation
Message-ID: <be96a66f050427193140032c6d@mail.gmail.com>

>>
>> I wanted them to visually shrink and visually move to a corner on the 
frame.
>> I did not know how to do it the way you explained, thanks for that. But 
is
>> there any way to do it visually?
>>
>
>I guess so, if you use the "place" geometry manager. With place() you can 
determine
>things like x- and y-coordinates on the parent widget and relative width / 
height,
>so if you start a loop that moves the button 2 pixels up and one pixel to 
the left
>every 50ms for example it might come close to the kind of animation you 
want.
>It's probably tricky, but I think it's possible.
>
>Best regards
>
>Michael

I tried your idea and it doesn't animate it. I made a for loop and told it 
to mover 1 pixel downward every .3 seconds for 25 times. It just waits till 
the for loop is completed and then displays the result of the loop ending. I 
also tried it without the for loop by writing each one of the steps out 
repetively and I had the same result. The only thing that has kind of got 
close to the visual is that I wrote a program that everytime the user 
clicked the button it moved down one pixel, but I want it to move 100 
pixels, one by one, with only one click from the user. Here's the code that 
I wrote:

from Tkinter import *
from time import sleep

class Main:

def __init__(self,master):
button = Button(master,text='button')
button.place(x=1,y=1)
y=3
for x in range(1,25):
sleep(.3)
button.place_forget()
button.place(x=1,y=y)
y+=2


root = Tk()
Main(root)
root.title('test')
root.mainloop()

Thanks for all the help so far.

Jeremiah
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050427/aff662d0/attachment.html
From jfouhy at paradise.net.nz  Thu Apr 28 04:47:00 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Thu Apr 28 04:48:43 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <BAY20-F17D3FCADB30691C5C37CA5B3230@phx.gbl>
References: <BAY20-F17D3FCADB30691C5C37CA5B3230@phx.gbl>
Message-ID: <1114656420.42704ea49f366@www.paradise.net.nz>

Quoting John Carmona <jeannot18@hotmail.com>:

> Is it that if you use "while 1:" you create a recursive function? Hope I
> am right.

No ...

Remember how functions can call other functions?

def add(x, y):
    """ Add two integers together. """
    return x+y

def mul(x, y):
    """ Multiply two integers together. """
    if x == 0:
        return 0
    if x < 0:
        x = -x
    product = y
    while x > 1:
        product = add(product, y)
        x = add(x, -1)

The mul function calls add to do some of its work for it.

A recursive functio nis just a function that calls itself.  For example, we
could rewrite add as:

def increment(x):
    """ Increment an integer. """
    return x + 1

def decrement(x):
    """ Decrement an integer. """
    return x - 1

def add(x, y):
    """ Add two integers together. """
    if x == 0:
        return y
    if x == 1:
        return increment(y)
    if x == -1:
        return decrement(y)
    if x < 0:
        return add(-1, add(add(1, x), y))
    else:
        return add(1, add(add(-1, x), y))

In this case, add is a recursive function, because it makes calls to itself. 
There's nothing magical about recursive functions or recursion; you just have to
be a bit careful to make sure that your program will end.  

Example:

def poem():
    print 'A mad metaprogrammer wrote a mad metaprogram,\n which started: "',
    poem()
    print 'sort of close," were the words that the programmer finally chose\nTo
bring his mad program to some sort of close.'

The poem() function will call the poem() function which will call the poem()
function which will call the poem() function, with no end in sight...

Another example:

def qsort(lst):
    """ Quicksort a list. """
    if len(lst) <= 1:
        return lst
    pivot = lst[0]
    return qsort([x for x in lst if x < pivot]) + [pivot] + qsort([x for x in
lst if x > pivot])

This will stop because the argument in each recursive call to qsort is smaller
than the original, and because there is a smallest value ([]).

Does this help?

[Bonus questions:

1. Can you rewrite the recursive add() so that you only need one of (increment,
decrement)?

2. Do you recognise the inspiration for poem()?
]

-- 
John.
From jfouhy at paradise.net.nz  Thu Apr 28 05:00:55 2005
From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz)
Date: Thu Apr 28 05:02:02 2005
Subject: [Tutor] Re: Re: Re: Tkinter and Animation
In-Reply-To: <be96a66f050427193140032c6d@mail.gmail.com>
References: <be96a66f050427193140032c6d@mail.gmail.com>
Message-ID: <1114657255.427051e7bd3b6@www.paradise.net.nz>

Quoting Jeremiah Rushton <jeremiah.rushton@gmail.com>:

> from Tkinter import *
> from time import sleep
> 
> class Main:
> 
>  def __init__(self,master):
>   button = Button(master,text='button')
>   button.place(x=1,y=1)
>   y=3
>   for x in range(1,25):
>    sleep(.3)
>    button.place_forget()
>    button.place(x=1,y=y)
>    y +=2
> 
> 
> root = Tk()
> Main(root)
> root.title('test')
> root.mainloop()

Try adding a call to master.update_idletasks() in your for loop.  Still not
ideal, though, but maybe it would work better if you were doing the animation
after the Tk mainloop had started. (I'm just guessing there, though)

-- 
John.
From alan.gauld at freenet.co.uk  Thu Apr 28 09:10:12 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu Apr 28 09:12:42 2005
Subject: [Tutor] Re Help with this script
References: <BAY20-F17D3FCADB30691C5C37CA5B3230@phx.gbl>
Message-ID: <00e001c54bc1$52e6dcc0$43ce8651@xp>


> OK Alan, I thing I have seen the light!!.

Almost. :-)

> --------------------------------------------------------------------
-----
> def print_options():
>        print "------------------------------"
>        print "Options:"
>        print "a. print options"
>        print "f. quit the programme"
>        print "------------------------------"
>
> print_options()
> choice = 0
> while choice != 'f':
>     print
>     choice = raw_input("Choose an option: ")
>     if choice == 'a':
>         print "Here we go again"
>         print_options()
>     if choice == 'f': break

That should be all you need.

> print_options()

This shouldn't be needed.

> Is it that if you use "while 1:" you create a recursive function?
Hope I am
> right.

NO the recursive bit is where the function calls itself.
In the previous version you had the while loop inside
the function so that you called print_options while you
were still inside print_options, like this:

def print_options():
       print "------------------------------"
       print "Options:"
       print "a. print options"
       print "f. quit the programme"
       print "------------------------------"
    choice = 0
    while choice != 'f':
      print
      choice = raw_input("Choose an option: ")
      if choice == 'a':
          print "Here we go again"
          print_options()  ## THIS CALL IS INSIDE THE FUNCTION
      if choice == 'f': break

It was the fact that the call was inside the function that made
it recursive. When you selected f to quit you simply quit that
call to the function and returned to the higher level call and
had to select f again until you eventually got back to the top
level.. I'll try to draw it:

print_options()
    choice = a
    print_options()
       choice = a
       print_options()
         choice = a
         print_options()
            choice = f
         choice = f
       choice = f
    choice = f
exit

You needed to select f to exit each call to print_options.

Any clearer?

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

From mark.kels at gmail.com  Thu Apr 28 22:33:38 2005
From: mark.kels at gmail.com (Mark Kels)
Date: Fri Apr 29 02:33:08 2005
Subject: [Tutor] Python and ICQ??
Message-ID: <c22592530504281333147e4b81@mail.gmail.com>

Hi list !
Does anyone here knows of a way to connect to ICQ with Python?

Thanks in advance.
-- 
1. The day Microsoft makes something that doesn't suck is probably the
day they start making vacuum cleaners.
2. Unix is user friendly - it's just picky about it's friends.
3. Documentation is like sex: when it is good, it is very, very good.
And when it is bad, it is better than nothing. - Dick Brandon
From jeffpeery at yahoo.com  Thu Apr 28 22:39:29 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Fri Apr 29 02:33:16 2005
Subject: [Tutor] missing module?
Message-ID: <20050428203929.93467.qmail@web30501.mail.mud.yahoo.com>

Hello, I get an error message from py2exe that it can't find a module ntpath.py.  I pasted the error message below:
 
Traceback (most recent call last):
  File "wxApp1.py", line 4, in ?
  File "wx\__init__.pyc", line 42, in ?
  File "wx\_core.pyc", line 4, in ?
  File "wx\_core_.pyc", line 9, in ?
  File "wx\_core_.pyc", line 3, in __load
  File "C:\Python24\lib\os.py", line 62, in ?
    import ntpath as path
zipimport.ZipImportError: can't find module 'ntpath'

 
I can find ntpath why can't py2exe? how can I get this thing working? thanks for the help.
 
jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050428/32feb1dc/attachment.html
From jeffpeery at yahoo.com  Thu Apr 28 19:12:47 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Fri Apr 29 02:44:48 2005
Subject: [Tutor] wxpython error when upgrading?
Message-ID: <20050428171248.80054.qmail@web30507.mail.mud.yahoo.com>

hello, I recently upgraded my wxpython to 2.5, now I get an error message when I try to edit a dialog in the boa constructor that says : collection body not in init, body, fin form - anyone have an idea what this means? thanks.
 
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050428/72099b3a/attachment.htm
From albertito_g at hotmail.com  Fri Apr 29 00:06:19 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr 29 02:49:12 2005
Subject: [Tutor] Help with daemon
In-Reply-To: <2ee178fe156c9bbe2cb356f8495e57f5@yahoo.fr>
Message-ID: <BAY106-F853EC45F929EE261D053889230@phx.gbl>

Hi

I will make it with CRON. Thanks Max for the idea

Now I have another problem

How can I kill a process???????

I know that if I run ps --user username it returns all the process started 
by username even the PIDs and with kill -9 PID I destroy the process but I 
don't know how to execute it from Python

I tried:
>>>import os
>>>os.system("ps --user root")

and I get

0
as a return
How can I get the PID and bind the command above with a variable?? I mean
varusername="root"
os.system("ps --user varusername")
works???????

thanks in advanced

Alberto

>From: Max Noel <maxnoel_fr@yahoo.fr>
>To: "Alberto Troiano" <albertito_g@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] Help with daemon
>Date: Wed, 27 Apr 2005 23:38:00 +0100
>
>
>On Apr 27, 2005, at 22:35, Alberto Troiano wrote:
>
>>I'm gonna give you an example:
>>
>>The program will check for new users and to check record time every 10 
>>seconds. But first the program will have to finish the checking process 
>>that started before so it won't be 10 seconds right?
>>Unless I have one process for each user to check the database at the same 
>>time is checking other users
>
>	This sounds like it'd be better done as a cron job (man cron for more 
>info).
>
>-- Max
>maxnoel_fr at yahoo dot fr -- ICQ #85274019
>"Look at you hacker... A pathetic creature of meat and bone, panting and 
>sweating as you run through my corridors... How can you challenge a 
>perfect, immortal machine?"
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From maxnoel_fr at yahoo.fr  Fri Apr 29 02:05:12 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 29 02:52:37 2005
Subject: [Tutor] Help with daemon
In-Reply-To: <BAY106-F853EC45F929EE261D053889230@phx.gbl>
References: <BAY106-F853EC45F929EE261D053889230@phx.gbl>
Message-ID: <bca2cdb21a236ec7a3805e83dd39849b@yahoo.fr>


On Apr 28, 2005, at 23:06, Alberto Troiano wrote:

> I tried:
>>>> import os
>>>> os.system("ps --user root")
>
> and I get
>
> 0
> as a return
> How can I get the PID and bind the command above with a variable?? I 
> mean
> varusername="root"
> os.system("ps --user varusername")
> works???????

	So in essence, what you're trying to do is store the output of a 
command in a variable, right?
	You might be interested in the os.popen family of functions.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From tanja.pislar at gmail.com  Fri Apr 29 12:48:28 2005
From: tanja.pislar at gmail.com (tanja pislar)
Date: Fri Apr 29 12:48:31 2005
Subject: [Tutor] Python and ICQ??
In-Reply-To: <c22592530504281333147e4b81@mail.gmail.com>
References: <c22592530504281333147e4b81@mail.gmail.com>
Message-ID: <f686a68a05042903483bd8e5b4@mail.gmail.com>

try pyICQ-t, (it's an ICQ transport for jabber implemented in python)
http://pyicq-t.blathersource.org/

regards,
tanja

On 4/28/05, Mark Kels <mark.kels@gmail.com> wrote:
> Hi list !
> Does anyone here knows of a way to connect to ICQ with Python?
> 
> Thanks in advance.
> --
> 1. The day Microsoft makes something that doesn't suck is probably the
> day they start making vacuum cleaners.
> 2. Unix is user friendly - it's just picky about it's friends.
> 3. Documentation is like sex: when it is good, it is very, very good.
> And when it is bad, it is better than nothing. - Dick Brandon
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
www.klaustrofobik.org
From servando at mac.com  Fri Apr 29 14:55:20 2005
From: servando at mac.com (Servando Garcia)
Date: Fri Apr 29 14:55:26 2005
Subject: [Tutor] input()
Message-ID: <d5aa1d3a8fcf3df9fb72cb5b60c21ae4@mac.com>

Hello and  thanks in advance.
	I am trying to prompt the user for some input. I need three values 
from the user so,I used input() like so;
Matrix = input("Matrix=")
error=input("error=")
alpha= input("alpha=")
  using  Macpython it works fine but when I use a terminal all I get is 
a blank line. When I try to enter at the command line I get this
Matrix=error=alpha=
Also I need to redirect any output from the program into another file, 
which is why I used the terminal in the first place. So, I guess I have 
two problems
	1. How do I redirect output using Macpython?
	2. How do I use input() while using a terminal?

From ewald.ertl at hartter.com  Fri Apr 29 15:17:12 2005
From: ewald.ertl at hartter.com (Ewald Ertl)
Date: Fri Apr 29 15:17:16 2005
Subject: [Tutor] input()
In-Reply-To: <d5aa1d3a8fcf3df9fb72cb5b60c21ae4@mac.com>
References: <d5aa1d3a8fcf3df9fb72cb5b60c21ae4@mac.com>
Message-ID: <20050429151712.00005aa4@sunray1>

Hi!

I don't have a Mac and so I don't know Macpython. 

on Fri, 29 Apr 2005 07:55:20 -0500  Servando Garcia <servando@mac.com> wrote :
---------------------------------------------------------------------------------------------

Servando Garcia > Hello and  thanks in advance.
Servando Garcia > 	I am trying to prompt the user for some input. I need three values 
Servando Garcia > from the user so,I used input() like so;
Servando Garcia > Matrix = input("Matrix=")
Servando Garcia > error=input("error=")
Servando Garcia > alpha= input("alpha=")
Servando Garcia >   using  Macpython it works fine but when I use a terminal all I get is 
Servando Garcia > a blank line. When I try to enter at the command line I get this
Servando Garcia > Matrix=error=alpha=
Here on my sun i get the following:

>>> a=input("hello=")
hello=5+6
>>> a
11


When calling help on input the result is the following:

>>> help(input)
Help on built-in function input:

input(...)
    input([prompt]) -> value
    
    Equivalent to eval(raw_input(prompt)).


So the inputvalue is evaluated in python. 

Using raw_input() gives back the entered value: 

>>> a=raw_input("hello=")
hello=myInput
>>> a
'myInput'

Perhaps this work's also on a Mac



Servando Garcia > Also I need to redirect any output from the program into another file, 
Servando Garcia > which is why I used the terminal in the first place. So, I guess I have 
Servando Garcia > two problems

On a UNIX-Shell two programms are connected via the "|" - Pipe. 
The first one writes to stdout ( sys.stdout or print ) and the second 
reads from stdin

Servando Garcia > 	1. How do I redirect output using Macpython?
Servando Garcia > 	2. How do I use input() while using a terminal?
Servando Garcia > 
Servando Garcia > _______________________________________________
Servando Garcia > Tutor maillist  -  Tutor@python.org
Servando Garcia > http://mail.python.org/mailman/listinfo/tutor
Servando Garcia > 


------------------- end ----------------------
HTH 

Ewald 

From mark.kels at gmail.com  Fri Apr 29 15:26:31 2005
From: mark.kels at gmail.com (Mark Kels)
Date: Fri Apr 29 15:26:35 2005
Subject: [Tutor] Python and ICQ??
In-Reply-To: <f686a68a05042903483bd8e5b4@mail.gmail.com>
References: <c22592530504281333147e4b81@mail.gmail.com>
	<f686a68a05042903483bd8e5b4@mail.gmail.com>
Message-ID: <c225925305042906266b3bbcd@mail.gmail.com>

On 4/29/05, tanja pislar <tanja.pislar@gmail.com> wrote:
> try pyICQ-t, (it's an ICQ transport for jabber implemented in python)
> http://pyicq-t.blathersource.org/
> 
> regards,
> tanja

Thanks, but its to complicated for my needs. What I need is a simple
module that will allow me to connect to ICQ and send some messages to
users.

-- 
1. The day Microsoft makes something that doesn't suck is probably the
day they start making vacuum cleaners.
2. Unix is user friendly - it's just picky about it's friends.
3. Documentation is like sex: when it is good, it is very, very good.
And when it is bad, it is better than nothing. - Dick Brandon
From cpu.crazy at gmail.com  Fri Apr 29 05:48:55 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri Apr 29 15:31:45 2005
Subject: [Tutor] cPickle (Joseph Q.)
Message-ID: <6.1.0.6.2.20050428212019.01ef4728@pop.gmail.com>

Hi all,
	How could I have the user name his file? I learned that I type file_name = 
"foo.bar"
How could I make it that the use could name it "hello.hi"?

Thanks,
	Joe

From jeannot18 at hotmail.com  Fri Apr 29 15:33:43 2005
From: jeannot18 at hotmail.com (John Carmona)
Date: Fri Apr 29 15:33:47 2005
Subject: [Tutor] Re Help with this script
In-Reply-To: <009101c54ab2$801c2750$43ce8651@xp>
Message-ID: <BAY20-F334D0123477E2636005936B3240@phx.gbl>

Hi Alan, I did not receive personally your last email but I have read it on 
the forum.

OK i understand now what you were talking about, sorry it took such a long 
time for me to see the solution, the good thing about it is that I am 
learning tons.

I will probably post soon again once I hit a wall on my next exercise. 
Thanks a million for your help (also Kent and John - I will try to rewrite 
your poem/exercise once I get a minute, thanks)

Regards
JC


From gilly775 at gmail.com  Fri Apr 29 16:48:01 2005
From: gilly775 at gmail.com (Brian Wurtzel)
Date: Fri Apr 29 16:48:12 2005
Subject: [Tutor] Issue with "Entry"/GUI/PIL
Message-ID: <722d5f8f05042907488f6d482@mail.gmail.com>

Skipped content of type multipart/alternative-------------- next part --------------
A non-text attachment was scrubbed...
Name: AL.gif
Type: image/gif
Size: 783 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050429/e96cdd11/AL-0001.gif
From maxnoel_fr at yahoo.fr  Fri Apr 29 17:44:11 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 29 17:44:19 2005
Subject: [Tutor] cPickle (Joseph Q.)
In-Reply-To: <6.1.0.6.2.20050428212019.01ef4728@pop.gmail.com>
References: <6.1.0.6.2.20050428212019.01ef4728@pop.gmail.com>
Message-ID: <3cea4f008513b3b82d645e199778d5a3@yahoo.fr>


On Apr 29, 2005, at 04:48, Joseph Quigley wrote:

> Hi all,
> 	How could I have the user name his file? I learned that I type 
> file_name = "foo.bar"
> How could I make it that the use could name it "hello.hi"?
>
> Thanks,
> 	Joe

	Well, all you have to do is have the user input a string, and use this 
string as the name of the file. The raw_input function should allow you 
to do that.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From maxnoel_fr at yahoo.fr  Fri Apr 29 18:22:18 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Fri Apr 29 18:22:22 2005
Subject: Fwd: [Tutor] cPickle (Joseph Q.)
Message-ID: <8e14d40a6120e1d1fb752a106292ee93@yahoo.fr>



Begin forwarded message:

> From: Joseph Quigley <cpu.crazy@gmail.com>
> Date: April 29, 2005 17:16:22 BST
> To: Max Noel <maxnoel_fr@yahoo.fr>
> Subject: Re: [Tutor] cPickle (Joseph Q.)
>
> I tried that and it doesn't work!
> I type the name and it just sits there!
>
> Here's the code:
>
> # variables
> name = "JOTEX "
> versn = "0.1"
> # end variables
>
> print name + versn
>
>
> def intro():
>     print """JOTEX is a very simple command based text editor with a 
> maximum of
> 6 lines (counting up though). Similar to early version of TEX."""
>
> def commands():
>     print """\nThe following commands are:
>     \jn$ for a new line.
>         Ex: Hello!\jn$  then Hi again! returns:
>             Hello!
>             Hi again!
>
>     \jq$ for quiting the program at any prompt.
>
>     \js$ for saving (feature not currently available)
>
> No more commands.
> """
>     main()
>
> def l6():
>     l6 = raw_input("")
>     print
>     print
>     save()
>     main()
> def l5():
>     l5 = raw_input("")
>     l6()
> def l4():
>     l4 = raw_input("")
>     l5()
> def l3():
>     l3 = raw_input("")
>     l4()
> def l2():
>     l2 = raw_input("")
>     l3()
> def l1():
>     l1 = raw_input("")
>     l2()
>
>
> def main():
>     intro()
>     print "\nYou may want to see the commands. Type \jhc for 
> commands.\nPress\
> 'Enter' (Return) to begin a document"
>     prompt = raw_input(">>> ")
>     if "\jhc$" in prompt:
>         commands()
>     elif "\jq$" in prompt:
>         raise SystemExit
>     else:
>         print "\n\n\n"
>         l1()
> def save():
>     import cPickle as p
>     file_name = "test.txt"
>     f = file(file_name, 'w')
>     all = [l1(), l2(), l3(), l4(), l5(), l6()]
>     p.dump(all, f)
>     f.close()
>     main()
>
> main()
>
>
>
> At 09:44 AM 4/29/2005, you wrote:
>
>> On Apr 29, 2005, at 04:48, Joseph Quigley wrote:
>>
>>> Hi all,
>>>         How could I have the user name his file? I learned that I 
>>> type file_name = "foo.bar"
>>> How could I make it that the use could name it "hello.hi"?
>>>
>>> Thanks,
>>>         Joe
>>
>>         Well, all you have to do is have the user input a string, and 
>> use this string as the name of the file. The raw_input function 
>> should allow you to do that.
>>
>> -- Max
>> maxnoel_fr at yahoo dot fr -- ICQ #85274019
>> "Look at you hacker... A pathetic creature of meat and bone, panting 
>> and sweating as you run through my corridors... How can you challenge 
>> a perfect, immortal machine?"
>
>
-- 
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From dyoo at hkn.eecs.berkeley.edu  Fri Apr 29 22:00:08 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Apr 29 22:00:23 2005
Subject: [Tutor] wxpython error when upgrading?
In-Reply-To: <20050428171248.80054.qmail@web30507.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.44.0504291258510.30160-100000@hkn.eecs.berkeley.edu>



On Thu, 28 Apr 2005, Jeff Peery wrote:

> hello, I recently upgraded my wxpython to 2.5, now I get an error
> message when I try to edit a dialog in the boa constructor that says :
> collection body not in init, body, fin form - anyone have an idea what
> this means? thanks.

Hi Jeff,

This sounds a bit specialized; you may want to talk with the wxPython
user's group:

    http://www.wxpython.org/maillist.php

They should have more experience with what you're running into with
wxPython.


Best of wishes!

From albertito_g at hotmail.com  Fri Apr 29 22:45:07 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri Apr 29 22:45:18 2005
Subject: [Tutor] Issue with "Entry"/GUI/PIL
In-Reply-To: <722d5f8f05042907488f6d482@mail.gmail.com>
Message-ID: <BAY106-F35F88415FC95E377A8325989240@phx.gbl>

Replace the 0.0 for only 0

But you have a problem. You are inserting the question and that's what the 
if  clause analyze so it will be always wrong you have to add another Entry 
and a submit button so it will analyze the result of the second Entry
Regards

Alberto

>From: Brian Wurtzel <gilly775@gmail.com>
>Reply-To: Brian Wurtzel <gilly775@gmail.com>
>To: tutor@python.org
>Subject: [Tutor] Issue with "Entry"/GUI/PIL
>Date: Fri, 29 Apr 2005 09:48:01 -0500
>
>Please ignore the rest of the code, except for the highlighted part (or the
>line 'ent1=Entry(topf, width=25)' to line 'ent1.insert(INSERT, wrong, if 
>you
>cannot see the color). You can copy this into Python and make sure you have
>the GIF file in the same dir. Also, make sure that you have PIL installed.
>The only radio button that currently works is Alabama.
>
>I cannot get this to work. I get an error after running it after selecting
>"Take the quiz" for Alabama, and what I'm trying to do it to evaluate what
>the person enters in the box for the capital of Alabama. I want the user to
>enter the capital and if it's not right, I want the program to tell them
>within that box. Apparently, Python does not like the "0.0" entry within 
>the
>box.
>  The error in Python is
>  Exception in Tkinter callback
>Traceback (most recent call last):
>File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
>return self.func(*args)
>File "C:\Documents and Settings\Student\Desktop\map-test.py", line 98, in
>stateget
>ent1.delete(0.0, END)
>File "C:\Python24\lib\lib-tk\Tkinter.py", line 2307, in delete
>self.tk.call(self._w, 'delete', first, last)
>TclError: bad entry index "0.0"
>  Why is this not working? Here's the code:
>
>from Tkinter import *
>import ImageTk
>class Gui(Frame):
>
>def lab(self):
># A generic text label for the frame
>self.lab1 = Label(base, text = "Text for label") #text will be reset later
>self.lab1.grid(columnspan=3)
>
>def but(self):
># A generic button for the frame
>self.but1 = Button(bottom, text="Take the quiz") #text and command to be 
>set
>later
>self.but1.pack(side=RIGHT)
>
>def labR(self):
># A generic text label for the right frame
>self.lab1R = Label(R, text = "Text for label") #text will be reset later
>self.lab1R.pack(side = TOP)
>
>#def butL(self):
># A generic button for the left frame
>#self.but1L = Button(L, text="text on button") #text and command to be set
>later
>#self.but1L.pack(side = LEFT)
>
>def butR(self):
># A generic button for the right frame
>self.but1R = Button(RB, text="text on button") #text and command to be set
>later
>self.but1R.pack(side = LEFT)
>
>#def entcap(None):
># A generic text entry for the left frame
>#self.entcap1 = Entry(width=25) #width can be changed later
>#self.entcap1.pack(side = BOTTOM)
>
>def entR(self):
># A generic text entry for the right frame
>ent1R = Entry(RB, width=20) #width can be changed later
>ent1R.pack(side = TOP)
>
>def txtL(self):
># A generic text box for the left frame
>self.txt1L = Text(L, width=100, height=5, wrap=WORD)
>self.txt1L.pack(side = BOTTOM)
>
>def txtR(self):
># A generic text box for the right frame
>self.txt1R = Text(R, width=100, height=5, wrap=WORD, padx=5, pady=5)
>self.txt1R.pack(side = TOP)
>
>def rdbut(self):
>
>self.states = StringVar()
>Radiobutton(base, text="Alabama", variable=self.states,
>value="AL").grid(row=20, column=0, sticky=W)
>Radiobutton(base, text="Arkansas", variable=self.states,
>value="AK").grid(row=20, column=1, sticky=W)
>Radiobutton(base, text="Florida", variable=self.states,
>value="FL").grid(row=20, column=2, sticky=W)
>Radiobutton(base, text="Georgia", variable=self.states,
>value="GA").grid(row=25, column=0, sticky=W)
>Radiobutton(base, text="Kentucky", variable=self.states,
>value="KY").grid(row=25, column=1, sticky=W)
>Radiobutton(base, text="Louisiana", variable=self.states,
>value="LA").grid(row=25, column=2, sticky=W)
>Radiobutton(base, text="Mississippi", variable=self.states,
>value="MS").grid(row=30, column=0, sticky=W)
>Radiobutton(base, text="North Carolina", variable=self.states,
>value="NC").grid(row=30, column=1, sticky=W)
>Radiobutton(base, text="South Carolina", variable=self.states,
>value="SC").grid(row=30, column=2, sticky=W)
>Radiobutton(base, text="Tennessee", variable=self.states,
>value="TN").grid(row=35, column=0, sticky=W)
>Radiobutton(base, text="Virginia", variable=self.states,
>value="VA").grid(row=35, column=1, sticky=W)
>Radiobutton(base, text="West Virginia", variable=self.states,
>value="WV").grid(row=35, column=2, sticky=W)
>
>
>
>def stateget(self):
>state = self.states.get()
>if state == "AL":
>top = Toplevel()
>top.title("Alabama Capital Quiz")
>topf = Frame(top)
>topf.pack()
>topb = Frame(top)
>topb.pack()
>pct = ImageTk.PhotoImage(file="AL.gif")
>var = Canvas(topb, height=250, width=250)
>img = var.create_image(10, 10, anchor=N, image=pct)
>var.pack()
>#top.geometry("500x500")
># Now I add a text box
>#txtbx2 = Text(topf, height=5, width=40, bg="yellow", wrap=WORD)
>#txtbx2.pack(side=TOP)
>#txtbx2.insert(INSERT, message2)
>close = Button(topb, text="Close", command=top.destroy)
>close.pack(side=RIGHT)
>ent1=Entry(topf, width=25)
>ent1.insert(INSERT, "What is the capital of Alabama?")
>ent1.pack()
>name = ent1.get()
>right = "Correct!!!"
>wrong = "No, please try again."
>if name == "montgomery":
>ent1.delete(0.0, END)
>ent1.insert(INSERT, right)
>else:
>ent1.delete(0.0, END)
>ent1.insert(INSERT, wrong)
>
>
>root = Tk()
>root.title("US Southeast Regional Quiz")
>
>
>gui = Gui(root)
>
>
>base = Frame(root)
>base.grid()
>
>gui.lab()
>gui.lab1.configure(text="Welcome to the Southeast US State Quiz!")
>
># I will bring in another label explaining what I want
>gui.lab()
>gui.lab1["text"]="Please select a state to begin and click on the 'Take the
>quiz' button below."
>
># Now for the radiobuttons displayed with the updatemsg textbox
>gui.rdbut()
>#gui.updatemsg()
>
># I Need a frame for my buttons
>bottom = Frame(base)
>bottom.grid(row=99)
>
># To get out of the program
>gui.but()
>gui.but1.configure(text="Exit", command=gui.quit)
>
># To run the msg function
>gui.but()
>gui.but1.configure(text="Take the Quiz", command=gui.stateget)
>
>
>root.mainloop()
><< AL.gif >>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho


From alan.gauld at freenet.co.uk  Fri Apr 29 23:54:01 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri Apr 29 23:53:46 2005
Subject: [Tutor] input()
References: <d5aa1d3a8fcf3df9fb72cb5b60c21ae4@mac.com>
Message-ID: <014501c54d05$f4768370$43ce8651@xp>

> Matrix = input("Matrix=")
> error=input("error=")
> alpha= input("alpha=")
>   using  Macpython it works fine but when I use a terminal all I get
is
> a blank line.

Can you tell us a bit more about how you areusing MacPython
and the terminal?

Macpython has a console which presents a Python prompt and you type
the commands as shown. If you want to run the program at the Terminal
you have two options:

1) write the program into a text file using vi, emacs, BB EDit or
similar.
   Then run the fuile using python:

$ python myscript.py

or

2) type python and type the commands in at the >>> prompt.

To use the script in the way you describe below you must go with
option (1)
and create a text file with the program in.

> When I try to enter at the command line I get this
> Matrix=error=alpha=


This actually looks like you are using a script file but then just
hiting
enter when prompted. Are you actually typing any input at the Terminal
prompt?
If so is it showing up anywhere?

> Also I need to redirect any output from the program into another
file,
> which is why I used the terminal in the first place. So, I guess I
have
> two problems
> 1. How do I redirect output using Macpython?

Thats difficult and I wouldn't even try. Running the program script
at the Termninal is the way to go.

> 2. How do I use input() while using a terminal?

First can you start Python in command prompt mode - so you get the >>>
prompt?

If so does using input() work there?

Second try a very simple program that asks the user for their name
and says hello back:

name = raw_input("What's your name? ")
print "Hello", name

[ Notice I used raw_input which is safer than input from a security
point
  of view, but you don;t need to worry too much about that just yet.]

Does that work as expected?

If so type it into a plain text file called hello.py
and try running it from the Terminal prompt by typing

python hello.py

Does that work?

Tell us how you get on.

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

From smichr at bigfoot.com  Sat Apr 30 00:39:09 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Sat Apr 30 00:40:04 2005
Subject: [Tutor] Re: input()
In-Reply-To: <20050429144848.1CC8A1E4340@bag.python.org>
Message-ID: <806DB8A9-B8FF-11D9-BF5A-000393C0D100@bigfoot.com>


On Friday, Apr 29, 2005, at 09:48 America/Chicago, 
tutor-request@python.org wrote:

> Hello and  thanks in advance.
> 	I am trying to prompt the user for some input. I need three values
> from the user so,I used input() like so;
> Matrix = input("Matrix=")
> error=input("error=")
> alpha= input("alpha=")
>   using  Macpython it works fine but when I use a terminal all I get is
> a blank line. When I try to enter at the command line I get this
> Matrix=error=alpha=
> Also I need to redirect any output from the program into another file,
> which is why I used the terminal in the first place. So, I guess I have
> two problems
> 	1. How do I redirect output using Macpython?
> 	2. How do I use input() while using a terminal?
>

It seems to work fine here for me, but I'm not sure what you are trying 
to do.  I'm using Python 2.4 under OS 10.2.8.  Perhaps you could paste 
a copy of the terminal prompts as they appear?  Here is what my session 
looked like when I entered 12 and 4 for two inputs:

###
csmith% cat go.py
a=input('a=')
b=input('b=')
print a,b
csmith% python go.py
a=12
b=4
12 4
###

If I make a file and feed it to the program rather than entering the 
text by hand I get:

###
csmith% cat > dat
12
4
^C
csmith% python go.py < dat
a=b=12 4
###

If I try to redirect this to a file I get:

###
csmith% python go.py < dat > out
csmith% cat out
a=b=12 4
###

One thing you might try is to change your prompt from something like 
"a=" to "a=\n"

Which of the above scenarios are you trying to work with and what do 
you want the result to be? It looks like the input to input() is not 
echoed so you should do that yourself if you want the values the user 
entered to be displayed in the file/output. e.g.

###
csmith% cat go2.py
def echoInput(prompt=""):
   ret = input(prompt)
   print ret
   return ret
a=echoInput('a=')
b=echoInput('b=')
print a,b
csmith% python go2.py < dat > out
csmith% cat out
a=12
b=4
12 4
###

/c

From smichr at bigfoot.com  Sat Apr 30 01:01:00 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Sat Apr 30 01:01:53 2005
Subject: [Tutor] tokenize row numbering
Message-ID: <8DA5600F-B902-11D9-BF5A-000393C0D100@bigfoot.com>

I got over my intimidation with tokenize and learned to use it to strip 
comments from code files.  In the process, I learned that the tuples 
that it returns for the position in the code of various tokens is 
1-based in the row rather than 0-based, so the tuple pair (3,1),(3,2) 
would be the start and stop position of the "=" OP in the following 
code:

###
# line 1 according to tokenize tuple
# line 2
a=b #line 3
###

Does anyone have an idea of *why* the rows/physical lines of code 
beginning their count at 1 instead of 0? In order to process the code I 
either have to subtract 1 from all the first elements of tuple 
positions or else insert a blank line at the beginning of the list that 
I make out of my code when I want to process it.

Is this a candidate for a feature change request?
/c

From smichr at bigfoot.com  Sat Apr 30 01:15:10 2005
From: smichr at bigfoot.com (Chris Smith)
Date: Sat Apr 30 01:16:05 2005
Subject: [Tutor] enumerate offset?
Message-ID: <888D0F6C-B904-11D9-BF5A-000393C0D100@bigfoot.com>

Does anybody else ever run into the case of using enumerate on a slice 
but then wish that the original list indices were being returned 
instead of the ones starting at zero?

I would like to see an offset argument that could be used with 
enumerate:

###
l=range(5)
for i,li in enumerate(l[3:]):
	print i, li

def myenumerate(l,offset=0):
	for i,li in enumerate(l):
		yield i+offset, li

print
for i,li in myenumerate(l[3:],3):
	print i,li
###
'''--the output--
0 3
1 4

3 3
4 4
    --end output--'''

/c

From dianahawks at optusnet.com.au  Sat Apr 30 10:49:48 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Sat Apr 30 10:53:40 2005
Subject: [Tutor] guess the number game help
Message-ID: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>

Hello list!



I have started teaching Python to a group of High School students. I set them the "Guess the Number" game as a GUI as an assignment. One of the students has passed in some script that is foreign to any tutorial work we have done.  Some of it is below. Does anyone recognise it? Can you tell me where it would have been downloaded from? I have searched for scripted guess the number games, but there are thousands of them - except for a Python version. 



If my student has plagiarised - I need to know.



TIA Diana





from Tkinter import *

from whrandom import *

 

 

class rand: 

   def __init__(self, low, high):   #whrandom number is made here

      self.ro = whrandom()

      self.num = self.ro.randint(low, high)

 

   def number(self):                

      return self.num

 

   def set(self):                   

      self.num = self.ro.randint(low, high)

 

#this part evaluates the users guess

def evaluate_ans(guess_str, whrandom, low_str, high_str, guess_left, \

                 guess_eval_str, yg_label):

   guesses_left = int(guess_left.get())   

   guesses_left = guesses_left - 1

   guess_left.set(str(guesses_left))

   guess = int(guess_str.get())

   if guess == whrandom.number():           #User has guessed the number.

      guess_eval_str.set("correct")

      play_agn.configure(state=NORMAL)

   else:                                  #User has not guessed the number.

      if guess < whrandom.number():            #Guess is too low.

         low_str.set(str(guess))

         guess_eval_str.set("too low")

      elif guess > whrandom.number():          #Guess is too high.

         high_str.set(str(guess))

         guess_eval_str.set("too high")

      guess_str.set("")

      if guesses_left == 0:                  #User has no guesses left.

         yg_label.configure(text="Correct answer:")

         guess_eval_str.set(str(whrandom.number()))

         play_agn.configure(state=NORMAL)

   return

 

#Reset variables for next game

def reset(whrandom,play_agn, low_str, high_str, guess_left, guess_str, \

          yg_label, guess_eval_str, low, high):

   play_agn.configure(state=DISABLED)

   whrandom.set()

   low_str.set(str(low - 1))

   high_str.set(str(high + 1))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050430/0b0dd14a/attachment.html
From maxnoel_fr at yahoo.fr  Sat Apr 30 12:05:46 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr 30 12:05:53 2005
Subject: [Tutor] guess the number game help
In-Reply-To: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
References: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
Message-ID: <b610de82fb90a3617c5bf388703d9d11@yahoo.fr>


On Apr 30, 2005, at 09:49, Diana Hawksworth wrote:

> Hello list!
> ?
> I?have started teaching Python to a group of High School students. I 
> set them the "Guess the Number" game as a GUI as an assignment. One of 
> the students has passed in some script that is foreign to any tutorial 
> work we have done.? Some of it is below. Does anyone recognise it? Can 
> you tell me where it would have been downloaded from? I have searched 
> for scripted guess the number games, but there are thousands of them - 
> except for a Python version.
> ?
> If my student has plagiarised - I need to know.
> ?
> TIA Diana

	I hate to be the bearer of bad news, but I'm afraid he has: 
http://granite.sru.edu/~conlon/python/tk_guess.py
	This looks awfully similar, down to the use of whrandom instead of 
random. First hit in Google for "guess the number" +python +tkinter.
	Seems like your student is not only guilty of plagiarism, but also in 
violation of the GPL.

Hope that helps,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

From albertito_g at hotmail.com  Sat Apr 30 15:44:02 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Sat Apr 30 15:44:05 2005
Subject: [Tutor] Re: Issue with "Entry"/GUI/PIL
In-Reply-To: <722d5f8f050429152248499972@mail.gmail.com>
Message-ID: <BAY106-F4D8CA2E79E8404A5AF31489250@phx.gbl>

Hey

It's a matter of fancyness (Sorry, I think I invented an English word, :D)

you are asking in the same Entry you want them to answer, so in order to 
answer your question, I'll have to delete the question. Secondly, how can 
you analyze if you don't give the chance to the user to type an answer???? 
You can ask and answer on the same Entry(although is no pretty nice but...), 
but in order to do that you'll have to give the user the oportunity to type 
and a way to tell Python "I finish please correct me!!!" so that's why I 
think you'll have to add a Button like Submit and in the command you can put 
a function that erase the answer and put the message

Regards

Alberto

>From: Brian Wurtzel <gilly775@gmail.com>
>Reply-To: Brian Wurtzel <gilly775@gmail.com>
>To: albertito_g@hotmail.com
>Subject: Re: Issue with "Entry"/GUI/PIL
>Date: Fri, 29 Apr 2005 15:22:56 -0700
>
>So, I cannot use the original entry box? I have to add a second one?
>How come python cannot figure it out in the first entry box, it seems
>so obvious...
>
>= = = Original message = = =
>
>Replace the 0.0 for only 0
>
>But you have a problem. You are inserting the question and that's what the
>if  clause analyze so it will be always wrong you have to add another Entry
>and a submit button so it will analyze the result of the second Entry
>Regards
>
>Alberto
>
> >From: Brian Wurtzel <gilly775@gmail.com>
> >Reply-To: Brian Wurtzel <gilly775@gmail.com>
> >To: tutor@python.org
> >Subject: [Tutor] Issue with "Entry"/GUI/PIL
> >Date: Fri, 29 Apr 2005 09:48:01 -0500
>[Quoted text hidden]><< AL.gif >>
> >_______________________________________________
> >Tutor maillist  -  Tutor@python.org
> >http://mail.python.org/mailman/listinfo/tutor
>
>Gaucho


Gaucho


From servando at mac.com  Sat Apr 30 18:00:08 2005
From: servando at mac.com (Servando Garcia)
Date: Sat Apr 30 18:00:22 2005
Subject: [Tutor] input() : part two
Message-ID: <51ccd71d549b113e41932f82cd2dfa04@mac.com>


Hello everyone
	Thank you for the quick response to my last request. Here is an 
update, the program I am writing takes three values from the user than 
produces the source code for another program.
THE PROBLEM:
	I needed to prompt the user for three values. I used input() like so  
M= input("Matrix=")
The IDE for Macpython works great.  It works to well, it handled the 
GUI interfaces automatically.  By using Macpython a input window was 
created for user input.  User entered code then the source code was 
generated in the output window.  I needed to redirect the output so the 
user could run the new program.  I was unable to redirect the output so 
I decided to use a terminal to run the program like this  Python 
Meta.py > comp.py  By redirecting the output the user could now run the 
program but there was problems.
	My nice input window was gone and only a blank line was present.  When 
I entered the the data the outputted file looked like this
Matrix=error=alpha

I found a work around for the terminal it appears that the message in 
the input("message")  was being assigned to the next variable making
Matrix=error=alpha
  So I created a variable with the input() blank
Matrix= input()
error= input()
alpha= input()
print Matrix
print error
print alpha

When I use the terminal to redirect the output it works fine so the 
user can now run the other program like this
Python meta.py > comp.py
python comp.py

once again thanks to everyone for the ideas. It was the brain storming 
of this group that lead me down the path I took to solve this problem
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 1888 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050430/954c042c/attachment.bin
From alan.gauld at freenet.co.uk  Sat Apr 30 20:50:15 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 30 20:50:29 2005
Subject: [Tutor] guess the number game help
References: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
Message-ID: <017c01c54db5$735448d0$43ce8651@xp>

> If my student has plagiarised - I need to know.

Could you ask him(?) to explain some of the more "interesting"
features?
Maybe how he came up with the variable names? It is possible that
he/she has come up with it themselves since its not really a great
version - a very strange mix of OOP and procedural styles etc.

Or ask how he/she would modify it to some other criteria - in other
words do the actually understand it? If they wrote it they should...
Actually thats quite a good thing to do with all the students!

   def __init__(self, low, high):   #whrandom number is made here
      self.ro = whrandom()

Why ro for instance? - random object presumably, but does the student
know that?

   def number(self):
      return self.num

And why this apparently useless method? Why not just access self.num?


#this part evaluates the users guess
def evaluate_ans(guess_str, whrandom, low_str, high_str, guess_left, \
                 guess_eval_str, yg_label):

And what are all these parameters for? Are there ways they could have
cut down the number?

etc etc...

And if they do understand it and know how to modify it then even if
they did copy it they did the assignment and understood the code.
Software reuse is not necessarily an evil to be stifled...

Just some thoughts.

Alan G.

From maxnoel_fr at yahoo.fr  Sat Apr 30 21:30:43 2005
From: maxnoel_fr at yahoo.fr (Max Noel)
Date: Sat Apr 30 21:30:56 2005
Subject: [Tutor] guess the number game help
In-Reply-To: <017c01c54db5$735448d0$43ce8651@xp>
References: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
	<017c01c54db5$735448d0$43ce8651@xp>
Message-ID: <EE057292-26C4-4C05-B489-707285C932E0@yahoo.fr>


On Apr 30, 2005, at 19:50, Alan Gauld wrote:

>> If my student has plagiarised - I need to know.
>>
>
> Could you ask him(?) to explain some of the more "interesting"
> features?
> Maybe how he came up with the variable names? It is possible that
> he/she has come up with it themselves since its not really a great
> version - a very strange mix of OOP and procedural styles etc.
>
[...]

> And if they do understand it and know how to modify it then even if
> they did copy it they did the assignment and understood the code.
> Software reuse is not necessarily an evil to be stifled...


     Have a look at the link I posted, Alan. Honestly, at that point  
it's not "software reuse" anymore. It's straight lifting of code (and  
removing of comments that would identify the original author). Worse,  
lifting of *bad* code that happened to be the first hit returned by  
Google, which tends to indicate that this particular student,  
assuming his Google-fu is better than his coding skills, spent a  
grand total of five minutes on this assignment.

     However, you still have a point. If I were Diana, I would show  
up at the next lecture expressing great interest toward, and asking  
plenty of questions about, that piece of code. I'd compliment that  
guy for using whrandom instead of random, as it ensures a  
statistically equivalent behavior no matter the platform, and then  
point out that the problem with this is that it prevents the use of  
the program in strong cryptography applications.
     I'd ask him how long he's been programming in Java (over-use of  
getter/setter methods) and in Haskell/Lisp/[functional programming  
language of choice] (lambda functions galore) for. Ask him what he  
thinks of some features of the aforementioned languages (let's say,  
the overuse of the Decorator design pattern in Java, and monads in  
Haskell)...
     ...Then mention that I didn't know he had a Ph. D and that his  
real name was Michael Conlon. Grin evilly, produce a printout of the  
original code, explain to him what "pulling a CherryOS" is and why  
it's stupid, dangerous and illegal.

     Yeah, I guess that's why I'm not a teacher :D

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"

From alan.gauld at freenet.co.uk  Sat Apr 30 22:58:29 2005
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat Apr 30 22:57:57 2005
Subject: [Tutor] guess the number game help
References: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
	<017c01c54db5$735448d0$43ce8651@xp>
	<EE057292-26C4-4C05-B489-707285C932E0@yahoo.fr>
Message-ID: <018101c54dc7$5d49de80$43ce8651@xp>

> > And if they do understand it and know how to modify it then even
if
> > they did copy it they did the assignment and understood the code.
> > Software reuse is not necessarily an evil to be stifled...
>
>
>      Have a look at the link I posted, Alan. Honestly, at that point
> it's not "software reuse" anymore. It's straight lifting of code
(and
> removing of comments that would identify the original author).
Worse,
> lifting of *bad* code that happened to be the first hit returned by
> Google, which tends to indicate that this particular student,

But that was my point. Lifting bad code and stripping comments
suggests he/she didn't understand it. So the questioning should
reveal that. And without going very deep into the depths I suspect.

But if they did take the time to understand how every line worked
after downloading it then it is indeed a passed assignment - finding
code and reusing it is a plus. BUT stripping the authors name is is a
no-no and should be pointed out - it may even be illegal and
prosecutable.

Alan G.

From dianahawks at optusnet.com.au  Sat Apr 30 23:41:30 2005
From: dianahawks at optusnet.com.au (Diana Hawksworth)
Date: Sat Apr 30 23:43:13 2005
Subject: [Tutor] guess the number game help
References: <000801c54d61$d9e8b440$4e08a4cb@dianahawks>
	<017c01c54db5$735448d0$43ce8651@xp>
	<EE057292-26C4-4C05-B489-707285C932E0@yahoo.fr>
	<018101c54dc7$5d49de80$43ce8651@xp>
Message-ID: <000b01c54dcd$5feb0780$29c41dd3@dianahawks>

Thanks Alan and Max for confirming my worst fears - and for supplying the
necessary link, Max. This kid left at the end of term with no clue - and
came back 2 weeks later with this script.  As his paper work doesn't support
the script, and his in-class understanding doesn't indicate the knowledge
shown by the script - then I guess he gets a zero for this!  Too bad.

Thanks for your help, fellows.  Seems we need some more lessons on
plagiarism and lifting code without due recognition!

Diana

----- Original Message ----- 
From: "Alan Gauld" <alan.gauld@freenet.co.uk>
To: "Max Noel" <maxnoel_fr@yahoo.fr>
Cc: "Diana Hawksworth" <dianahawks@optusnet.com.au>; <tutor@python.org>
Sent: Sunday, May 01, 2005 6:58 AM
Subject: Re: [Tutor] guess the number game help


> > > And if they do understand it and know how to modify it then even
> if
> > > they did copy it they did the assignment and understood the code.
> > > Software reuse is not necessarily an evil to be stifled...
> >
> >
> >      Have a look at the link I posted, Alan. Honestly, at that point
> > it's not "software reuse" anymore. It's straight lifting of code
> (and
> > removing of comments that would identify the original author).
> Worse,
> > lifting of *bad* code that happened to be the first hit returned by
> > Google, which tends to indicate that this particular student,
>
> But that was my point. Lifting bad code and stripping comments
> suggests he/she didn't understand it. So the questioning should
> reveal that. And without going very deep into the depths I suspect.
>
> But if they did take the time to understand how every line worked
> after downloading it then it is indeed a passed assignment - finding
> code and reusing it is a plus. BUT stripping the authors name is is a
> no-no and should be pointed out - it may even be illegal and
> prosecutable.
>
> Alan G.
>
>


From klappnase at freenet.de  Thu Apr 28 11:20:40 2005
From: klappnase at freenet.de (Michael Lange)
Date: Thu, 28 Apr 2005 11:20:40 +0200
Subject: [Tutor] Tkinter and Animation
In-Reply-To: <be96a66f050427193140032c6d@mail.gmail.com>
References: <be96a66f050427193140032c6d@mail.gmail.com>
Message-ID: <20050428112040.3eccb831.klappnase@freenet.de>

On Wed, 27 Apr 2005 19:31:06 -0700
Jeremiah Rushton <jeremiah.rushton at gmail.com> wrote:

> 
> I tried your idea and it doesn't animate it. I made a for loop and told it 
> to mover 1 pixel downward every .3 seconds for 25 times. It just waits till 
> the for loop is completed and then displays the result of the loop ending. I 
> also tried it without the for loop by writing each one of the steps out 
> repetively and I had the same result. The only thing that has kind of got 
> close to the visual is that I wrote a program that everytime the user 
> clicked the button it moved down one pixel, but I want it to move 100 
> pixels, one by one, with only one click from the user. Here's the code that 
> I wrote:
> 
> from Tkinter import *
> from time import sleep
> 
> class Main:
> 
> def __init__(self,master):
> button = Button(master,text='button')
> button.place(x=1,y=1)
> y=3
> for x in range(1,25):
> sleep(.3)
> button.place_forget()
> button.place(x=1,y=y)
> y+=2
> 
> 
> root = Tk()
> Main(root)
> root.title('test')
> root.mainloop()
> 
> Thanks for all the help so far.
> 
> Jeremiah
> 

Hi Jeremiah,

you should call update_idletasks() to make the changed geometry visible. I've written a (very quick and dirty)
demo that shows how to animate a Label with place() :

###########################################################

from Tkinter import *

class AnimatedFrame(Frame):
    def __init__(self, master, **kw):
        Frame.__init__(self, master, **kw)
        self.labelx = 100
        self.labely = 100
        self.label = Label(self, text='Look at me!')
        self.label.place(x=self.labelx, y=self.labely)
        self.button = Button(self, text='Start', command=self.start)
        self.button.place(x=100, y=200)
    
    def start(self):
        if self.labelx > 20:
            self.labelx -= 1
            self.labely -= 1
            self.label.place(x=self.labelx, y=self.labely)
            self.update_idletasks()
            self.start()

def test():
    root = Tk()
    f = AnimatedFrame(root, width=300, height=300)
    f.pack()
    root.mainloop()

if __name__ == '__main__':
    test()

#########################################################

I hope this helps

Michael