From dkuhlman at rexx.com  Tue Jan  1 01:02:40 2008
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 31 Dec 2007 16:02:40 -0800
Subject: [Tutor] Mobile Python
In-Reply-To: <d4a3dc80712310912t20ceccd3m94b6b260c161dc92@mail.gmail.com>
References: <d4a3dc80712310912t20ceccd3m94b6b260c161dc92@mail.gmail.com>
Message-ID: <20080101000240.GA34636@cutter.rexx.com>

On Mon, Dec 31, 2007 at 12:12:34PM -0500, Antonio Salgado wrote:
> Hello to everyone and wishing you all the best and succes  in this new
> year!!
> Well i'm wondering if someone can point me out or help on this, I want to
> write apps for mobile devices, but for the regular nokia (like the 5300),
> but i haven't find documentation or anything. Hope someone can help me.
> My best wishes and greeting from Mexico!!

Try doing a Web search for "python s60 pys60".

Among other links, you will find:

    http://wiki.opensource.nokia.com/projects/Python_for_S60
    http://sourceforge.net/projects/pys60/

There is an emulator, so you can test some of your code without
even loading it onto a cell phone device.

This sounds like exciting stuff.  Please keep us informed about
your progress.

- Dave



-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Tue Jan  1 04:41:40 2008
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Tue, 01 Jan 2008 06:41:40 +0300
Subject: [Tutor] Mobile Python
In-Reply-To: <20080101000240.GA34636@cutter.rexx.com>
References: <d4a3dc80712310912t20ceccd3m94b6b260c161dc92@mail.gmail.com>
	<20080101000240.GA34636@cutter.rexx.com>
Message-ID: <1199158900.23027.8.camel@gobuntu>


On Mon, 2007-12-31 at 16:02 -0800, Dave Kuhlman wrote:
> On Mon, Dec 31, 2007 at 12:12:34PM -0500, Antonio Salgado wrote:
> > Hello to everyone and wishing you all the best and succes  in this new
> > year!!
> > Well i'm wondering if someone can point me out or help on this, I want to
> > write apps for mobile devices, but for the regular nokia (like the 5300),
> > but i haven't find documentation or anything. Hope someone can help me.
> > My best wishes and greeting from Mexico!!
> 
> Try doing a Web search for "python s60 pys60".
That won't help Antonio.  Nokia 5300 is *not* an S60/Symbian mobile
device.

> 
> Among other links, you will find:
> 
>     http://wiki.opensource.nokia.com/projects/Python_for_S60
>     http://sourceforge.net/projects/pys60/
> 
> There is an emulator, so you can test some of your code without
> even loading it onto a cell phone device.
> 
> This sounds like exciting stuff.  Please keep us informed about
> your progress.
> 
> - Dave
> 
As for you Antonio, I don't think Python will run on that device.  It's
an S40 device, which is a propriety platform from Nokia.  Nokia
published documentation on how to program it only through "Java ME" and
nothing else!

You either need to contact Nokia directly to obtain the closed API (and
then port Python to it), or use Java ME to interact with your device.

Does anyone know if Jython will help in this situation? (or am I way
off, and Jython is not used like that?!)

Hope that help.
Ziyad.


From garry.willgoose at newcastle.edu.au  Tue Jan  1 06:58:07 2008
From: garry.willgoose at newcastle.edu.au (Garry Willgoose)
Date: Tue, 1 Jan 2008 16:58:07 +1100
Subject: [Tutor] providing a Python command line within a Tkinter appl
Message-ID: <35FC004C-394D-4D02-9E5D-F7C194516B6C@newcastle.edu.au>

I'm writing a platform independent environmental modelling framework  
where I provide a GUI (in Tkinter) to a range of env modeling tools  
in a number of modules written in fortran, C and Python. It all works  
well but for generality I'd like to provide the user with a command  
line where he can do analyses using Python that are not provided by  
the framework's tools (e.g. some one off analysis either using Python  
directly or perhaps linking to another program like R using RPy,  
etc). However, once I kick off Tkinter's event loop I need  to  
provide a window where Python commands are entered and interpreted  
(Think the command line for Matlab or R but with a serious GUI and  
language ... lets not go down the route of why I didn't use these  
packages in the first place). Plan A was that I'd somehow like to use  
the python interpreter for this but I can't find any obvious way to  
do this. Plan B would seem to be to simply provide a text entry  
window and to interpret each line entered by the user using eval and  
providing sensible error messages. So I'd have a loop executed for  
each line entered that looks like

text =my_get_pythoncommand()   	# text is the line of text entered in  
the window by the user
try:
   result=eval(text)
   my_print_pythoncommand_result(result)	# echoing the result of the  
command back to the user
except error1:
   some error message
except error2:
   some other error message
except error3:
   ... etc ...
except:
   some generic error message for unrecognised errors

The question is does this make sense or is there an easier way,  
particularly one where I'd be able to get the same error messages  
provided by the command line python interpreter?

I guess the other question I have is if this the way to go, are there  
any gotchas re the Python code I can execute in this way. Remember I  
am trying to provide a means of doing analyses  that are not provided  
by the framework so it would nice to just say to the user "Enter  
anything that is valid Python ... just like in the Python interpreter  
or IDLE".


====================================================================
Prof Garry Willgoose,
Australian Professorial Fellow in Environmental Engineering,
Director, Centre for Climate Impact Management (C2IM),
School of Engineering, The University of Newcastle,
Callaghan, 2308
Australia.

Centre webpage: www.c2im.org.au

Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574  
(Fri PM-Mon)
FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal  
and Telluric)
Env. Engg. Secretary: (International) +61 2 4921 6042

email:  garry.willgoose at newcastle.edu.au;  
g.willgoose at telluricresearch.com
email-for-life: garry.willgoose at alum.mit.edu
personal webpage: www.telluricresearch.com/garry
====================================================================
"Do not go where the path may lead, go instead where there is no path  
and leave a trail"
                           Ralph Waldo Emerson
====================================================================






From alan.gauld at btinternet.com  Tue Jan  1 10:29:19 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jan 2008 09:29:19 -0000
Subject: [Tutor] providing a Python command line within a Tkinter appl
References: <35FC004C-394D-4D02-9E5D-F7C194516B6C@newcastle.edu.au>
Message-ID: <fld15k$2vv$1@ger.gmane.org>


"Garry Willgoose" <garry.willgoose at newcastle.edu.au> wrote

> packages in the first place). Plan A was that I'd somehow like to 
> use
> the python interpreter for this but I can't find any obvious way to
> do this.

Take a look at the IDLE source cocde. IDLE's interactive shell is
essentially what you want - a python interpreter insode aTkinter 
window...

If you were using wxPyton then the WxPy package has a shell
component that you could have used, but I don't know of any such
component for Tkinter. However it might be possible to re-use
the IDLE code...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From michaelarpsorensen at stevnstrup.dk  Tue Jan  1 13:54:08 2008
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Tue, 1 Jan 2008 13:54:08 +0100
Subject: [Tutor] Learning about callbaks
In-Reply-To: <20071229185826.GA30751@cutter.rexx.com>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
	<20071229185826.GA30751@cutter.rexx.com>
Message-ID: <9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com>

Greetings, my masters.

This is somewhat difficult to transfer to my program with 2 classes/objects.
All examples I've seen is not for more than one instance of a single object.
I use more than one class in my program.

I have a game class and a menu class. When the user chooses "quit" in the
menu, I want the menu object to call a method that executes a quit_program()
from the game class. Obviously, menu is an object within the game object.

class UserInput(CommonBase):
    def __init__(self, queue, game):
        self.loop = 1
        self.queue = queue
        self.game = game

    def main(self):
        while True:
            tstr = raw_input("Input string: ")
            print "Input: ", tstr
            if tstr == "q":
                self.quitProgram()

    def quitProgram(self, game, quit_callback):
        self.loop = 0
        game.loop = 0
        quit_callback()

class Game(CommonBase):
    def __init__(self):
        self.loop = 1
        self.queue = Queue.Queue()

    def startUI(self, tid):
        ui = UserInput(self.queue, self)
        ui.main()

    def stoploop():
        self.loop = 0

    def main(self):
        thread.start_new_thread(self.startUI, (1,))

        while self.loop:
            try:
                data = self.queue.get(block = False)
            except Queue.Empty:
                pass
            else:
                pass
            time.sleep(0.1)

g = Game()
g.main()

It is so frustrating not to see the light. I feel that I'm close to
understanding the general idea. Allthough I might be wrong on that point.
:-)

I'm desperate.

Thanks in advance.

On Dec 29, 2007 7:58 PM, Dave Kuhlman <dkuhlman at rexx.com> wrote:

> Here is a trivial example:
>
>    def f1(x):
>        print 'f1: %s' % x
>
>    def f2(x):
>        print 'f2: %s' % x
>
>    def use_them(funcs):
>        for func in funcs:
>            func('abcd')
>
>    def test():
>        funcs = [f1, f2]
>        use_them(funcs)
>
>    test()
>


-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080101/8e70a924/attachment.htm 

From alan.gauld at btinternet.com  Tue Jan  1 15:17:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jan 2008 14:17:17 -0000
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com><20071229185826.GA30751@cutter.rexx.com>
	<9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com>
Message-ID: <fldi1j$6uk$1@ger.gmane.org>


"Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I have a game class and a menu class. When the user chooses
> "quit" in the menu, I want the menu object to call a method that
> executes a quit_program() from the game class.

self.game.quit_program()

should do it.

Except in your code bekow you don't define a quit_program method
in the Game class.

> Obviously, menu is an object within the game object.

Not obviously, but it's certainly an option. You could have
kept menu as a separate object if that made more sense
to you. But having a menu contained by Game is also fine.

> -----------------
class UserInput(CommonBase):
    def __init__(self, queue, game):
        self.loop = 1
        self.queue = queue
        self.game = game

    def main(self):
        while True:
            tstr = raw_input("Input string: ")
            print "Input: ", tstr
            if tstr == "q":
                self.quitProgram()

    def quitProgram(self, game, quit_callback):
        self.loop = 0
        game.loop = 0
        quit_callback()

> ---------------------------

I'm not sure I really understand what this class is modelling.
What kind of an object is UserInput?
Does it represent a single command or is it representing an
action - getting input from the user? In which case its a
very abstract kind of object.

If this (as I think) is the "menu" that you refer to above
then I'd expect it to be responsible for displaying a menu
and obtaing a selection, it could then dispatch a message
to the associated operatrion (a callback).

However this class has a queue and game parameter that
are assigned to local attribiutes but then never used...

The main() method displays the prompt and then
calls the quit method with no arguments.

The quit method tries to use a call back function but the
call back is never passed to it.

In fact in this case you don't even need a callback
since the UserInput object has an attribute pointing
at the game object so you can call game methods
directly.

I'm also not sure what the threading stuff is needed
for either. Try to simplify the example by cutting out
all the redundant stuff and not using callbacks
initially, just call the game methods via the game
attribute.

Then once it works modify it to use callback style.

Also, in the code below you are using loop as a boolean
so it would be better to assign True/False rather than 1/0
as values.


> ----------------
class Game(CommonBase):
    def __init__(self):
        self.loop = 1
        self.queue = Queue.Queue()

    def startUI(self, tid):
        ui = UserInput(self.queue, self)
        ui.main()

    def stoploop():
        self.loop = 0

    def main(self):
        thread.start_new_thread(self.startUI, (1,))

        while self.loop:
            try:
                data = self.queue.get(block = False)
            except Queue.Empty:
                pass
            else:
                pass
            time.sleep(0.1)

g = Game()
g.main()

> Allthough I might be wrong on that point.
> I'm desperate.

I think you need to strip back and simplify, it looks like
you may have been reading too many different resources
and incorporated some ieas without really undertansding
what they do and why.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From dineshbvadhia at hotmail.com  Tue Jan  1 17:18:40 2008
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Tue, 1 Jan 2008 08:18:40 -0800
Subject: [Tutor] Displaying images on a web page
Message-ID: <BAY109-DAV18FF50F9F1AFA53558753A3510@phx.gbl>

I want to display a fixed number of same-size (jpeg) images on a web page.  The images displayed will change on user input.

I can use PIL to write the code but has anyone come across open source code that already does this?  Thank-you

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080101/3c9899ab/attachment.htm 

From alan.gauld at btinternet.com  Tue Jan  1 17:48:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Jan 2008 16:48:59 -0000
Subject: [Tutor] Displaying images on a web page
References: <BAY109-DAV18FF50F9F1AFA53558753A3510@phx.gbl>
Message-ID: <fldqtq$sb6$1@ger.gmane.org>

"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote 

> I want to display a fixed number of same-size (jpeg) images 
> on a web page.  The images displayed will change on user input.

Can you be more specific?
Do you mean they should change dynamically in the browser 
or that they will change after a form submission?

In other words is the change done as part of a refresh of the 
page or dynamically within the browser? If its the latter there 
are several JavaScript recipes for doing this usually involving 
caching a set of images and selecting the appropriate one 
in response to user events.

If you mean as part of a server page refresh then normal CGI 
techniques will work. Again if you have a list of images you 
can select the appropriate one.

> I can use PIL to write the code but has anyone come across 
> open source code that already does this?  

I'm not sure where PIIL comes in? Normally PIL would be used 
to create the images before displaying them. What part of the 
problem are you haveing difficulty with - creating the images? 
(maybe dynamically?) or displaying a different image to the user?

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From mlangford.cs03 at gtalumni.org  Tue Jan  1 18:39:26 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Tue, 1 Jan 2008 12:39:26 -0500
Subject: [Tutor] Displaying images on a web page
In-Reply-To: <BAY109-DAV18FF50F9F1AFA53558753A3510@phx.gbl>
References: <BAY109-DAV18FF50F9F1AFA53558753A3510@phx.gbl>
Message-ID: <82b4f5810801010939t77f62237h37ff63b5a8934174@mail.gmail.com>

On Jan 1, 2008 11:18 AM, Dinesh B Vadhia <dineshbvadhia at hotmail.com> wrote:

>  I want to display a fixed number of same-size (jpeg) images on a web
> page.  The images displayed will change on user input.
>
>
I can use PIL to write the code but has anyone come across open source code
> that already does this?  Thank-you
>

You only need PIL if you're creating the pictures with the python code. If
you're merely choosing which pictures to display based on the input, you
merely need to generate different HTML (or have a javascript page, and
return different XML from your python backend).

If you're really trying to avoid writing your own HTML out, the table
example from GWT(
http://gwt.google.com/samples/KitchenSink/KitchenSink.html#Panels) will do
what you're looking for. Pyjamas(http://code.google.com/p/pyjamas/)  will
generate GWT code from python for you.

        --Michael

-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080101/3b5d3c6e/attachment.htm 

From michaelarpsorensen at stevnstrup.dk  Wed Jan  2 12:48:11 2008
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Wed, 2 Jan 2008 12:48:11 +0100
Subject: [Tutor] Learning about callbaks
In-Reply-To: <fldi1j$6uk$1@ger.gmane.org>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
	<20071229185826.GA30751@cutter.rexx.com>
	<9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com>
	<fldi1j$6uk$1@ger.gmane.org>
Message-ID: <9b1867560801020348x5cb0d253t2d6ef0e344f53f1b@mail.gmail.com>

Greetings, my master.

I think you need to strip back and simplify, it looks like
> you may have been reading too many different resources
> and incorporated some ideas without really understanding
> what they do and why.


I'm humbled by your insight. This is absolutely true.

I did some research, reading and test last night and I finally got it
working. There was a missing bit that I needed to understand, and suddenly I
saw the light. :-) In a manner of speaking. I wrote this piece of code:

class UserInput:
    def __init__(self):
        pass
    def test_callback(self, this_callback):
        print "testing the callback"
        this_callback

class Game:
    def __init__(self):
        self.ui = UserInput()
    def hello(self):
        print "hello world"
    def useUI(self):
        self.ui.test_callback(self.hello())

g = Game()
g.useUI()

I wanted to understand how a "parent" object could send a callback to a
"child" object, and now I got it.

Feel free to comment on this, please.

Thank you for your patience, Alan.

-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/04cc89fd/attachment.htm 

From alan.gauld at btinternet.com  Wed Jan  2 14:25:28 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Jan 2008 13:25:28 -0000
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com><20071229185826.GA30751@cutter.rexx.com><9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com><fldi1j$6uk$1@ger.gmane.org>
	<9b1867560801020348x5cb0d253t2d6ef0e344f53f1b@mail.gmail.com>
Message-ID: <flg38f$fqf$1@ger.gmane.org>

"Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I did some research, reading and test last night and I finally got 
> it
> working.

Sorry, but you didn't! However you are very nearly there...

class UserInput:
    def __init__(self):
        pass
    def test_callback(self, this_callback):
        print "testing the callback"
        this_callback

To actually use the callback you need to use parens:

this_callback()

But this won't work because of the problem below...

class Game:
    def __init__(self):
        self.ui = UserInput()
    def hello(self):
        print "hello world"
    def useUI(self):
        self.ui.test_callback(self.hello())

Here you do not pass the function object to your test_callback 
function,
you actually call it here! You bneed to pass the function as an object
then call it in the receiver

self.ui.test_callback(self, self.hello)   # no parens means treat as 
object

What you have done is executed the function(which prints the message
thus leading you to think it has worked) and passes the return 
vaklue(None)
to your test_callback. But since you never actually call the function 
there
(missing parens) there is no error message.

You can prove this by inserting a raw_input statement into
your test_callback before you use the callback. That way the
message should only appear after you hit return...

> I wanted to understand how a "parent" object could send a callback
> to a "child" object, and now I got it.

Nearly. You apply the parens when you want to execute the function
you omit parens when you want to treat the function as an object.
You need to swap your use of parens.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From michaelarpsorensen at stevnstrup.dk  Wed Jan  2 15:06:33 2008
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Wed, 2 Jan 2008 15:06:33 +0100
Subject: [Tutor] Learning about callbaks
In-Reply-To: <flg38f$fqf$1@ger.gmane.org>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
	<20071229185826.GA30751@cutter.rexx.com>
	<9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com>
	<fldi1j$6uk$1@ger.gmane.org>
	<9b1867560801020348x5cb0d253t2d6ef0e344f53f1b@mail.gmail.com>
	<flg38f$fqf$1@ger.gmane.org>
Message-ID: <9b1867560801020606q25999756y5348bb2a1426a56e@mail.gmail.com>

Hi again.

On Jan 2, 2008 2:25 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> > I did some research, reading and test last night and I finally got
> > it
> > working.
>
> Sorry, but you didn't! However you are very nearly there...
>

Darn. :-(

I've read what to wrote about the *parentheses*. I see why I was wrong in my
premature assumption. but I fail to understand why it did work.

Anyway, I removed the parentheses from the game method and added it in the
userinput method. It still works. Do I dare say that I'm "there" now? :-)

Thanks a lot for this test of my humility and for your effort.

-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/02ae04a0/attachment.htm 

From roychenlei at gmail.com  Wed Jan  2 15:08:10 2008
From: roychenlei at gmail.com (Roy Chen)
Date: Wed, 2 Jan 2008 23:08:10 +0900
Subject: [Tutor] Choice of GUI builders
Message-ID: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>

Hello all,

I've been using PythonCard to build a GUI for a simple program I'm trying to
write. It's simple and easy to use, and rather intuitive.

However, it seems that it hasn't been updated in some time, and so I would
like a recommendation for a cross-platform (preferably) GUI builder. I'm
leaning towards wxPython so far (it's had a recent release just a month or
so ago), but if anyone has any suggestions, that'd be great.

Thanks in advance,
Roy Chen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/811ea144/attachment.htm 

From nephish at gmail.com  Wed Jan  2 15:25:36 2008
From: nephish at gmail.com (shawn bright)
Date: Wed, 2 Jan 2008 08:25:36 -0600
Subject: [Tutor] need a way to get my own ip address
Message-ID: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>

Greetings,

i am looking for an easy way to get my own ip address as a string from
python.
I am using Ubuntu Linux if that makes any difference.
thanks !

shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/8fded829/attachment.htm 

From titleistfour at gmail.com  Wed Jan  2 15:31:39 2008
From: titleistfour at gmail.com (jay)
Date: Wed, 2 Jan 2008 08:31:39 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
Message-ID: <7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>

You could perhaps use this method

import socket
myIP = socket.gethostbyaddr(socket.gethostname())[2]

Jay

On Jan 2, 2008 8:25 AM, shawn bright <nephish at gmail.com> wrote:

> Greetings,
>
> i am looking for an easy way to get my own ip address as a string from
> python.
> I am using Ubuntu Linux if that makes any difference.
> thanks !
>
> shawn
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/be652078/attachment.htm 

From nephish at gmail.com  Wed Jan  2 15:45:28 2008
From: nephish at gmail.com (shawn bright)
Date: Wed, 2 Jan 2008 08:45:28 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
	<7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
Message-ID: <384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>

Thanks, Jay,
in IDLE, this gave me 127.0.0.1
is there a way to get my assigned ip instead of the localhost one?
thanks

On Jan 2, 2008 8:31 AM, jay <titleistfour at gmail.com> wrote:

> You could perhaps use this method
>
> import socket
> myIP = socket.gethostbyaddr(socket.gethostname())[2]
>
> Jay
>
> On Jan 2, 2008 8:25 AM, shawn bright < nephish at gmail.com> wrote:
>
> > Greetings,
> >
> > i am looking for an easy way to get my own ip address as a string from
> > python.
> > I am using Ubuntu Linux if that makes any difference.
> > thanks !
> >
> > shawn
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/ce4e272f/attachment-0001.htm 

From titleistfour at gmail.com  Wed Jan  2 15:50:56 2008
From: titleistfour at gmail.com (jay)
Date: Wed, 2 Jan 2008 08:50:56 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
	<7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
	<384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>
Message-ID: <7c25bb490801020650m5c15bc9fkfbadcef2ecf5ae83@mail.gmail.com>

Well that will return the reverse lookup of the current hostname assigned to
your system.  Is this a Windows or Linux/Unix system?  What does this
return?

print socket.gethostname()
print socket.gethostbyaddr(socket.gethostname())

j

On Jan 2, 2008 8:45 AM, shawn bright <nephish at gmail.com> wrote:

> Thanks, Jay,
> in IDLE, this gave me 127.0.0.1
> is there a way to get my assigned ip instead of the localhost one?
> thanks
>
>
> On Jan 2, 2008 8:31 AM, jay < titleistfour at gmail.com> wrote:
>
> > You could perhaps use this method
> >
> > import socket
> > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> >
> > Jay
> >
> > On Jan 2, 2008 8:25 AM, shawn bright < nephish at gmail.com> wrote:
> >
> > > Greetings,
> > >
> > > i am looking for an easy way to get my own ip address as a string from
> > > python.
> > > I am using Ubuntu Linux if that makes any difference.
> > > thanks !
> > >
> > > shawn
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/9b57b7e9/attachment.htm 

From mlangford.cs03 at gtalumni.org  Wed Jan  2 15:56:54 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 2 Jan 2008 09:56:54 -0500
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
Message-ID: <82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>

While some people are Adobe haters("They hate the web...etc"), I think
a slick alternative available now is Flex2 calling python via XMLRPC.

I've been doing so lately. It is fast to pick up and makes slick
looking GUI's rather quickly. It has a cheap GUI builder that actually
works if you don't feel like just typing out MXML files. You can use
Apollo to do desktop apps and just Flex to do web apps, and all the
controls are the same. (The difference is a build setting and a change
to a couple tags, and voila, desktop app is on the web or vice versa).

Bruce Eckel (the thinking in Java Guy) has written an article on this
Approach: http://www.artima.com/weblogs/viewpost.jsp?thread=208528

The ActionScript module I'm currently using for XMLRPC:
http://code.google.com/p/as3python-xmlrpc-lib/

You don't really need to know any ActionScript to do this. Very little
is required to marshal data in and out of the controls. Other then
that, everything is python!

Flex is open source now, so you even have that going for you. And it's
actively maintained (and updated) by Adobe. The install on a client
computer is easier than with wxPython as the GUI toolkit, and I've
done several wxPython apps that needed installers. The python back end
to all this is SimpleXMLRPCServer, which is also, very easy to use.
Exceptions even work well (a big surprise for me). And the fact this
approach is cross platform, for "platform" being defined as Windows,
Linux, Mac, Firefox, IE6, IE7 and Opera, makes this a great choice for
a easy UI toolkit.

         --Michael

On Jan 2, 2008 9:08 AM, Roy Chen <roychenlei at gmail.com> wrote:
> Hello all,
>
> I've been using PythonCard to build a GUI for a simple program I'm trying to write. It's simple and easy to use, and rather intuitive.
>
> However, it seems that it hasn't been updated in some time, and so I would like a recommendation for a cross-platform (preferably) GUI builder. I'm leaning towards wxPython so far (it's had a recent release just a month or so ago), but if anyone has any suggestions, that'd be great.
>
> Thanks in advance,
> Roy Chen
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From nephish at gmail.com  Wed Jan  2 16:00:13 2008
From: nephish at gmail.com (shawn bright)
Date: Wed, 2 Jan 2008 09:00:13 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <7c25bb490801020650m5c15bc9fkfbadcef2ecf5ae83@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
	<7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
	<384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>
	<7c25bb490801020650m5c15bc9fkfbadcef2ecf5ae83@mail.gmail.com>
Message-ID: <384c93600801020700p1bdcd03dt9d0e4ff7b29026@mail.gmail.com>

It returns this
('hostname', [], ['127.0.1.1'])
i am running this on a linux system
thanks

On Jan 2, 2008 8:50 AM, jay <titleistfour at gmail.com> wrote:

> Well that will return the reverse lookup of the current hostname assigned
> to your system.  Is this a Windows or Linux/Unix system?  What does this
> return?
>
> print socket.gethostname()
> print socket.gethostbyaddr(socket.gethostname ())
>
> j
>
>
> On Jan 2, 2008 8:45 AM, shawn bright <nephish at gmail.com> wrote:
>
> > Thanks, Jay,
> > in IDLE, this gave me 127.0.0.1
> > is there a way to get my assigned ip instead of the localhost one?
> > thanks
> >
> >
> > On Jan 2, 2008 8:31 AM, jay < titleistfour at gmail.com> wrote:
> >
> > > You could perhaps use this method
> > >
> > > import socket
> > > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> > >
> > > Jay
> > >
> > > On Jan 2, 2008 8:25 AM, shawn bright < nephish at gmail.com> wrote:
> > >
> > > > Greetings,
> > > >
> > > > i am looking for an easy way to get my own ip address as a string
> > > > from python.
> > > > I am using Ubuntu Linux if that makes any difference.
> > > > thanks !
> > > >
> > > > shawn
> > > >
> > > > _______________________________________________
> > > > Tutor maillist  -  Tutor at python.org
> > > > http://mail.python.org/mailman/listinfo/tutor
> > > >
> > > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/4f42a9b0/attachment.htm 

From titleistfour at gmail.com  Wed Jan  2 16:10:46 2008
From: titleistfour at gmail.com (jay)
Date: Wed, 2 Jan 2008 09:10:46 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <384c93600801020700p1bdcd03dt9d0e4ff7b29026@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
	<7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
	<384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>
	<7c25bb490801020650m5c15bc9fkfbadcef2ecf5ae83@mail.gmail.com>
	<384c93600801020700p1bdcd03dt9d0e4ff7b29026@mail.gmail.com>
Message-ID: <7c25bb490801020710w2fb95c09oe980e892162b159@mail.gmail.com>

Well that is what I normally use, but I always have my hostname setup
properly.  In your case, that socket call won't work.  You could try this
link I found on google

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094

jay

On Jan 2, 2008 9:00 AM, shawn bright <nephish at gmail.com> wrote:

> It returns this
> ('hostname', [], ['127.0.1.1'])
> i am running this on a linux system
> thanks
>
>
> On Jan 2, 2008 8:50 AM, jay < titleistfour at gmail.com> wrote:
>
> > Well that will return the reverse lookup of the current hostname
> > assigned to your system.  Is this a Windows or Linux/Unix system?  What does
> > this return?
> >
> > print socket.gethostname()
> > print socket.gethostbyaddr(socket.gethostname ())
> >
> > j
> >
> >
> > On Jan 2, 2008 8:45 AM, shawn bright <nephish at gmail.com > wrote:
> >
> > > Thanks, Jay,
> > > in IDLE, this gave me 127.0.0.1
> > > is there a way to get my assigned ip instead of the localhost one?
> > > thanks
> > >
> > >
> > > On Jan 2, 2008 8:31 AM, jay < titleistfour at gmail.com> wrote:
> > >
> > > > You could perhaps use this method
> > > >
> > > > import socket
> > > > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> > > >
> > > > Jay
> > > >
> > > > On Jan 2, 2008 8:25 AM, shawn bright < nephish at gmail.com> wrote:
> > > >
> > > > > Greetings,
> > > > >
> > > > > i am looking for an easy way to get my own ip address as a string
> > > > > from python.
> > > > > I am using Ubuntu Linux if that makes any difference.
> > > > > thanks !
> > > > >
> > > > > shawn
> > > > >
> > > > > _______________________________________________
> > > > > Tutor maillist  -  Tutor at python.org
> > > > > http://mail.python.org/mailman/listinfo/tutor
> > > > >
> > > > >
> > > >
> > > > _______________________________________________
> > > > Tutor maillist  -  Tutor at python.org
> > > > http://mail.python.org/mailman/listinfo/tutor
> > > >
> > > >
> > >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/4a1ec2ed/attachment.htm 

From nephish at gmail.com  Wed Jan  2 16:26:04 2008
From: nephish at gmail.com (shawn bright)
Date: Wed, 2 Jan 2008 09:26:04 -0600
Subject: [Tutor] need a way to get my own ip address
In-Reply-To: <7c25bb490801020710w2fb95c09oe980e892162b159@mail.gmail.com>
References: <384c93600801020625y6eac124dg838bfbfefd468863@mail.gmail.com>
	<7c25bb490801020631j68a6bf56k889a477b6aa2bb9@mail.gmail.com>
	<384c93600801020645v1e1defa1lbdd307f689c4dbc8@mail.gmail.com>
	<7c25bb490801020650m5c15bc9fkfbadcef2ecf5ae83@mail.gmail.com>
	<384c93600801020700p1bdcd03dt9d0e4ff7b29026@mail.gmail.com>
	<7c25bb490801020710w2fb95c09oe980e892162b159@mail.gmail.com>
Message-ID: <384c93600801020726w16875b8u5073953bd3f307d8@mail.gmail.com>

Thanks, Jay,
just what i was looking for. Works great.

shawn

On Jan 2, 2008 9:10 AM, jay <titleistfour at gmail.com> wrote:

> Well that is what I normally use, but I always have my hostname setup
> properly.  In your case, that socket call won't work.  You could try this
> link I found on google
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094
>
> jay
>
>
> On Jan 2, 2008 9:00 AM, shawn bright <nephish at gmail.com> wrote:
>
> > It returns this
> > ('hostname', [], [' 127.0.1.1'])
> > i am running this on a linux system
> > thanks
> >
> >
> > On Jan 2, 2008 8:50 AM, jay < titleistfour at gmail.com> wrote:
> >
> > > Well that will return the reverse lookup of the current hostname
> > > assigned to your system.  Is this a Windows or Linux/Unix system?  What does
> > > this return?
> > >
> > > print socket.gethostname()
> > > print socket.gethostbyaddr(socket.gethostname ())
> > >
> > > j
> > >
> > >
> > > On Jan 2, 2008 8:45 AM, shawn bright <nephish at gmail.com > wrote:
> > >
> > > > Thanks, Jay,
> > > > in IDLE, this gave me 127.0.0.1
> > > > is there a way to get my assigned ip instead of the localhost one?
> > > > thanks
> > > >
> > > >
> > > > On Jan 2, 2008 8:31 AM, jay < titleistfour at gmail.com> wrote:
> > > >
> > > > > You could perhaps use this method
> > > > >
> > > > > import socket
> > > > > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> > > > >
> > > > > Jay
> > > > >
> > > > > On Jan 2, 2008 8:25 AM, shawn bright < nephish at gmail.com> wrote:
> > > > >
> > > > > > Greetings,
> > > > > >
> > > > > > i am looking for an easy way to get my own ip address as a
> > > > > > string from python.
> > > > > > I am using Ubuntu Linux if that makes any difference.
> > > > > > thanks !
> > > > > >
> > > > > > shawn
> > > > > >
> > > > > > _______________________________________________
> > > > > > Tutor maillist  -  Tutor at python.org
> > > > > > http://mail.python.org/mailman/listinfo/tutor
> > > > > >
> > > > > >
> > > > >
> > > > > _______________________________________________
> > > > > Tutor maillist  -  Tutor at python.org
> > > > > http://mail.python.org/mailman/listinfo/tutor
> > > > >
> > > > >
> > > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/b825c40a/attachment-0001.htm 

From jfabiani at yolo.com  Wed Jan  2 18:15:36 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 2 Jan 2008 09:15:36 -0800
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
Message-ID: <200801020915.36492.jfabiani@yolo.com>

On Wednesday 02 January 2008 06:08:10 am Roy Chen wrote:
> Hello all,
>
> I've been using PythonCard to build a GUI for a simple program I'm trying
> to write. It's simple and easy to use, and rather intuitive.
>
> However, it seems that it hasn't been updated in some time, and so I would
> like a recommendation for a cross-platform (preferably) GUI builder. I'm
> leaning towards wxPython so far (it's had a recent release just a month or
> so ago), but if anyone has any suggestions, that'd be great.
>
> Thanks in advance,
> Roy Chen

Take a look at Dabo 
www.dabodev.com

and check the screencasts

-- 
John Fabiani

From alan.gauld at btinternet.com  Wed Jan  2 18:36:43 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Jan 2008 17:36:43 -0000
Subject: [Tutor] Learning about callbaks
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com><20071229185826.GA30751@cutter.rexx.com><9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com><fldi1j$6uk$1@ger.gmane.org><9b1867560801020348x5cb0d253t2d6ef0e344f53f1b@mail.gmail.com><flg38f$fqf$1@ger.gmane.org>
	<9b1867560801020606q25999756y5348bb2a1426a56e@mail.gmail.com>
Message-ID: <flghvh$2rh$1@ger.gmane.org>


"Michael Bernhard Arp S?rensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I've read what to wrote about the *parentheses*. I see why I was 
> wrong in my
> premature assumption. but I fail to understand why it did work.

I suspect that if you look closely you'll find that the "testing" 
print statement
came after the "hello world" rather than before it.

    def test_callback(self, this_callback):
        print "testing the callback"
        this_callback

> Anyway, I removed the parentheses from the game method and added it 
> in the
> userinput method. It still works. Do I dare say that I'm "there" 
> now? :-)

I hope so, and it should now display the "testing" message before
the "hello" message. As to whether you are "there" yet that really 
depends
on whether you are comfortable that you understand the concept 
clearly.

Can you modify the program *without modifying the classes* to use an
ordinary function as the callback? Say this goodbye function:

def goodbye():
     print "goodbye world"

This should not require more than 5 lines of new code and no changes 
to the
existing code. It could be done in 3...

If you succeed then I'll be happy that you've grasped it.

Alan G. 



From alan.gauld at btinternet.com  Wed Jan  2 18:41:46 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 2 Jan 2008 17:41:46 -0000
Subject: [Tutor] Choice of GUI builders
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com>
Message-ID: <flgi91$3pt$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote

> On Wednesday 02 January 2008 06:08:10 am Roy Chen wrote:
>> Hello all,
>>
>> I've been using PythonCard ...
>> However, it seems that it hasn't been updated in some time, and so 
>> I would
>> like a recommendation for a cross-platform (preferably) GUI 
>> builder.

I tried to fined a decent GUI builder for wxPython but failed.
There are two or three available but none of them really worked
all that well. SPE seemed the best of a poor bunch.

However...

> Take a look at Dabo
> www.dabodev.com

This looked promising but doesn't use the standard wxPython
widget set (this was also why I didn't choose PythonCard!), you have
to learn the Dabo API. But coming from PythonCard you would
have to learn the wxPython API anyway so that may not be an
issue for you.

Alan G.




From jfabiani at yolo.com  Wed Jan  2 18:51:19 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 2 Jan 2008 09:51:19 -0800
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>
Message-ID: <200801020951.19370.jfabiani@yolo.com>

On Wednesday 02 January 2008 06:56:54 am Michael Langford wrote:
> While some people are Adobe haters("They hate the web...etc"), I think
> a slick alternative available now is Flex2 calling python via XMLRPC.
>
> I've been doing so lately. It is fast to pick up and makes slick
> looking GUI's rather quickly. It has a cheap GUI builder that actually
> works if you don't feel like just typing out MXML files. You can use
> Apollo to do desktop apps and just Flex to do web apps, and all the
> controls are the same. (The difference is a build setting and a change
> to a couple tags, and voila, desktop app is on the web or vice versa).
>
> Bruce Eckel (the thinking in Java Guy) has written an article on this
> Approach: http://www.artima.com/weblogs/viewpost.jsp?thread=208528
>
> The ActionScript module I'm currently using for XMLRPC:
> http://code.google.com/p/as3python-xmlrpc-lib/
>
> You don't really need to know any ActionScript to do this. Very little
> is required to marshal data in and out of the controls. Other then
> that, everything is python!
>
> Flex is open source now, so you even have that going for you. And it's
> actively maintained (and updated) by Adobe. The install on a client
> computer is easier than with wxPython as the GUI toolkit, and I've
> done several wxPython apps that needed installers. The python back end
> to all this is SimpleXMLRPCServer, which is also, very easy to use.
> Exceptions even work well (a big surprise for me). And the fact this
> approach is cross platform, for "platform" being defined as Windows,
> Linux, Mac, Firefox, IE6, IE7 and Opera, makes this a great choice for
> a easy UI toolkit.
>
>          --Michael
I have been very interested in the Flex solution. Mostly because it supports 
both desktops and the web. I use Dabo for my UI solution and found it covers 
most everything I need at the moment.   But I have real concerns regarding 
data access using Flex.

Flex is asynchronous and most desktop data app's are synchronous when it comes 
to accessing data.  All I have been doing is reading about Flex so maybe 
there is a solution I am not aware of.  It sounds like you are working with 
Flex - is there a solution?

-- 
John Fabiani

From jfabiani at yolo.com  Wed Jan  2 18:58:09 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 2 Jan 2008 09:58:09 -0800
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <flgi91$3pt$1@ger.gmane.org>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com> <flgi91$3pt$1@ger.gmane.org>
Message-ID: <200801020958.09551.jfabiani@yolo.com>

On Wednesday 02 January 2008 09:41:46 am Alan Gauld wrote:

> I tried to fined a decent GUI builder for wxPython but failed.
> There are two or three available but none of them really worked
> all that well. SPE seemed the best of a poor bunch.
>
> However...
>
> > Take a look at Dabo
> > www.dabodev.com
>
> This looked promising but doesn't use the standard wxPython
> widget set (this was also why I didn't choose PythonCard!), you have
> to learn the Dabo API. But coming from PythonCard you would
> have to learn the wxPython API anyway so that may not be an
> issue for you.
>
> Alan G.

Dabo does use slightly different names (in most cases) but is nothing more 
than subclasses of the wxPython.  And of course Dabo does nothing to prevent 
the programmer from using wxPython directly.  

The work is learning how to use the subclasses with all of the added 
properties and attributes.



-- 
John Fabiani

From mlangford.cs03 at gtalumni.org  Wed Jan  2 19:16:14 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 2 Jan 2008 13:16:14 -0500
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <200801020951.19370.jfabiani@yolo.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>
	<200801020951.19370.jfabiani@yolo.com>
Message-ID: <82b4f5810801021016r26d65be6raf61d737dc5de8ac@mail.gmail.com>

When running local, the flex/xmlrpc solution is just as responsive as
a traditional GUI app in my experience with regards to data loading,
etc. The network/python latency isn't especially noticeable when
running the GUI local to the flex UI.

I didn't really get caught up on a difference between the async/sync
nature of the GUI, then again I come from a background (electronics
and embedded software) where asynchronous communications is more
common than for normal software development. If you have a concern
beyond latency, I'll need an example as to what you're worried about.
I don't think I understand your concern enough to address it. Are you
worried about reliability? Error checking? What in particular?

Perhaps you could cut and paste a bit of code you've already written
that you think would be complicated by the Async?

        --Michael

On Jan 2, 2008 12:51 PM, johnf <jfabiani at yolo.com> wrote:
>
> On Wednesday 02 January 2008 06:56:54 am Michael Langford wrote:
> > While some people are Adobe haters("They hate the web...etc"), I think
> > a slick alternative available now is Flex2 calling python via XMLRPC.
> >
> > I've been doing so lately. It is fast to pick up and makes slick
> > looking GUI's rather quickly. It has a cheap GUI builder that actually
> > works if you don't feel like just typing out MXML files. You can use
> > Apollo to do desktop apps and just Flex to do web apps, and all the
> > controls are the same. (The difference is a build setting and a change
> > to a couple tags, and voila, desktop app is on the web or vice versa).
> >
> > Bruce Eckel (the thinking in Java Guy) has written an article on this
> > Approach: http://www.artima.com/weblogs/viewpost.jsp?thread=208528
> >
> > The ActionScript module I'm currently using for XMLRPC:
> > http://code.google.com/p/as3python-xmlrpc-lib/
> >
> > You don't really need to know any ActionScript to do this. Very little
> > is required to marshal data in and out of the controls. Other then
> > that, everything is python!
> >
> > Flex is open source now, so you even have that going for you. And it's
> > actively maintained (and updated) by Adobe. The install on a client
> > computer is easier than with wxPython as the GUI toolkit, and I've
> > done several wxPython apps that needed installers. The python back end
> > to all this is SimpleXMLRPCServer, which is also, very easy to use.
> > Exceptions even work well (a big surprise for me). And the fact this
> > approach is cross platform, for "platform" being defined as Windows,
> > Linux, Mac, Firefox, IE6, IE7 and Opera, makes this a great choice for
> > a easy UI toolkit.
> >
> >          --Michael
> I have been very interested in the Flex solution. Mostly because it supports
> both desktops and the web. I use Dabo for my UI solution and found it covers
> most everything I need at the moment.   But I have real concerns regarding
> data access using Flex.
>
> Flex is asynchronous and most desktop data app's are synchronous when it comes
> to accessing data.  All I have been doing is reading about Flex so maybe
> there is a solution I am not aware of.  It sounds like you are working with
> Flex - is there a solution?
>
> --
> John Fabiani
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From keridee at jayco.net  Wed Jan  2 20:35:38 2008
From: keridee at jayco.net (Tiger12506)
Date: Wed, 2 Jan 2008 14:35:38 -0500
Subject: [Tutor] providing a Python command line within a Tkinter appl
References: <35FC004C-394D-4D02-9E5D-F7C194516B6C@newcastle.edu.au>
Message-ID: <008601c84d76$aaf17650$c7fce004@jslaptop>

eval will seriously limit you in this instance because eval only works on 
expressions, not statements. (Assignment won't work, for example). You can 
use exec though. (in which case, you wouldn't necessarily want a result 
back)

just fyi

> text =my_get_pythoncommand()   # text is the line of text entered in
> the window by the user
> try:
>   result=eval(text)
>   my_print_pythoncommand_result(result) # echoing the result of the
> command back to the user
> except error1:
>   some error message
> except error2:
>   some other error message
> except error3:
>   ... etc ...
> except:
>   some generic error message for unrecognised errors
>
> The question is does this make sense or is there an easier way,
> particularly one where I'd be able to get the same error messages
> provided by the command line python interpreter?
>
> I guess the other question I have is if this the way to go, are there
> any gotchas re the Python code I can execute in this way. Remember I
> am trying to provide a means of doing analyses  that are not provided
> by the framework so it would nice to just say to the user "Enter
> anything that is valid Python ... just like in the Python interpreter
> or IDLE".
>
>
> ====================================================================
> Prof Garry Willgoose,
> Australian Professorial Fellow in Environmental Engineering,
> Director, Centre for Climate Impact Management (C2IM),
> School of Engineering, The University of Newcastle,
> Callaghan, 2308
> Australia.
>
> Centre webpage: www.c2im.org.au
>
> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574
> (Fri PM-Mon)
> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal
> and Telluric)
> Env. Engg. Secretary: (International) +61 2 4921 6042
>
> email:  garry.willgoose at newcastle.edu.au;
> g.willgoose at telluricresearch.com
> email-for-life: garry.willgoose at alum.mit.edu
> personal webpage: www.telluricresearch.com/garry
> ====================================================================
> "Do not go where the path may lead, go instead where there is no path
> and leave a trail"
>                           Ralph Waldo Emerson
> ====================================================================
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From michaelarpsorensen at stevnstrup.dk  Wed Jan  2 21:19:23 2008
From: michaelarpsorensen at stevnstrup.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=)
Date: Wed, 2 Jan 2008 21:19:23 +0100
Subject: [Tutor] Learning about callbaks
In-Reply-To: <flghvh$2rh$1@ger.gmane.org>
References: <9b1867560712290758u6c041279s79c7c60972196dc3@mail.gmail.com>
	<20071229185826.GA30751@cutter.rexx.com>
	<9b1867560801010454h3d2ad8fbm90187a1ebc26f1cc@mail.gmail.com>
	<fldi1j$6uk$1@ger.gmane.org>
	<9b1867560801020348x5cb0d253t2d6ef0e344f53f1b@mail.gmail.com>
	<flg38f$fqf$1@ger.gmane.org>
	<9b1867560801020606q25999756y5348bb2a1426a56e@mail.gmail.com>
	<flghvh$2rh$1@ger.gmane.org>
Message-ID: <9b1867560801021219q1986b755pc2e7f43c7dd58d85@mail.gmail.com>

Hi.

On Jan 2, 2008 6:36 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> Can you modify the program *without modifying the classes* to use an
> ordinary function as the callback? Say this goodbye function:
>
> def goodbye():
>     print "goodbye world"
>
> This should not require more than 5 lines of new code and no changes
> to the
> existing code. It could be done in 3...
>

Like this?:

class UserInput:
    def __init__(self):
        pass

    def test_callback(self, this_callback):
        print "testing the callback"
        this_callback()

class Game:
    def __init__(self):
        self.ui = UserInput()

    def hello(self):
        print "hello world"

    def useUI(self):
        self.ui.test_callback(self.hello)

def goodbye():
    print "goodbye world"

g = Game()
g.useUI()
g.ui.test_callback(goodbye)

It took me a couple of minutes to understand your challenge. :-) Then I
remembered that "ui" is instantiated inside "g" and therefore callable with
the right parameter.

Thank you very, very much. I enjoy a good challenge.

-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/be4ba0aa/attachment-0001.htm 

From alan.gauld at btinternet.com  Wed Jan  2 23:11:37 2008
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 2 Jan 2008 22:11:37 +0000 (GMT)
Subject: [Tutor] Learning about callbaks
Message-ID: <646238.7518.qm@web86702.mail.ird.yahoo.com>

Yes, exactly like that. 
Well done, you are now callback aware :-)

Alan G.

----- Original Message ----
From: Michael Bernhard Arp S?rensen <michaelarpsorensen at stevnstrup.dk>
To: Alan Gauld <alan.gauld at btinternet.com>
Cc: tutor at python.org
Sent: Wednesday, 2 January, 2008 8:19:23 PM
Subject: Re: [Tutor] Learning about callbaks

Hi.

On Jan 2, 2008 6:36 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

Can you modify the program *without modifying the classes* to use an
ordinary function as the callback? Say this goodbye function:

def goodbye():
     print "goodbye world"

This should not require more than 5 lines of new code and no changes

to the
existing code. It could be done in 3...


Like this?:

class UserInput:

    def __init__(self):
        pass


    def test_callback(self, this_callback):
        print "testing the callback"

        this_callback()


class Game:
    def __init__(self):

        self.ui = UserInput()


    def hello(self):
        print "hello world"


    def useUI(self):
        self.ui.test_callback(self.hello)


def goodbye():

    print "goodbye world"

g = Game()

g.useUI()
g.ui.test_callback(goodbye)


It took me a couple of minutes to understand your challenge. :-) Then I remembered that "ui" is instantiated inside "g" and therefore callable with the right parameter.

Thank you very, very much. I enjoy a good challenge.


-- 
Med venlig hilsen/Kind regards

Michael B. Arp S?rensen
Programm?r / BOFH
I am /root and if you see me laughing you better have a backup.



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/df62db45/attachment.htm 

From roychenlei at gmail.com  Thu Jan  3 04:28:39 2008
From: roychenlei at gmail.com (Roy Chen)
Date: Thu, 3 Jan 2008 12:28:39 +0900
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<82b4f5810801020656t3f568118pf22bb4e8db43add9@mail.gmail.com>
Message-ID: <51740970801021928ub3cf760q692fba7538c7a158@mail.gmail.com>

Thanks, that certainly looks interesting and I'll give it a try. Perhaps
it's a little too much work for what I have in mind, but definitely
something useful to learn in the long run.

Best regards,
Roy

On Jan 2, 2008 11:56 PM, Michael Langford <mlangford.cs03 at gtalumni.org>
wrote:

> While some people are Adobe haters("They hate the web...etc"), I think
> a slick alternative available now is Flex2 calling python via XMLRPC.
>
> I've been doing so lately. It is fast to pick up and makes slick
> looking GUI's rather quickly. It has a cheap GUI builder that actually
> works if you don't feel like just typing out MXML files. You can use
> Apollo to do desktop apps and just Flex to do web apps, and all the
> controls are the same. (The difference is a build setting and a change
> to a couple tags, and voila, desktop app is on the web or vice versa).
>
> Bruce Eckel (the thinking in Java Guy) has written an article on this
> Approach: http://www.artima.com/weblogs/viewpost.jsp?thread=208528
>
> The ActionScript module I'm currently using for XMLRPC:
> http://code.google.com/p/as3python-xmlrpc-lib/
>
> You don't really need to know any ActionScript to do this. Very little
> is required to marshal data in and out of the controls. Other then
> that, everything is python!
>
> Flex is open source now, so you even have that going for you. And it's
> actively maintained (and updated) by Adobe. The install on a client
> computer is easier than with wxPython as the GUI toolkit, and I've
> done several wxPython apps that needed installers. The python back end
> to all this is SimpleXMLRPCServer, which is also, very easy to use.
> Exceptions even work well (a big surprise for me). And the fact this
> approach is cross platform, for "platform" being defined as Windows,
> Linux, Mac, Firefox, IE6, IE7 and Opera, makes this a great choice for
> a easy UI toolkit.
>
>         --Michael
>
> On Jan 2, 2008 9:08 AM, Roy Chen <roychenlei at gmail.com> wrote:
> > Hello all,
> >
> > I've been using PythonCard to build a GUI for a simple program I'm
> trying to write. It's simple and easy to use, and rather intuitive.
> >
> > However, it seems that it hasn't been updated in some time, and so I
> would like a recommendation for a cross-platform (preferably) GUI builder.
> I'm leaning towards wxPython so far (it's had a recent release just a month
> or so ago), but if anyone has any suggestions, that'd be great.
> >
> > Thanks in advance,
> > Roy Chen
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/524166dd/attachment.htm 

From roychenlei at gmail.com  Thu Jan  3 04:31:00 2008
From: roychenlei at gmail.com (Roy Chen)
Date: Thu, 3 Jan 2008 12:31:00 +0900
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <200801020958.09551.jfabiani@yolo.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com> <flgi91$3pt$1@ger.gmane.org>
	<200801020958.09551.jfabiani@yolo.com>
Message-ID: <51740970801021931o62836f37va472610f331a566d@mail.gmail.com>

Thanks for all the help, Dabo looks interesting, but perhaps a bit overkill
right now for what I have in mind. Certainly something useful to learn in
the long run, though.

I suppose with any GUI toolkit/builder, you're going to have learn some part
of the API anyway. I might just see how I go with wxPython for now.

Best regards,
Roy

On Jan 3, 2008 2:58 AM, johnf <jfabiani at yolo.com> wrote:

> On Wednesday 02 January 2008 09:41:46 am Alan Gauld wrote:
>
> > I tried to fined a decent GUI builder for wxPython but failed.
> > There are two or three available but none of them really worked
> > all that well. SPE seemed the best of a poor bunch.
> >
> > However...
> >
> > > Take a look at Dabo
> > > www.dabodev.com
> >
> > This looked promising but doesn't use the standard wxPython
> > widget set (this was also why I didn't choose PythonCard!), you have
> > to learn the Dabo API. But coming from PythonCard you would
> > have to learn the wxPython API anyway so that may not be an
> > issue for you.
> >
> > Alan G.
>
> Dabo does use slightly different names (in most cases) but is nothing more
> than subclasses of the wxPython.  And of course Dabo does nothing to
> prevent
> the programmer from using wxPython directly.
>
> The work is learning how to use the subclasses with all of the added
> properties and attributes.
>
>
>
> --
> John Fabiani
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/00b905cd/attachment.htm 

From jfabiani at yolo.com  Thu Jan  3 06:14:09 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 2 Jan 2008 21:14:09 -0800
Subject: [Tutor] is it legal to have a class within a def
Message-ID: <200801022114.09174.jfabiani@yolo.com>

def someMethod():
   class MyClass(object):
       .....
  if something:
     .....
     return someval
	
-- 
John Fabiani

From bgailer at alum.rpi.edu  Thu Jan  3 06:31:19 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 03 Jan 2008 00:31:19 -0500
Subject: [Tutor] is it legal to have a class within a def
In-Reply-To: <200801022114.09174.jfabiani@yolo.com>
References: <200801022114.09174.jfabiani@yolo.com>
Message-ID: <477C7327.2080700@alum.rpi.edu>

johnf wrote:
> def someMethod():
>    class MyClass(object):
>        .....
>   if something:
>      .....
>      return someval
> 	
>   
Legal? Well the police won't come after you!

Python allows a class statement anywhere. So this use is part of the 
language.

So the question becomes "why would you want to do that?"

Considerations:

1 - this usage creates a local object MyClass. The object will not be 
visible outside the function. The class definition is executed each time 
the function is called.

2 - the object could be returned or assigned to a global or added to a 
parameter that is a collection.

3 - if no instances are created in the function the object will 
disappear once the function execution ends.


From agoldgod at gmail.com  Thu Jan  3 07:45:40 2008
From: agoldgod at gmail.com (goldgod a)
Date: Thu, 3 Jan 2008 12:15:40 +0530
Subject: [Tutor] How to convert ogg to MP3
Message-ID: <105c9ccc0801022245p3c52fa98s94d56f5900087b70@mail.gmail.com>

hi,
    I would like to convert ogg files to mp3 files. how can I do that.
Is there any inbuilt package.

-- 
Thanks & Regards,
goldgod

From jfabiani at yolo.com  Thu Jan  3 07:28:49 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 2 Jan 2008 22:28:49 -0800
Subject: [Tutor] is it legal to have a class within a def
In-Reply-To: <477C7327.2080700@alum.rpi.edu>
References: <200801022114.09174.jfabiani@yolo.com>
	<477C7327.2080700@alum.rpi.edu>
Message-ID: <200801022228.49602.jfabiani@yolo.com>

On Wednesday 02 January 2008 09:31:19 pm you wrote:
> johnf wrote:
> > def someMethod():
> >    class MyClass(object):
> >        .....
> >   if something:
> >      .....
> >      return someval
>
> Legal? Well the police won't come after you!
>
That's a good thing!
> Python allows a class statement anywhere. So this use is part of the
> language.
>
> So the question becomes "why would you want to do that?"
>
> Considerations:
>
> 1 - this usage creates a local object MyClass. The object will not be
> visible outside the function. The class definition is executed each time
> the function is called.
>
> 2 - the object could be returned or assigned to a global or added to a
> parameter that is a collection.
>
> 3 - if no instances are created in the function the object will
> disappear once the function execution ends.

1 and 3 are my reasons.  I'm creating a Dabo app.  When I attempted to create 
a special class that contained a dialog box I discovered that the dialog 
class created an indepentant type of window and allowed my program to 
continue running without waiting for the dialog to return a value first.  
However, I noticed if I created the dialog within a function my program 
stopped and waited until the dialog was closed to continue.   I think that I 
could define the Classes outside of the function and just import them when 
needed.  But then I wanted a self contained function so I asked why not place 
the class code in the function?  What is the difference?

-- 
John Fabiani

From alan.gauld at btinternet.com  Thu Jan  3 09:11:05 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 08:11:05 -0000
Subject: [Tutor] Choice of GUI builders
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com><200801020915.36492.jfabiani@yolo.com>
	<flgi91$3pt$1@ger.gmane.org><200801020958.09551.jfabiani@yolo.com>
	<51740970801021931o62836f37va472610f331a566d@mail.gmail.com>
Message-ID: <fli570$g19$1@ger.gmane.org>


"Roy Chen" <roychenlei at gmail.com> wrote

> I suppose with any GUI toolkit/builder, you're going to have learn 
> some part
> of the API anyway. I might just see how I go with wxPython for now.

OK, wxPython is a fine toolkt. Just be aware that it does not have a 
GUI
builder per se, you have to write the GUI as source code or use a 
third
party GUI builder.

Alan G. 



From alan.gauld at btinternet.com  Thu Jan  3 09:15:41 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 08:15:41 -0000
Subject: [Tutor] is it legal to have a class within a def
References: <200801022114.09174.jfabiani@yolo.com>
Message-ID: <fli5fk$gmr$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote 

> def someMethod():
>   class MyClass(object):
>       .....
>  if something:
>     .....
>     return someval


Did you try it?

>>> def f():
...   class C: pass
...   return C
...
>>> def g(x):
...   class C: pass
...   if x == 42:
...     return C
...   else: return 666
...
>>> c = f()
>>> c
<class __main__.C at 0x7ff1bbfc>
>>>

It works for me...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Thu Jan  3 09:18:36 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 08:18:36 -0000
Subject: [Tutor] is it legal to have a class within a def
References: <200801022114.09174.jfabiani@yolo.com>
	<477C7327.2080700@alum.rpi.edu>
Message-ID: <fli5l3$h4d$1@ger.gmane.org>


"bob gailer" <bgailer at alum.rpi.edu> wrote

> So the question becomes "why would you want to do that?"

The main reason I could think of was to create a factory 
method for dynamically creating classes based on input 
parameters - for example currency convertors or similar.
Equally you could change method implementations 
by passing lambdas etc.

Useful in certain other languages but much less so in 
Python which allows dynamic changes to classes/objects 
after creation anyway.

Alan G.


From alan.gauld at btinternet.com  Thu Jan  3 09:24:10 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 08:24:10 -0000
Subject: [Tutor] How to convert ogg to MP3
References: <105c9ccc0801022245p3c52fa98s94d56f5900087b70@mail.gmail.com>
Message-ID: <fli5vh$hut$1@ger.gmane.org>


"goldgod a" <agoldgod at gmail.com> wrote in

>    I would like to convert ogg files to mp3 files. how can I do 
> that.
> Is there any inbuilt package.

I think Lame can do that.
You would need to access Lame via its command line (using the
subprocess module?) or maybe someone has a python library
to use the lame library/DLL directly.

Try googling "python lame" - I'm too lazy :-)

Alan G 



From alan.gauld at btinternet.com  Thu Jan  3 09:22:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 08:22:25 -0000
Subject: [Tutor] is it legal to have a class within a def
References: <200801022114.09174.jfabiani@yolo.com><477C7327.2080700@alum.rpi.edu>
	<200801022228.49602.jfabiani@yolo.com>
Message-ID: <fli5s8$hno$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote

> 1 and 3 are my reasons.  I'm creating a Dabo app.  When I attempted 
> to create
> a special class that contained a dialog box I discovered that the 
> dialog
> class created an indepentant type of window and allowed my program 
> to
> continue running without waiting for the dialog to return a value 
> first.

Are you sure you made it a modal dialog?
Any dialog will do that if it is opened modelessly, you need to
use the modal version to make it block the app.

Putting the class code in a functiion is legal but very inefficient
and also prevents you from storing state etc in the dialog - you
would need to reinitialise all valuues on each use. Thats OK if
its simple but a lot of work(and slow)  if its complex.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From hokkakada at khmeros.info  Thu Jan  3 22:04:48 2008
From: hokkakada at khmeros.info (Kakada)
Date: Fri, 4 Jan 2008 04:04:48 +0700
Subject: [Tutor] open email client from Help menu
Message-ID: <200801040404.48980.hokkakada@khmeros.info>

Hi every one,

In my program, I want to have "Report Bug..." under Help menu. So, whenever 
user clicks on it, it will open an email client for reporting bugs with the 
given address. How can I do this? 

I set text to actionReportBug like this:
<a href='mailto:wordforge2-devel at lists.sourceforge.net'>Report Bug...</a>
but it doesn't support html tag.

Any method?

dada

From marc.tompkins at gmail.com  Thu Jan  3 11:11:03 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 3 Jan 2008 02:11:03 -0800
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <fli570$g19$1@ger.gmane.org>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com> <flgi91$3pt$1@ger.gmane.org>
	<200801020958.09551.jfabiani@yolo.com>
	<51740970801021931o62836f37va472610f331a566d@mail.gmail.com>
	<fli570$g19$1@ger.gmane.org>
Message-ID: <40af687b0801030211o7467f24dqa8ebbeba2e684a1a@mail.gmail.com>

I'm using wxPython, after very brief forays into Tk and Qt, and I like it a
lot. wx generally wraps the native widgets of whatever OS/desktop it runs
on, and its idiom felt more comfortable to me than the others.  Also, unlike
Qt, it's free... I hate to be a cheapskate, but I'm a very small business
and I need to put food on my family, so the Qt license is a major hurdle.

<rant>
I have to say, though, that as a recovering Visual Studio user there is one
thing - believe me, it's the only thing! - I miss, and that's an
honest-to-goodness WYSIWYG GUI designer.  For the love of Pete, if Microsoft
can get it right - and it's the only thing they did get right, IMHO - why
can't we?  Why can't you just draw your GUI on the screen and concentrate on
the actual functionality in peace?

In the wx world, I tried both PythonCard and wxGlade.  PythonCard might be
OK, but I didn't like it a bit; its stated goal is to be a re-creation of
HyperCard, and I was never a fan.  Also, I tried it just as I was first
getting started with Python, and it sorta felt at odds with the gestalt of
the language.  I'm probably not being fair to it.  Ah well.

wxGlade wants to re-create the joys of working with Glade, but I've never
used Glade. If it's anything like wxGlade, I'm glad to have missed out.
wxGlade does some very nifty, sophisticated and impressive GUI work to
create, for your delectation, a representation of your GUI that looks
virtually nothing like the finished product.  Looking at the display
mid-process, you can neither see what the finished product will look like,
nor what the code will look like.  Along the way, there's a hierarchical
organizer thingy that in theory should help you to put widgets inside of the
frames, panels and sizers that contain them, but in my experience actually
tends to put them at the same hierarchical level and refuses to let you fix
any mistakes you might make.  I've tried it four or five times - every time
I get tired of wxCoding by hand - and each time I realize it's going to be
easier to do it by hand.

It's not really that hard, by the way.  Draw yourself a picture ahead of
time - on paper, or (as I do) with hyphens and pipe characters in the
comments - so you can keep straight which sizers go inside of which.  Then,
build from the inside out.  And when you get weary - and oh, you will get
weary - indulge in just a little nostalgie de la bue.

</rant>


On Jan 3, 2008 12:11 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> "Roy Chen" <roychenlei at gmail.com> wrote
>
> > I suppose with any GUI toolkit/builder, you're going to have learn
> > some part
> > of the API anyway. I might just see how I go with wxPython for now.
>
> OK, wxPython is a fine toolkt. Just be aware that it does not have a
> GUI
> builder per se, you have to write the GUI as source code or use a
> third
> party GUI builder.
>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/d109ad53/attachment.htm 

From tiagosaboga at terra.com.br  Thu Jan  3 13:06:01 2008
From: tiagosaboga at terra.com.br (Tiago Saboga)
Date: Thu, 3 Jan 2008 10:06:01 -0200
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <40af687b0801030211o7467f24dqa8ebbeba2e684a1a@mail.gmail.com>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com> <flgi91$3pt$1@ger.gmane.org>
	<200801020958.09551.jfabiani@yolo.com>
	<51740970801021931o62836f37va472610f331a566d@mail.gmail.com>
	<fli570$g19$1@ger.gmane.org>
	<40af687b0801030211o7467f24dqa8ebbeba2e684a1a@mail.gmail.com>
Message-ID: <20080103120601.GC7837@localdomain>

On Thu, Jan 03, 2008 at 02:11:03AM -0800, Marc Tompkins wrote:
> on, and its idiom felt more comfortable to me than the others.  Also, unlike
> Qt, it's free... I hate to be a cheapskate, but I'm a very small business
> and I need to put food on my family, so the Qt license is a major hurdle.

But since 2005, according to wikipedia, the Qt Windows is also
licensed under the GPL. Am I missing something?

> <rant>
> I have to say, though, that as a recovering Visual Studio user there is one
> thing - believe me, it's the only thing! - I miss, and that's an
> honest-to-goodness WYSIWYG GUI designer.  For the love of Pete, if Microsoft
> can get it right - and it's the only thing they did get right, IMHO - why
> can't we?  Why can't you just draw your GUI on the screen and concentrate on
> the actual functionality in peace?

It's why I finally started using Qt. In fact I do not really like
WYSIWYG designers - I always remember html produced by Dreamweaver and
co. - but qtdesigner + pyuic (see pyqt) always gave me readable code. 

Tiago Saboga.

From janos.juhasz at VELUX.com  Thu Jan  3 14:06:17 2008
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 3 Jan 2008 14:06:17 +0100
Subject: [Tutor] How to convert ogg to MP3
In-Reply-To: <mailman.67.1199358017.24438.tutor@python.org>
Message-ID: <OF87B2CBF8.6BD57549-ONC12573C5.0046DDAF-C12573C5.0047FC9A@velux.com>

> "goldgod a" <agoldgod at gmail.com> wrote in

> >    I would like to convert ogg files to mp3 files. how can I do
> > that.
> > Is there any inbuilt package.
> 
> I think Lame can do that.
> You would need to access Lame via its command line (using the
> subprocess module?) or maybe someone has a python library
> to use the lame library/DLL directly.

Pymedia promises to do that. (http://pymedia.org/)
There is a sample script about it called recode_audio.py,
but it chrashed my python interpreter on xp, when I tried to convert from 
ogg to mp3.


Best Regards,
Janos
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/632297b4/attachment.htm 

From cappy2112 at gmail.com  Thu Jan  3 16:40:51 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Thu, 3 Jan 2008 07:40:51 -0800
Subject: [Tutor] Choice of GUI builders
Message-ID: <8249c4ac0801030740o63ff0c66s98b9cfee9b6d02f3@mail.gmail.com>

Message: 1
Date: Thu, 3 Jan 2008 08:11:05 -0000
From: "Alan Gauld" <alan.gauld at btinternet.com>
Subject: Re: [Tutor] Choice of GUI builders
To: tutor at python.org
Message-ID: <fli570$g19$1 at ger.gmane.org>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
       reply-type=original


>>OK, wxPython is a fine toolkt. Just be aware that it does not have a GUI
>>builder per se, you have to write the GUI as source code or use a
>>third party GUI builder.


The Add-Ons & Demos for wxPython come with Xrced, which is a GUI
builder for wx, but is not the GUI builder we all think of (VB,
Delphi, C++ Builder, etc)
There are a handlfull of GUI builders for wx, all with varying degrees
of pain & pleasure.
wxDesigner,wxFormBuilder, BoaConstructor, Pythoncard are all builders
for wx, but not all support Python code generation.

I agree with Marc Tompkins" <marc.tompkins at gmail.com> comments and
like wx more than other GUI frameworks.
It's a shame that someone with adequate resources doesn't come up with
a nice commercial WYSIWIG builder for wx, in the same light as Visual
Basic, Delphi, or C++ Builder, (but with Python code generation &
event handler management.)

BTW- There is a list dedicated for wxPython users & development that
is extremely help for questions related to wx.

From kent37 at tds.net  Thu Jan  3 16:54:18 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Jan 2008 10:54:18 -0500
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <8249c4ac0801030740o63ff0c66s98b9cfee9b6d02f3@mail.gmail.com>
References: <8249c4ac0801030740o63ff0c66s98b9cfee9b6d02f3@mail.gmail.com>
Message-ID: <477D052A.5030503@tds.net>

Tony Cappellini wrote:

>>> OK, wxPython is a fine toolkt. Just be aware that it does not have a GUI
>>> builder per se, you have to write the GUI as source code or use a
>>> third party GUI builder.

> It's a shame that someone with adequate resources doesn't come up with
> a nice commercial WYSIWIG builder for wx, in the same light as Visual
> Basic, Delphi, or C++ Builder, (but with Python code generation &
> event handler management.)

I'm surprised no one else has chimed in for Dabo yet ;-)
Dabo has a UI designer and it is intended specifically for refugees from 
Visual FoxPro and VB. Dabo is kind of marginal as far as 'adequate 
resources' though; the docs are sorely lacking. Most of the 
documentation is in the screencasts AFAICT. Those who invest the effort 
to figure it out (not me, not yet) seem to like it, though.
http://dabodev.com/

Kent

From jfabiani at yolo.com  Thu Jan  3 17:45:10 2008
From: jfabiani at yolo.com (johnf)
Date: Thu, 3 Jan 2008 08:45:10 -0800
Subject: [Tutor] is it legal to have a class within a def
In-Reply-To: <fli5s8$hno$1@ger.gmane.org>
References: <200801022114.09174.jfabiani@yolo.com>
	<200801022228.49602.jfabiani@yolo.com> <fli5s8$hno$1@ger.gmane.org>
Message-ID: <200801030845.10874.jfabiani@yolo.com>

On Thursday 03 January 2008 12:22:25 am Alan Gauld wrote:
> Are you sure you made it a modal dialog?
> Any dialog will do that if it is opened modelessly, you need to
> use the modal version to make it block the app.

Yes.  I believe the way I have coded the dialog causes a bug.  If I create a 
static dialog and use showModal() it works as expected.
>
> Putting the class code in a functiion is legal but very inefficient
> and also prevents you from storing state etc in the dialog - you
> would need to reinitialise all valuues on each use. Thats OK if
> its simple but a lot of work(and slow) ?if its complex.

I am creating a function that does a lookup of PK or FK fields.  If the user 
does type in the correct identifier then the dialog does not appear and is 
not created.  If the user types in a partial of the key then the dialog 
appears and the user picks from the list.  The details of the dialog are 
dynamic for each call (based on some meta data) of the showModal(). 

So I started thinking why would I need the class outside of the function.  If 
I instead used "import class" would I get a performance improvement?  The 
function creates an instance each time it is required and then releases and 
closes.  

I am very interested in this possible difference between importing the class 
vs using the inline class.  Any thoughts as what the difference is will help 
me understand Python a little better.

-- 
John Fabiani

From alan.gauld at btinternet.com  Thu Jan  3 19:08:05 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 18:08:05 -0000
Subject: [Tutor] Choice of GUI builders
References: <8249c4ac0801030740o63ff0c66s98b9cfee9b6d02f3@mail.gmail.com>
	<477D052A.5030503@tds.net>
Message-ID: <flj86c$6ed$1@ger.gmane.org>

"Kent Johnson" <kent37 at tds.net> wrote 

> I'm surprised no one else has chimed in for Dabo yet ;-)

You missed it!
John F already did the Dabo recommendation.
The downside is that it comes with its own variety of 
widget set on top of wxPython

But, it does look good and if I was starting from 
scratch I might give it a spin.

Alan G.


From alan.gauld at btinternet.com  Thu Jan  3 19:13:18 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 18:13:18 -0000
Subject: [Tutor] is it legal to have a class within a def
References: <200801022114.09174.jfabiani@yolo.com><200801022228.49602.jfabiani@yolo.com>
	<fli5s8$hno$1@ger.gmane.org> <200801030845.10874.jfabiani@yolo.com>
Message-ID: <flj8g6$7ms$1@ger.gmane.org>

"johnf" <jfabiani at yolo.com> wrote

> ....  If the user types in a partial of the key then the dialog
> appears and the user picks from the list.  The details of the dialog 
> are
> dynamic for each call (based on some meta data) of the showModal().

This might be a valid case for defining the class in the function 
since
it could be that the number of fields, the labels etc change depending
on the input values. That is exactly the kind of place where a local 
class
makes sense.

> I am very interested in this possible difference between importing 
> the class
> vs using the inline class.  Any thoughts as what the difference is 
> will help
> me understand Python a little better.

There is no great secret, its just that by putting the class 
definition
into the function you have to execute the definition each time you
execute the function. If you put the class in a module and import
it then the class definition is executed at import time and thats it.

But if you need to change the definition each time you instantiate the
dialog you will have a very complex init method so you might find
it easier to redefine the class each time instead.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Thu Jan  3 19:16:01 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 18:16:01 -0000
Subject: [Tutor] open email client from Help menu
References: <200801040404.48980.hokkakada@khmeros.info>
Message-ID: <flj8l9$889$1@ger.gmane.org>


"Kakada" <hokkakada at khmeros.info> wrote

> In my program, I want to have "Report Bug..." under Help menu. So, 
> whenever
> user clicks on it, it will open an email client for reporting bugs 
> with the
> given address. How can I do this?

Which OS?
Which GUI toolkit?
Which email client?

You might be easier to write a dialog to capture the subject and 
message
text and use the Python email module to send the mail directly.


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From marc.tompkins at gmail.com  Thu Jan  3 19:21:09 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 3 Jan 2008 10:21:09 -0800
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <20080103120601.GC7837@localdomain>
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com>
	<200801020915.36492.jfabiani@yolo.com> <flgi91$3pt$1@ger.gmane.org>
	<200801020958.09551.jfabiani@yolo.com>
	<51740970801021931o62836f37va472610f331a566d@mail.gmail.com>
	<fli570$g19$1@ger.gmane.org>
	<40af687b0801030211o7467f24dqa8ebbeba2e684a1a@mail.gmail.com>
	<20080103120601.GC7837@localdomain>
Message-ID: <40af687b0801031021y77d02e65s2a8d723ff93f6fd1@mail.gmail.com>

On Jan 3, 2008 4:06 AM, Tiago Saboga <tiagosaboga at terra.com.br> wrote:

> But since 2005, according to wikipedia, the Qt Windows is also
> licensed under the GPL. Am I missing something?
>
>From the Trolltech website:

> *Qt Open Source Edition* is provided under the GNU General Public License
> version 2.0 (GPL). You may use the Qt Open Source Edition for:
>
>    - Development of open source/non-proprietary software that is also
>    released under the GPL license.
>    - Compiling and running GPL software developed by others.
>
> If you are writing commercial/proprietary software, or if you plan to
> commercialize the software you are writing with Qt, you must use a
> commercial version of Qt. Please refer to the Open Source Downloads<http://trolltech.com/developer/downloads/qt/faq>info page for reasons why.
>
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/768830fd/attachment-0001.htm 

From jfabiani at yolo.com  Thu Jan  3 19:23:46 2008
From: jfabiani at yolo.com (johnf)
Date: Thu, 3 Jan 2008 10:23:46 -0800
Subject: [Tutor] is it legal to have a class within a def
In-Reply-To: <flj8g6$7ms$1@ger.gmane.org>
References: <200801022114.09174.jfabiani@yolo.com>
	<200801030845.10874.jfabiani@yolo.com> <flj8g6$7ms$1@ger.gmane.org>
Message-ID: <200801031023.46138.jfabiani@yolo.com>

On Thursday 03 January 2008 10:13:18 am Alan Gauld wrote:
> "johnf" <jfabiani at yolo.com> wrote
>
> > ....  If the user types in a partial of the key then the dialog
> > appears and the user picks from the list.  The details of the dialog
> > are
> > dynamic for each call (based on some meta data) of the showModal().
>
> This might be a valid case for defining the class in the function
> since
> it could be that the number of fields, the labels etc change depending
> on the input values. That is exactly the kind of place where a local
> class
> makes sense.
>
> > I am very interested in this possible difference between importing
> > the class
> > vs using the inline class.  Any thoughts as what the difference is
> > will help
> > me understand Python a little better.
>
> There is no great secret, its just that by putting the class
> definition
> into the function you have to execute the definition each time you
> execute the function. If you put the class in a module and import
> it then the class definition is executed at import time and thats it.
>
> But if you need to change the definition each time you instantiate the
> dialog you will have a very complex init method so you might find
> it easier to redefine the class each time instead.

Thanks for the response.  Having only a short period using python under my 
belt I find your type of help reassuring.

-- 
John Fabiani

From alan.gauld at btinternet.com  Thu Jan  3 19:28:04 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 3 Jan 2008 18:28:04 -0000
Subject: [Tutor] Choice of GUI builders
References: <51740970801020608t71e1782clec000ce1ab8bccd9@mail.gmail.com><200801020915.36492.jfabiani@yolo.com>
	<flgi91$3pt$1@ger.gmane.org><200801020958.09551.jfabiani@yolo.com><51740970801021931o62836f37va472610f331a566d@mail.gmail.com><fli570$g19$1@ger.gmane.org>
	<40af687b0801030211o7467f24dqa8ebbeba2e684a1a@mail.gmail.com>
Message-ID: <flj9br$aqi$1@ger.gmane.org>

"Marc Tompkins" <marc.tompkins at gmail.com> wrote

> on, and its idiom felt more comfortable to me than the others. 
> Also, unlike
> Qt, it's free... I hate to be a cheapskate, but I'm a very small 
> business
> and I need to put food on my family, so the Qt license is a major 
> hurdle.

Umm, so do the folks at TrollTech :-)

But I believe there are Free versions available for non-commercial use 
now.
But if you are putting food on your table then you also need to put
some on TrollTech's...

> I have to say, though, that as a recovering Visual Studio user there 
> is one
> thing - believe me, it's the only thing! - I miss, and that's an
> honest-to-goodness WYSIWYG GUI designer.

The Visual Studio one is not bad but it's taken Microsoft 15 years of
continuous development to get there. The early Visual C++ GUI Builder
(or Resource editor as it was then) was not much better than Glade.
It wasn't till VC v6 (after 7 years?) that they managed a decent GUI 
builder
and it was still poor at handling resize events etc.

And of course it only works for Windows...

If it takes MS that long charging money for the work its not that
surprising that OpenSource is taking longer to produce a good
product that works for all platforms..

> Why can't you just draw your GUI on the screen and concentrate on
> the actual functionality in peace?

Coz its hard! Especially taking into the platform variations and
the tricks needed to handle resizing etc. It requires a lot of
introspection of the widgets and dynamic drawing of the GUI.
Remember its not just gif files that you are placing on the designer
its real widgets on a real UI...

> In the wx world, I tried both PythonCard and wxGlade.

I agree with you about both...

> It's not really that hard, by the way.  Draw yourself a picture 
> ahead of
> time - on paper, or (as I do) with hyphens and pipe characters in 
> the
> comments - so you can keep straight which sizers go inside of which. 
> Then,
> build from the inside out.  And when you get weary - and oh, you 
> will get
> weary - indulge in just a little nostalgie de la bue.

And this. I use Delphi for all my heavy duty UI work and call a Python
server for the heavy processing. Thankfully I don;t do much heavy UI 
work!

Alan G. 



From cappy2112 at gmail.com  Thu Jan  3 19:31:43 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Thu, 3 Jan 2008 10:31:43 -0800
Subject: [Tutor] Tutor Digest, Vol 47, Issue 8
In-Reply-To: <mailman.404.1199384474.894.tutor@python.org>
References: <mailman.404.1199384474.894.tutor@python.org>
Message-ID: <8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>

Message: 1
Date: Thu, 3 Jan 2008 10:06:01 -0200
From: Tiago Saboga <tiagosaboga at terra.com.br>
Subject: Re: [Tutor] Choice of GUI builders
To: tutor at python.org
Message-ID: <20080103120601.GC7837 at localdomain>
Content-Type: text/plain; charset=us-ascii

>>But since 2005, according to wikipedia, the Qt Windows is also
>>licensed under the GPL. Am I missing something?
There is a GPL version of QT, I believe it came into being for QT 3.x

>>t's why I finally started using Qt. In fact I do not really like
>>WYSIWYG designers -
There is a free designer for QT/PyQT as well. I started with qt/Pyqt
but have moved to wx since then.

Putting  widgets into sizers is easy with the designers. Not knowing
how to fix your code when the widgets don't appear as you want them is
a problem. I've never seen any docs written to help overcome this for
any framework.

From bertha.rambler at gmail.com  Thu Jan  3 20:06:51 2008
From: bertha.rambler at gmail.com (c t)
Date: Thu, 3 Jan 2008 14:06:51 -0500
Subject: [Tutor] help with list permutations
Message-ID: <8133e2d60801031106m5229c77bp9fcacce35100a858@mail.gmail.com>

Greeting from a real newbie,

I think that their might exist an easy way, in Python, for my list
permutation issue. I need to be able to permute all elements from across
several lists, while ensuring order is maintained across the lists.

For example: list1=[a b]   list2=[c d e]  list3=[f]  list4=[g h]

permute(list1, list2, list3, list4) =

[ [a c f g], [a c f h], [a d f g], [a d f h], [a e f g], [a e f h],
  [b c f g], [b c f h], [b d f g], [b d f h], [b e f g], [b e f h] ]

Of course, the number of the lists is arbitrary and the size of each list is
also arbitrary.

Any help would be greatly appreciated.

thanks,
Bertha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/7ea660f4/attachment.htm 

From kent37 at tds.net  Thu Jan  3 20:43:56 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Jan 2008 14:43:56 -0500
Subject: [Tutor] Choice of GUI builders
In-Reply-To: <flj86c$6ed$1@ger.gmane.org>
References: <8249c4ac0801030740o63ff0c66s98b9cfee9b6d02f3@mail.gmail.com>	<477D052A.5030503@tds.net>
	<flj86c$6ed$1@ger.gmane.org>
Message-ID: <477D3AFC.8030504@tds.net>

Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote 
> 
>> I'm surprised no one else has chimed in for Dabo yet ;-)
> 
> You missed it!
> John F already did the Dabo recommendation.

Funny, I didn't miss it, for some reason I thought that was a different 
thread!

OK, back to my cave :-)

Kent

From kent37 at tds.net  Thu Jan  3 20:47:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 03 Jan 2008 14:47:27 -0500
Subject: [Tutor] is it legal to have a class within a def
In-Reply-To: <200801030845.10874.jfabiani@yolo.com>
References: <200801022114.09174.jfabiani@yolo.com>	<200801022228.49602.jfabiani@yolo.com>
	<fli5s8$hno$1@ger.gmane.org> <200801030845.10874.jfabiani@yolo.com>
Message-ID: <477D3BCF.20307@tds.net>

johnf wrote:
> So I started thinking why would I need the class outside of the function.  If 
> I instead used "import class" would I get a performance improvement?  The 
> function creates an instance each time it is required and then releases and 
> closes.  
> 
> I am very interested in this possible difference between importing the class 
> vs using the inline class.

There is another possibility which is probably what I would do - just 
define the class at global scope in the same module that uses it. 
Instead of

def f():
   class Z(object):
     pass
   # do something with Z

write

def f():
   # do something with Z

class Z(object):
   pass


I.e. you don't have to put the class def'n in a separate module.
Kent

From marc.tompkins at gmail.com  Thu Jan  3 22:00:59 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 3 Jan 2008 13:00:59 -0800
Subject: [Tutor] Tutor Digest, Vol 47, Issue 8
In-Reply-To: <8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>
References: <mailman.404.1199384474.894.tutor@python.org>
	<8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>
Message-ID: <40af687b0801031300i7f402867ua42dbd49a5ccb79d@mail.gmail.com>

On Jan 3, 2008 10:31 AM, Tony Cappellini <cappy2112 at gmail.com> wrote:

> Putting  widgets into sizers is easy with the designers. Not knowing how
> to fix your code when the widgets don't appear as you want them is a
> problem. I've never seen any docs written to help overcome this for any
> framework.


It's like OCR and speech-to-text.  At some point it becomes easier to do it
by hand than to straighten out the dog's breakfast that the "labor-saving"
tool made for you.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/a7af5b0b/attachment.htm 

From cappy2112 at gmail.com  Thu Jan  3 22:24:36 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Thu, 3 Jan 2008 13:24:36 -0800
Subject: [Tutor] Tutor Digest, Vol 47, Issue 8
In-Reply-To: <40af687b0801031300i7f402867ua42dbd49a5ccb79d@mail.gmail.com>
References: <mailman.404.1199384474.894.tutor@python.org>
	<8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>
	<40af687b0801031300i7f402867ua42dbd49a5ccb79d@mail.gmail.com>
Message-ID: <8249c4ac0801031324s3ab7a298h48ba9027e13b88bd@mail.gmail.com>

The point I was trying to make that didn't come across is:
Until one has enough experience to hand code the GUIs, the designers
are helpful and a good place to begin.

The problem with widgets not appearing where they should is not a
problem with the GUI designer, but the lack experience with the
particular toolkit by the programmer.


On Jan 3, 2008 1:00 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Jan 3, 2008 10:31 AM, Tony Cappellini <cappy2112 at gmail.com> wrote:

> It's like OCR and speech-to-text.  At some point it becomes easier to do it
> by hand than to straighten out the dog's breakfast that the "labor-saving"
> tool made for you.
>

From marc.tompkins at gmail.com  Thu Jan  3 22:32:50 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 3 Jan 2008 13:32:50 -0800
Subject: [Tutor] Tutor Digest, Vol 47, Issue 8
In-Reply-To: <8249c4ac0801031324s3ab7a298h48ba9027e13b88bd@mail.gmail.com>
References: <mailman.404.1199384474.894.tutor@python.org>
	<8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>
	<40af687b0801031300i7f402867ua42dbd49a5ccb79d@mail.gmail.com>
	<8249c4ac0801031324s3ab7a298h48ba9027e13b88bd@mail.gmail.com>
Message-ID: <40af687b0801031332s68775b0et52ea4e67cb717e34@mail.gmail.com>

On Jan 3, 2008 1:24 PM, Tony Cappellini <cappy2112 at gmail.com> wrote:

> The point I was trying to make that didn't come across is:
> Until one has enough experience to hand code the GUIs, the designers are
> helpful and a good place to begin.
>
> The problem with widgets not appearing where they should is not a problem
> with the GUI designer, but the lack experience with the particular toolkit
> by the programmer.


That's probably true.  But my philosophy is that tools shouldn't be more
complicated than the problem they're supposed to solve.
If it takes me half an hour to code a screen of my GUI by hand, and I could
do it in five minutes in a designer - and not spend an extra half hour after
that cleaning it up by hand - then hurrah for the designer.  Sign me up!
But if, to achieve the proper level of proficiency with the designer, I have
to invest many hours of study and practice... well, it's going to be a hard
sell.  I'd rather be coding.
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/293f825c/attachment-0001.htm 

From marc.tompkins at gmail.com  Thu Jan  3 22:52:44 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 3 Jan 2008 13:52:44 -0800
Subject: [Tutor] Tutor Digest, Vol 47, Issue 8
In-Reply-To: <40af687b0801031332s68775b0et52ea4e67cb717e34@mail.gmail.com>
References: <mailman.404.1199384474.894.tutor@python.org>
	<8249c4ac0801031031u7106785bkd479221735237eb@mail.gmail.com>
	<40af687b0801031300i7f402867ua42dbd49a5ccb79d@mail.gmail.com>
	<8249c4ac0801031324s3ab7a298h48ba9027e13b88bd@mail.gmail.com>
	<40af687b0801031332s68775b0et52ea4e67cb717e34@mail.gmail.com>
Message-ID: <40af687b0801031352q3ad80ee2g376e9e10da5d3b32@mail.gmail.com>

Let me clarify this:

> But if, to achieve the proper level of proficiency with the designer, I
> have to invest many hours of study and practice... well, it's going to be a
> hard sell.  I'd rather be coding.
>

An hour spent learning something new in Python makes me a better programmer,
and probably a smarter, better human being.  An hour spent learning
something new in wxPython makes me a better GUI programmer, and probably
teaches me things I need to know about the OS and the desktop environment
I'm using.

An hour spent learning to use a designer had better pay me off with an hour
saved somewhere else, and that right soon, or else I'm going to feel I
wasted that hour.
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/f4d79470/attachment.htm 

From gtxy20 at gmail.com  Thu Jan  3 23:00:45 2008
From: gtxy20 at gmail.com (GTXY20)
Date: Thu, 3 Jan 2008 17:00:45 -0500
Subject: [Tutor] Review and criticism of python project
Message-ID: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>

Hello all,

Is there a forum or group where I can upload my python project for review?

I am new at Python and at this point my program is doing what it needs to I
just can't help but feeling I have some errors or improper coding going on
inside.

Any advice is very much appreciated.

Thanks.

GTXY20
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080103/32196240/attachment.htm 

From bgailer at alum.rpi.edu  Fri Jan  4 00:27:51 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 03 Jan 2008 18:27:51 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
Message-ID: <477D6F77.3090802@alum.rpi.edu>

GTXY20 wrote:
>
> Hello all,
>
> Is there a forum or group where I can upload my python project for review?
Others on this list can guide you to web sites for uploading code.

If the program is relatively small you can just email it to this list as 
body text. How small? For me I'd rather wade thru 200 or so lines in an 
email.
>
> I am new at Python and at this point my program is doing what it needs 
> to I just can't help but feeling I have some errors
Errors? Do you mean bugs that have not yet surfaced but might under some 
conditions?
> or improper coding
Are you concerned about performance, readability & maintainability, 
easier / better ways to do things, conformance to Python coding 
guidelines, etc?

If so this is the right place to get suggestions.


From bhaaluu at gmail.com  Fri Jan  4 00:28:39 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 3 Jan 2008 18:28:39 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
Message-ID: <ea979d70801031528y153ce5ean404778ae79c87f30@mail.gmail.com>

If you have a web page, you can upload the code to your web page,
then post here with a link to the code and a request for reviews.
That's one way to do it.
-- 
b h a a l u u at g m a i l dot c o m

On Jan 3, 2008 5:00 PM, GTXY20 <gtxy20 at gmail.com> wrote:
>
> Hello all,
>
> Is there a forum or group where I can upload my python project for review?
>
> I am new at Python and at this point my program is doing what it needs to I
> just can't help but feeling I have some errors or improper coding going on
> inside.
>
> Any advice is very much appreciated.
>
> Thanks.
>
> GTXY20
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From pyprog05 at gmail.com  Fri Jan  4 02:45:53 2008
From: pyprog05 at gmail.com (PyProg PyProg)
Date: Fri, 4 Jan 2008 02:45:53 +0100
Subject: [Tutor] Test
Message-ID: <b763fa190801031745i768c020rc0c78c29b994c56f@mail.gmail.com>

It's just a test message

-- 
http://ekd.tolosano.info
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/687a18b5/attachment.htm 

From cfuller084 at thinkingplanet.net  Fri Jan  4 08:15:33 2008
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 4 Jan 2008 07:15:33 GMT
Subject: [Tutor] help with list permutations
Message-ID: <200801040715.m047FX0b030529@mail.authsmtp.com>

This is a good case for recursion. My solution is in two steps. A straightforward application of recursion (I was casting about semi-randomly) yields a attractive tree structure:

               root
       a                  b
 c     d     e      c     d    e
 f     f     f      f     f    f
g h   g h   g h    g h   g h  g h

It returns a list, of course, but when unpacked in two dimensions looks like a tree. Trees are often represented this way in programming.

One thing to note is that the tree structure naturally preserves the order of the lists, as required.


Here is the code:

def recursion_is_your_friend(l):
   if len(l) == 1:
      return l
   else:
      return [ (i, recursion_is_your_friend(l[1:])) for i in l[0] ]

l = recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])


The idea is that each element of the first list in the list has all the rest of the lists applied to it. Something like that. Talking about recursion isn't a skill I have much skill in. Cue groaning!

The next step is to trace all the paths from the root to the leaves. There is a wikipedia page that discusses this: http://en.wikipedia.org/wiki/Depth-first_search. Stacks would seem a natural way to do this to me. It can also be done with more recursion. I may implement something a little later, but this should get you started. Another way to look at step two is to start at the leaves and follow the (unique) path back to the root.

Cheers

From kent37 at tds.net  Fri Jan  4 14:34:05 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Jan 2008 08:34:05 -0500
Subject: [Tutor] help with list permutations
In-Reply-To: <200801040715.m047FX0b030529@mail.authsmtp.com>
References: <200801040715.m047FX0b030529@mail.authsmtp.com>
Message-ID: <477E35CD.5090309@tds.net>

Chris Fuller wrote:
> This is a good case for recursion. My solution is in two steps.
> Here is the code:
> 
> def recursion_is_your_friend(l):
>    if len(l) == 1:
>       return l
>    else:
>       return [ (i, recursion_is_your_friend(l[1:])) for i in l[0] ]
> 
> l = recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])

> The next step is to trace all the paths from the root to the leaves.

You don't have to do this in two steps, you can generate the desired 
list directly. For example:

def recursion_is_your_friend(l):
    if not l:
       return [[]]
    else:
       values = [[i] + value
           for i in l[0]
               for value in recursion_is_your_friend(l[1:]) ]
       return values

print recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])

Kent

From remco at gerlich.nl  Fri Jan  4 15:19:58 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Fri, 4 Jan 2008 15:19:58 +0100
Subject: [Tutor] how to compare elements of 2 lists
In-Reply-To: <525604.39677.qm@web33202.mail.mud.yahoo.com>
References: <525604.39677.qm@web33202.mail.mud.yahoo.com>
Message-ID: <7ae3ca10801040619x30da68cas9afb4c9380835020@mail.gmail.com>

Hi,

a = [4,3,2,6,7,9]
b = [8,6,3,3,2,7]

You can turn this into a list of two element tuples with zip():
>>> zip(a,b)
[ (4,8),(3,6,),(2,3),(6,3),(7,2),(9,7) ]

Now you can loop through that and compare both elements, for instance I
believe this list comprehension is what you're looking for:

[ t[0] < t[1] for t in zip(a,b) ]

but of course we can write that more elegantly with

[ i<j for i,j in zip(a,b) ]

Gives a list of booleans.

Remco Gerlich

On Dec 25, 2007 4:52 PM, sith . <sith618 at yahoo.com> wrote:

> sith . wrote:
> > Hi,
> > I've read the posts on comparing 2 lists and couldn't find the answer to
> > my question.
> > I have 2 lists
> > a = [4,3,2,6,7,9]
> > b = [8,6,3,3,2,7]
> > How can I determine if the elements in a are larger or smaller than the
> > elements in b.
> >
> > for i in a:
> >     for u in b:
> >         i > u
> > does not return the result I seek.
> >
> > In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> > compared to all the elements in b.
> > I'd like
> > 4 to 8,
> > 3 to 6,
> > 2 to 3 and so on; like 2 columns in excel, the third column would be a
> > new list of boolean values.
> > Can someone help please?  Thank you.
> >
> all(all(i>j for j in b) for i in a)
> HTH
>
>
> Hi,
> Thanks for your reply.  This is what I get:
> >>> a = [4,3,2,6,7,9]
> >>> b = [8,6,3,3,2,7]
> >>> all(all(i>j for j in b) for i in a)
> >>> all(all(i>j for j in b) for i in a)
> False
> How do I make it loop through the whole list?
>
> ------------------------------
> Never miss a thing. Make Yahoo your homepage.<http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/05dc4470/attachment.htm 

From jnewton at fuelindustries.com  Fri Jan  4 17:29:01 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Fri, 4 Jan 2008 11:29:01 -0500
Subject: [Tutor] Snakes and Ladders
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD2401083DF8@ex1.Fuel.Ott>

Hi Python People!

I've recently started learning Python in order to create educational
content for the One Laptop Per Child project:

  <http://www.laptop.org/en/vision/index.shtml>

The first application I'm working on is a game of Snakes and Ladders, to
help younger children understand the concepts of counting and placing
numbers in the right order.

You can find a first draft of the game here:

  <http://olpc-dev.fuelindustries.com/snakes_080104.zip>

To play, click on the dice to obtain a number, then click on the board
squares in the right order.  When you've counted up to the number on the
dice, you'll need to click on the dice again to continue.

I'm looking for help with a number of issues (I'll treat each of the
issues in a separate thread).  To start with what I hope will be an easy
one:

***

I'm importing a graphic named Counter_1.png for the counter.  I'd like
its background to be transparent, using the PNG's built-in alpha
channel.

As this is for the OLPC laptop, where every electron is precious, I want
to load the minimum number of modules to have the minimum processor
overhead.  What is the cheapest way (in terms of RAM usage and CPU
cycles) to display a PNG image with alpha-transparency?
  
I am aware of the VisionEgg demo at...
  <http://visionegg.org/svn/trunk/visionegg/demo/alpha_texture.py>
... but I am concerned that this would be overkill for a simple 2D
application: VisionEgg requires a mini-series of other modules before it
will work.

Or should I forgo alpha-transparency and simply use pygame's
image.set_colorkey(), which will give me a pixelated edge to the
transparent parts of the image?

***

Thanks in advance,

James   

From geekomancerone at gmail.com  Fri Jan  4 19:17:59 2008
From: geekomancerone at gmail.com (Michael Schultz)
Date: Fri, 4 Jan 2008 12:17:59 -0600
Subject: [Tutor] Tkinter OptionMenu question
Message-ID: <9a326b160801041017i7a93b08br3f674a36bc5dcc7d@mail.gmail.com>

Hello list!

I was wondering if any of you could help me with this:

I've got a small GUI connected to a SQLite DB. My OptionMenu pulls a
category list from the DB, and there's a field to add a new Category if you
need to. Now, I'd like the have the OptionMenu update with the new category
after the changes are saved to the DB, but I'm having trouble finding docs
on how, or if, this is possible! If you guys could steer me in the right
direction, I'd appreciate it!

Thanks,
~Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/a94fb24c/attachment.htm 

From gtxy20 at gmail.com  Fri Jan  4 19:25:40 2008
From: gtxy20 at gmail.com (GTXY20)
Date: Fri, 4 Jan 2008 13:25:40 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
	<78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
Message-ID: <39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>

There are no errors per se - the script is doing what it needs to I guess I
just want to check it for compliance - for some reason I think itis a mess
and should be much cleaner.

I am only concerned with one particular area of the complete project - it is
229 lines in total - would this be too much to post? I do not have a website
to post code to - just don't want to post too much for the group and annoy
anyone.

Thanks for your comments and let me know.

GTXY20

On Jan 3, 2008 6:08 PM, wesley chun <wescpy at gmail.com> wrote:

> > Is there a forum or group where I can upload my python project for
> review?
> >
> > I am new at Python and at this point my program is doing what it needs
> to I
> > just can't help but feeling I have some errors or improper coding going
> on
> > inside.
>
>
> if it's not too huge, feel free to post it here for feedback!  let us
> know a bit about what it does, your intentions and/or perhaps how you
> built it, and any specific areas of concern. also post any error msgs
> if applicable.
>
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>    http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/ca5d25f7/attachment.htm 

From bgailer at alum.rpi.edu  Fri Jan  4 20:23:10 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 04 Jan 2008 14:23:10 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>	<78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
	<39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>
Message-ID: <477E879E.4060708@alum.rpi.edu>

GTXY20 wrote:
>  
> There are no errors per se - the script is doing what it needs to I 
> guess I just want to check it for compliance - for some reason I think 
> itis a mess and should be much cleaner.
>  
> I am only concerned with one particular area of the complete project - 
> it is 229 lines in total - would this be too much to post?

Did you get my invitation to post programs in that size range? Please 
just do it. The suspense is killing me!
> I do not have a website to post code to - just don't want to post too 
> much for the group and annoy anyone.
Dialogging about it is more painful than just reading the code.
>  
> Thanks for your comments and let me know.


From jnewton at fuelindustries.com  Fri Jan  4 21:15:10 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Fri, 4 Jan 2008 15:15:10 -0500
Subject: [Tutor] Snakes and Ladders (is: PNG transparency)
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD2401083DF8@ex1.Fuel.Ott>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD2401083EDA@ex1.Fuel.Ott>

Hello again Python Programmers!

To reply to my own question:

-----Original Message-----
I'm importing a graphic named Counter_1.png for the counter.  I'd like
its background to be transparent, using the PNG's built-in alpha
channel.
--------------------------

I've modified the code at...
<http://rene.f0o.com/mywiki/LectureFour#head-52d34285fd010fdc1164ea8ccbe
77980cac42b61>
... so that it uses pygame's image.convert_alpha() if the loaded image
appears to have an alpha channel (see below).  My code does this by
checking if image.get_masks()[3] is non-zero.

However, the pygame documentation at...
  <http://www.pygame.org/docs/ref/surface.html#Surface.get_masks>
... states that .get_masks() is "not needed for normal Pygame usage".
This suggests to me that I am missing a more standard way of detecting
if an pygame.image has an alpha channel.

Is my technique likely to fail?  Is there a better way of doing this?

Thanks in advance for your insights,

James




def load_image(filename, colorkey=None):
    # INPUT: <filename> should be an absolute or relative path to an
    #         image file
    #        <colorkey> should be None, an rgb tuple, or -1, in which
    #         case the color of the top left pixel will be used.
    # ACTION: Attempts to read in an image from filename, and (if
    #         required) applies a transparency mask to it.
    # OUTPUT: Returns a pygame Surface   
    
    try:
        image = pygame.image.load(filename)
    except pygame.error, message:
        print "Cannot load image:", filename
        raise SystemExit, message
    
    # Make a new copy of a Surface and convert it to screen depth
    vAlpha = image.get_masks()[3]
    # (255, 65280, 16711680, -16777216) for an RGBA image
    # (31744, 992, 31, 0) for a 2-bit/pixel rrrrrgggggbbbbbx BMP image

    if vAlpha != 0:
        # The image has an alpha channel
        image = image.convert_alpha()
    else:
        # The image has no alpha channel, but we may have a colorkey
        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



From gtxy20 at gmail.com  Fri Jan  4 23:25:07 2008
From: gtxy20 at gmail.com (GTXY20)
Date: Fri, 4 Jan 2008 17:25:07 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <477E879E.4060708@alum.rpi.edu>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
	<78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
	<39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>
	<477E879E.4060708@alum.rpi.edu>
Message-ID: <39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>

Hi there.

What this section area does is takes a data file that is comma separated and
imports - there is a unique ID in the first field and a code in the second
field that corresponds to a certain section of information. What I need from
this is for the process to role up against unique ID all section holdings
withot duplicates, report on section combinations, and overal section
counts. In addtion I need the ability to assigna value for page count to
these sections and have the ability to uploada translation file just in case
a section is identiifed by multiple values that needs to be normalized to a
single unique value.

Sorry for the lengthly code response - all commenst are appreciated - as
mentioned I am quite new with Python - it is doing what I need it to do but
I think that it is a mess and needs to be cleaned up a little.

Thanks for any comments.

GTXY20

import sys
import os
class __analysis:
    def __init__(self):
        print '***Analysis Tool***'
        datafile=raw_input('data file name:')
        self.datafile=datafile
        self.parsefile()

# script to import unitID section data and section page count reference and
create a sorted dictionary
# where in uhdata{} key=unitID and value=unitID section holdings
# where in pgcnt{} key=Section and value=page count

    def parsefile(self):
        try:
            uhdatafile = open(self.datafile, 'r')
            records = uhdatafile.read()
            uhdatafile.close()
            lines = records.split()
            self.uhdata={}
            for line in lines:
                uh, tf = line.split(',')
                if uh in self.uhdata:
                    f=self.uhdata[uh]
                    if tf not in f:
                        f.append(tf)
                else:
                    self.uhdata[uh]=[tf]

            for uh, Sections in self.uhdata.items():
                Sections.sort()
        except IOError:
            print 'file not found check file name'
            analysis()

        ftranslateok=raw_input('would you like to translate section codes?
(y/n):')
        if ftranslateok == 'y':
            self.transFn()
        else:
            pass
        pgcountok=raw_input('would you like to assign section page counts?
(y/n):')
        if pgcountok == 'y':
            self.setPageCounts()
        else:
            missingpgcounts={}
            fmissingpgcounts=[]
            for x in self.uhdata:
                for f in self.uhdata[x]:
                    if f not in fmissingpgcounts:
                        fmissingpgcounts.append(f)
            for x in fmissingpgcounts:
                missingpgcounts[x]=0
            self.pgcounts = missingpgcounts
        fdistmodel=raw_input('would you like to define max section
distribution cut off? (y/n):')
        if fdistmodel == 'y':
            self.fdistmax=raw_input('what is the max distributions before a
full book?:')
            self.fdistmax=int(self.fdistmax)
            self.Sectiondistmax()
        else:
            self.fdistmax=1000000000
            self.Sectiondistmax()
        sys.exit(1)

# function to determine number of uniqueID for each section
    def Sectionqty(self):
        Sectionqtyoutfile = open('Sectionqty.txt', 'w+')
        Sectionqtyoutfile.write ('Section\tQTY\n')
        from collections import defaultdict
        fcounts=defaultdict(int)
        flst=[]
        flst2=[]
        if self.fdistmax == 1000000000:
            for v in self.uhdata.values():
                for item in v:
                    fcounts[item]+=1

            for k,v in sorted(fcounts.items()):
                Section=k
                fqty=v
                Sectionqtyoutfile.write ('%s\t%s\n' % (Section, fqty))

        else:
            for k,v in self.uhdata.items():
                if len(v)<=self.fdistmax:
                    flst.append(self.uhdata[k])
            for i in flst:
                for x in i:
                    flst2.append(x)
            for Sections in flst2:
                    fcounts[Sections]+=1
            for k,v in sorted(fcounts.items()):
                Section= k
                fqty= v
                Sectionqtyoutfile.write ('%s\t%s\n' % (Section, fqty))

        Sectionqtyoutfile.close()
        self.SectionCombqty()

# function to determine number of uniqueID section combinations and
associated section page counts
    def SectionCombqty(self):
        SectionCombqtyoutfile = open('SectionCombqty.txt', 'w+')
        SectionCombqtyoutfile.write('Combination Qty\tNumber of
Sections\tCombination\tCombinationPageCount\tTotalPages\n')
        fullbook = 'Full Book'
        fgreater=[]
        fcheck=0
        from collections import defaultdict
        fcomb=defaultdict(int)
        for uh in self.uhdata.keys():
            fcomblst=self.uhdata[uh]
            fcomb[tuple(fcomblst)]+=1
        if self.fdistmax == 1000000000:
            for count, items in sorted( ((v,k) for k,v in fcomb.items
()),reverse=True):
                fpgcounts = sum([self.pgcounts.get(i,i) for i in
list(items)])
                Sectioncomb = ','.join(items)
                holdings = len(items)
                totpgcounts = count*fpgcounts
                SectionCombqtyoutfile.write ('%s\t%s\t%s\t%s\t%s\n' %
(count,holdings,Sectioncomb,fpgcounts,totpgcounts))

        else:
            for count, items in sorted( ((v,k) for k,v in fcomb.items
()),reverse=True):
                if len(items) <= self.fdistmax:
                    fpgcounts = sum([self.pgcounts.get(i,i) for i in
list(items)])
                    Sectioncomb = ','.join(items)
                    holdings = len(items)
                    totpgcounts = count*fpgcounts
                    SectionCombqtyoutfile.write ('%s\t%s\t%s\t%s\t%s\n' %
(count,holdings,Sectioncomb,fpgcounts,totpgcounts))
            for count, items in sorted( ((v,k) for k,v in fcomb.items
()),reverse=True):
                if len(items)>self.fdistmax:
                    fgreater.append(count)

            fcheck=sum(fgreater)
            SectionCombqtyoutfile.write ('%s\t''>''%s\t%s\t%s\t%s\n' %
(fcheck,self.fdistmax,fullbook,fullbook,fullbook))


        SectionCombqtyoutfile.close()

# where in pgcnt{} key=Section and value=page count
    def setPageCounts(self):
        pagecountfile=raw_input('page count file name:')
        self.pagecountfile=pagecountfile
        try:
            pagecountinfile = open(self.pagecountfile, 'r')
            records = pagecountinfile.read()
            pagecountinfile.close()
            self.pgcounts={}
            lines = records.split()
            for line in lines:
                fpg, cnt = line.split(',')
                self.pgcounts[fpg]=int(cnt)
        except IOError:
            print 'file not found check file name'
            analysis()

# function to determine number of uniqueID distributions and associated
Sections held
    def Sectiondistmax(self):
        from collections import defaultdict
        Sectiondistoutfile = open('Sectiondist.txt', 'w+')
        Sectiondistoutfile.write ('SectionDistributions\tQTY\n')
        fgreater=[]
        fullbook = "Full Book"
        fcheck=0
        fcount=defaultdict(int)
        for uh in self.uhdata.keys():
            f=self.uhdata[uh]
            fcount[len(f)]+=1
        if self.fdistmax == 1000000000:
            for k,v in sorted(fcount.items()):
                fdist=k
                fqty=v
                Sectiondistoutfile.write ('%s\t%s\n' % (fdist,fqty))

        else:
            for k,v in sorted(fcount.items()):
                if k <= self.fdistmax:
                    fdist=k
                    fqty=v
                    Sectiondistoutfile.write ('%s\t%s\n' % (fdist,fqty))

            for k,v in sorted(fcount.items()):
                if k > self.fdistmax:
                    fgreater.append(fcount[k])
            fcheck=sum(fgreater)
            Sectiondistoutfile.write ('%s\t%s\n' % (fullbook,fcheck))
        Sectiondistoutfile.close()
        self.Sectionqty()

#function to translate UnitID Sectioncodes to normalized assigned Section
code (e.g. parent and mulitple child section codes)
    def transFn(self):
        transfile=raw_input('Section translate file name:')
        self.transfile=transfile
        try:
            transfilein=open(self.transfile, 'r')
            records = transfilein.read()
            transfilein.close()
            lines = records.split()
            transDict = {}
            for line in lines:
                key, value = line.split(',')
                transDict[key] = value

            for key, value in self.uhdata.items():
                self.uhdata[key] = [ transDict.get(i, i) for i in value ]
            for k in self.uhdata:
                self.uhdata[k]=sorted(set(self.uhdata[k]))

        except IOError:
            print 'file not found check file name'
            analysis()




On Jan 4, 2008 2:23 PM, bob gailer <bgailer at alum.rpi.edu> wrote:

> GTXY20 wrote:
> >
> > There are no errors per se - the script is doing what it needs to I
> > guess I just want to check it for compliance - for some reason I think
> > itis a mess and should be much cleaner.
> >
> > I am only concerned with one particular area of the complete project -
> > it is 229 lines in total - would this be too much to post?
>
> Did you get my invitation to post programs in that size range? Please
> just do it. The suspense is killing me!
> > I do not have a website to post code to - just don't want to post too
> > much for the group and annoy anyone.
> Dialogging about it is more painful than just reading the code.
>  >
> > Thanks for your comments and let me know.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/f14c4c90/attachment-0001.htm 

From keridee at jayco.net  Fri Jan  4 23:25:15 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 4 Jan 2008 17:25:15 -0500
Subject: [Tutor] Tkinter OptionMenu question
References: <9a326b160801041017i7a93b08br3f674a36bc5dcc7d@mail.gmail.com>
Message-ID: <00e301c84f20$d622c5d0$fefce004@jslaptop>

Try the .add_command(...) method.



> Hello list!
>
> I was wondering if any of you could help me with this:
>
> I've got a small GUI connected to a SQLite DB. My OptionMenu pulls a
> category list from the DB, and there's a field to add a new Category if
> you
> need to. Now, I'd like the have the OptionMenu update with the new
> category
> after the changes are saved to the DB, but I'm having trouble finding docs
> on how, or if, this is possible! If you guys could steer me in the right
> direction, I'd appreciate it!
>
> Thanks,
> ~Mike
>


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


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


From ricaraoz at gmail.com  Sat Jan  5 00:47:01 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 04 Jan 2008 20:47:01 -0300
Subject: [Tutor] Program review
Message-ID: <477EC575.4050607@bigfoot.com>

Considering we are reviewing programs I'd like to submit one of mine and
I would be thankful for any critic/improvement you can suggest.
My ex needs to send mails to a long list of customers, problem is that
she can not send more than 70 every 10 minutes or her ISP will consider
her a spammer. So she spends hours sending these mails one by one.
This program was meant to help her with that. It takes a configuration
file which tells the program the name of a text file with an email
address per line for mail to be sent to, the name of another text file
with addresses to be ignored, and the name of an HTML file with the
message to be sent. Also how many messages every how many seconds to be
sent.

Procesar.py
-----------

#!/usr/bin/env python

import time
import smtplib
import email
import ConfigParser
import logging

class Mensaje(object) :
    def __init__(self) :
        cfg = ConfigParser.ConfigParser()
        try :
            cfg.readfp(open('config.cfg'))
        except Exception, e :
            logging.error('No pude leer "config.cfg" : %s', e.strerror)

        self.direcciones = cfg.get('Archivos', 'Direcciones')
        self.excluidas = cfg.get('Archivos', 'Excluir')
        self.cuantos = cfg.getint('Correo', 'MailsPorVez')
        self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos')

        try :
            htmlFile = open(cfg.get('Archivos', 'Mensaje'))
            self.HTML = htmlFile.read()
            htmlFile.close()
        except Exception, e :
            logging.error('No pude leer "%s" : %s',
                            cfg.get('Archivos', 'Mensaje'),
                            e.strerror)

        self.De = cfg.get('Encabezados', 'De')
        self.Para = ''
        self.Encabezado = cfg.get('Encabezados', 'Encabezado')
        self.ResponderA = cfg.get('Encabezados', 'ResponderA')
        self.Servidor = cfg.get('Correo', 'Servidor')
        self.Usuario = cfg.get('Correo', 'Usuario')
        self.Contra = cfg.get('Correo', 'Contrasenia')

class Correo(object) :
    def __init__(self, mensaje) :
        self.messg = email.MIMEMultipart.MIMEMultipart()
        self.messg['From'] = mensaje.De
        self.messg['To'] = mensaje.Para
        self.messg['Subject'] = mensaje.Encabezado
        self.messg['Reply-To'] = mensaje.ResponderA
        self.messg.preamble = 'This is a multi-part message in MIME format'
        self.messg.attach(email.MIMEText.MIMEText(mensaje.HTML, 'html'))

        self.Servidor = mensaje.Servidor
        self.Conexion = smtplib.SMTP()
        self.Usuario = mensaje.Usuario
        self.Contra = mensaje.Contra

    def connect(self) :
        try :
            self.Conexion.connect(self.Servidor)
            self.Conexion.set_debuglevel(False)
            self.Conexion.ehlo()
            self.Conexion.starttls()
            self.Conexion.ehlo()
            self.Conexion.login(self.Usuario, self.Contra)
            return True
        except :
            logging.error('No me pude conectar al Servidor')
            return False

    def disconnect(self) :
        self.Conexion.close()

    def enviar(self, addr) :
        self.messg.replace_header('To', addr)
        try :
            self.Conexion.sendmail(self.messg['From'],
                                    self.messg['To'],
                                    self.messg.as_string())
            logging.info('Enviado a : %s', self.messg['To'])
        except SMTPRecipientsRefused :
            logging.error('El destinatario fue rechazado por el servidor')
        except SMTPHeloError :
            logging.error('El servidor no respondio apropiadamente')
        except SMTPSenderRefused :
            logging.error('El From: fue rechazado por el servidor')
        except SMTPDataError :
            logging.error('El servidor respondio con un error desconocido')

def procesar(mensaje):
    try :
        try :
            fIncl = open(mensaje.direcciones)
        except Exception, e :
            logging.error('Error!!! No pude abrir "%s" : %s',
                            mensaje.direcciones,
                            e.strerror)
            raise
        try :
            fExcl = open(mensaje.excluidas)
        except Exception, e :
            logging.error('No pude abrir "%s" : %s',
                            mensaje.excluidas,
                            e.strerror)
            fIncl.close()
            raise
    except : pass
    else :
        mails = enumerate(addr.strip() for addr in fIncl
                    if addr.strip() not in (excl.strip() for excl in fExcl))
        empiezo = time.clock()
        miCorreo = Correo(mensaje)
        miCorreo.connect()
        for nro, addr in mails :
            if nro%mensaje.cuantos == 0 and nro > 0 :
                miCorreo.disconnect()
                time.sleep(mensaje.intervalo - (time.clock() - empiezo))
                if not miCorreo.connect() :
                    logging.info('Terminando')
                    return
                empiezo = time.clock()
            miCorreo.enviar(addr)
        miCorreo.disconnect()
        fIncl.close()
        fExcl.close()


if __name__ == '__main__' :
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',

filename='informe-'+time.strftime('%Y-%m-%d-%H-%M-%S')+'.log',
                        filemode='w')
    procesar(Mensaje())

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

config.cfg
----------

[Archivos]
; En Direcciones va el nombre del archivo de texto
;     que contiene las direcciones de mail una por renglon
; En Excluir va el nombre del archivo de texto
;     que contiene las direcciones a las que NO se les manda
;     mail, una por renglon
; En mensaje va el nombre del archivo html con el mensaje.
;     El mensaje lo creas en tu programa de mail y le das
;     "guardar como..." y lo guardas como "html"

Direcciones = mails.txt
Excluir = excluir.txt
Mensaje = mensaje.html


[Encabezados]

De = xxx at yyyyyyy.com
Encabezado = Prueba de Procesar
ResponderA = bbbbbbb at fffffff.com


[Correo]

Servidor = smtp.servidor.com
Usuario = nombreUsuario
Contrasenia = contrasenia

MailsPorVez = 10
IntervaloEnSegundos = 120

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

TIA



From keridee at jayco.net  Sat Jan  5 00:38:00 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 4 Jan 2008 18:38:00 -0500
Subject: [Tutor] Program review
References: <477EC575.4050607@bigfoot.com>
Message-ID: <001001c84f2b$ace13ed0$7bfce004@jslaptop>

After quickly looking over the code, I find it has a good foundation, it 
seems to have been designed very solidly. I haven't looked very closely, but 
if the messages are mostly alike with just one or two slight differences, 
you might consider dynamically creating the messages (from a customer list, 
for example) so that it's easier to setup the use of this program.

> filename='informe-'+time.strftime('%Y-%m-%d-%H-%M-%S')+'.log',
>      filemode='w')

This filename can be written as

filename=time.strftime('informe-%Y-%m-%d-%H-%M-%S.log')

This gets rid of the intermediate strings, it's just cleaner.

>        mails = enumerate(addr.strip() for addr in fIncl
>                    if addr.strip() not in (excl.strip() for excl in 
> fExcl))

This~~ works, but may be a little inefficient. Especially the double 
addr.strip() here. Given, it doesn't really matter, but I like even better
Perhaps a use of sets here... particularly intersection somehow...

----- Original Message ----- 
From: "Ricardo Ar?oz" <ricaraoz at gmail.com>
To: <tutor at python.org>
Sent: Friday, January 04, 2008 6:47 PM
Subject: [Tutor] Program review


> Considering we are reviewing programs I'd like to submit one of mine and
> I would be thankful for any critic/improvement you can suggest.
> My ex needs to send mails to a long list of customers, problem is that
> she can not send more than 70 every 10 minutes or her ISP will consider
> her a spammer. So she spends hours sending these mails one by one.
> This program was meant to help her with that. It takes a configuration
> file which tells the program the name of a text file with an email
> address per line for mail to be sent to, the name of another text file
> with addresses to be ignored, and the name of an HTML file with the
> message to be sent. Also how many messages every how many seconds to be
> sent.
>
> Procesar.py
> -----------
>
> #!/usr/bin/env python
>
> import time
> import smtplib
> import email
> import ConfigParser
> import logging
>
> class Mensaje(object) :
>    def __init__(self) :
>        cfg = ConfigParser.ConfigParser()
>        try :
>            cfg.readfp(open('config.cfg'))
>        except Exception, e :
>            logging.error('No pude leer "config.cfg" : %s', e.strerror)
>
>        self.direcciones = cfg.get('Archivos', 'Direcciones')
>        self.excluidas = cfg.get('Archivos', 'Excluir')
>        self.cuantos = cfg.getint('Correo', 'MailsPorVez')
>        self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos')
>
>        try :
>            htmlFile = open(cfg.get('Archivos', 'Mensaje'))
>            self.HTML = htmlFile.read()
>            htmlFile.close()
>        except Exception, e :
>            logging.error('No pude leer "%s" : %s',
>                            cfg.get('Archivos', 'Mensaje'),
>                            e.strerror)
>
>        self.De = cfg.get('Encabezados', 'De')
>        self.Para = ''
>        self.Encabezado = cfg.get('Encabezados', 'Encabezado')
>        self.ResponderA = cfg.get('Encabezados', 'ResponderA')
>        self.Servidor = cfg.get('Correo', 'Servidor')
>        self.Usuario = cfg.get('Correo', 'Usuario')
>        self.Contra = cfg.get('Correo', 'Contrasenia')
>
> class Correo(object) :
>    def __init__(self, mensaje) :
>        self.messg = email.MIMEMultipart.MIMEMultipart()
>        self.messg['From'] = mensaje.De
>        self.messg['To'] = mensaje.Para
>        self.messg['Subject'] = mensaje.Encabezado
>        self.messg['Reply-To'] = mensaje.ResponderA
>        self.messg.preamble = 'This is a multi-part message in MIME format'
>        self.messg.attach(email.MIMEText.MIMEText(mensaje.HTML, 'html'))
>
>        self.Servidor = mensaje.Servidor
>        self.Conexion = smtplib.SMTP()
>        self.Usuario = mensaje.Usuario
>        self.Contra = mensaje.Contra
>
>    def connect(self) :
>        try :
>            self.Conexion.connect(self.Servidor)
>            self.Conexion.set_debuglevel(False)
>            self.Conexion.ehlo()
>            self.Conexion.starttls()
>            self.Conexion.ehlo()
>            self.Conexion.login(self.Usuario, self.Contra)
>            return True
>        except :
>            logging.error('No me pude conectar al Servidor')
>            return False
>
>    def disconnect(self) :
>        self.Conexion.close()
>
>    def enviar(self, addr) :
>        self.messg.replace_header('To', addr)
>        try :
>            self.Conexion.sendmail(self.messg['From'],
>                                    self.messg['To'],
>                                    self.messg.as_string())
>            logging.info('Enviado a : %s', self.messg['To'])
>        except SMTPRecipientsRefused :
>            logging.error('El destinatario fue rechazado por el servidor')
>        except SMTPHeloError :
>            logging.error('El servidor no respondio apropiadamente')
>        except SMTPSenderRefused :
>            logging.error('El From: fue rechazado por el servidor')
>        except SMTPDataError :
>            logging.error('El servidor respondio con un error desconocido')
>
> def procesar(mensaje):
>    try :
>        try :
>            fIncl = open(mensaje.direcciones)
>        except Exception, e :
>            logging.error('Error!!! No pude abrir "%s" : %s',
>                            mensaje.direcciones,
>                            e.strerror)
>            raise
>        try :
>            fExcl = open(mensaje.excluidas)
>        except Exception, e :
>            logging.error('No pude abrir "%s" : %s',
>                            mensaje.excluidas,
>                            e.strerror)
>            fIncl.close()
>            raise
>    except : pass
>    else :
>        mails = enumerate(addr.strip() for addr in fIncl
>                    if addr.strip() not in (excl.strip() for excl in 
> fExcl))
>        empiezo = time.clock()
>        miCorreo = Correo(mensaje)
>        miCorreo.connect()
>        for nro, addr in mails :
>            if nro%mensaje.cuantos == 0 and nro > 0 :
>                miCorreo.disconnect()
>                time.sleep(mensaje.intervalo - (time.clock() - empiezo))
>                if not miCorreo.connect() :
>                    logging.info('Terminando')
>                    return
>                empiezo = time.clock()
>            miCorreo.enviar(addr)
>        miCorreo.disconnect()
>        fIncl.close()
>        fExcl.close()
>
>
> if __name__ == '__main__' :
>    logging.basicConfig(level=logging.INFO,
>                        format='%(asctime)s %(levelname)-8s %(message)s',
>                        datefmt='%a, %d %b %Y %H:%M:%S',
>
> filename='informe-'+time.strftime('%Y-%m-%d-%H-%M-%S')+'.log',
>                        filemode='w')
>    procesar(Mensaje())
>
> ----------------------------------------------------------------------------------------
>
> config.cfg
> ----------
>
> [Archivos]
> ; En Direcciones va el nombre del archivo de texto
> ;     que contiene las direcciones de mail una por renglon
> ; En Excluir va el nombre del archivo de texto
> ;     que contiene las direcciones a las que NO se les manda
> ;     mail, una por renglon
> ; En mensaje va el nombre del archivo html con el mensaje.
> ;     El mensaje lo creas en tu programa de mail y le das
> ;     "guardar como..." y lo guardas como "html"
>
> Direcciones = mails.txt
> Excluir = excluir.txt
> Mensaje = mensaje.html
>
>
> [Encabezados]
>
> De = xxx at yyyyyyy.com
> Encabezado = Prueba de Procesar
> ResponderA = bbbbbbb at fffffff.com
>
>
> [Correo]
>
> Servidor = smtp.servidor.com
> Usuario = nombreUsuario
> Contrasenia = contrasenia
>
> MailsPorVez = 10
> IntervaloEnSegundos = 120
>
> -------------------------------------------------------------------
>
> TIA
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From keridee at jayco.net  Sat Jan  5 00:46:39 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 4 Jan 2008 18:46:39 -0500
Subject: [Tutor] Program review
Message-ID: <003601c84f2c$105f3750$7bfce004@jslaptop>

> This~~ works, but may be a little inefficient. Especially the double 
> addr.strip() here. Given, it doesn't really matter, but I like even better
> Perhaps a use of sets here... particularly intersection somehow...

Whoops, I'm not versed in sets (blush) I meant difference_update 


From alan.gauld at btinternet.com  Sat Jan  5 01:10:28 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 5 Jan 2008 00:10:28 -0000
Subject: [Tutor] Review and criticism of python project
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com><78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com><39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com><477E879E.4060708@alum.rpi.edu>
	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
Message-ID: <flmhps$a06$1@ger.gmane.org>


"GTXY20" <gtxy20 at gmail.com> wrote

> Sorry for the lengthly code response - all commenst are 
> appreciated - as
> mentioned I am quite new with Python - it is doing what I need it to 
> do but
> I think that it is a mess and needs to be cleaned up a little.

I've only skimmed it very quickly and a few things popped out at me.

1) Separate the UI from the logic. In particular dont put print 
statements
or raw_input statements in init methods - you will never be able to 
use
the class in a GUI context! Instead pass the values into the class
when you instantiate it.

2) If you must use import inside methods put it at the top - thats 
where
most readers will look for it. Its more conventional to put all 
imports in
a file at the top of the file.

3) Double underscore before a name in Python usually means
its a magic Python feature or a private attribute of a class. Using it 
for a
class name is very unusual. A single underscore would indicate the 
class
was "private" and not intended for general use and might be more
appropriate..

4) This section
>            self.uhdata={}
>            for line in lines:
>                uh, tf = line.split(',')
>                if uh in self.uhdata:
>                    f=self.uhdata[uh]
>                    if tf not in f:
>                        f.append(tf)
>                else:
>                    self.uhdata[uh]=[tf]
>
Looks like it should be cleaner. I don;t thionk you shouldneed all
those if/in checks using a dictionary. I can't be sure without 
spending
more time reading it than I've got right now but it looks wrong 
somehow.

5) What is the po8int of this:
>            for k,v in sorted(fcounts.items()):
>                Section=k
>                fqty=v
>                Sectionqtyoutfile.write ('%s\t%s\n' % (Section, 
> fqty))
>

Why not just
>            for k,v in sorted(fcounts.items()):
>                Sectionqtyoutfile.write ('%s\t%s\n' % (k,v))

The extra variables dont add anything and if you really prefer the
names then do this:
>            for Section,fqty in sorted(fcounts.items()):
>                Sectionqtyoutfile.write ('%s\t%s\n' % (Section,fqty))

> Thanks for any comments.

Thats as far as I got,

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




From keridee at jayco.net  Sat Jan  5 02:32:06 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 4 Jan 2008 20:32:06 -0500
Subject: [Tutor] Review and criticism of python project
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com><78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com><39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com><477E879E.4060708@alum.rpi.edu>
	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
Message-ID: <005001c84f3b$32782ae0$7bfce004@jslaptop>

Cool! Code! (gullom voice - we must look at code, yesss....)

> Hi there.
>
> What this section area does is takes a data file that is comma separated 
> and
> imports - there is a unique ID in the first field and a code in the second
> field that corresponds to a certain section of information. What I need 
> from
> this is for the process to role up against unique ID all section holdings
> withot duplicates, report on section combinations, and overal section
> counts. In addtion I need the ability to assigna value for page count to
> these sections and have the ability to uploada translation file just in 
> case
> a section is identiifed by multiple values that needs to be normalized to 
> a
> single unique value.
>
> Sorry for the lengthly code response - all commenst are appreciated - as
> mentioned I am quite new with Python - it is doing what I need it to do 
> but
> I think that it is a mess and needs to be cleaned up a little.
>
> Thanks for any comments.
>
> GTXY20
>
> import sys
> import os
> class __analysis:
>    def __init__(self):
>        print '***Analysis Tool***'
>        datafile=raw_input('data file name:')
>        self.datafile=datafile
>        self.parsefile()

Ouch. Usually in OOP, one never puts any user interaction into a class. 
Anytime you want to make an __analysis object, code execution is halted unto 
the user responds.... Yuck. If necessary, then make the datafile a parameter 
you pass in and do the raw_input outside of the class definition before you 
instantiate an object.
As an aside... setting the filename to datafile and then datafile directly 
to self.datafile is a little wasteful when you can set it directly to 
self.datafile

> # script to import unitID section data and section page count reference 
> and
> create a sorted dictionary
> # where in uhdata{} key=unitID and value=unitID section holdings
> # where in pgcnt{} key=Section and value=page count
>
>    def parsefile(self):
>        try:
>            uhdatafile = open(self.datafile, 'r')
>            records = uhdatafile.read()
>            uhdatafile.close()
>            lines = records.split()

Ummm this will split on every space also. Using the name 'lines' as an 
indicator I think you were expecting this to actually split on newline 
characters, so instead you should use uhdatafile.readlines()

>            self.uhdata={}
>            for line in lines:

Here you iterate over a created list. It is easier and more efficient to 
iterate over the file itself.
for line in uhdatafile:
   do_stuff()
uhdatafile.close()

>                uh, tf = line.split(',')
>                if uh in self.uhdata:
>                    f=self.uhdata[uh]
>                    if tf not in f:
>                        f.append(tf)
>                else:
>                    self.uhdata[uh]=[tf]

This can read

try:
  f = self.uhdata[uh]
except KeyError:
  self.uhdata[uh] = []
finally:
  self.uhdata[uh].append(tf)


Also note that there is no error checking in the algorithm anywhere here. 
The file must be exactly formatted or it will create an error.

>            for uh, Sections in self.uhdata.items():
>                Sections.sort()

This will not work. In the documentation, it says that dictionary object 
return a *copy* of the (key,value) pairs.
You are sorting those *copies*.  Also sinces uh is not used here 
itervalues() is sufficient.

for Sections in self.uhdata.itervalues():
  Sections.sort()


>        except IOError:
>            print 'file not found check file name'
>            analysis()
>
>        ftranslateok=raw_input('would you like to translate section codes?
> (y/n):')
>        if ftranslateok == 'y':
>            self.transFn()
>        else:
>            pass

This is unnecessary, code execution will continue whether you use else: pass 
or not.

>        pgcountok=raw_input('would you like to assign section page counts?
> (y/n):')
>        if pgcountok == 'y':
>            self.setPageCounts()
>        else:
>            missingpgcounts={}
>            fmissingpgcounts=[]
>            for x in self.uhdata:
>                for f in self.uhdata[x]:
>                    if f not in fmissingpgcounts:
>                        fmissingpgcounts.append(f)

fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in 
fmissingpgcounts]
Ahhh... This looks like a set.
fmissingpgcounts = set(self.uhdata.itervalues())

>            for x in fmissingpgcounts:
>                missingpgcounts[x]=0
>            self.pgcounts = missingpgcounts

Oh my. So we have a dictionary, create a unique list of the values and then 
create another dictionary from that?
The intermediate variable missingpgcounts is not necessary.

self.pgcounts = dict((x,0) for x in fmissingpgcounts)

>        fdistmodel=raw_input('would you like to define max section
> distribution cut off? (y/n):')
>        if fdistmodel == 'y':
>            self.fdistmax=raw_input('what is the max distributions before a
> full book?:')
>            self.fdistmax=int(self.fdistmax)
>            self.Sectiondistmax()
>        else:
>            self.fdistmax=1000000000
>            self.Sectiondistmax()

self.Sectiondistmax() needs to be typed only once unindented after the 
if/else block.
If self.fdistmax will never be zero, then you can do this...

self.fdistmax = int(self.fdistmax) or 1000000000
Oh, and if the user presses enter without puttting in a number then your 
program will exit with
an error. If you want you can use this to your advantage. (Press enter for 
default of all)

try:
    self.fdistmax = int(self.fdistmax)
except ValueError:
    self.fdistmax = False

False is a better flag here. Though you will never have a value of a 
billion, you could never, ever possibly have a value of False. (0)
Also helps readability. See below.

>        sys.exit(1)
>
> # function to determine number of uniqueID for each section
>    def Sectionqty(self):
>        Sectionqtyoutfile = open('Sectionqty.txt', 'w+')
>        Sectionqtyoutfile.write ('Section\tQTY\n')
>        from collections import defaultdict
>        fcounts=defaultdict(int)
>        flst=[]
>        flst2=[]

Okay this whole section can be rewritten. The reason is because the two 
blocks are basically the same thing with the one stipulation based on a 
flag. I will attempt to rewrite this so the code is not copied.

>        if self.fdistmax == 1000000000:
>            for v in self.uhdata.values():
>                for item in v:
>                    fcounts[item]+=1
>
>            for k,v in sorted(fcounts.items()):
>                Section=k
>                fqty=v
>                Sectionqtyoutfile.write ('%s\t%s\n' % (Section, fqty))
>
>        else:
>            for k,v in self.uhdata.items():
>                if len(v)<=self.fdistmax:
>                    flst.append(self.uhdata[k])
>            for i in flst:
>                for x in i:
>                    flst2.append(x)
>            for Sections in flst2:
>                    fcounts[Sections]+=1
>            for k,v in sorted(fcounts.items()):
>                Section= k
>                fqty= v
>                Sectionqtyoutfile.write ('%s\t%s\n' % (Section, fqty))

for k,v in self.uhdata.items():
  if self.fdistmax or len(v)<=self.fdistmax:
    for x in self.uhdata[k]:
      fcounts[x]+=1
for (Section, fqty) in sorted(fcounts.items()):
  Sectionqtyoutfile.write('%s\t%s\n'%(Section,fqty))

>        Sectionqtyoutfile.close()
>        self.SectionCombqty()
>
> # function to determine number of uniqueID section combinations and
> associated section page counts
>    def SectionCombqty(self):
>        SectionCombqtyoutfile = open('SectionCombqty.txt', 'w+')
>        SectionCombqtyoutfile.write('Combination Qty\tNumber of
> Sections\tCombination\tCombinationPageCount\tTotalPages\n')
>        fullbook = 'Full Book'
>        fgreater=[]
>        fcheck=0
>        from collections import defaultdict
>        fcomb=defaultdict(int)
>        for uh in self.uhdata.keys():
>            fcomblst=self.uhdata[uh]
>            fcomb[tuple(fcomblst)]+=1

for value in self.uhdata.itervalues():
  fcomb[tuple(value)]+=1

>        if self.fdistmax == 1000000000:
>            for count, items in sorted( ((v,k) for k,v in fcomb.items
> ()),reverse=True):
>                fpgcounts = sum([self.pgcounts.get(i,i) for i in
> list(items)])
>                Sectioncomb = ','.join(items)
>                holdings = len(items)
>                totpgcounts = count*fpgcounts
>                SectionCombqtyoutfile.write ('%s\t%s\t%s\t%s\t%s\n' %
> (count,holdings,Sectioncomb,fpgcounts,totpgcounts))
>
>        else:
>            for count, items in sorted( ((v,k) for k,v in fcomb.items
> ()),reverse=True):
>                if len(items) <= self.fdistmax:
>                    fpgcounts = sum([self.pgcounts.get(i,i) for i in
> list(items)])
>                    Sectioncomb = ','.join(items)
>                    holdings = len(items)
>                    totpgcounts = count*fpgcounts
>                    SectionCombqtyoutfile.write ('%s\t%s\t%s\t%s\t%s\n' %
> (count,holdings,Sectioncomb,fpgcounts,totpgcounts))
>            for count, items in sorted( ((v,k) for k,v in fcomb.items
> ()),reverse=True):
>                if len(items)>self.fdistmax:
>                    fgreater.append(count)
>
>            fcheck=sum(fgreater)
>            SectionCombqtyoutfile.write ('%s\t''>''%s\t%s\t%s\t%s\n' %
> (fcheck,self.fdistmax,fullbook,fullbook,fullbook))

See what I did to the section above to see how to make this one block 
instead of two copy&paste blocks.

>
>        SectionCombqtyoutfile.close()
>
> # where in pgcnt{} key=Section and value=page count
>    def setPageCounts(self):
>        pagecountfile=raw_input('page count file name:')
>        self.pagecountfile=pagecountfile
>        try:
>            pagecountinfile = open(self.pagecountfile, 'r')
>            records = pagecountinfile.read()
>            pagecountinfile.close()
>            self.pgcounts={}
>            lines = records.split()
>            for line in lines:
>                fpg, cnt = line.split(',')
>                self.pgcounts[fpg]=int(cnt)

This is very similar to the block at the beginning of this post. Make the 
same changes here.

>        except IOError:
>            print 'file not found check file name'
>            analysis()
>
> # function to determine number of uniqueID distributions and associated
> Sections held
>    def Sectiondistmax(self):
>        from collections import defaultdict
>        Sectiondistoutfile = open('Sectiondist.txt', 'w+')
>        Sectiondistoutfile.write ('SectionDistributions\tQTY\n')
>        fgreater=[]
>        fullbook = "Full Book"
>        fcheck=0
>        fcount=defaultdict(int)
>        for uh in self.uhdata.keys():
>            f=self.uhdata[uh]
>            fcount[len(f)]+=1
>        if self.fdistmax == 1000000000:
>            for k,v in sorted(fcount.items()):

You don't have to name these k,v. Any name is fine like:
for fdist, fqty in fcount.items(sorted=True):

>                fdist=k
>                fqty=v
>                Sectiondistoutfile.write ('%s\t%s\n' % (fdist,fqty))
>
>        else:
>            for k,v in sorted(fcount.items()):
>                if k <= self.fdistmax:
>                    fdist=k
>                    fqty=v

Same name thing.

>                    Sectiondistoutfile.write ('%s\t%s\n' % (fdist,fqty))
>
>            for k,v in sorted(fcount.items()):
>                if k > self.fdistmax:
>                    fgreater.append(fcount[k])
>            fcheck=sum(fgreater)
>            Sectiondistoutfile.write ('%s\t%s\n' % (fullbook,fcheck))
>        Sectiondistoutfile.close()
>        self.Sectionqty()
>
> #function to translate UnitID Sectioncodes to normalized assigned Section
> code (e.g. parent and mulitple child section codes)
>    def transFn(self):
>        transfile=raw_input('Section translate file name:')
>        self.transfile=transfile
>        try:
>            transfilein=open(self.transfile, 'r')
>            records = transfilein.read()
>            transfilein.close()
>            lines = records.split()
>            transDict = {}
>            for line in lines:
>                key, value = line.split(',')
>                transDict[key] = value

Again, the same thing here as way up above.

>            for key, value in self.uhdata.items():
>                self.uhdata[key] = [ transDict.get(i, i) for i in value ]
>            for k in self.uhdata:
>                self.uhdata[k]=sorted(set(self.uhdata[k]))

Uhhh... Right.

>        except IOError:
>            print 'file not found check file name'
>            analysis()

Just some suggestions. A long piece of code for what you are trying to 
accomplish... It probably could be shortened, seeing how much duplicate code 
is within it. All I did was work through it block by block changing pieces 
so that they make a little more sense and are more efficient. I suspect that 
a rework of the complete design would be beneficial. I'm just too tired and 
busy to think for that long. ;-)

HTH,
JS 


From python at mrfab.info  Sat Jan  5 03:45:21 2008
From: python at mrfab.info (Michael)
Date: Sat, 05 Jan 2008 10:45:21 +0800
Subject: [Tutor] classes and the deepcopy function
Message-ID: <477EEF41.8060102@mrfab.info>

Hi

I was trying to learn about classes in Python and have been playing 
around but I am having a problem with the deepcopy function. I want to 
have a function that returns a clean copy of an object that you can 
change without it changing the original, but no matter what I do the 
original changes as well. Can anyone give ma a pointer?

Thanks
Michael
--------------------------
import copy

class point:
    "represents a point in 2d space"
    x = 0
    y = 0
    def printpoints(self):
        print "x is %g, y is %g" %(self.x, self.y)

class rectangle:
    "represents a rectangle"
    width = 0
    height = 0
    corner = point()

def move_rectangle(rect, dx, dy):
    rect2 = copy.deepcopy(rect)
    rect2.corner.x += dx
    rect2.corner.y += dy
    return rect2

r1 = rectangle()
r1.width = 20
r1.height = 40
r1.corner.x = 10
r1.corner.y = 10
r2 = move_rectangle(r1,5,2)
print 'Rectangle', r1.width, r1.height
r1.corner.printpoints()
print 'Rectangle 2', r2.width, r2.height
r2.corner.printpoints()




From kent37 at tds.net  Sat Jan  5 03:29:37 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Jan 2008 21:29:37 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <005001c84f3b$32782ae0$7bfce004@jslaptop>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com><78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com><39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com><477E879E.4060708@alum.rpi.edu>	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
	<005001c84f3b$32782ae0$7bfce004@jslaptop>
Message-ID: <477EEB91.5010209@tds.net>

Tiger12506 wrote:

> Ouch. Usually in OOP, one never puts any user interaction into a class. 

That seems a bit strongly put to me. Generally user interaction should 
be separated from functional classes but you might have a class to help 
with command line interaction (e.g. the cmd module in the std lib) and 
GUI frameworks are usually built with classes.


>>                uh, tf = line.split(',')
>>                if uh in self.uhdata:
>>                    f=self.uhdata[uh]
>>                    if tf not in f:
>>                        f.append(tf)
>>                else:
>>                    self.uhdata[uh]=[tf]
> 
> This can read
> 
> try:
>   f = self.uhdata[uh]
> except KeyError:
>   self.uhdata[uh] = []
> finally:
>   self.uhdata[uh].append(tf)

These are not equivalent - the original code avoids duplicates in 
self.uhdata[uh].

Possibly self.uhdata[uh] could be a set instead of a list. Then this 
could be written very nicely using defaultdict:

from collections import defaultdict
   ...
   self.uhdata = defaultdict(set)
   ...
   self.uhdata[uh].add(tf)

>>            for uh, Sections in self.uhdata.items():
>>                Sections.sort()
> 
> This will not work. In the documentation, it says that dictionary object 
> return a *copy* of the (key,value) pairs.
> You are sorting those *copies*.  

No, the original code is fine. The docs say that dict.items() returns "a 
copy of a's list of (key, value) pairs". This is a little misleading, 
perhaps. A dict does not actually contain a list of key, value pairs, it 
is implemented with a hash table. dict.items() returns a new list 
containing the key, value pairs.

But the keys and values in the new list are references to the same keys 
and values in the dict. So mutating the values in the returned list, via 
sort(), will also mutate the values in the dict.


>>            missingpgcounts={}
>>            fmissingpgcounts=[]
>>            for x in self.uhdata:
>>                for f in self.uhdata[x]:
>>                    if f not in fmissingpgcounts:
>>                        fmissingpgcounts.append(f)
> 
> fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in 
> fmissingpgcounts]
> Ahhh... This looks like a set.
> fmissingpgcounts = set(self.uhdata.itervalues())

Again, this is not quite the same thing. The original code builds a set 
of the contents of the values. You are building a set from the values 
(which are already lists). You still need one loop:
fmissingpgcounts = set()
for v in self.uhdate.itervalues():
   fmissingpgcounts.update(v)

> self.pgcounts = dict((x,0) for x in fmissingpgcounts)

or, self.pgcounts = dict.fromkeys(fmissingpgcounts, 0)

That's all I have energy for...
Kent


From goldwamh at slu.edu  Sat Jan  5 03:42:33 2008
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Fri, 4 Jan 2008 20:42:33 -0600
Subject: [Tutor]  classes and the deepcopy function
In-Reply-To: <477EEF41.8060102@mrfab.info>
References: <477EEF41.8060102@mrfab.info>
Message-ID: <18302.61081.906115.143224@euclid.slu.edu>


Hi Michael,

  This is a very interesting example.  You do indeed have two distinct
  copies.  The interdependence you are observing is because you have
  defined CLASS-LEVEL variables (akin to static in Java) rather than
  instance-level variables. This is because of their declaration
  within the context of the class definition.

  You should typically initialize instance variables within an
  __init__ method and using names qualified with self.

  Here is an updated version of your code.  If you still need another
  explanation of why your previous code executed the way it did, just
  let me know.

With regard,
Michael

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

import copy

class point:
    "represents a point in 2d space"
    def __init__(self):
        self.x = 0
        self.y = 0

    def printpoints(self):
        print "x is %g, y is %g" %(self.x, self.y)

class rectangle:
    "represents a rectangle"
    def __init__(self):
        self.width = 0
        self.height = 0
        self.corner = point()

def move_rectangle(rect, dx, dy):
    rect2 = copy.deepcopy(rect)
    rect2.corner.x += dx
    rect2.corner.y += dy
    return rect2

r1 = rectangle()
r1.width = 20
r1.height = 40
r1.corner.x = 10
r1.corner.y = 10
r2 = move_rectangle(r1,5,2)
print 'Rectangle', r1.width, r1.height
r1.corner.printpoints()
print 'Rectangle 2', r2.width, r2.height
r2.corner.printpoints()





On Saturday January 5, 2008, Michael wrote: 

>    Hi
>    
>    I was trying to learn about classes in Python and have been playing 
>    around but I am having a problem with the deepcopy function. I want to 
>    have a function that returns a clean copy of an object that you can 
>    change without it changing the original, but no matter what I do the 
>    original changes as well. Can anyone give ma a pointer?
>    
>    Thanks
>    Michael
>    --------------------------
>    import copy
>    
>    class point:
>        "represents a point in 2d space"
>        x = 0
>        y = 0
>        def printpoints(self):
>            print "x is %g, y is %g" %(self.x, self.y)
>    
>    class rectangle:
>        "represents a rectangle"
>        width = 0
>        height = 0
>        corner = point()
>    
>    def move_rectangle(rect, dx, dy):
>        rect2 = copy.deepcopy(rect)
>        rect2.corner.x += dx
>        rect2.corner.y += dy
>        return rect2
>    
>    r1 = rectangle()
>    r1.width = 20
>    r1.height = 40
>    r1.corner.x = 10
>    r1.corner.y = 10
>    r2 = move_rectangle(r1,5,2)
>    print 'Rectangle', r1.width, r1.height
>    r1.corner.printpoints()
>    print 'Rectangle 2', r2.width, r2.height
>    r2.corner.printpoints()


From kent37 at tds.net  Sat Jan  5 04:14:56 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 04 Jan 2008 22:14:56 -0500
Subject: [Tutor] Program review
In-Reply-To: <477EC575.4050607@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>
Message-ID: <477EF630.2070808@tds.net>

Ricardo Ar?oz wrote:

>         except Exception, e :
>             logging.error('No pude leer "config.cfg" : %s', e.strerror)

You might like to use
   logging.error('No pude...', exc_info=True)
which will include the full traceback in the log. You can use the 
exc_info keyword with any of the logging commands.

>         mails = enumerate(addr.strip() for addr in fIncl
>                     if addr.strip() not in (excl.strip() for excl in fExcl))

I don't think this is doing what you want. (excl.strip() for excl in 
fExcl) will execute for each addr. But fExcl is a file which can only be 
iterated once, so only the first address will actually be checked.

I would write this as

   addrExcl = set(excl.strip() for excl in fExcl)
   mails = enumerate(addr.strip() for addr in fIncl
                     if addr.strip() not in addrExcl)

or even iterate over fIncl directly though you would have to change the 
way you count:
   for addr in fExcl:
     if addr.strip() in addrExcl:
       continue
     ...


You might consider adding a method to Mensaje that creates the message, 
rather than having Correo.__init__() read all the data values from 
mensaje. The current implementation has a code smell or two:
http://c2.com/cgi/wiki?FeatureEnvy and Data Class

Attribute names conventionally begin with lower case. If you must use 
upper case, at least be consistent!

Kent

From gtxy20 at gmail.com  Sat Jan  5 04:46:32 2008
From: gtxy20 at gmail.com (GTXY20)
Date: Fri, 4 Jan 2008 22:46:32 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <477EEB91.5010209@tds.net>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
	<78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
	<39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>
	<477E879E.4060708@alum.rpi.edu>
	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
	<005001c84f3b$32782ae0$7bfce004@jslaptop> <477EEB91.5010209@tds.net>
Message-ID: <39cb7e5d0801041946o7bd270fem379715b45019b394@mail.gmail.com>

thanks for the feedback - i will go through your comments line by line
adjust and test and will re-post when complete.

GTXY20

On Jan 4, 2008 9:29 PM, Kent Johnson <kent37 at tds.net> wrote:

> Tiger12506 wrote:
>
> > Ouch. Usually in OOP, one never puts any user interaction into a class.
>
> That seems a bit strongly put to me. Generally user interaction should
> be separated from functional classes but you might have a class to help
> with command line interaction (e.g. the cmd module in the std lib) and
> GUI frameworks are usually built with classes.
>
>
> >>                uh, tf = line.split(',')
> >>                if uh in self.uhdata:
> >>                    f=self.uhdata[uh]
> >>                    if tf not in f:
> >>                        f.append(tf)
> >>                else:
> >>                    self.uhdata[uh]=[tf]
> >
> > This can read
> >
> > try:
> >   f = self.uhdata[uh]
> > except KeyError:
> >   self.uhdata[uh] = []
> > finally:
> >   self.uhdata[uh].append(tf)
>
> These are not equivalent - the original code avoids duplicates in
> self.uhdata[uh].
>
> Possibly self.uhdata[uh] could be a set instead of a list. Then this
> could be written very nicely using defaultdict:
>
> from collections import defaultdict
>   ...
>   self.uhdata = defaultdict(set)
>   ...
>   self.uhdata[uh].add(tf)
>
> >>            for uh, Sections in self.uhdata.items():
> >>                Sections.sort()
> >
> > This will not work. In the documentation, it says that dictionary object
> > return a *copy* of the (key,value) pairs.
> > You are sorting those *copies*.
>
> No, the original code is fine. The docs say that dict.items() returns "a
> copy of a's list of (key, value) pairs". This is a little misleading,
> perhaps. A dict does not actually contain a list of key, value pairs, it
> is implemented with a hash table. dict.items() returns a new list
> containing the key, value pairs.
>
> But the keys and values in the new list are references to the same keys
> and values in the dict. So mutating the values in the returned list, via
> sort(), will also mutate the values in the dict.
>
>
> >>            missingpgcounts={}
> >>            fmissingpgcounts=[]
> >>            for x in self.uhdata:
> >>                for f in self.uhdata[x]:
> >>                    if f not in fmissingpgcounts:
> >>                        fmissingpgcounts.append(f)
> >
> > fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in
> > fmissingpgcounts]
> > Ahhh... This looks like a set.
> > fmissingpgcounts = set(self.uhdata.itervalues())
>
> Again, this is not quite the same thing. The original code builds a set
> of the contents of the values. You are building a set from the values
> (which are already lists). You still need one loop:
> fmissingpgcounts = set()
> for v in self.uhdate.itervalues():
>   fmissingpgcounts.update(v)
>
> > self.pgcounts = dict((x,0) for x in fmissingpgcounts)
>
> or, self.pgcounts = dict.fromkeys(fmissingpgcounts, 0)
>
> That's all I have energy for...
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/b1f8d923/attachment.htm 

From gtxy20 at gmail.com  Sat Jan  5 04:46:32 2008
From: gtxy20 at gmail.com (GTXY20)
Date: Fri, 4 Jan 2008 22:46:32 -0500
Subject: [Tutor] Review and criticism of python project
In-Reply-To: <477EEB91.5010209@tds.net>
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com>
	<78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com>
	<39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com>
	<477E879E.4060708@alum.rpi.edu>
	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
	<005001c84f3b$32782ae0$7bfce004@jslaptop> <477EEB91.5010209@tds.net>
Message-ID: <39cb7e5d0801041946o7bd270fem379715b45019b394@mail.gmail.com>

thanks for the feedback - i will go through your comments line by line
adjust and test and will re-post when complete.

GTXY20

On Jan 4, 2008 9:29 PM, Kent Johnson <kent37 at tds.net> wrote:

> Tiger12506 wrote:
>
> > Ouch. Usually in OOP, one never puts any user interaction into a class.
>
> That seems a bit strongly put to me. Generally user interaction should
> be separated from functional classes but you might have a class to help
> with command line interaction (e.g. the cmd module in the std lib) and
> GUI frameworks are usually built with classes.
>
>
> >>                uh, tf = line.split(',')
> >>                if uh in self.uhdata:
> >>                    f=self.uhdata[uh]
> >>                    if tf not in f:
> >>                        f.append(tf)
> >>                else:
> >>                    self.uhdata[uh]=[tf]
> >
> > This can read
> >
> > try:
> >   f = self.uhdata[uh]
> > except KeyError:
> >   self.uhdata[uh] = []
> > finally:
> >   self.uhdata[uh].append(tf)
>
> These are not equivalent - the original code avoids duplicates in
> self.uhdata[uh].
>
> Possibly self.uhdata[uh] could be a set instead of a list. Then this
> could be written very nicely using defaultdict:
>
> from collections import defaultdict
>   ...
>   self.uhdata = defaultdict(set)
>   ...
>   self.uhdata[uh].add(tf)
>
> >>            for uh, Sections in self.uhdata.items():
> >>                Sections.sort()
> >
> > This will not work. In the documentation, it says that dictionary object
> > return a *copy* of the (key,value) pairs.
> > You are sorting those *copies*.
>
> No, the original code is fine. The docs say that dict.items() returns "a
> copy of a's list of (key, value) pairs". This is a little misleading,
> perhaps. A dict does not actually contain a list of key, value pairs, it
> is implemented with a hash table. dict.items() returns a new list
> containing the key, value pairs.
>
> But the keys and values in the new list are references to the same keys
> and values in the dict. So mutating the values in the returned list, via
> sort(), will also mutate the values in the dict.
>
>
> >>            missingpgcounts={}
> >>            fmissingpgcounts=[]
> >>            for x in self.uhdata:
> >>                for f in self.uhdata[x]:
> >>                    if f not in fmissingpgcounts:
> >>                        fmissingpgcounts.append(f)
> >
> > fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in
> > fmissingpgcounts]
> > Ahhh... This looks like a set.
> > fmissingpgcounts = set(self.uhdata.itervalues())
>
> Again, this is not quite the same thing. The original code builds a set
> of the contents of the values. You are building a set from the values
> (which are already lists). You still need one loop:
> fmissingpgcounts = set()
> for v in self.uhdate.itervalues():
>   fmissingpgcounts.update(v)
>
> > self.pgcounts = dict((x,0) for x in fmissingpgcounts)
>
> or, self.pgcounts = dict.fromkeys(fmissingpgcounts, 0)
>
> That's all I have energy for...
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/b1f8d923/attachment-0003.htm 

From python at mrfab.info  Sat Jan  5 09:00:53 2008
From: python at mrfab.info (Michael)
Date: Sat, 05 Jan 2008 16:00:53 +0800
Subject: [Tutor] classes and the deepcopy function
In-Reply-To: <18302.61081.906115.143224@euclid.slu.edu>
References: <477EEF41.8060102@mrfab.info>
	<18302.61081.906115.143224@euclid.slu.edu>
Message-ID: <477F3935.3010509@mrfab.info>

Hi Michael

Thanks for the quick reply, I think I get it. So becuase I did not 
declare them withing the init method using self they are shared by every 
object that is created, even completely brand new ones?

Is it normal practice to declare your variables in a class? I notice 
that you don't have to, you can create them as you go, but i thought 
declaring and initialising them in the class would make it easier to 
understand and see what the class is for and should contain.

Thanks again

Michael

Michael H. Goldwasser wrote:
> Hi Michael,
>
>   This is a very interesting example.  You do indeed have two distinct
>   copies.  The interdependence you are observing is because you have
>   defined CLASS-LEVEL variables (akin to static in Java) rather than
>   instance-level variables. This is because of their declaration
>   within the context of the class definition.
>
>   You should typically initialize instance variables within an
>   __init__ method and using names qualified with self.
>
>   Here is an updated version of your code.  If you still need another
>   explanation of why your previous code executed the way it did, just
>   let me know.
>
> With regard,
> Michael
>
> -----------------------------------------------------
>
> import copy
>
> class point:
>     "represents a point in 2d space"
>     def __init__(self):
>         self.x = 0
>         self.y = 0
>
>     def printpoints(self):
>         print "x is %g, y is %g" %(self.x, self.y)
>
> class rectangle:
>     "represents a rectangle"
>     def __init__(self):
>         self.width = 0
>         self.height = 0
>         self.corner = point()
>
> def move_rectangle(rect, dx, dy):
>     rect2 = copy.deepcopy(rect)
>     rect2.corner.x += dx
>     rect2.corner.y += dy
>     return rect2
>
> r1 = rectangle()
> r1.width = 20
> r1.height = 40
> r1.corner.x = 10
> r1.corner.y = 10
> r2 = move_rectangle(r1,5,2)
> print 'Rectangle', r1.width, r1.height
> r1.corner.printpoints()
> print 'Rectangle 2', r2.width, r2.height
> r2.corner.printpoints()
>
>
>
>
>
> On Saturday January 5, 2008, Michael wrote: 
>
>   
>>    Hi
>>    
>>    I was trying to learn about classes in Python and have been playing 
>>    around but I am having a problem with the deepcopy function. I want to 
>>    have a function that returns a clean copy of an object that you can 
>>    change without it changing the original, but no matter what I do the 
>>    original changes as well. Can anyone give ma a pointer?
>>    
>>    Thanks
>>    Michael
>>    --------------------------
>>    import copy
>>    
>>    class point:
>>        "represents a point in 2d space"
>>        x = 0
>>        y = 0
>>        def printpoints(self):
>>            print "x is %g, y is %g" %(self.x, self.y)
>>    
>>    class rectangle:
>>        "represents a rectangle"
>>        width = 0
>>        height = 0
>>        corner = point()
>>    
>>    def move_rectangle(rect, dx, dy):
>>        rect2 = copy.deepcopy(rect)
>>        rect2.corner.x += dx
>>        rect2.corner.y += dy
>>        return rect2
>>    
>>    r1 = rectangle()
>>    r1.width = 20
>>    r1.height = 40
>>    r1.corner.x = 10
>>    r1.corner.y = 10
>>    r2 = move_rectangle(r1,5,2)
>>    print 'Rectangle', r1.width, r1.height
>>    r1.corner.printpoints()
>>    print 'Rectangle 2', r2.width, r2.height
>>    r2.corner.printpoints()
>>     
>
>
>   


From alan.gauld at btinternet.com  Sat Jan  5 10:09:48 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 5 Jan 2008 09:09:48 -0000
Subject: [Tutor] classes and the deepcopy function
References: <477EEF41.8060102@mrfab.info><18302.61081.906115.143224@euclid.slu.edu>
	<477F3935.3010509@mrfab.info>
Message-ID: <flnhd4$amk$1@ger.gmane.org>


"Michael" <python at mrfab.info> wrote

> Is it normal practice to declare your variables in a class? I notice
> that you don't have to, you can create them as you go, but i thought
> declaring and initialising them in the class would make it easier to
> understand and see what the class is for and should contain.

Its normal to declare them in the definition. Its just that instance
variables go in the init method whereas class variables go in the
class scope and are, as you say, shatred by all instances.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From ricaraoz at gmail.com  Sat Jan  5 11:44:03 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 05 Jan 2008 07:44:03 -0300
Subject: [Tutor] Program review
In-Reply-To: <477EF630.2070808@tds.net>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
Message-ID: <477F5F73.9020305@bigfoot.com>

Thanks everyone for your feedback. I'll correct the code and re-post it.



From bgailer at alum.rpi.edu  Sat Jan  5 16:18:07 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 05 Jan 2008 10:18:07 -0500
Subject: [Tutor] classes and the deepcopy function
In-Reply-To: <477F3935.3010509@mrfab.info>
References: <477EEF41.8060102@mrfab.info>	<18302.61081.906115.143224@euclid.slu.edu>
	<477F3935.3010509@mrfab.info>
Message-ID: <477F9FAF.50004@alum.rpi.edu>

Michael wrote:
> Hi Michael
>
> Thanks for the quick reply, I think I get it. So becuase I did not 
> declare them withing the init method using self they are shared by every 
> object that is created, even completely brand new ones?
>
> Is it normal practice to declare your variables in a class? I notice 
> that you don't have to, you can create them as you go, but i thought 
> declaring and initialising them in the class would make it easier to 
> understand and see what the class is for and should contain.
And now for the rest of the story:

class Foo:
  a = 0
  b = []

f = Foo()
f.a = 3
f.b.append(1)

g = Foo()
g.a = 4
g.b.append(2)

print f.a, g.a # 3 4
print f.b, g.b # [1, 2] [1, 2]

[snip]

From ricaraoz at gmail.com  Sat Jan  5 20:17:48 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 05 Jan 2008 16:17:48 -0300
Subject: [Tutor] Program review
In-Reply-To: <477EF630.2070808@tds.net>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
Message-ID: <477FD7DC.6090600@bigfoot.com>

Ok, here is a corrected new version, I hope.

Kent, the fact that Mensaje.__init__ reads the message configuration is
by design (it's a feature, not a bug ;c) ). The class is meant to be
instantiated for using only once and with only one configuration and one
message so including the configuration in the __init__ method kind of
stresses that fact. What's more, I've been thinking of reading both
files in the __init__ method so that the object is created ready to do
it's intended job. Anyway, I guess it's a matter of personal taste in
this case.

Here's the code :

#!/usr/bin/env python

import time
import smtplib
import email
import ConfigParser
import logging

class Mensaje(object) :
    def __init__(self) :
        cfg = ConfigParser.ConfigParser()
        try :
            cfg.readfp(open('config.cfg'))
        except Exception, e :
            logging.error('No pude leer "config.cfg" : %s', e.strerror)

        self.direcciones = cfg.get('Archivos', 'Direcciones')
        self.excluidas = cfg.get('Archivos', 'Excluir')
        self.cuantos = cfg.getint('Correo', 'MailsPorVez')
        self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos')

        try :
            htmlFile = open(cfg.get('Archivos', 'Mensaje'))
            self.html = htmlFile.read()
            htmlFile.close()
        except Exception, e :
            logging.error('No pude leer "%s" : %s',
                            cfg.get('Archivos', 'Mensaje'),
                            e.strerror)

        self.De = cfg.get('Encabezados', 'De')
        self.Para = ''
        self.Encabezado = cfg.get('Encabezados', 'Encabezado')
        self.ResponderA = cfg.get('Encabezados', 'ResponderA')
        self.Servidor = cfg.get('Correo', 'Servidor')
        self.Usuario = cfg.get('Correo', 'Usuario')
        self.Contra = cfg.get('Correo', 'Contrasenia')

class Correo(object) :
    def __init__(self, mensaje) :
        self.messg = email.MIMEMultipart.MIMEMultipart()
        self.messg['From'] = mensaje.De
        self.messg['To'] = mensaje.Para
        self.messg['Subject'] = mensaje.Encabezado
        self.messg['Reply-To'] = mensaje.ResponderA
        self.messg.preamble = 'This is a multi-part message in MIME format'
        self.messg.attach(email.MIMEText.MIMEText(mensaje.html, 'html'))

        self.Servidor = mensaje.Servidor
        self.Conexion = smtplib.SMTP()
        self.Usuario = mensaje.Usuario
        self.Contra = mensaje.Contra

    def connect(self) :
        try :
            self.Conexion.connect(self.Servidor)
            self.Conexion.set_debuglevel(False)
            self.Conexion.ehlo()
            self.Conexion.starttls()
            self.Conexion.ehlo()
            self.Conexion.login(self.Usuario, self.Contra)
            return True
        except :
            logging.error('No me pude conectar al Servidor')
            return False

    def disconnect(self) :
        self.Conexion.close()

    def enviar(self, addr) :
        self.messg.replace_header('To', addr)
        try :
            self.Conexion.sendmail(self.messg['From'],
                                    self.messg['To'],
                                    self.messg.as_string())
            logging.info('Enviado a : %s', self.messg['To'])
        except SMTPRecipientsRefused :
            logging.error('El destinatario fue rechazado por el servidor')
        except SMTPHeloError :
            logging.error('El servidor no respondio apropiadamente')
        except SMTPSenderRefused :
            logging.error('El From: fue rechazado por el servidor')
        except SMTPDataError :
            logging.error('El servidor respondio con un error desconocido')

def procesar(mensaje):
    try :
        try :
            fIncl = open(mensaje.direcciones)
        except Exception, e :
            logging.error('Error!!! No pude abrir "%s" : %s',
                            mensaje.direcciones,
                            e.strerror)
            raise
        try :
            fExcl = open(mensaje.excluidas)
        except Exception, e :
            logging.error('No pude abrir "%s" : %s',
                            mensaje.excluidas,
                            e.strerror)
            fIncl.close()
            raise
    except : pass
    else :
        mails = enumerate(
                        set(addr.strip() for addr in fIncl)
                        - set(excl.strip() for excl in fExcl))
        fIncl.close()
        fExcl.close()
        miCorreo = Correo(mensaje)
        miCorreo.connect()
        empiezo = time.clock()
        for nro, addr in mails :
            if nro%mensaje.cuantos == 0 and nro > 0 :
                miCorreo.disconnect()
                time.sleep(mensaje.intervalo - (time.clock() - empiezo))
                if not miCorreo.connect() :
                    logging.info('Terminando')
                    return
                empiezo = time.clock()
            miCorreo.enviar(addr)
        miCorreo.disconnect()


if __name__ == '__main__' :
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',

filename=time.strftime('informe-%Y-%m-%d-%H-%M-%S.log'),
                        filemode='w')
    procesar(Mensaje())
--------------------------------------------------------------------------------------------

From zhugekongming51 at hotmail.com  Sat Jan  5 19:45:57 2008
From: zhugekongming51 at hotmail.com (Alvin Tan)
Date: Sat, 5 Jan 2008 18:45:57 +0000
Subject: [Tutor] Create popup image
Message-ID: <BAY117-W29C80514021EC888DD375CAE4D0@phx.gbl>


hi all,
 
 
I am doing a project, something like friend finder. 
 
for example , mobile 1 request the location of mobile 2, then a map will actually display on mobile 1 to show the location of mobile 2. But how can i have the popup image?
 
 
Alvin
_________________________________________________________________
Get your free suite of Windows Live services today!
http://www.get.live.com/wl/all
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080105/c63d591a/attachment.htm 

From kent37 at tds.net  Sat Jan  5 21:08:19 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 05 Jan 2008 15:08:19 -0500
Subject: [Tutor] Program review
In-Reply-To: <477FD7DC.6090600@bigfoot.com>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
Message-ID: <477FE3B3.20703@tds.net>

Ricardo Ar?oz wrote:
> Ok, here is a corrected new version, I hope.
> 
> Kent, the fact that Mensaje.__init__ reads the message configuration is
> by design (it's a feature, not a bug ;c) ).

You misunderstood my suggestion. I would add a method to Mensaje that 
creates the email.MIMEMultipart.MIMEMultipart() currently done by 
Correo.__init__().

Almost every line of Correo.__init__() is reading data from attributes 
of mensaje. This is a code smell called Feature Envy and is a clear sign 
that the code is in the wrong place.

In Mensaje you could have
     def createMessage(self):
         messg = email.MIMEMultipart.MIMEMultipart()
         messg['From'] = self.De
         messg['To'] = self.Para
         messg['Subject'] = self.Encabezado
         messg['Reply-To'] = self.ResponderA
         messg.preamble = 'This is a multi-part message in MIME format'
         messg.attach(email.MIMEText.MIMEText(self.html, 'html'))

Then in Correo.__init__() you would have
         self.messg = mensaje.createMessage()

It doesn't change the functionality but it is a better design.

Kent

From ricaraoz at gmail.com  Sat Jan  5 22:28:21 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 05 Jan 2008 18:28:21 -0300
Subject: [Tutor] Program review
In-Reply-To: <477FE3B3.20703@tds.net>
References: <477EC575.4050607@bigfoot.com>
	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>
	<477FE3B3.20703@tds.net>
Message-ID: <477FF675.1000208@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>> Ok, here is a corrected new version, I hope.
>>
>> Kent, the fact that Mensaje.__init__ reads the message configuration is
>> by design (it's a feature, not a bug ;c) ).
> 
> You misunderstood my suggestion. I would add a method to Mensaje that 
> creates the email.MIMEMultipart.MIMEMultipart() currently done by 
> Correo.__init__().
> 
> Almost every line of Correo.__init__() is reading data from attributes 
> of mensaje. This is a code smell called Feature Envy and is a clear sign 
> that the code is in the wrong place.
> 
> In Mensaje you could have
>      def createMessage(self):
>          messg = email.MIMEMultipart.MIMEMultipart()
>          messg['From'] = self.De
>          messg['To'] = self.Para
>          messg['Subject'] = self.Encabezado
>          messg['Reply-To'] = self.ResponderA
>          messg.preamble = 'This is a multi-part message in MIME format'
>          messg.attach(email.MIMEText.MIMEText(self.html, 'html'))
> 
> Then in Correo.__init__() you would have
>          self.messg = mensaje.createMessage()
> 
> It doesn't change the functionality but it is a better design.
> 

I see, yes it is better, I'll correct it. Thanks


From jeff at san-dc.com  Sat Jan  5 22:58:21 2008
From: jeff at san-dc.com (Jeff Johnson)
Date: Sat, 05 Jan 2008 14:58:21 -0700
Subject: [Tutor] Program review
In-Reply-To: <477FF675.1000208@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<477FE3B3.20703@tds.net>
	<477FF675.1000208@bigfoot.com>
Message-ID: <477FFD7D.10906@san-dc.com>

I would like to "butt" in here and mention that this is some of the most 
useful information I have seen!  I am a programmer of 25 years that is 
new to Python.  This type of back and forth dialog on actual production 
code is extremely useful to learning the language.  I have done this 
with Ed Leafe with Dabo and it has helped a lot.

Keep it up!

Jeff

Jeff Johnson
jeff at san-dc.com
SanDC, Inc.
623-582-0323
Fax 623-869-0675

Ricardo Ar?oz wrote:
> Kent Johnson wrote:
>> Ricardo Ar?oz wrote:
>>> Ok, here is a corrected new version, I hope.
>>>
>>> Kent, the fact that Mensaje.__init__ reads the message configuration is
>>> by design (it's a feature, not a bug ;c) ).
>> You misunderstood my suggestion. I would add a method to Mensaje that 
>> creates the email.MIMEMultipart.MIMEMultipart() currently done by 
>> Correo.__init__().
>>
>> Almost every line of Correo.__init__() is reading data from attributes 
>> of mensaje. This is a code smell called Feature Envy and is a clear sign 
>> that the code is in the wrong place.
>>
>> In Mensaje you could have
>>      def createMessage(self):
>>          messg = email.MIMEMultipart.MIMEMultipart()
>>          messg['From'] = self.De
>>          messg['To'] = self.Para
>>          messg['Subject'] = self.Encabezado
>>          messg['Reply-To'] = self.ResponderA
>>          messg.preamble = 'This is a multi-part message in MIME format'
>>          messg.attach(email.MIMEText.MIMEText(self.html, 'html'))
>>
>> Then in Correo.__init__() you would have
>>          self.messg = mensaje.createMessage()
>>
>> It doesn't change the functionality but it is a better design.
>>
> 
> I see, yes it is better, I'll correct it. Thanks
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

From alan.gauld at btinternet.com  Sun Jan  6 00:15:24 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 5 Jan 2008 23:15:24 -0000
Subject: [Tutor] Create popup image
References: <BAY117-W29C80514021EC888DD375CAE4D0@phx.gbl>
Message-ID: <flp2ul$o6p$1@ger.gmane.org>


"Alvin Tan" <zhugekongming51 at hotmail.com> wrote 

> I am doing a project, something like friend finder. 

Sorry, I don't now it...

> for example , mobile 1 request the location of 
> mobile 2, then a map will actually display on 
> mobile 1 to show the location of mobile 2. 
> But how can i have the popup image?

What platform, OS etc?

Are you using a GIS package forlocations?

Alan G


From jeff at drinktomi.com  Sat Jan  5 23:18:20 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Sat, 5 Jan 2008 17:18:20 -0500
Subject: [Tutor] Program review
In-Reply-To: <477FD7DC.6090600@bigfoot.com>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
Message-ID: <77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>

The procesar function is complicated.   It tries to do several things
that that are better done elsewhere.  It needs to be broken up into
several functions and methods.   This also clarifies and isolates the
exception handling.

> def procesar(mensaje):
>    try :
The enclosing try block isn't needed.  More on this later.
>
>        try :
>            fIncl = open(mensaje.direcciones)
>        except Exception, e :
>            logging.error('Error!!! No pude abrir "%s" : %s',
>                            mensaje.direcciones,
>                            e.strerror)
>            raise

This is one function.  It has the argument filename.
>
>        try :
>            fExcl = open(mensaje.excluidas)
>        except Exception, e :
>            logging.error('No pude abrir "%s" : %s',
>                            mensaje.excluidas,
>                            e.strerror)
>            fIncl.close()
>            raise

This is the same function with a different argument.

>
>    except : pass
>    else :

The outer exception block here does nothing.   If an exception
is raised then the following code won't be executed anyway.

>        mails = enumerate(
>                        set(addr.strip() for addr in fIncl)
>                        - set(excl.strip() for excl in fExcl))
>        fIncl.close()
>        fExcl.close()

This is a method that gets the addresses from the files specified in
mensaje.  It opens the files.  It reads the contents.  It closes the  
files.
It should probably go in mensaje.   You should use try-finally blocks
to close the open files.  (or with blocks in python 2.5)

>       miCorreo = Correo(mensaje)
>        miCorreo.connect()
>        empiezo = time.clock()
>        for nro, addr in mails :
>            if nro%mensaje.cuantos == 0 and nro > 0 :
>                miCorreo.disconnect()
>                time.sleep(mensaje.intervalo - (time.clock() -  
> empiezo))
>                if not miCorreo.connect() :
>                    logging.info('Terminando')
>                    return
>                empiezo = time.clock()
>            miCorreo.enviar(addr)
>        miCorreo.disconnect()

This is the real meat.  Everything before it can be reduced to one line.

-jeff

From varsha.purohit at gmail.com  Sun Jan  6 05:22:57 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 5 Jan 2008 20:22:57 -0800
Subject: [Tutor] [tutor] Pil image related question -- resending message
	without attachments
Message-ID: <c2157c790801052022m5a5dd3f1pa22ce8a47ec96058@mail.gmail.com>

Hello All,
      I am actually working on a project which deals with image processing.
I just used pil function to resize the image into the dimensions i want. i
was able to resize the image but the clarity of the new image is not good.
Can anyone suggest which other functions i should use to improve the
clarity. I am attaching the code and sending the images in the attachment.
Can anyone suggest me how to do it ?

import Image

imageFile = "srk.jpg" #original small image

im1 = Image.open(imageFile)

width = 680
height = 420

im2 = im1.resize((width,height), Image.NEAREST)
im3 = im1.resize ((width,height), Image.BICUBIC)

#images get saved in c drive with jpg extensions
ext = ".jpg"
im2.save("C:/nearest" + ext)
im3.save("C:/Bicubic" + ext)

print "files are saved"



-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080105/eb78722a/attachment-0001.htm 

From python at mrfab.info  Sun Jan  6 11:16:19 2008
From: python at mrfab.info (Michael)
Date: Sun, 06 Jan 2008 18:16:19 +0800
Subject: [Tutor] classes and the deepcopy function
In-Reply-To: <477F9FAF.50004@alum.rpi.edu>
References: <477EEF41.8060102@mrfab.info>	<18302.61081.906115.143224@euclid.slu.edu>
	<477F3935.3010509@mrfab.info> <477F9FAF.50004@alum.rpi.edu>
Message-ID: <4780AA73.70502@mrfab.info>

Okay

Just when I think I am getting it you throw this in. So why does a 
become local to each variable but b seem global?

Michael

bob gailer wrote:
> Michael wrote:
>> Hi Michael
>>
>> Thanks for the quick reply, I think I get it. So becuase I did not 
>> declare them withing the init method using self they are shared by 
>> every object that is created, even completely brand new ones?
>>
>> Is it normal practice to declare your variables in a class? I notice 
>> that you don't have to, you can create them as you go, but i thought 
>> declaring and initialising them in the class would make it easier to 
>> understand and see what the class is for and should contain.
> And now for the rest of the story:
>
> class Foo:
>  a = 0
>  b = []
>
> f = Foo()
> f.a = 3
> f.b.append(1)
>
> g = Foo()
> g.a = 4
> g.b.append(2)
>
> print f.a, g.a # 3 4
> print f.b, g.b # [1, 2] [1, 2]
>
> [snip]
>


From ricaraoz at gmail.com  Sun Jan  6 12:28:42 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 06 Jan 2008 08:28:42 -0300
Subject: [Tutor] Program review
In-Reply-To: <77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
Message-ID: <4780BB6A.5000501@bigfoot.com>

Jeff Younker wrote:
> The procesar function is complicated.   It tries to do several things
> that that are better done elsewhere.  It needs to be broken up into
> several functions and methods.   This also clarifies and isolates the
> exception handling.
> 
>> def procesar(mensaje):
>>    try :
> The enclosing try block isn't needed.  More on this later.
>>
>>        try :
>>            fIncl = open(mensaje.direcciones)
>>        except Exception, e :
>>            logging.error('Error!!! No pude abrir "%s" : %s',
>>                            mensaje.direcciones,
>>                            e.strerror)
>>            raise
> 
> This is one function.  It has the argument filename.
>>
>>        try :
>>            fExcl = open(mensaje.excluidas)
>>        except Exception, e :
>>            logging.error('No pude abrir "%s" : %s',
>>                            mensaje.excluidas,
>>                            e.strerror)
>>            fIncl.close()
>>            raise
> 
> This is the same function with a different argument.
> 
>>
>>    except : pass
>>    else :
> 
> The outer exception block here does nothing.   If an exception
> is raised then the following code won't be executed anyway.
> 
>>        mails = enumerate(
>>                        set(addr.strip() for addr in fIncl)
>>                        - set(excl.strip() for excl in fExcl))
>>        fIncl.close()
>>        fExcl.close()
> 

Maybe it is my poor understanding of exception handling. My intention
here is to open the first file, if error then report in logging and
finish normally, else open the 2nd file, if error then report in logging
close the 1st file and finish normally. If no error then process.


From bgailer at alum.rpi.edu  Sun Jan  6 14:26:12 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 06 Jan 2008 08:26:12 -0500
Subject: [Tutor] classes and the deepcopy function
In-Reply-To: <4780AA73.70502@mrfab.info>
References: <477EEF41.8060102@mrfab.info>	<18302.61081.906115.143224@euclid.slu.edu>	<477F3935.3010509@mrfab.info>
	<477F9FAF.50004@alum.rpi.edu> <4780AA73.70502@mrfab.info>
Message-ID: <4780D6F4.6050507@alum.rpi.edu>

Michael wrote:
> Okay
>
> Just when I think I am getting it you throw this in. 
You're welcome.
> So why does a become local to each variable but b seem global?
>   
A better way to ask that is "why does a become an instance property but 
b remain a class property?"

f.a = 3

This is an assignment statement. It creates a property of the instance. The class property a is ignored.

f.b.append(1)

This is not an assignment. It references a property of the instance that does not exist, so Python goes up the inheritance hierarchy and finds the class property.

HTH



From kent37 at tds.net  Sun Jan  6 14:27:55 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 06 Jan 2008 08:27:55 -0500
Subject: [Tutor] Program review
In-Reply-To: <4780BB6A.5000501@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>
	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
	<4780BB6A.5000501@bigfoot.com>
Message-ID: <4780D75B.1080706@tds.net>

Ricardo Ar?oz wrote:
> Jeff Younker wrote:

>> The enclosing try block isn't needed.  More on this later.

> Maybe it is my poor understanding of exception handling. My intention
> here is to open the first file, if error then report in logging and
> finish normally, else open the 2nd file, if error then report in logging
> close the 1st file and finish normally. If no error then process.

The code is correct for what you want to do. It does seem a bit awkward 
but it's hard to get much better and preserve the logging.

You could use 'return' instead of 'raise' and eliminate the outer try block.

You could put the duplicate code in a function (with raise):
def my_open(f):
     try :
         fIncl = open(f)
     except Exception, e :
         logging.error('Error!!! No pude abrir "%s" : %s',
                         f,
                         e.strerror)
         raise

but you would still need try/except in the calling function:

try :
     fIncl = my_open(mensaje.direcciones)
except:
     return
try :
     fExcl = my_open(mensaje.excluidas)
except:
     fIncl.close()
     return

It is safe to omit the close() in this situation - the file will be 
closed by the OS when the program terminates - so you could use a single 
try block:
try :
     fIncl = my_open(mensaje.direcciones)
     fExcl = my_open(mensaje.excluidas)
except:
     return

That is the only version I can come up with that seems significantly 
simpler than what you wrote.

Kent

From ricaraoz at gmail.com  Sun Jan  6 16:20:15 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 06 Jan 2008 12:20:15 -0300
Subject: [Tutor] Program review
In-Reply-To: <4780D75B.1080706@tds.net>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>
	<4780D75B.1080706@tds.net>
Message-ID: <4780F1AF.7050109@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>> Jeff Younker wrote:
> 
>>> The enclosing try block isn't needed.  More on this later.
> 
>> Maybe it is my poor understanding of exception handling. My intention
>> here is to open the first file, if error then report in logging and
>> finish normally, else open the 2nd file, if error then report in logging
>> close the 1st file and finish normally. If no error then process.
> 
> The code is correct for what you want to do. It does seem a bit awkward 
> but it's hard to get much better and preserve the logging.
> 

Yes, I guessed so.

> You could use 'return' instead of 'raise' and eliminate the outer try block.
> 
> You could put the duplicate code in a function (with raise):
> def my_open(f):
>      try :
>          fIncl = open(f)
>      except Exception, e :
>          logging.error('Error!!! No pude abrir "%s" : %s',
>                          f,
>                          e.strerror)
>          raise
> 
> but you would still need try/except in the calling function:
> 
> try :
>      fIncl = my_open(mensaje.direcciones)
> except:
>      return
> try :
>      fExcl = my_open(mensaje.excluidas)
> except:
>      fIncl.close()
>      return
> 

AND the code would have an added depth that gives me no real benefit,
which is why I chose to do it that way. So long as meaning is not
obscured by complicated or lengthy code I'd rather keep it shallow.


> It is safe to omit the close() in this situation - the file will be 
> closed by the OS when the program terminates - so you could use a single 
> try block:
> try :
>      fIncl = my_open(mensaje.direcciones)
>      fExcl = my_open(mensaje.excluidas)
> except:
>      return

True, I usually prefer to explicitly close the file anyway.

From ricaraoz at gmail.com  Sun Jan  6 17:04:04 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 06 Jan 2008 13:04:04 -0300
Subject: [Tutor] Program review
In-Reply-To: <4780D75B.1080706@tds.net>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>
	<4780D75B.1080706@tds.net>
Message-ID: <4780FBF4.9000800@bigfoot.com>

Ok, new version.
In procesar() I tried getting rid of the outer try block and having
'return' instead of 'raise' in the inner try blocks but I didn't like
the result. I'd rather have one more indent level but have only one exit
point from the function.
Redesigned class Mensaje so that it now includes a MIME message, I think
it simplifies the code and less attributes are going around, now
Correo.__init__() is simpler.
I was tempted to put 'messg = self.mensage.messg' as the first line of
Correo.enviar() so as to shorten things like
self.mensaje.messg.replace_header('To', addr) to
messg.replace_header('To', addr) but I didn't like it, I'd rather stress
the fact that 'messg' belongs to Correo's attribute 'mensaje'.

Here's the code (untested):

#!/usr/bin/env python

import time
import smtplib
import email
import ConfigParser
import logging

class Mensaje(object) :
    def __init__(self) :
        cfg = ConfigParser.ConfigParser()
        try :
            cfg.readfp(open('config.cfg'))
        except Exception, e :
            logging.error('No pude leer "config.cfg" : %s', e.strerror)

        self.direcciones = cfg.get('Archivos', 'Direcciones')
        self.excluidas = cfg.get('Archivos', 'Excluir')
        self.cuantos = cfg.getint('Correo', 'MailsPorVez')
        self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos')

        try :
            htmlFile = open(cfg.get('Archivos', 'Mensaje'))
            self.html = htmlFile.read()
            htmlFile.close()
        except Exception, e :
            logging.error('No pude leer "%s" : %s',
                            cfg.get('Archivos', 'Mensaje'),
                            e.strerror)

        self.messg = email.MIMEMultipart.MIMEMultipart()
        self.messg['From'] = cfg.get('Encabezados', 'De')
        self.messg['To'] = ''
        self.messg['Subject'] = cfg.get('Encabezados', 'Encabezado')
        self.messg['Reply-To'] = cfg.get('Encabezados', 'ResponderA')
        self.messg.preamble = 'This is a multi-part message in MIME format'
        self.messg.attach(email.MIMEText.MIMEText(mensaje.html, 'html'))

        self.Servidor = cfg.get('Correo', 'Servidor')
        self.Usuario = cfg.get('Correo', 'Usuario')
        self.Contra = cfg.get('Correo', 'Contrasenia')

class Correo(object) :
    def __init__(self, mensaje) :
        self.mensaje = mensaje
        self.conexion = smtplib.SMTP()

    def connect(self) :
        try :
            self.Conexion.connect(self.mensaje.servidor)
            self.Conexion.set_debuglevel(False)
            self.Conexion.ehlo()
            self.Conexion.starttls()
            self.Conexion.ehlo()
            self.Conexion.login(self.mensaje.usuario, self.mensaje.contra)
            return True
        except :
            logging.error('No me pude conectar al Servidor')
            return False

    def disconnect(self) :
        self.Conexion.close()

    def enviar(self, addr) :
        self.mensaje.messg.replace_header('To', addr)
        try :
            self.Conexion.sendmail(self.mensaje.messg['From'],
                                    self.mensaje.messg['To'],
                                    self.mensaje.messg.as_string())
            logging.info('Enviado a : %s', self.mensaje.messg['To'])
        except SMTPRecipientsRefused :
            logging.error('El destinatario fue rechazado por el servidor')
        except SMTPHeloError :
            logging.error('El servidor no respondio apropiadamente')
        except SMTPSenderRefused :
            logging.error('El From: fue rechazado por el servidor')
        except SMTPDataError :
            logging.error('El servidor respondio con un error desconocido')

def procesar(mensaje):
    try :
        try :
            fIncl = open(mensaje.direcciones)
        except Exception, e :
            logging.error('Error!!! No pude abrir "%s" : %s',
                            mensaje.direcciones,
                            e.strerror)
            raise
        try :
            fExcl = open(mensaje.excluidas)
        except Exception, e :
            logging.error('No pude abrir "%s" : %s',
                            mensaje.excluidas,
                            e.strerror)
            fIncl.close()
            raise
    except : pass
    else :
        mails = enumerate(
                        set(addr.strip() for addr in fIncl)
                        - set(excl.strip() for excl in fExcl))
        fIncl.close()
        fExcl.close()
        miCorreo = Correo(mensaje)
        miCorreo.connect()
        empiezo = time.clock()
        for nro, addr in mails :
            if nro%mensaje.cuantos == 0 and nro > 0 :
                miCorreo.disconnect()
                time.sleep(mensaje.intervalo - (time.clock() - empiezo))
                if not miCorreo.connect() :
                    logging.info('Terminando')
                    return
                empiezo = time.clock()
            miCorreo.enviar(addr)
        miCorreo.disconnect()


if __name__ == '__main__' :
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',

filename=time.strftime('informe-%Y-%m-%d-%H-%M-%S.log'),
                        filemode='w')
    procesar(Mensaje())

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

From ricaraoz at gmail.com  Sun Jan  6 17:08:15 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 06 Jan 2008 13:08:15 -0300
Subject: [Tutor] Program review
In-Reply-To: <477FFD7D.10906@san-dc.com>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<477FE3B3.20703@tds.net>	<477FF675.1000208@bigfoot.com>
	<477FFD7D.10906@san-dc.com>
Message-ID: <4780FCEF.9090904@bigfoot.com>

Jeff Johnson wrote:
> I would like to "butt" in here and mention that this is some of the most 
> useful information I have seen!  I am a programmer of 25 years that is 
> new to Python.  This type of back and forth dialog on actual production 
> code is extremely useful to learning the language.  I have done this 
> with Ed Leafe with Dabo and it has helped a lot.
> 
> Keep it up!
> 
> Jeff
> 

Guys, I really learned with this exercise (and my code was improved). I
got to think how good it would be to have one or two ongoing small
projects where we contribute code and the code is criticized and
enhanced by our community. We could agree on a subject, someone could
volunteer to give it a try (if the subject is big enough then many could
volunteer with different parts of the whole) then post the code so that
it can be viewed and reviewed by the rest. We could learn a lot and we
might end up with some useful pieces of code.
What do you think?

Ricardo

From dos.fool at gmail.com  Sun Jan  6 19:45:13 2008
From: dos.fool at gmail.com (max baseman)
Date: Sun, 6 Jan 2008 11:45:13 -0700
Subject: [Tutor] locating python scripts
Message-ID: <5EFD9A6B-D422-4B38-95F9-0C84933C767F@gmail.com>

hey i just have a small question, doesn't have much to do with  
programing but it has to do with python.
anyways Im running a apple computer  version 10.4 and have been  
keeping my scripts in the user folder i was wondering where and how i  
can change the files that python looks in when looking for programs i  
would like to make it so that i can have separate folders in the user  
folder for different projects
any help would be great
thanks 
   

From ricaraoz at gmail.com  Sun Jan  6 22:07:36 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 06 Jan 2008 18:07:36 -0300
Subject: [Tutor] Program review
In-Reply-To: <4780D75B.1080706@tds.net>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>
	<4780D75B.1080706@tds.net>
Message-ID: <47814318.6030209@bigfoot.com>

Ok, now the "tested" version (has been corrected) :

#!/usr/bin/env python

import time
import smtplib
import email
import ConfigParser
import logging

class Mensaje(object) :
    def __init__(self) :
        cfg = ConfigParser.ConfigParser()
        try :
            cfg.readfp(open('config.cfg'))
        except Exception, e :
            logging.error('No pude leer "config.cfg" : %s', e.strerror)

        self.direcciones = cfg.get('Archivos', 'Direcciones')
        self.excluidas = cfg.get('Archivos', 'Excluir')
        self.cuantos = cfg.getint('Correo', 'MailsPorVez')
        self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos')

        try :
            htmlFile = open(cfg.get('Archivos', 'Mensaje'))
            htmlMessage = htmlFile.read()
            htmlFile.close()
        except Exception, e :
            logging.error('No pude leer "%s" : %s',
                            cfg.get('Archivos', 'Mensaje'),
                            e.strerror)

        self.messg = email.MIMEMultipart.MIMEMultipart()
        self.messg['From'] = cfg.get('Encabezados', 'De')
        self.messg['To'] = ''
        self.messg['Subject'] = cfg.get('Encabezados', 'Encabezado')
        self.messg['Reply-To'] = cfg.get('Encabezados', 'ResponderA')
        self.messg.preamble = 'This is a multi-part message in MIME format'
        self.messg.attach(email.MIMEText.MIMEText(htmlMessage, 'html'))

        self.servidor = cfg.get('Correo', 'Servidor')
        self.usuario = cfg.get('Correo', 'Usuario')
        self.contra = cfg.get('Correo', 'Contrasenia')

class Correo(object) :
    def __init__(self, mensaje) :
        self.mensaje = mensaje
        self.conexion = smtplib.SMTP()

    def connect(self) :
        try :
            self.conexion.connect(self.mensaje.servidor)
            self.conexion.set_debuglevel(False)
            self.conexion.ehlo()
            self.conexion.starttls()
            self.conexion.ehlo()
            self.conexion.login(self.mensaje.usuario, self.mensaje.contra)
            return True
        except :
            logging.error('No me pude conectar al Servidor')
            return False

    def disconnect(self) :
        self.conexion.close()

    def enviar(self, addr) :
        self.mensaje.messg.replace_header('To', addr)
        try :
            self.conexion.sendmail(self.mensaje.messg['From'],
                                    self.mensaje.messg['To'],
                                    self.mensaje.messg.as_string())
            logging.info('Enviado a : %s', self.mensaje.messg['To'])
        except smtplib.SMTPRecipientsRefused :
            logging.error('El destinatario fue rechazado por el servidor')
        except smtplib.SMTPHeloError :
            logging.error('El servidor no respondio apropiadamente')
        except smtplib.SMTPSenderRefused :
            logging.error('El From: fue rechazado por el servidor')
        except smtplib.SMTPDataError :
            logging.error('El servidor respondio con un error desconocido')

def procesar(mensaje):
    try :
        try :
            fIncl = open(mensaje.direcciones)
        except Exception, e :
            logging.error('Error!!! No pude abrir "%s" : %s',
                            mensaje.direcciones,
                            e.strerror)
            raise
        try :
            fExcl = open(mensaje.excluidas)
        except Exception, e :
            logging.error('No pude abrir "%s" : %s',
                            mensaje.excluidas,
                            e.strerror)
            fIncl.close()
            raise
    except : pass
    else :
        mails = enumerate(
                        set(addr.strip() for addr in fIncl)
                        - set(excl.strip() for excl in fExcl))
        fIncl.close()
        fExcl.close()
        miCorreo = Correo(mensaje)
        if miCorreo.connect() :
            empiezo = time.clock()
            for nro, addr in mails :
                if nro%mensaje.cuantos == 0 and nro > 0 :
                    miCorreo.disconnect()
                    time.sleep(mensaje.intervalo - (time.clock() - empiezo))
                    if not miCorreo.connect() :
                        logging.info('Terminando')
                        return
                    empiezo = time.clock()
                miCorreo.enviar(addr)
            miCorreo.disconnect()


if __name__ == '__main__' :
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',

filename=time.strftime('informe-%Y-%m-%d-%H-%M-%S.log'),
                        filemode='w')
    procesar(Mensaje())

From brendan.rankin at gmail.com  Sun Jan  6 22:25:38 2008
From: brendan.rankin at gmail.com (Brendan Rankin)
Date: Sun, 6 Jan 2008 21:25:38 +0000 (UTC)
Subject: [Tutor] locating python scripts
References: <5EFD9A6B-D422-4B38-95F9-0C84933C767F@gmail.com>
Message-ID: <loom.20080106T212320-155@post.gmane.org>

max baseman <dos.fool <at> gmail.com> writes:

> 
> hey i just have a small question, doesn't have much to do with  
> programing but it has to do with python.
> anyways Im running a apple computer  version 10.4 and have been  
> keeping my scripts in the user folder i was wondering where and how i  
> can change the files that python looks in when looking for programs i  
> would like to make it so that i can have separate folders in the user  
> folder for different projects
> any help would be great
> thanks 
> 
> _______________________________________________
> Tutor maillist  -  Tutor <at> python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

I've always just added paths to the PYTHONPATH environment variable.  It's value
is now:

/home/brendan/scripts/Python:/home/brendan/lib/python:.

This is on Linux, but I don't see why it shouldn't work identically on OSX.

Cheers,

- Brendan



From jeff at drinktomi.com  Mon Jan  7 04:32:43 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Sun, 6 Jan 2008 22:32:43 -0500
Subject: [Tutor] Program review
In-Reply-To: <4780BB6A.5000501@bigfoot.com>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
	<4780BB6A.5000501@bigfoot.com>
Message-ID: <5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>

>
> Maybe it is my poor understanding of exception handling. My intention
> here is to open the first file, if error then report in logging and
> finish normally, else open the 2nd file, if error then report in  
> logging
> close the 1st file and finish normally. If no error then process.
>

Right, but it helps to break up the error handling and the cleanup.
Right now the error reporting exception handlers are intermixed
with your cleanup error handlers.  Separating them makes the code
clearer.

def open_file(filename):
      try :
          return open(filename)
      except Exception:
          logging.error('No pude abrir "%s"' % filename, exec_info=True)
          raise

# Goes into configuration class
def mails(self):
   fIncl = open_file(self.direcciones)
   try:
      fExcl = open_file(self.excluidas)
      try:
          return enumerate(
                      set(addr.strip() for addr in fIncl)
                      - set(excl.strip() for excl in fExcl))
      finally:
           fExcl.close()
   finally:
        fIncl.close()

Or if you're using python 2.5 then you can use with statements:

from __future__ import with_statements
from contextlib import closing
...
def mails(self):
     with closing(open_file(self.direcciones)) as fIncl:
            with closing(open_file(self.excluidas)) as fExcl:
                return enumerate(
                        set(addr.strip() for addr in fIncl)
                        - set(excl.strip() for excl in fExcl))

> close the 1st file and finish normally. If no error then process.

If an exception is raised then the code terminates right there and
then.   So, if procesar is written as:

def procesar(mensaje):
      mails = mensaje.mails()
      miCorreo = Correo(mensaje)
      ....

then if mensaje.mails() raises an exception then the code
terminates immediately, and the body of Correo will only be
executed if there is no error.

As you have it written it terminates, but it also silently consumes the
exception.  If something goes wrong with your program then there is
no way of diagnosing the problem because the failure cause is never
reported.

-jeff

From kent37 at tds.net  Mon Jan  7 12:45:07 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 06:45:07 -0500
Subject: [Tutor] Program review
In-Reply-To: <5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
References: <477EC575.4050607@bigfoot.com> <477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
	<4780BB6A.5000501@bigfoot.com>
	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
Message-ID: <478210C3.2080203@tds.net>

Jeff Younker wrote:

> Or if you're using python 2.5 then you can use with statements:
> 
> from __future__ import with_statements
> from contextlib import closing
> ...
> def mails(self):
>     with closing(open_file(self.direcciones)) as fIncl:
>            with closing(open_file(self.excluidas)) as fExcl:

closing() is not needed, this can be written as
     with open_file(self.direcciones) as fIncl:
            with open_file(self.excluidas) as fExcl:

because open files are context managers.
Or,
from contextlib import nested
     with nested(open_file(self.direcciones), open_file(self.excluidas)) 
as (fIncl, fExcl):

> As you have it written it terminates, but it also silently consumes the
> exception.  If something goes wrong with your program then there is
> no way of diagnosing the problem because the failure cause is never
> reported.

The exception is written to the log. He may not want the traceback 
printed to the console.

Kent

From shumail_siddiqui at yahoo.com  Mon Jan  7 08:08:09 2008
From: shumail_siddiqui at yahoo.com (Shumail Siddiqui)
Date: Sun, 6 Jan 2008 23:08:09 -0800 (PST)
Subject: [Tutor] Urgent: Help
Message-ID: <63097.38727.qm@web50608.mail.re2.yahoo.com>

Dear tutor, 
       I have a question regarding a functions based assignment. The assignment is:
  For this project, you will write two small Python programs: 
  
    
   Investment Thresholds   
    
      Define a Python function threshold(dailyGains, goal) that behaves as follows. The first parameter is a list of integers that represent the daily gains in the value of a stock. The second paramter is a single positive number that is a profit goal. The function should return the minimum number of days for which the stock should be owned in order to achieve a profit that is equal to or greater than the stated goal. If the goal is unreachable, the function should return 0.   
For example,   
threshold ([5, 3, 8, 2, 9, 1], 17)   
should return 4 because the goal (17) can be reached after the first four days (e.g., 5 + 3 + 8 + 2).   
  
      Write a small Python program that uses your threshold() function to demonstrate that it works correctly. Your program may use a pre-defined list of stock gains or it may generate one randomly (see the "Helpful Hints" section below for tips on how to do this). Your program should display this list, prompt the user to enter a profit goal, and then print out the total number of days required to reach that goal (or a message stating that the goal is impossible).   

  
  
   Word Windows   
    
      Define a Python function sliding(word, num) that behaves as follows. It should print out each num-length slice of the original word , aligned vertically as shown below.   
For example, a call to sliding("examples", 4) should produce the output   

exam   xamp    ampl     mple      ples      
  
  
      Write a small Python program to demonstrate that your sliding() function works correctly. Your program should prompt the user to enter a word and a window size, and then call sliding() with those values.   


  
  Helpful Hints      
   Python contains a set of facilities to handle random number generation. Full details are available at http://docs.python.org/lib/module-random.html. A quick summary is as follows:   
    
      Add the statement   
import random   
at the beginning of your program source code. This tells Python where to find the code that describes how to generate random values.   
  
      Pass your list of values to the random.choice() function. The function will return a single randomly-selected element from that list.   
For example, random.choice(range(5)) will return a random value in the range 0-4.   
Please note that "random" does not necessarily mean "unique"; sequential calls to this function may return the same answer, because it is randomly chosen each time! 

    
  This is what I have so far:
   
  import random
dailyGains = int(random.range(6))
goal = random.choice(range(4)
result = []
def threshold(dailyGains, goal):
  if goal!= result: 0
  else:
    result.reverse()
    result.remove()
   
  As you can see I am having a great problem.


       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080106/e77f756b/attachment.htm 

From alan.gauld at btinternet.com  Mon Jan  7 16:17:56 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 7 Jan 2008 15:17:56 -0000
Subject: [Tutor] Urgent: Help
References: <63097.38727.qm@web50608.mail.re2.yahoo.com>
Message-ID: <fltfne$kao$1@ger.gmane.org>

"Shumail Siddiqui" <shumail_siddiqui at yahoo.com> wrote

>       I have a question regarding a functions based assignment. The 
> assignment is:
>  For this project, you will write two small Python programs:
>

OK, Since this is for homework I cannot give you the answers
but I will point out some things you shouild look at and an approach.


>   Investment Thresholds
>
>      Define a Python function threshold(dailyGains, goal) that 
> behaves as follows.

First define the function and test it using the >>> prompt.

>      Write a small Python program that uses your threshold() 
> function
> to demonstrate that it works correctly. Your program may use a
> pre-defined list of stock gains or it may generate one randomly

Use a predefined list initially, it's easier!
Only once that works try introducing random elements.

>   Word Windows

One problem at a time...

>  This is what I have so far:
>
>  import random
> dailyGains = int(random.range(6))
> goal = random.choice(range(4)

missing parenthesis, I assume a typo?

> result = []
> def threshold(dailyGains, goal):
>  if goal!= result: 0
>  else:
>    result.reverse()
>    result.remove()

you need to investigate the return statement in functions.

However I don;t understand how you think this will
achieve anything like what the original specification
asked for. You need to use the dailyGains list
somewhere... And why you are checking against
result I don't know.

Can you describe in English what the function should
do and how you would go about it manually using
pen and paper? Can you translate that process to
Python?

>  As you can see I am having a great problem.

It looks like the normal learning process to me :-)
Just take your time, solve one bit at a time and
build on your previous work. If you get stuck come
back here and ask specific questions and show
us what you have done.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From bgailer at alum.rpi.edu  Mon Jan  7 17:40:35 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 07 Jan 2008 11:40:35 -0500
Subject: [Tutor] Urgent: Help
In-Reply-To: <63097.38727.qm@web50608.mail.re2.yahoo.com>
References: <63097.38727.qm@web50608.mail.re2.yahoo.com>
Message-ID: <47825603.8070903@alum.rpi.edu>

Shumail Siddiqui wrote:
> Dear tutor,
>      I have a question regarding a functions based assignment.
I agree with Alan.

And I wonder why this assignment is hard for you.

Are you in the wrong course (insufficient prerequisites)?

Is the instructor failing to provide the resources you need?

Are you overwhelmed with life and struggling to get through?

Or do you just want to get a passing grade and don't care about learning 
programming and Python?

It might help us if we understood why you are seeking help.

Bob



From jnewton at fuelindustries.com  Mon Jan  7 21:07:06 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Mon, 7 Jan 2008 15:07:06 -0500
Subject: [Tutor] Scope and elegance
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD2401083EDA@ex1.Fuel.Ott>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>

Hi Python Practicioners!

I'm trying to come to terms with how Python handles the scope of
objects.  In particular, I'd like to create an instance of one class and
make it available inside instances of other classes.  Something like:


# Test 1-------------------------------------
# I want a "global" instance of this class...
class Foo(object):
    def doFoo(self):
        return "foo"


# So that I can call one of its functions from another instance 
class Bar(object):
    def doBar(self):
        # I'd like be able to call a "global" object, but this fails:
        # global name 'foo_instance' is not defined
	  return foo_instance.doFoo()
    

def main():
    foo_instance = Foo()
    bar_instance = Bar()
    print bar_instance.doBar()


if __name__ == '__main__': main()
# --------------------------------------------


I know that I can pass a pointer to foo_instance as a parameter to the
Bar() call.  For example, this will work:


# Test 2 -------------------------------------
class Foo(object):
    def doFoo(self):
        return "foo"



class Bar(object):
    def doBar(self, aFooInstance):
         return aFooInstance.doFoo()
    

def main():
    foo_instance = Foo()
    bar_instance = Bar()
    print bar_instance.doBar(foo_instance)


if __name__ == '__main__': main()
# --------------------------------------------


I know that I can also create a global instance outside the main()
function.  This will also work:


# Test 3 -------------------------------------
class Foo(object):
    def doFoo(self):
        return "foo"


class Bar(object):
    def doBar(self):
         return foo_instance.doFoo()

    
foo_instance = Foo()


def main():
    bar_instance = Bar()
    print bar_instance.doBar()


if __name__ == '__main__': main()
# --------------------------------------------


However, this assumes that the Foo instance() is independent of anything
that needs to be done inside the main() function. 


To put the question in context: in the Snakes and Ladders game that I am
making, I have a board divided into 100 squares.  I want a Counter
instance to know which position on the Board it should move to.  I may
have several Counter instances, but only one Board instance.  Each
Counter knows the index number of the square it should move to.  The
Board instance knows how to convert that index number into a screen
position.  I want the Counter instances to be able to ask the Board
instance for that screen position.


Is it unPythonic of me to:
a) Want to create the Board instance inside the main() function
AND
b) Want the Board instance to be globally available so that
   Counters and other objects can talk to it directly?

Or is there just a declaration that I have overlooked that can make an
instance created inside a function visible inside any instance?


I am not so much concerned in getting this to work (I can already do
that); I am more concerned with understanding how to treat this in the
most Pythonesque way.


Thanks in advance for your insights,

James 

From kent37 at tds.net  Mon Jan  7 21:30:52 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 15:30:52 -0500
Subject: [Tutor] Scope and elegance
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <47828BFC.2010600@tds.net>

James Newton wrote:

> # So that I can call one of its functions from another instance 
> class Bar(object):
>     def doBar(self):
>         # I'd like be able to call a "global" object, but this fails:
>         # global name 'foo_instance' is not defined
> 	  return foo_instance.doFoo()

It fails because foo_instance is not a global; it is a local variable in 
the main() function. main() is a function too!

> def main():
       global foo_instance # This will do what you want
>     foo_instance = Foo()
>     bar_instance = Bar()
>     print bar_instance.doBar()


> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.

In general I would say that is a better design; I'm not generally a fan 
of globals.

> To put the question in context: in the Snakes and Ladders game that I am
> making, I have a board divided into 100 squares.  I want a Counter
> instance to know which position on the Board it should move to.  I may
> have several Counter instances, but only one Board instance.  Each
> Counter knows the index number of the square it should move to.  The
> Board instance knows how to convert that index number into a screen
> position.  I want the Counter instances to be able to ask the Board
> instance for that screen position.

Hmm. Why does a Counter need to know about screen position? It sounds 
like the Counter might be doing too much. Maybe the Counters should be 
attributes of the Board which can ask them their index numbers and do 
the appropriate drawing? Maybe the code that is drawing the counter 
should ask the Board where to draw it? I can't tell for sure but it 
sounds like your design might be inside out.

> Is it unPythonic of me to:
> a) Want to create the Board instance inside the main() function

That's OK

> b) Want the Board instance to be globally available so that
>    Counters and other objects can talk to it directly?

In general, globals are a bad idea in any language, not just Python.

> Or is there just a declaration that I have overlooked that can make an
> instance created inside a function visible inside any instance?

See above.

Kent

From marc.tompkins at gmail.com  Mon Jan  7 21:37:17 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 7 Jan 2008 12:37:17 -0800
Subject: [Tutor] Scope and elegance
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD2401083EDA@ex1.Fuel.Ott>
	<1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <40af687b0801071237ra5a7a1en6375396321a80263@mail.gmail.com>

On Jan 7, 2008 12:07 PM, James Newton <jnewton at fuelindustries.com> wrote:

> Hi Python Practicioners!
> ...
> I am not so much concerned in getting this to work (I can already do
> that); I am more concerned with understanding how to treat this in the
> most Pythonesque way.
>

I'd like to get the party line on this as well.  For a while now, I've made
a habit of defining an empty class called Global (Mr. Newton's could be
called Board, of course) at the top of my apps, and using its attributes as
if they were global variables.  It works, of course, but it feels a bit...
dirty.  Is there a more orthodox way to handle it?  Of course, it would be
optimal to remove any need for globals...

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080107/7e98ad92/attachment-0001.htm 

From gslindstrom at gmail.com  Mon Jan  7 21:51:07 2008
From: gslindstrom at gmail.com (Greg Lindstrom)
Date: Mon, 7 Jan 2008 14:51:07 -0600
Subject: [Tutor] Tutorials at PyCon 2008 (US)
Message-ID: <a9f39a410801071251r42a862e1p58e6e65e782d8571@mail.gmail.com>

Hello Everyone-

I'd like to announce the tutorials sessions for PyCon 2008 (US).  As you may
know, this year PyCon is being held in Chicago, Illinois March 14-16 with
the Thursday before (the 13th) being "Tutorial Thursday".  We are expecting
nearly 600 Python enthusiasts to meet up for the conference and have 29
tutorial sessions scheduled on Thursday in three sessions; morning,
afternoon, and evening.  There is an extra fee to attend a tutorial, but the
sessions are 3 hours long (with a break) and are taught by some of the
smartest cookies in the Python community.  Pop on over to
http://us.pycon.org/2008/about/ for more information

Here's a list of the sessions currently offered (we may cancel a session if
there are fewer than 10 people registered, but that doesn't happen very
often). In particular, note that there are 4 different introduction to
Python tutorials aimed at different audiences.

*Morning Session* (9:00am-12:20pm)

   - Eggs and Buildout Deployment in
Python<http://us.pycon.org/2008/tutorials/EggsRush/>(Jeff Rush)
   - Python 101 for
Programmers<http://us.pycon.org/2008/tutorials/Python101Holden/>(Steve
Holden)
   - Introduction to
SQLAlchemy<http://us.pycon.org/2008/tutorials/SQLAlechemyIEllis/>(Jonathan
Ellis and and Michael Baye)
   - Python plotting with matplotlib and
pylab<http://us.pycon.org/2008/tutorials/MatLabHunter/>(John Hunter)
   - SWIG Master Class
<http://us.pycon.org/2008/tutorials/SwigBeazley/>(David Beazley)
   - Secrets of the Framework
Creators<http://us.pycon.org/2008/tutorials/FrameworksHsu/>(Feihong
Hsu)
   - Introduction to
NumPy<http://us.pycon.org/2008/tutorials/NumPyJones/>(Travis Oliphant
and Eric Jones)
   - Making Small Software for Small People, Sugar/OLPC Coding by
Example<http://us.pycon.org/2008/tutorials/SugarFletcher/>(Mike C.
Fletcher)
   - Hands-on Python for the Absolute Beginner
I<http://us.pycon.org/2008/tutorials/Python101AHarrington/>(Dr. Andrew
Harrington)

*Afternoon Session* (1:20pm-4:40pm)

   - Python 101
<http://us.pycon.org/2008/tutorials/Python101Williams/>(Stuart
Williams)
   - Getting Started with Pylons/TurboGears2 & WSGI: Modern Python Web
   Development <http://us.pycon.org/2008/tutorials/TurboGearsI/> (Mark
   Ramm and Ben Bangert)
   - Advanced SQLAlchemy<http://us.pycon.org/2008/tutorials/SQLAlechemyIIEllis/>(Jonathan
Ellis and and Michael Baye)
   - Django Tutorial
<http://us.pycon.org/2008/tutorials/DjangoMoss>(Jacob Kaplan-Moss)
   - wxPython I: Intro to GUI Programming with wxPython and
MVC<http://us.pycon.org/2008/tutorials/wxPythonIGoodger/>(David
Goodger)
   - Faster Python Programs through Optimization and Extensions
I<http://us.pycon.org/2008/tutorials/PerformatnceIMuller/>(Mike
M?ller)
   - Tools for Scientific Computing in
Python<http://us.pycon.org/2008/tutorials/SciComputing/>(Travis
Oliphant and Eric Jones)
   - Generator Tricks for Systems
Programmers<http://us.pycon.org/2008/tutorials/Generators/>(David
Beazley)
   - Basic Python for Java
Programmers<http://us.pycon.org/2008/tutorials/Python101Martelli/>(Alex
Martelli and Anna Ravenscroft)
   - Hands-on Python for the Absolute Beginner
II<http://us.pycon.org/2008/tutorials/Python101AHarrington/>(Dr.
Andrew Harrington)

*Evening Session* (6:10pm-9:30pm)

   - Python 102
<http://us.pycon.org/2008/tutorials/Python102Williams/>(Stuart
Williams)
   - Mastering Pylons and TurboGears 2: Moving Beyond the
Basics.<http://us.pycon.org/2008/tutorials/TurboGearsII/>(Mark Ramm,
Ben Bangert)
   - Practical Applications of Agile (Web) Testing
Tools<http://us.pycon.org/2008/tutorials/AgileWebTesing/>(C. Titus
Brown and Grig Gheorghiu)
   - Django Code Lab
<http://us.pycon.org/2008/tutorials/DjangoLab/>(Jacob Kaplan-Moss,
Adrian Holovaty and James Bennett)
   - wxPython II: Advanced GUI Programming with wxPython and
MVC<http://us.pycon.org/2008/tutorials/wxPythonIIGoodger/>(David
Goodger)
   - Faster Python Programs through Optimization and Extensions
II<http://us.pycon.org/2008/tutorials/PerformatnceIIMuller/>(Mike
M?ller)
   - Automating Windows Applications with
win32com<http://us.pycon.org/2008/tutorials/AutomatingWindows/>(Roy H.
Han)
   - Internet Programming with
Python<http://us.pycon.org/2008/tutorials/InternetProgamming/>(Wesley
J. Chun)
   - Tail Wags Fangs: What Python Developers Should Know About
Plone<http://us.pycon.org/2008/tutorials/Plone/>(Rob Lineberger)
   - Pygame: Modern game
development<http://us.pycon.org/2008/tutorials/PyGame/>(Noah
Kantrowitz and Marc Destefano)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080107/267013b8/attachment.htm 

From jnewton at fuelindustries.com  Mon Jan  7 21:56:37 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Mon, 7 Jan 2008 15:56:37 -0500
Subject: [Tutor] Scope and elegance
In-Reply-To: <47828BFC.2010600@tds.net>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8593@ex1.Fuel.Ott>

Kent Johnson [mailto:kent37 at tds.net] wrote:
> Why does a Counter need to know about screen position?
> It sounds like the Counter might be doing too much.
> Maybe the Counters should be attributes of the Board
> which can ask them their index numbers and do the
> appropriate drawing?
> Maybe the code that is drawing the counter should ask
> the Board where to draw it? I can't tell for sure but
> it sounds like your design might be inside out.

Hi Kent,

Thanks for your reply.  It has encouraged me to think in new directions.

James 

From shlomme at gmx.net  Mon Jan  7 21:58:19 2008
From: shlomme at gmx.net (Torsten Marek)
Date: Mon, 07 Jan 2008 21:58:19 +0100
Subject: [Tutor] Scope and elegance
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <1199739499.22529.9.camel@ansatz>

Hi,

I'll try to swallow down the "Globals are eevil" comment, there's enough
literature on that already.

Maybe I'm spoiled from programming too much Java in the last year, but
IMHO it's a good idea to put the singleton instance into the class
itself rather than into some module.

This way, you (can) make sure that all accesses to the class really go
to the same instance. 

There are, of course, many ways to do that, but I'd prefer a method on
the class:

class Foo(object):
    @classmethod
    def instance(cls):
        try:
           return cls._inst
        except AttributeError:
           cls._inst = Foo()
           return cls._inst
            
You can also make more advanced singletons with overwriting __new__ etc,
but that probably overdoes it for the case at hand.

> Is it unPythonic of me to:
> a) Want to create the Board instance inside the main() function
> AND
No.
> b) Want the Board instance to be globally available so that
>    Counters and other objects can talk to it directly?
Yes.

> 
> I am not so much concerned in getting this to work (I can already do
> that); I am more concerned with understanding how to treat this in the
> most Pythonesque way.
> 
IMHO it would be better to hand in the board instance into the counter
instances. Globals add hidden dependencies, make code harder to test
etcetc. (Swallowing down didn't work ;-)


best regards,

Torsten
-- 
Torsten Marek <shlomme at gmx.net>
ID: A244C858 -- FP: 1902 0002 5DFC 856B F146  894C 7CC5 451E A244 C858
Keyserver: subkeys.pgp.net

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080107/ae73728d/attachment.pgp 

From goldwamh at slu.edu  Mon Jan  7 22:08:43 2008
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Mon, 7 Jan 2008 15:08:43 -0600
Subject: [Tutor]  Urgent: Help
In-Reply-To: <63097.38727.qm@web50608.mail.re2.yahoo.com>
References: <63097.38727.qm@web50608.mail.re2.yahoo.com>
Message-ID: <18306.38107.75743.473027@euclid.slu.edu>


Very good questions indeed.  Also familiar ones to me. The first is
Exercise 5.28 and the second is Exercise 5.23 from the text book
"Object-Oriented Programming in Python."

Alan's advice was very sound, but I strongly recommend that you work
with your instructor in guiding you through these problems.  He or she
is best qualified to know your current level and the context for such
a homework assignment. Of course, reading the book is also likely to
help.

For everyone else, if you like these exercises there are 300 more
where they came from.  ;-)

With regard,
Michael

       +-----------------------------------------------
       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007



On Sunday January 6, 2008, Shumail Siddiqui wrote: 

>       Investment Thresholds   
>        
>          Define a Python function threshold(dailyGains, goal) that behaves as follows. The first parameter is a list of integers that represent the daily gains in the value of a stock. The second paramter is a single positive number that is a profit goal. The function should return the minimum number of days for which the stock should be owned in order to achieve a profit that is equal to or greater than the stated goal. If the goal is unreachable, the function should return 0.   
>    For example,   
>    threshold ([5, 3, 8, 2, 9, 1], 17)   
>    should return 4 because the goal (17) can be reached after the first four days (e.g., 5 + 3 + 8 + 2).   
>      
>          Write a small Python program that uses your threshold() function to demonstrate that it works correctly. Your program may use a pre-defined list of stock gains or it may generate one randomly (see the "Helpful Hints" section below for tips on how to do this). Your program should display this list, prompt the user to enter a profit goal, and then print out the total number of days required to reach that goal (or a message stating that the goal is impossible).   


>       Word Windows   
>        
>          Define a Python function sliding(word, num) that behaves as follows. It should print out each num-length slice of the original word , aligned vertically as shown below.   
>    For example, a call to sliding("examples", 4) should produce the output   
>    
>    exam   xamp    ampl     mple      ples      
>      
>      
>          Write a small Python program to demonstrate that your sliding() function works correctly. Your program should prompt the user to enter a word and a window size, and then call sliding() with those values.   



From kent37 at tds.net  Mon Jan  7 22:13:40 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 16:13:40 -0500
Subject: [Tutor] Scope and elegance
In-Reply-To: <40af687b0801071237ra5a7a1en6375396321a80263@mail.gmail.com>
References: <1861F7D138B8034FAAB4BF433EBCAD2401083EDA@ex1.Fuel.Ott>	<1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
	<40af687b0801071237ra5a7a1en6375396321a80263@mail.gmail.com>
Message-ID: <47829604.2050206@tds.net>

Marc Tompkins wrote:
> I'd like to get the party line on this as well.  For a while now, I've 
> made a habit of defining an empty class called Global (Mr. Newton's 
> could be called Board, of course) at the top of my apps, and using its 
> attributes as if they were global variables.  It works, of course, but 
> it feels a bit... dirty.  Is there a more orthodox way to handle it?  Of 
> course, it would be optimal to remove any need for globals...

We had a discussion pretty recently on the evils of global variables:
http://thread.gmane.org/gmane.comp.python.tutor/44760

In most cases there is a better way, either direct parameter passing or 
instance attributes. Without seeing some code it's hard to make a 
suggestion, though.

Kent

From kent37 at tds.net  Mon Jan  7 22:23:29 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 16:23:29 -0500
Subject: [Tutor] Scope and elegance
In-Reply-To: <1199739499.22529.9.camel@ansatz>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
	<1199739499.22529.9.camel@ansatz>
Message-ID: <47829851.4080300@tds.net>

Torsten Marek wrote:

> Maybe I'm spoiled from programming too much Java in the last year, but

Hmm. Would that be
spoil 3 a: to damage seriously : ruin
or
spoil 4 b: to pamper excessively : coddle

? ;-)

> IMHO it's a good idea to put the singleton instance into the class
> itself rather than into some module.
> 
> This way, you (can) make sure that all accesses to the class really go
> to the same instance. 

This is not needed in Python, module-level variables are essentially 
singletons.

> There are, of course, many ways to do that, but I'd prefer a method on
> the class:
> 
> class Foo(object):
>     @classmethod
>     def instance(cls):
>         try:
>            return cls._inst
>         except AttributeError:
>            cls._inst = Foo()
>            return cls._inst

Yikes! Looks like 3a to me! How is this safer than having a single 
global instance?

Kent

From keridee at jayco.net  Mon Jan  7 22:50:48 2008
From: keridee at jayco.net (Tiger12506)
Date: Mon, 7 Jan 2008 16:50:48 -0500
Subject: [Tutor] [tutor] Pil image related question -- resending
	messagewithout attachments
References: <c2157c790801052022m5a5dd3f1pa22ce8a47ec96058@mail.gmail.com>
Message-ID: <010f01c85177$9debbf10$6e01a8c0@jslaptop>

I assume you realize that jpeg is a lossy format and that consecutively
resizing the same image will no doubt end poorly in image quality.

Also, I assume that you have a better understanding of the NEAREST and
BICUBIC options than I do because you are apparently comparing them. I do
know that those will affect your image quality.

I do not doubt that somewhere in the documentation for PIL (it can be an old
copy) that it will tell you how to set the compression level for jpeg
images, particularly when you save them back, possibly a default
parameter(?).

Kinda shooting in the dark.

> Hello All,
>      I am actually working on a project which deals with image processing.
> I just used pil function to resize the image into the dimensions i want. i
> was able to resize the image but the clarity of the new image is not good.
> Can anyone suggest which other functions i should use to improve the
> clarity. I am attaching the code and sending the images in the attachment.
> Can anyone suggest me how to do it ?
>
> import Image
>
> imageFile = "srk.jpg" #original small image
>
> im1 = Image.open(imageFile)
>
> width = 680
> height = 420
>
> im2 = im1.resize((width,height), Image.NEAREST)
> im3 = im1.resize ((width,height), Image.BICUBIC)
>
> #images get saved in c drive with jpg extensions
> ext = ".jpg"
> im2.save("C:/nearest" + ext)
> im3.save("C:/Bicubic" + ext)
>
> print "files are saved"
>
>
>
> -- 
> Varsha Purohit,
> Graduate Student
>


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


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


From keridee at jayco.net  Mon Jan  7 23:23:12 2008
From: keridee at jayco.net (Tiger12506)
Date: Mon, 7 Jan 2008 17:23:12 -0500
Subject: [Tutor] classes and the deepcopy function
References: <477EEF41.8060102@mrfab.info>
Message-ID: <01b901c8517b$fc991fe0$6e01a8c0@jslaptop>

> Hi
>
> I was trying to learn about classes in Python and have been playing
> around but I am having a problem with the deepcopy function. I want to
> have a function that returns a clean copy of an object that you can
> change without it changing the original, but no matter what I do the
> original changes as well. Can anyone give ma a pointer?

What's really cute about this is the underlying pointers to PyObject s 
giving you troubles. ;-) So you see, you have lots of pointers!

> def move_rectangle(rect, dx, dy):
>    rect2 = copy.deepcopy(rect)
>    rect2.corner.x += dx
>    rect2.corner.y += dy
>    return rect2

I want to mention something, even though the whole discussion has been 
beneficial to me as well as to others I'm sure, that you don't need a 
deepcopy here at all. I know that perhaps this is a simplified version of 
code that you might be working on, but perhaps the full version can be 
adapted as well???

def move_rectangle(rect, dx, dy):
  rect2 = rectange()
  rect2.width = rect.width
  rect2.height = rect.height
  rect2.corner.x = rect.corner.x+dx
  rect2.corner.y = rect.corner.y+dy
  return rect2

Hmmm... perhaps the necessary but cumbersome width and the height 
assignments are what makes the deepcopy so helpful in this example... 
Certainly they foreshadow the application of a lot of work with similar 
examples and larger objects....

HTH 


From ricaraoz at gmail.com  Tue Jan  8 00:26:56 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 20:26:56 -0300
Subject: [Tutor] Program review
In-Reply-To: <5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
References: <477EC575.4050607@bigfoot.com>
	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>
	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
Message-ID: <4782B540.70907@bigfoot.com>

Jeff Younker wrote:
>> Maybe it is my poor understanding of exception handling. My intention
>> here is to open the first file, if error then report in logging and
>> finish normally, else open the 2nd file, if error then report in  
>> logging
>> close the 1st file and finish normally. If no error then process.
>>
> 
> Right, but it helps to break up the error handling and the cleanup.
> Right now the error reporting exception handlers are intermixed
> with your cleanup error handlers.  Separating them makes the code
> clearer.
> 

Yes, but in such a simple program I'd rather have shallow level of
function/method callings. After all the pertinent code fits all in a
screen and is not hard to understand. If it was bigger or more
complicated I agree with you and I would re-factor it.

> def open_file(filename):
>       try :
>           return open(filename)
>       except Exception:
>           logging.error('No pude abrir "%s"' % filename, exec_info=True)
>           raise
> 
> # Goes into configuration class
> def mails(self):
>    fIncl = open_file(self.direcciones)
>    try:
>       fExcl = open_file(self.excluidas)
>       try:
>           return enumerate(
>                       set(addr.strip() for addr in fIncl)
>                       - set(excl.strip() for excl in fExcl))
>       finally:
>            fExcl.close()
>    finally:
>         fIncl.close()
> 

Both open_file assignments should go after the respective 'try:' statement.
Besides both 'finally:' blocks will be executed after an exception (i.e.
the file is not open) generating a second exception. Wrong use of
'finally:', it is executed even if an exception has occurred.
>From Python 2.5 Documentation :
"""
If finally is present, it specifies a `cleanup' handler. The try clause
is executed, including any except and else clauses. If an exception
occurs in any of the clauses and is not handled, the exception is
temporarily saved. The finally clause is executed. If there is a saved
exception, it is re-raised at the end of the finally clause. If the
finally clause raises another exception or executes a return or break
statement, the saved exception is lost.
"""

> Or if you're using python 2.5 then you can use with statements:
> 
> from __future__ import with_statements
> from contextlib import closing
> ...
> def mails(self):
>      with closing(open_file(self.direcciones)) as fIncl:
>             with closing(open_file(self.excluidas)) as fExcl:
>                 return enumerate(
>                         set(addr.strip() for addr in fIncl)
>                         - set(excl.strip() for excl in fExcl))
> 
>> close the 1st file and finish normally. If no error then process.
> 

How would that look with exception handling included? PEP 0343 is not an
example of clarity in the definition of a statement, it mixes
justification with historic development with definition with actual
equivalent code. Couldn't or wouldn't bother to understand it.

> If an exception is raised then the code terminates right there and
> then.   So, if procesar is written as:
> 
> def procesar(mensaje):
>       mails = mensaje.mails()
>       miCorreo = Correo(mensaje)
>       ....
> 
> then if mensaje.mails() raises an exception then the code
> terminates immediately, and the body of Correo will only be
> executed if there is no error.
> 
> As you have it written it terminates, but it also silently consumes the
> exception.  If something goes wrong with your program then there is
> no way of diagnosing the problem because the failure cause is never
> reported.

Yes, it is reported in the log. And that's exactly how I want it to be.
In my experience non tech users will go into panic if they see an error
screen with all that info up their faces. OTOH if they look at a log
file they seem to feel they have more control over the situation and
that what happened is not catastrophic.

Ricardo


From ricaraoz at gmail.com  Tue Jan  8 00:31:04 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 20:31:04 -0300
Subject: [Tutor] Program review
In-Reply-To: <478210C3.2080203@tds.net>
References: <477EC575.4050607@bigfoot.com>
	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<478210C3.2080203@tds.net>
Message-ID: <4782B638.6040406@bigfoot.com>

Kent Johnson wrote:
> Jeff Younker wrote:
> 
>> Or if you're using python 2.5 then you can use with statements:
>>
>> from __future__ import with_statements
>> from contextlib import closing
>> ...
>> def mails(self):
>>     with closing(open_file(self.direcciones)) as fIncl:
>>            with closing(open_file(self.excluidas)) as fExcl:
> 
> closing() is not needed, this can be written as
>      with open_file(self.direcciones) as fIncl:
>             with open_file(self.excluidas) as fExcl:
> 
> because open files are context managers.
> Or,
> from contextlib import nested
>      with nested(open_file(self.direcciones), open_file(self.excluidas)) 
> as (fIncl, fExcl):
> 

Nice! How would you add exception reporting to this?

>> As you have it written it terminates, but it also silently consumes the
>> exception.  If something goes wrong with your program then there is
>> no way of diagnosing the problem because the failure cause is never
>> reported.
> 
> The exception is written to the log. He may not want the traceback 
> printed to the console.
> 

Right!

From keridee at jayco.net  Mon Jan  7 23:33:53 2008
From: keridee at jayco.net (Tiger12506)
Date: Mon, 7 Jan 2008 17:33:53 -0500
Subject: [Tutor] Review and criticism of python project
References: <39cb7e5d0801031400p5d8d6d70ucbc47a6031d56eb@mail.gmail.com><78b3a9580801031508k56e11920j3222e87a1bcdd511@mail.gmail.com><39cb7e5d0801041025h166f017eraacab351af572f84@mail.gmail.com><477E879E.4060708@alum.rpi.edu>	<39cb7e5d0801041425k77d6b793va1d5952e69f065f5@mail.gmail.com>
	<005001c84f3b$32782ae0$7bfce004@jslaptop>
	<477EEB91.5010209@tds.net>
Message-ID: <01f101c8517d$9a74b200$6e01a8c0@jslaptop>

> Tiger12506 wrote:
>
>> Ouch. Usually in OOP, one never puts any user interaction into a class.
>
> That seems a bit strongly put to me. Generally user interaction should be
> separated from functional classes but you might have a class to help with
> command line interaction (e.g. the cmd module in the std lib) and GUI
> frameworks are usually built with classes.

Sorry... made that a little too general. I just have personal experiences
with putting a whole bunch of raw_inputs in a class once and learned never
to make that mistake again when I wanted to use the code for something else.
;-)

>>>                uh, tf = line.split(',')
>>>                if uh in self.uhdata:
>>>                    f=self.uhdata[uh]
>>>                    if tf not in f:
>>>                        f.append(tf)
>>>                else:
>>>                    self.uhdata[uh]=[tf]
>>
>> This can read
>>
>> try:
>>   f = self.uhdata[uh]
>> except KeyError:
>>   self.uhdata[uh] = []
>> finally:
>>   self.uhdata[uh].append(tf)
>
> These are not equivalent - the original code avoids duplicates in
> self.uhdata[uh].
>
> Possibly self.uhdata[uh] could be a set instead of a list. Then this could
> be written very nicely using defaultdict:
>
> from collections import defaultdict
>   ...
>   self.uhdata = defaultdict(set)
>   ...
>   self.uhdata[uh].add(tf)
>
>>>            for uh, Sections in self.uhdata.items():
>>>                Sections.sort()
>>
>> This will not work. In the documentation, it says that dictionary object
>> return a *copy* of the (key,value) pairs.
>> You are sorting those *copies*.
>
> No, the original code is fine. The docs say that dict.items() returns "a
> copy of a's list of (key, value) pairs". This is a little misleading,
> perhaps. A dict does not actually contain a list of key, value pairs, it
> is implemented with a hash table. dict.items() returns a new list
> containing the key, value pairs.
>
> But the keys and values in the new list are references to the same keys
> and values in the dict. So mutating the values in the returned list, via
> sort(), will also mutate the values in the dict.

Ah hah! Yes knew about hashes... It was the references that got me. I need
to learn to use id() at the python prompt a little more often. ;-)

>>>            missingpgcounts={}
>>>            fmissingpgcounts=[]
>>>            for x in self.uhdata:
>>>                for f in self.uhdata[x]:
>>>                    if f not in fmissingpgcounts:
>>>                        fmissingpgcounts.append(f)
>>
>> fmissingpgcounts = [f for f in self.uhdata.itervalues() if f not in
>> fmissingpgcounts]
>> Ahhh... This looks like a set.
>> fmissingpgcounts = set(self.uhdata.itervalues())
>
> Again, this is not quite the same thing. The original code builds a set of
> the contents of the values. You are building a set from the values (which
> are already lists). You still need one loop:
> fmissingpgcounts = set()
> for v in self.uhdate.itervalues():
>   fmissingpgcounts.update(v)
>
>> self.pgcounts = dict((x,0) for x in fmissingpgcounts)
>
> or, self.pgcounts = dict.fromkeys(fmissingpgcounts, 0)
>
> That's all I have energy for...
> Kent
>

Hmm... Apparently I didn't have enough energy. I must remember to eat
breakfast more often, it's affecting how I think... You're completely right
of course, Kent! What would all of us do without you?


From kent37 at tds.net  Mon Jan  7 23:43:49 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 17:43:49 -0500
Subject: [Tutor] Program review
In-Reply-To: <4782B540.70907@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<4782B540.70907@bigfoot.com>
Message-ID: <4782AB25.9000304@tds.net>

Ricardo Ar?oz wrote:
> PEP 0343 is not an
> example of clarity in the definition of a statement, it mixes
> justification with historic development with definition with actual
> equivalent code. Couldn't or wouldn't bother to understand it.

Here is a better starting point:
http://docs.python.org/whatsnew/pep-343.html

Kent

From ricaraoz at gmail.com  Tue Jan  8 00:58:32 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 20:58:32 -0300
Subject: [Tutor] Scope and elegance
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <4782BCA8.3060101@bigfoot.com>

James Newton wrote:
> Hi Python Practicioners!
> 
> I'm trying to come to terms with how Python handles the scope of
> objects.  In particular, I'd like to create an instance of one class and
> make it available inside instances of other classes.  Something like:
> 
> 
> # Test 1-------------------------------------
> # I want a "global" instance of this class...
> class Foo(object):
>     def doFoo(self):
>         return "foo"
> 

Puafff!!! Global = BAAAADDDD (unless, of course, there is no other way)

> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.  For example, this will work:
> 

Better!

> I know that I can also create a global instance outside the main()
> function.  This will also work:
> 

Worse!


> To put the question in context: in the Snakes and Ladders game that I am
> making, I have a board divided into 100 squares.  I want a Counter
> instance to know which position on the Board it should move to.  I may
> have several Counter instances, but only one Board instance.  Each
> Counter knows the index number of the square it should move to.  The
> Board instance knows how to convert that index number into a screen
> position.  I want the Counter instances to be able to ask the Board
> instance for that screen position.
> 

Maybe you have a design issue here (it is usually the case if you have
to use globals). I would think it this way initially, a Board object has
(amongst other properties) a list property containing Piece objects, the
 Piece objects have the piece owner's name and the piece's position in
the board. The Board has a throwDice method which gets the dice result
and applies it to the nextPlayer (another property of Board, or of the
player's list which could be an object itself and manage nextPlayer),
nextPlayer would update it's position and ask the Board (it's container)
to update it's position. This comes off the top of my head so it will
certainly require redesign, but you get the idea, no globals. To start
the game you would call Board.play() which would have a loop till the
end of game is reached.

HTH

From kent37 at tds.net  Mon Jan  7 23:54:02 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 17:54:02 -0500
Subject: [Tutor] Program review
In-Reply-To: <4782B638.6040406@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>
	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<478210C3.2080203@tds.net> <4782B638.6040406@bigfoot.com>
Message-ID: <4782AD8A.2050902@tds.net>

Ricardo Ar?oz wrote:
> Kent Johnson wrote:
>> from contextlib import nested
>>      with nested(open_file(self.direcciones), open_file(self.excluidas)) 
>> as (fIncl, fExcl):
>>
> 
> Nice! How would you add exception reporting to this?

I don't have a good answer to that, that's why I didn't propose it 
originally. You could use

try:
   with nested(open_file(self.direcciones), open_file(self.excluidas))
as (fIncl, fExcl):
     try:
       do_something_with(fIncl, fExcl)
     except:
       # handle exceptions from do_something_with()
except:
   pass # We already logged exceptions from the open_file calls

You could omit the inner try/except if you are sure that 
do_something_with() won't raise an exception, but it's pretty hard to be 
sure of that unless it wraps its contents already.

Looking at PEP 343, it's pretty clear ;-) that exceptions raised by 
open_file() will just be passed out of the with statement. Look at the 
pseudo-code in the section "Specification: The 'with' Statement". The 
exception is raised in the very first line - mgr = (EXPR) - when 
open_file() is called.

Kent

From ricaraoz at gmail.com  Tue Jan  8 01:15:44 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 21:15:44 -0300
Subject: [Tutor] Program review
In-Reply-To: <4782AB25.9000304@tds.net>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<4782B540.70907@bigfoot.com> <4782AB25.9000304@tds.net>
Message-ID: <4782C0B0.7030008@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>> PEP 0343 is not an
>> example of clarity in the definition of a statement, it mixes
>> justification with historic development with definition with actual
>> equivalent code. Couldn't or wouldn't bother to understand it.
> 
> Here is a better starting point:
> http://docs.python.org/whatsnew/pep-343.html
> 
> Kent
> 

Thanks Kent, it's clearer, but it gets rapidly complicated. Anyway
looking at the simpler use, if you would have exception handling in :

try :
    with open('/etc/passwd', 'r') as f:
        for line in f:
            print line
            ... more processing code ...
except ExceptionsOnOpening :
    ... exception handling
except :
    ... exceptions inside the for



Whereas traditionally :

try :
    f = open('/etc/passwd', 'r')
    for line in f:
        print line
        ... more processing code ...
except ExceptionsOnOpening :
    ... exception handling
except :
    ... exceptions inside the for


I don't see much difference except in the with example you have one more
level of indentation.

Don't know about more advanced uses, I'll try to understand them when
and if I ever need them.







From ricaraoz at gmail.com  Tue Jan  8 01:22:43 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 21:22:43 -0300
Subject: [Tutor] Program review
In-Reply-To: <4782AD8A.2050902@tds.net>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>	<478210C3.2080203@tds.net>
	<4782B638.6040406@bigfoot.com> <4782AD8A.2050902@tds.net>
Message-ID: <4782C253.6050409@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
>> Kent Johnson wrote:
>>> from contextlib import nested
>>>      with nested(open_file(self.direcciones), open_file(self.excluidas)) 
>>> as (fIncl, fExcl):
>>>
>> Nice! How would you add exception reporting to this?
> 
> I don't have a good answer to that, that's why I didn't propose it 
> originally. You could use
> 
> try:
>    with nested(open_file(self.direcciones), open_file(self.excluidas))
> as (fIncl, fExcl):
>      try:
>        do_something_with(fIncl, fExcl)
>      except:
>        # handle exceptions from do_something_with()
> except:
>    pass # We already logged exceptions from the open_file calls
> 
> You could omit the inner try/except if you are sure that 
> do_something_with() won't raise an exception, but it's pretty hard to be 
> sure of that unless it wraps its contents already.
> 
> Looking at PEP 343, it's pretty clear ;-) that exceptions raised by 
> open_file() will just be passed out of the with statement. Look at the 
> pseudo-code in the section "Specification: The 'with' Statement". The 
> exception is raised in the very first line - mgr = (EXPR) - when 
> open_file() is called.
> 

Yes, I can see that. I don't like it, too much hair splitting to get
something that is easily programmed the traditional way. I don't want to
be thinking about if the exception will or will not be passed out of the
with statement, and I CERTAINLY don't want the person who will be
modifying my code to have to think about those things. I'll stay with
the old way, easier, clearer and almost the same length, I fail to see
what I would win by coding this way.



From shlomme at gmx.net  Tue Jan  8 00:38:30 2008
From: shlomme at gmx.net (Torsten Marek)
Date: Tue, 08 Jan 2008 00:38:30 +0100
Subject: [Tutor] Program review
In-Reply-To: <4782C0B0.7030008@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>
	<477FD7DC.6090600@bigfoot.com>
	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>
	<4780BB6A.5000501@bigfoot.com>
	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<4782B540.70907@bigfoot.com> <4782AB25.9000304@tds.net>
	<4782C0B0.7030008@bigfoot.com>
Message-ID: <1199749110.6594.6.camel@ansatz>


On Mo, 2008-01-07 at 21:15 -0300, Ricardo Ar?oz wrote:
> Kent Johnson wrote:
> > Ricardo Ar?oz wrote:
> >> PEP 0343 is not an
> >> example of clarity in the definition of a statement, it mixes
> >> justification with historic development with definition with actual
> >> equivalent code. Couldn't or wouldn't bother to understand it.
> > 
> > Here is a better starting point:
> > http://docs.python.org/whatsnew/pep-343.html
> > 
> > Kent
> > 
> 
> Thanks Kent, it's clearer, but it gets rapidly complicated. Anyway
> looking at the simpler use, if you would have exception handling in :
> 
> try :
>     with open('/etc/passwd', 'r') as f:
>         for line in f:
>             print line
>             ... more processing code ...
> except ExceptionsOnOpening :
>     ... exception handling
> except :
>     ... exceptions inside the for
> 
> 
> 
> Whereas traditionally :
> 
> try :
>     f = open('/etc/passwd', 'r')
>     for line in f:
>         print line
>         ... more processing code ...
> except ExceptionsOnOpening :
>     ... exception handling
> except :
>     ... exceptions inside the for

Hi Ricardo,

don't forget the "f.close()" call after the for loop, in a finally block
[0]. Context managers are all about generalizing non-adjacent parts of
setup and teardown code  

Actually, the fact that you forgot the close call is an argument for
using the context manager;)

best,

Torsten
[0] http://docs.python.org/lib/bltin-file-objects.html
-- 
Torsten Marek <shlomme at gmx.net>
ID: A244C858 -- FP: 1902 0002 5DFC 856B F146  894C 7CC5 451E A244 C858
Keyserver: subkeys.pgp.net

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080108/32e9a029/attachment.pgp 

From keridee at jayco.net  Tue Jan  8 00:40:12 2008
From: keridee at jayco.net (Tiger12506)
Date: Mon, 7 Jan 2008 18:40:12 -0500
Subject: [Tutor] Scope and elegance
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <024e01c85186$c5c8ae30$6e01a8c0@jslaptop>

I like this.

class Counter:
  def __init__(self):
      self.score = 0
  def incr(x, y):
     self.score += 2*x+3*y

class Board:
  def __init__(self):
    self.counter = Counter()
    self.curcoords = (0,0)
  def update(self)
    self.counter.incr(*self.curcoords)


Whatever OOP term is used to describe that. In other words, make your board
class be a container for the various counters. Especially if certain Boards
always contain certain counters. Just personal opinion...


From ricaraoz at gmail.com  Tue Jan  8 01:46:40 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 07 Jan 2008 21:46:40 -0300
Subject: [Tutor] Program review
In-Reply-To: <1199749110.6594.6.camel@ansatz>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>	<4782B540.70907@bigfoot.com>
	<4782AB25.9000304@tds.net>	<4782C0B0.7030008@bigfoot.com>
	<1199749110.6594.6.camel@ansatz>
Message-ID: <4782C7F0.9000101@bigfoot.com>

Torsten Marek wrote:
>> try :
>>     with open('/etc/passwd', 'r') as f:
>>         for line in f:
>>             print line
>>             ... more processing code ...
>> except ExceptionsOnOpening :
>>     ... exception handling
>> except :
>>     ... exceptions inside the for
>>
>>
>>
>> Whereas traditionally :
>>
>> try :
>>     f = open('/etc/passwd', 'r')
>>     for line in f:
>>         print line
>>         ... more processing code ...
>> except ExceptionsOnOpening :
>>     ... exception handling
>> except :
>>     ... exceptions inside the for
> 
> Hi Ricardo,
> 
> don't forget the "f.close()" call after the for loop, in a finally block
> [0]. Context managers are all about generalizing non-adjacent parts of
> setup and teardown code  
> 
> Actually, the fact that you forgot the close call is an argument for
> using the context manager;)
> 

Hi Torsten,

or an argument for going to sleep at 10 pm after a hard day's work and
38? Centigrades temperature.  ;c)



From bgailer at alum.rpi.edu  Tue Jan  8 00:49:27 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 07 Jan 2008 18:49:27 -0500
Subject: [Tutor] Urgent: Help
In-Reply-To: <816036.77606.qm@web50605.mail.re2.yahoo.com>
References: <816036.77606.qm@web50605.mail.re2.yahoo.com>
Message-ID: <4782BA87.8090607@alum.rpi.edu>

Please reply to the list not just me. We all participate and learn.

Shumail Siddiqui wrote:
> I know this assignment is not too hard, but I have been greatly 
> overwhelmed with work as I have been taking a 19 credits recently. I 
> kind of have an approach to this by importing random numbers and 
> random.choice leaves the first four numbers as a result. But, I don't 
> know how to add these numbers in the program, 
One approach is:

start with a total of 0
add the first number to the total
if the total does not reach the goal
add the next number
etc.

That can be implemented in a loop.

Give it a try and show us how far you can come.

> while I know that I can use append to add those scores.
I don't know how to use append to add....


From kent37 at tds.net  Tue Jan  8 00:50:53 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 07 Jan 2008 18:50:53 -0500
Subject: [Tutor] Program review
In-Reply-To: <4782C0B0.7030008@bigfoot.com>
References: <477EC575.4050607@bigfoot.com>	<477EF630.2070808@tds.net>	<477FD7DC.6090600@bigfoot.com>	<77DD9BCD-2D34-4839-A1B0-8AAB04E85FA7@drinktomi.com>	<4780BB6A.5000501@bigfoot.com>	<5130CBA6-5D3F-47A5-A601-9CB0864CB47C@drinktomi.com>
	<4782B540.70907@bigfoot.com> <4782AB25.9000304@tds.net>
	<4782C0B0.7030008@bigfoot.com>
Message-ID: <4782BADD.5010206@tds.net>

Ricardo Ar?oz wrote:
> looking at the simpler use, if you would have exception handling in :
> 
> try :
>     with open('/etc/passwd', 'r') as f:
>         for line in f:
>             print line
>             ... more processing code ...
> except ExceptionsOnOpening :
>     ... exception handling
> except :
>     ... exceptions inside the for
> 
> 
> 
> Whereas traditionally :
> 
> try :
>     f = open('/etc/passwd', 'r')
>     for line in f:
>         print line
>         ... more processing code ...
> except ExceptionsOnOpening :
>     ... exception handling
> except :
>     ... exceptions inside the for
> 
> 
> I don't see much difference except in the with example you have one more
> level of indentation.

The with version will close the file when the with block exits.

> Don't know about more advanced uses, I'll try to understand them when
> and if I ever need them.

Maybe 'with open(...) as ...' is more useful in contexts where you are 
not so picky about exception handling.

Here is a context manager and associated decorator you might be 
interested in - it traps errors and logs them :-)
http://blogmaker.googlecode.com/svn/trunk/blogmaker/util/trap_errors.py

Kent

From lupin at orcon.net.nz  Tue Jan  8 05:58:05 2008
From: lupin at orcon.net.nz (Brett Wilkins)
Date: Tue, 08 Jan 2008 17:58:05 +1300
Subject: [Tutor] Error checking and such in a console "guess my number" game
Message-ID: <478302DD.5070303@orcon.net.nz>

Hi there,

I'm been following a tutorial in a Python Programming book, making a 
Guess My Number game.
I decided to go and modify it a bit more, therefore expanding it.

What I added in was the ability to modify the range of the pseudo-random 
number generator, an exit strategy (i.e. type stop at the prompt), 
something that keeps track of the amount of times you've gotten it 
right, and error checking. Now, without further ado, here's the code 
I've got:


#! /usr/bin/python

#imports area
import random

#main body
guessed_number = 0
stop = "n"
times_played = 0
range_for_random = 0
inter_range = ''
default = 100
print """
        Welcome to

        Guess My Number!

In this game you will attempt to guess a number that
the computer will psuedo-randomly generate, With
a range for which you dictate the ending point.
        Good Luck!"""
while 1:
    inter_range = raw_input("\n\n Please specify the range for the 
randon number to reside within: ")

    alphabet = "abcdefghijklmnopqrstuvwxyz"
    intermediary_number = raw_input("\n\nPlease enter your guess, or 
type stop to end game: ")

    if intermediary_number == "stop":
        exit()
    elif 1:
        for char in alphabet:
            if char in inter_range:
                range_for_random = default
                continue
            else:
                if inter_range == '':
                    range_for_random = default
                else:
                    range_for_random = int(inter_range)

    while 1:
        if times_played > 0:
            stop = raw_input("\n\nTo end the game, type in stop, Or to 
change the range, type change. Otherwise just press Enter:")
            if stop.lower() == "change": break
            elif stop.lower() == "stop": exit()
        print "\n\nTime to start Guessing My Number!"
        random_number = random.randrange(range_for_random) + 1
   
        while 1:
            alphabet = "abcdefghijklmnopqrstuvwxyz"
            intermediary_number = raw_input("\n\nPlease enter your 
guess, or type stop to end game: ")
   
            if intermediary_number == "stop":
                exit()
            elif 1:
                for char in alphabet:
                    if char in intermediary_number:
                        guessed_number = 0
                        continue
                    else:
                        if intermediary_number == '':
                            guessed_number = 0
                        else:
                            guessed_number = int(intermediary_number)
            if guessed_number > random_number:
                print "\nYour guess was too high!"
            elif guessed_number < random_number:
                print "\nYour guess was too low!"
            elif guessed_number == random_number:
                print "\nYes, you got the right answer! The answer was: 
" + str(random_number)
                times_played += 1
                print "You have now played %s time(s)." % (times_played)
                break

Now I was wondering first off, is there a better way about doing the 
error checking? I already tried try-except blocks, but as I'm new to 
python (this is my second program after "Hello World") I don't know how 
to only catch certain exceptions (in this case a ValueError). Using 
try-except without limiting seems to disable Ctrl+C breaking in the 
console, I found.

The next thing is my real problem:

if times_played > 0:
            stop = raw_input("\n\nTo end the game, type in stop, Or to 
change the range, type change. Otherwise just press Enter:")
            if stop.lower() == "change": break
            elif stop.lower() == "stop": exit()

What I want the break statement to do here is exit the while loop isn't 
currently in, but it just seems to break the current if decision, making 
it rather redundant. A little help with this in particular would be much 
appreciated :)

And just so you know, I'm teaching myself python, for fun and for an 
upcoming job, and this is just fun for me.

Cheers,

Brett


-- 
**************
Brett Wilkins
A.K.A Beedub
The Fixit


From alan.gauld at btinternet.com  Tue Jan  8 09:56:13 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Jan 2008 08:56:13 -0000
Subject: [Tutor] Error checking and such in a console "guess my number"
	game
References: <478302DD.5070303@orcon.net.nz>
Message-ID: <flvdno$ruv$1@ger.gmane.org>

Hi Brett,

If this is really just your second program then I think you
are being a bit too ambitious. I'd try simplifying it a bit first,
get it to work and then add the extra features - like all of
the error checks etc. As it stands there are a few basic
errors to be fixed.

> #main body
> guessed_number = 0
> stop = "n"
> times_played = 0
> range_for_random = 0
> inter_range = ''
> default = 100

You don't really need to define all the variables up front,
but there's no harm in doing so.

> while 1:

Now that Python supports boolean types its better
to write this as

while True:


>    inter_range = raw_input("\n\n Please specify the range for the
> randon number to reside within: ")
>
>    alphabet = "abcdefghijklmnopqrstuvwxyz"
>    intermediary_number = raw_input("\n\nPlease enter your guess, or
> type stop to end game: ")
>
>    if intermediary_number == "stop":
>        exit()

exit() is part of the sys module which you haven't imported yet...

>    elif 1:

This is always true so you don't need it.

>        for char in alphabet:
>            if char in inter_range:

inter_range is supposed to be a number (or the
character representation of a number since we
haven't converted it yet) but here we check
every letter in the alphabet to see if its in that
number, which is highly unlikely to happen
unless the user typed "eleven" or similar

So I'm not sure what you think this loop will do.

>                range_for_random = default
>                continue
>            else:
>                if inter_range == '':
>                    range_for_random = default
>                else:
>                    range_for_random = int(inter_range)

The empty string check is reasonable but the
else will be repeated for most letters of the
alphabet so that at the end of the loop you will
wind up with an int version of inter_loop, which
is what you want, but you got there byy a very
complicated route!

>    while 1:
>        if times_played > 0:

times_played is set to zero at the top and nothing changes
it up to here so this will never be true.

>            stop = raw_input("\n\nTo end the game, type in stop, Or 
> to
> change the range, type change. Otherwise just press Enter:")
>            if stop.lower() == "change": break

Since there is nothing beyond the outer while loop
this will stop the program not change the values.

>            elif stop.lower() == "stop": exit()
>        print "\n\nTime to start Guessing My Number!"
>        random_number = random.randrange(range_for_random) + 1
>
>        while 1:
>            alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet hasn't changed so you don;t need to define it again.

>            intermediary_number = raw_input("\n\nPlease enter your
> guess, or type stop to end game: ")
>
>            if intermediary_number == "stop":
>                exit()
>            elif 1:
>                for char in alphabet:
>                    if char in intermediary_number:
>                        guessed_number = 0
>                        continue
>                    else:
>                        if intermediary_number == '':
>                            guessed_number = 0
>                        else:
>                            guessed_number = int(intermediary_number)

Again, this is a very complicated way of getting where you
want to go most of the time. Rather than checking every letter
in alphabet it would be better to apply some rules to the
intermediary number itself.

try:
     guessed_number = int(intermediary_number)
except: guessed_number = 0     # for any error at all.


>            if guessed_number > random_number:
>                print "\nYour guess was too high!"
>            elif guessed_number < random_number:
>                print "\nYour guess was too low!"
>            elif guessed_number == random_number:
>                print "\nYes, you got the right answer! The answer 
> was:
> " + str(random_number)

You don;t need to convert back to a str, just separate with a comma:

 print "\nYes, you got the right answer! The answer was: 
",random_number

>                times_played += 1

You only update times_played if they get it right. Are you sure
thats what you want? It is if times played means the number
of differnt numbers guessed, but not if its the number of
guesses per number...

>                print "You have now played %s time(s)." % 
> (times_played)
>                break

> Now I was wondering first off, is there a better way about doing the
> error checking?

Yes, see the comments above.

> I already tried try-except blocks, but as I'm new to
> python (this is my second program after "Hello World") I don't know 
> how
> to only catch certain exceptions (in this case a ValueError).

In fact I suspect you don't care about the specific type of error
since you always set a default value. But if you do want to
catch only one error type simply list them in the Except clause:

try:
    # your code here
except ValueEerror:
    # handle the error

> try-except without limiting seems to disable Ctrl+C breaking in the
> console, I found.

Thats because Ctrl-C generates an exception so yes it will catch
that too. If you limit the try/except to just the convertion operation
it shouldn't be a problem since the try/except will be so short lived.

> The next thing is my real problem:
>
> if times_played > 0:
>            stop = raw_input("\n\nTo end the game, type in stop, Or 
> to
> change the range, type change. Otherwise just press Enter:")
>            if stop.lower() == "change": break
>            elif stop.lower() == "stop": exit()
>
> What I want the break statement to do here is exit the while loop 
> isn't
> currently in, but it just seems to break the current if decision, 
> making
> it rather redundant. A little help with this in particular would be 
> much
> appreciated :)

It shouldn't. It should exit the loop. Try it with a simpler example
to check how it works.

> And just so you know, I'm teaching myself python, for fun and for an
> upcoming job, and this is just fun for me.

Learning for fun is good :-)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From mobiledreamers at gmail.com  Wed Jan  9 01:26:54 2008
From: mobiledreamers at gmail.com (mobiledreamers at gmail.com)
Date: Tue, 8 Jan 2008 16:26:54 -0800
Subject: [Tutor] Spaces and tabs messing up code
Message-ID: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>

 my friend uses vim
and i use xemacs
so our shared python code is a mix of tabs and spaces and it is hard for him
to edit it in vim

any idea on how to make it clean
convert it all to 4 spaces?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080108/f4b92c62/attachment.htm 

From bill at celestial.net  Wed Jan  9 01:49:41 2008
From: bill at celestial.net (Bill Campbell)
Date: Tue, 8 Jan 2008 16:49:41 -0800
Subject: [Tutor] Spaces and tabs messing up code
In-Reply-To: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
References: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
Message-ID: <20080109004941.GA25990@ayn.mi.celestial.com>

On Tue, Jan 08, 2008, mobiledreamers at gmail.com wrote:
>
>   my friend uses vim
>
>   and i use xemacs
>
>   so our shared python code is a mix of tabs and spaces and it is hard
>   for him to edit it in vim
>
>   any idea on how to make it clean
>
>   convert it all to 4 spaces?

Do that, and in his ~/.vimrc file, add a line ``set expandtab''

(Friends don't let friends use emacs :-).

Bill
--
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Giving money and power to government is like giving whiskey and car keys to
teenage boys -- P.J. O'Rourke

From billburns at pennswoods.net  Wed Jan  9 01:56:33 2008
From: billburns at pennswoods.net (Bill Burns)
Date: Tue, 08 Jan 2008 19:56:33 -0500
Subject: [Tutor] Spaces and tabs messing up code
In-Reply-To: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
References: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
Message-ID: <47841BC1.3050306@pennswoods.net>

mobiledreamers at gmail.com wrote:
> my friend uses vim
> and i use xemacs
> so our shared python code is a mix of tabs and spaces and it is hard for 
> him to edit it in vim
>  
> any idea on how to make it clean
> convert it all to 4 spaces?
>  
> Thanks
> 

Take a look at reindent.py. This script lives in your Python distribution.

On my Windows box it lives here:

C:\Python24\Tools\Scripts\reindent.py

HTH,

Bill

From reed at reedobrien.com  Wed Jan  9 03:02:24 2008
From: reed at reedobrien.com (Reed O'Brien)
Date: Tue, 8 Jan 2008 21:02:24 -0500
Subject: [Tutor] Spaces and tabs messing up code
In-Reply-To: <20080109004941.GA25990@ayn.mi.celestial.com>
References: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
	<20080109004941.GA25990@ayn.mi.celestial.com>
Message-ID: <8863C706-200A-41CE-AAE9-739C7328C9E8@reedobrien.com>

On Jan 8, 2008, at 7:49 PM, Bill Campbell wrote:

> On Tue, Jan 08, 2008, mobiledreamers at gmail.com wrote:
>>
>>   my friend uses vim

Small editors for small minds;)

>>
>>   and i use xemacs
>>
>>   so our shared python code is a mix of tabs and spaces and it is  
>> hard
>>   for him to edit it in vim
>>
>>   any idea on how to make it clean
>>
>>   convert it all to 4 spaces?
>
> Do that, and in his ~/.vimrc file, add a line ``set expandtab''

Tell him to use emacs.

>
> (Friends don't let friends use emacs :-).
>
> Bill
> --
> INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206)  
> 236-1676
>
> Giving money and power to government is like giving whiskey and car  
> keys to
> teenage boys -- P.J. O'Rourke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From sigzero at gmail.com  Wed Jan  9 03:46:44 2008
From: sigzero at gmail.com (Robert Hicks)
Date: Tue, 08 Jan 2008 21:46:44 -0500
Subject: [Tutor] Spaces and tabs messing up code
In-Reply-To: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
References: <c1870d60801081626g2966a718q2d60594d7d2d902d@mail.gmail.com>
Message-ID: <fm1cip$cv4$1@ger.gmane.org>

mobiledreamers at gmail.com wrote:
> my friend uses vim
> and i use xemacs
> so our shared python code is a mix of tabs and spaces and it is hard for 
> him to edit it in vim
>  
> any idea on how to make it clean
> convert it all to 4 spaces?
>  
> Thanks
> 

:set ts=4
:retab!

:h retab


From eric at abrahamsen.com  Wed Jan  9 03:43:19 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Wed, 9 Jan 2008 10:43:19 +0800
Subject: [Tutor] subclassing strings
Message-ID: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>

I'm playing around with subclassing the built-in string type, and  
realizing there's quite a bit I don't know about what's going on with  
the built-in types. When I create a string like so:

x = 'myvalue'

my understanding is that this is equivalent to:

x = str('myvalue')

and that this second form is more fundamental: the first is a  
shorthand for the second. What is 'str()' exactly? Is it a class name?  
If so, is the string value I pass in assigned to an attribute, the way  
I might create a "self.value =" statement in the __init__ function of  
a class I made myself? If so, does that interior attribute have a  
name? I've gone poking in the python lib, but haven't found anything  
enlightening.

I started out wanting to subclass str so I could add metadata to  
objects which would otherwise behave exactly like strings. But then I  
started wondering where the actual value of the string was stored,  
since I wasn't doing it myself, and whether I'd need to be careful of  
__repr__ and __str__ so as not to interfere with the basic string  
functioning of the object. As far as I can tell the object functions  
normally as a string without my doing anything ? where does the string  
value 'go', and is there any way I might inadvertently step on it by  
overriding the wrong attribute or method?

Thanks for any insight,

Eric

From keridee at jayco.net  Wed Jan  9 04:12:57 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 8 Jan 2008 22:12:57 -0500
Subject: [Tutor] Scope and elegance
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8735@ex1.Fuel.Ott>
Message-ID: <005201c8526d$8c11d170$79fde004@jslaptop>

> Thanks Tiger12506!
> 
> This has helped me understand the function(*tuple) syntax, as well as
> providing me with a concrete example.
> 
> James

Cool. ;-)
Here's another, totally unrelated to counters and boards.
Kinda the opposite use of the * syntax I used earlier.

def printall(*li):
  for x in li:
    print x

printall(1)
printall(1,"yes")
printall(2,1,'y',3.14)

Cheers,
Tiger12506

From mobiledreamers at gmail.com  Wed Jan  9 04:32:33 2008
From: mobiledreamers at gmail.com (Mark)
Date: Tue, 08 Jan 2008 19:32:33 -0800
Subject: [Tutor] Pyflakes pre-commit hook in subversion
Message-ID: <47844051.7090401@gmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080108/89648823/attachment.htm 

From keridee at jayco.net  Wed Jan  9 04:48:17 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 8 Jan 2008 22:48:17 -0500
Subject: [Tutor] subclassing strings
References: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>
Message-ID: <009a01c85272$7c4a4290$79fde004@jslaptop>

Ahh. Excellent questions.

> I'm playing around with subclassing the built-in string type, and
> realizing there's quite a bit I don't know about what's going on with
> the built-in types. When I create a string like so:
>
> x = 'myvalue'
>
> my understanding is that this is equivalent to:
>
> x = str('myvalue')

Um. Yeah. Sort of. Python creates the 'myvalue' as a string object as it
interprets it. So str('myvalue') is just saying create a string object from
a string object. But I think I know what you intended to ask, see below.

> and that this second form is more fundamental: the first is a
> shorthand for the second. What is 'str()' exactly? Is it a class name?

>>> str
<type 'str'>

[edit] Here's a good thought I just thought. These are equivalent
>>> a = "hello"
>>> str(a) == a.__str__()
True
>>> repr(a) == a.__repr__()
True
>>> str(a) == str.__str__(a)
True
>>> repr(a) == str.__repr__(a)

It's a built-in type. That is~ it has a constructor, destructor, methods,
etc. like any other object in python. When you say str('myvalue') you are
passing the python string object containing 'myvalue' into the constructor
the str type and creating a new string object.

> If so, is the string value I pass in assigned to an attribute, the way
> I might create a "self.value =" statement in the __init__ function of
> a class I made myself? If so, does that interior attribute have a
> name? I've gone poking in the python lib, but haven't found anything
> enlightening.

Here we come to secrets of Python. It's written in C. Since str is a
built-in type, the storing of the variable you ask about is a C style buffer
(*not* a linked list - strings are immutable). Whenever you call str(),
Python constructs a new python object and stores the string in a new C-style
buffer. The same occurs for adding string together with '+', and is why
"".join(list_of_strs)  is the preferred method (Because python can build the
buffer all in one go)

No it's not accessible from python. (At least I don't think so. And you
never should need to)

> I started out wanting to subclass str so I could add metadata to
> objects which would otherwise behave exactly like strings.

Okay.

> But then I
> started wondering where the actual value of the string was stored,
> since I wasn't doing it myself, and whether I'd need to be careful of
> __repr__ and __str__ so as not to interfere with the basic string
> functioning of the object.

Okay.

> As far as I can tell the object functions
> normally as a string without my doing anything ? where does the string
> value 'go', and is there any way I might inadvertently step on it by
> overriding the wrong attribute or method?

Okay. You can overwrite string methods like __str__ and __repr__. If you
look it up, the definition of these special methods (in layman's terms) is
that whenever str() is called on an object (explicitly or *implicitly*) then
the objects __str__ method is called which will return a string object which
should give an appropriate representation. The built-in string object does
the equivalent of

def __str__(self):
  return self
def __repr__(self):
  return "'%s'" % self      #Notice this will give extra single quotes
around string

No, you will not interfere with the internal representation of the string,
but you can change completely how that representation is presented to the
user of the object.

For an implemented simple example just say the word.

HTH,
Tiger12506

PS. Anyone who's interested. A significant study of C has brought me to
these conclusions.
immutable -> implemented with static buffer
mutable -> implemented with linked list
Anyone know a little more detail?


From kent37 at tds.net  Wed Jan  9 04:49:59 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 08 Jan 2008 22:49:59 -0500
Subject: [Tutor] subclassing strings
In-Reply-To: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>
References: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>
Message-ID: <47844467.2010205@tds.net>

Eric Abrahamsen wrote:
> When I create a string like so:
> 
> x = 'myvalue'
> 
> my understanding is that this is equivalent to:
> 
> x = str('myvalue')
> 
> and that this second form is more fundamental: the first is a  
> shorthand for the second. 

The second does nothing that the first doesn't already do.

'myvalue' is a string:
In [4]: s='myvalue'
In [5]: type(s)
Out[5]: <type 'str'>

So is str('myvalue'):
In [6]: t=str(s)
In [7]: type(t)
Out[7]: <type 'str'>

In fact they are the *same* string - str(s) is the same as s if s is 
already a string:
In [8]: s is t
Out[8]: True

What is 'str()' exactly? Is it a class name?

Close; str is a type name. str() is an invocation of the type.

> If so, is the string value I pass in assigned to an attribute, the way  
> I might create a "self.value =" statement in the __init__ function of  
> a class I made myself? If so, does that interior attribute have a  
> name? I've gone poking in the python lib, but haven't found anything  
> enlightening.

No, not really. At the C level, IIUC there is a structure containing a 
pointer to a byte array, but there is no access to this level of 
internals from Python. For Python, strings are fundamental types like 
integers and floats. The internal representation is not available.

I guess you may have a background in C++ where a char array is different 
from an instance of the string class. Python does not have this 
distinction; you don't have access to a bare char array that is not 
wrapped in some class.

> I started out wanting to subclass str so I could add metadata to  
> objects which would otherwise behave exactly like strings. But then I  
> started wondering where the actual value of the string was stored,  
> since I wasn't doing it myself, and whether I'd need to be careful of  
> __repr__ and __str__ so as not to interfere with the basic string  
> functioning of the object. As far as I can tell the object functions  
> normally as a string without my doing anything ? where does the string  
> value 'go', and is there any way I might inadvertently step on it by  
> overriding the wrong attribute or method?

No, you can't access the actual byte array from Python and you can't 
damage it.

You might want to take a look at BeautifulSoup, which subclasses unicode 
to create a page element, and path.py which subclasses string to add 
file path manipulation operations.
http://www.crummy.com/software/BeautifulSoup/
file://localhost/Users/kent/Desktop/Downloads/Python/path-2.1/index.html

The actual string object implementation is in stringobject.h & .c:
http://svn.python.org/view/python/trunk/Include/stringobject.h?rev=59564&view=markup
http://svn.python.org/view/python/trunk/Objects/stringobject.c?rev=59564&view=markup

Kent

From kent37 at tds.net  Wed Jan  9 05:05:59 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 08 Jan 2008 23:05:59 -0500
Subject: [Tutor] subclassing strings
In-Reply-To: <009a01c85272$7c4a4290$79fde004@jslaptop>
References: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>
	<009a01c85272$7c4a4290$79fde004@jslaptop>
Message-ID: <47844827.7080509@tds.net>

Tiger12506 wrote:
> PS. Anyone who's interested. A significant study of C has brought me to
> these conclusions.
> immutable -> implemented with static buffer
> mutable -> implemented with linked list
> Anyone know a little more detail?

Certainly not true of Python. I don't know of any standard Python data 
structure that is implemented with a linked list. list is implemented as 
an array of references, not a linked list. dict and set are hash tables. 
User-defined classes are implemented however you like, with a dict to 
hold the attributes.

Kent

From kent37 at tds.net  Wed Jan  9 05:08:35 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 08 Jan 2008 23:08:35 -0500
Subject: [Tutor] Pyflakes pre-commit hook in subversion
In-Reply-To: <47844051.7090401@gmail.com>
References: <47844051.7090401@gmail.com>
Message-ID: <478448C3.3020105@tds.net>

Mark wrote:

> The small "configuration" file for enforce can be found here 
> <http://www.async.com.br/%7Ejdahlin/misc/enforcer.conf>.

That link is broken.
> 
> Can you share enforcer file? or a means to ensure safe code in python repo

I don't understand what you are asking.

Kent


From eric at abrahamsen.com  Wed Jan  9 05:26:54 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Wed, 9 Jan 2008 12:26:54 +0800
Subject: [Tutor] subclassing strings
In-Reply-To: <47844467.2010205@tds.net>
References: <37048EFE-E889-4B51-8A6E-339E59B12A94@abrahamsen.com>
	<47844467.2010205@tds.net>
Message-ID: <3D822AFE-562F-43E9-8937-23044A58EB06@abrahamsen.com>

Thanks both of you, that cleared a lot of things up.

On Jan 9, 2008, at 11:49 AM, Kent Johnson wrote:
>
> No, you can't access the actual byte array from Python and you can't  
> damage it.

I don't know a lick of C and probably never will, but I do like to  
know what it is, exactly, that I don't know, and this is nice. I'll  
stop worrying about stepping on the actual value of the strings.

On Jan 9, 2008, at 11:48 AM, Tiger12506 wrote:
> def __str__(self):
>  return self
> def __repr__(self):
>  return "'%s'" % self      #Notice this will give extra single quotes
> around string

Excellent, this was very helpful. I know about the str() vs .__str__()  
equivalence, but had never seen what these two functions were actually  
doing under the hood.

What I wasn't figuring out was passing the string value of my custom  
string class into the constructor of the actual str type, rather than  
rerouting it into a data attribute of my custom class. So now I've got  
this, for example:

class StampedString(str):
     def __init__(self, val):
         super(StampedString, self).__init__(val)
         import datetime
         self.timestamp = datetime.datetime.now()

so that this:
x = StampedString('This is a time-stamped string')
works exactly like a string, apart from the metadata.

At least, I think I've understood this correctly...

Thanks again for the interesting explanations.

Eric

From kent37 at tds.net  Wed Jan  9 05:28:22 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 08 Jan 2008 23:28:22 -0500
Subject: [Tutor] Pyflakes pre-commit hook in subversion
In-Reply-To: <c1870d60801082024n5d24f5a4me0cde99f749a5dc2@mail.gmail.com>
References: <47844051.7090401@gmail.com> <478448C3.3020105@tds.net>
	<c1870d60801082024n5d24f5a4me0cde99f749a5dc2@mail.gmail.com>
Message-ID: <47844D66.9090405@tds.net>

Why are you sending this to the tutor list? Do you have a question?

Kent

mobiledreamers at gmail.com wrote:
> yes the link is broken and hence i sent it in
> since it is a conf file for svn pre-commit hook
> so pyflakes is run of your tree and it emits an error if python files 
> have any error preventing bad commits poisoning svn tree so dev can fix 
> the bug and recommit
> 
> On Jan 8, 2008 8:08 PM, Kent Johnson <kent37 at tds.net 
> <mailto:kent37 at tds.net>> wrote:
> 
>     Mark wrote:
> 
>      > The small "configuration" file for enforce can be found here
>      > <http://www.async.com.br/%7Ejdahlin/misc/enforcer.conf
>     <http://www.async.com.br/~jdahlin/misc/enforcer.conf>>.
> 
>     That link is broken.
>      >
>      > Can you share enforcer file? or a means to ensure safe code in
>     python repo
> 
>     I don't understand what you are asking.
> 
>     Kent
> 
> 


From mobiledreamers at gmail.com  Wed Jan  9 05:24:27 2008
From: mobiledreamers at gmail.com (mobiledreamers at gmail.com)
Date: Tue, 8 Jan 2008 20:24:27 -0800
Subject: [Tutor] Pyflakes pre-commit hook in subversion
In-Reply-To: <478448C3.3020105@tds.net>
References: <47844051.7090401@gmail.com> <478448C3.3020105@tds.net>
Message-ID: <c1870d60801082024n5d24f5a4me0cde99f749a5dc2@mail.gmail.com>

yes the link is broken and hence i sent it in
since it is a conf file for svn pre-commit hook
so pyflakes is run of your tree and it emits an error if python files have
any error preventing bad commits poisoning svn tree so dev can fix the bug
and recommit

On Jan 8, 2008 8:08 PM, Kent Johnson <kent37 at tds.net> wrote:

> Mark wrote:
>
> > The small "configuration" file for enforce can be found here
> > <http://www.async.com.br/%7Ejdahlin/misc/enforcer.conf<http://www.async.com.br/~jdahlin/misc/enforcer.conf>
> >.
>
> That link is broken.
> >
> > Can you share enforcer file? or a means to ensure safe code in python
> repo
>
> I don't understand what you are asking.
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080108/41bbb623/attachment.htm 

From agoldgod at gmail.com  Wed Jan  9 08:44:00 2008
From: agoldgod at gmail.com (goldgod a)
Date: Wed, 9 Jan 2008 13:14:00 +0530
Subject: [Tutor] Zooming option in TKinter
Message-ID: <105c9ccc0801082344v2e2cf039k4b3d8610fd998bc3@mail.gmail.com>

hi,
    I am developing one project using python-tkinter. I want to know
whether the zoom in and zoom out option is present in Tkinter.  If it
is not present then Can you give some idea to create a option in
manually.

-- 
Thanks & Regards,
goldgod

From alan.gauld at btinternet.com  Wed Jan  9 10:20:45 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jan 2008 09:20:45 -0000
Subject: [Tutor] Zooming option in TKinter
References: <105c9ccc0801082344v2e2cf039k4b3d8610fd998bc3@mail.gmail.com>
Message-ID: <fm23p9$8mc$1@ger.gmane.org>


"goldgod a" <agoldgod at gmail.com> wrote

>    I am developing one project using python-tkinter. I want to know
> whether the zoom in and zoom out option is present in Tkinter.  If 
> it
> is not present then Can you give some idea to create a option in
> manually.

Sorry, I'm not sure what you mean by zoom in/out?
Are you talking about graphics? Or some other widget?

Can you explain what you mean?

Alan G. 



From agoldgod at gmail.com  Wed Jan  9 11:12:08 2008
From: agoldgod at gmail.com (goldgod a)
Date: Wed, 9 Jan 2008 15:42:08 +0530
Subject: [Tutor] Zooming option in TKinter
In-Reply-To: <fm23p9$8mc$1@ger.gmane.org>
References: <105c9ccc0801082344v2e2cf039k4b3d8610fd998bc3@mail.gmail.com>
	<fm23p9$8mc$1@ger.gmane.org>
Message-ID: <105c9ccc0801090212v546fe5fdn744d68258e9f6bba@mail.gmail.com>

hi,
> Sorry, I'm not sure what you mean by zoom in/out?
> Are you talking about graphics? Or some other widget?
>
> Can you explain what you mean?

I want to zoom the page like 100,200,300. For example, take a pdf
viewers we can zoom like what ever the sizes. Like that is there any
packages available.

-- 
Thanks & Regards,
goldgod

From brindly at gmail.com  Wed Jan  9 11:24:10 2008
From: brindly at gmail.com (brindly sujith)
Date: Wed, 9 Jan 2008 15:54:10 +0530
Subject: [Tutor] how to open a file using os.system
Message-ID: <bfb67a4d0801090224k65d632chba4cd8fea475df3a@mail.gmail.com>

hi

i am developing a GUI application using TKINTER

i want to open a file from the askopenfile(which is a tkFileDialog) using
OS.SYSTEM.

i have already created the file open dilog using
tkFileDialog.askopenfile(parent=root,mode='rb',title='choose a file')
Now i want to open a file from this dialog using OS.SYSTEM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080109/9c9a89b3/attachment.htm 

From alan.gauld at btinternet.com  Wed Jan  9 11:31:38 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jan 2008 10:31:38 -0000
Subject: [Tutor] Zooming option in TKinter
References: <105c9ccc0801082344v2e2cf039k4b3d8610fd998bc3@mail.gmail.com><fm23p9$8mc$1@ger.gmane.org>
	<105c9ccc0801090212v546fe5fdn744d68258e9f6bba@mail.gmail.com>
Message-ID: <fm27u6$m6r$1@ger.gmane.org>


"goldgod a" <agoldgod at gmail.com> wrote

>> Can you explain what you mean?
>
> I want to zoom the page like 100,200,300. For example, take a pdf
> viewers we can zoom like what ever the sizes. Like that is there any
> packages available.

Ok, I see.

Sadly the answer is no. There is nothing in Tkinter's Text
widget that allows zooming of the image that is something
you would need to do yourself by changing fonts etc.

You might find someone has created a zoomabnle Text widget
if you ask on the Tkinter mailing list, but I'm pretty sure it's not
a feature thats standard.

Sorry,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From shlomme at gmx.net  Wed Jan  9 11:38:02 2008
From: shlomme at gmx.net (Torsten Marek)
Date: Wed, 09 Jan 2008 11:38:02 +0100
Subject: [Tutor] how to open a file using os.system
In-Reply-To: <bfb67a4d0801090224k65d632chba4cd8fea475df3a@mail.gmail.com>
References: <bfb67a4d0801090224k65d632chba4cd8fea475df3a@mail.gmail.com>
Message-ID: <1199875082.4785.3.camel@ansatz>


On Mi, 2008-01-09 at 15:54 +0530, brindly sujith wrote:
> hi
> 
> i am developing a GUI application using TKINTER
> 
> i want to open a file from the askopenfile(which is a tkFileDialog)
> using OS.SYSTEM.
> 
> i have already created the file open dilog using
> tkFileDialog.askopenfile (parent=root,mode='rb',title='choose a file')
> Now i want to open a file from this dialog using OS.SYSTEM

Hi, 

why would you want to open it using os.system, and how? os.system is for executing
commands in a subshell. If you want to open a file for reading, just do

f = open(filename, "r")

and then read from using using .read(), .readline() or by looping over it.

best,

Torsten
-- 
Torsten Marek <shlomme at gmx.net>
ID: A244C858 -- FP: 1902 0002 5DFC 856B F146  894C 7CC5 451E A244 C858
Keyserver: subkeys.pgp.net

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080109/2a29f093/attachment-0001.pgp 

From alan.gauld at btinternet.com  Wed Jan  9 15:04:20 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jan 2008 14:04:20 -0000
Subject: [Tutor] how to open a file using os.system
References: <bfb67a4d0801090224k65d632chba4cd8fea475df3a@mail.gmail.com>
Message-ID: <fm2kcv$1l6$1@ger.gmane.org>

"brindly sujith" <brindly at gmail.com> wrote

> i am developing a GUI application using TKINTER
>
> i want to open a file from the askopenfile(which is a tkFileDialog) 
> using
> OS.SYSTEM.

Your terminology is a bit confusing.

os.system(lowercase) is for executing system commands.
Do you want to execute a file as a command?
Do you  want to pass a file to a command?

In either case executing os.system requires a command
string, and the askopenfile dialog returns you a filename
as a string.

So what is the problem that you are experiencing?
Can you show us what you have tried and explain
what you want to happen.

Also be aware that os.system does not give you access
to the output of the executed command, for that
you need to use the subprocess module.

> i have already created the file open dilog using
> tkFileDialog.askopenfile(parent=root,mode='rb',title='choose a 
> file')
> Now i want to open a file from this dialog using OS.SYSTEM

You can execute a file but you cannot "open" it in any
meaningful (to Python) sense.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From varsha.purohit at gmail.com  Wed Jan  9 20:40:04 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 9 Jan 2008 11:40:04 -0800
Subject: [Tutor] [tutor] Zoom in and zoom out capability
Message-ID: <c2157c790801091140j615f942cxcf615a655b7bb8ce@mail.gmail.com>

Hello All,
        In my program i have a gui where i am showing an image on the panel.
I want to implement zoom in and zoom out functions using wxpython and PIL. I
am tryin to find in PIL if there is any functionality like that. I want the
user to select either of the button and when they click on the image panel
it shd accordingly zoomin or zoom out. Or may be once user selects an area
inside the image where he wants to zoom in and see. Lemme know if anybody
came across this kind of implementation.

Any help is appreciated.

-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080109/8e4eb455/attachment.htm 

From jnewton at fuelindustries.com  Wed Jan  9 21:12:27 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Wed, 9 Jan 2008 15:12:27 -0500
Subject: [Tutor] Scope and elegance revisited
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8527@ex1.Fuel.Ott>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8B6B@ex1.Fuel.Ott>

Hi Python Purists!

I want all instances of a given class to share a piece of information,
but I want to set that information on the fly.  I have found that this
works:


  class Foo(object):
      # class_variable = None # There is no real need to declare this 

      def __init__(self):
          print self.__class__.class_variable


  def main():
      Foo.class_variable = "Done"
      Foo()
    

  if __name__ == '__main__': main()


Running the script prints out "Done" as expected.

However, this looks ugly to me.  Is there a more elegant way of doing
this?


To give you the context: my application allows you to select a skin for
the user interface.  I want to set the access path to the skin folder as
a class variable, so that all instances of that class use images from
the appropriate folder.  The access path will be read in from a
preferences file before any instances of the class are created.

Thanks in advance for your advice.

James

From alan.gauld at btinternet.com  Wed Jan  9 21:11:18 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 9 Jan 2008 20:11:18 -0000
Subject: [Tutor] [tutor] Zoom in and zoom out capability
References: <c2157c790801091140j615f942cxcf615a655b7bb8ce@mail.gmail.com>
Message-ID: <fm39t2$ke2$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

> I want to implement zoom in and zoom out functions using wxpython 
> and PIL. I
> am tryin to find in PIL if there is any functionality like that.

A few minutes browsing the PIL documentation leads
me to think there are. Try reading about crop and resize and
maybe thumbnail.

Between them these should just about cover your needs I think.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From kent37 at tds.net  Wed Jan  9 21:37:58 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 09 Jan 2008 15:37:58 -0500
Subject: [Tutor] Scope and elegance revisited
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8B6B@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8B6B@ex1.Fuel.Ott>
Message-ID: <478530A6.5010508@tds.net>

James Newton wrote:
> Hi Python Purists!
> 
> I want all instances of a given class to share a piece of information,
> but I want to set that information on the fly.  I have found that this
> works:
> 
> 
>   class Foo(object):
>       # class_variable = None # There is no real need to declare this 
> 
>       def __init__(self):
>           print self.__class__.class_variable

could be just self.class_variable, attributes are looked up in the class 
if not found in the instance (that's how method access works, e.g.).

>   def main():
>       Foo.class_variable = "Done"
>       Foo()
>     
> 
>   if __name__ == '__main__': main()
> 
> 
> Running the script prints out "Done" as expected.
> 
> However, this looks ugly to me.  Is there a more elegant way of doing
> this?

Seems OK to me.

> To give you the context: my application allows you to select a skin for
> the user interface.  I want to set the access path to the skin folder as
> a class variable, so that all instances of that class use images from
> the appropriate folder.  The access path will be read in from a
> preferences file before any instances of the class are created.

Why do you have multiple instances of the class? You might be interested 
in the Borg pattern:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

Kent

From jnewton at fuelindustries.com  Wed Jan  9 22:28:33 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Wed, 9 Jan 2008 16:28:33 -0500
Subject: [Tutor] Scope and elegance revisited
In-Reply-To: <478530A6.5010508@tds.net>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8BB1@ex1.Fuel.Ott>

Kent Johnson wrote: 
>> To give you the context: my application allows you to select a skin
for
>> the user interface.  I want to set the access path to the skin folder
as
>> a class variable, so that all instances of that class use images from
>> the appropriate folder.  The access path will be read in from a
>> preferences file before any instances of the class are created.

> Why do you have multiple instances of the class? You might be
interested 
> in the Borg pattern:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

Hi Kent,

Thanks for your suggestion.

The folder in question contains images for counters for a board game.
Each player instance will use a separate counter image, but all counter
images will be chosen from the same folder.

It looks as if the Borg pattern would make all players use the same
counter image.

Or am I misunderstanding something?

James

From kent37 at tds.net  Wed Jan  9 22:36:50 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 09 Jan 2008 16:36:50 -0500
Subject: [Tutor] Scope and elegance revisited
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8BB1@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8BB1@ex1.Fuel.Ott>
Message-ID: <47853E72.8020704@tds.net>

James Newton wrote:
> The folder in question contains images for counters for a board game.
> Each player instance will use a separate counter image, but all counter
> images will be chosen from the same folder.
> 
> It looks as if the Borg pattern would make all players use the same
> counter image.
> 
> Or am I misunderstanding something?

You understand correctly. Borg is not appropriate for this. I was 
guessing (incorrectly) about what you might be doing.

Kent

From trs164 at hotmail.com  Wed Jan  9 23:27:53 2008
From: trs164 at hotmail.com (Timothy Sikes)
Date: Wed, 9 Jan 2008 16:27:53 -0600
Subject: [Tutor] Windowss sidebar gadgets with Python?
Message-ID: <BAY140-W3070F8E0B4AFEBCA8BCB4F89490@phx.gbl>

Hello all.I have been working with Python for a couple years off and on, and am currently enrolled in a java class. Python was my first language, and I think it's probably my favorite. But anyway, I was wondering about whether a Windows SideBar application could be built with Python.  I'm not completely sure how they work, as honestly, HTML just confuses me.... I know you can use JavaScript, but I don't know if you can apply it with Python.  I'll probably be back with more questions, as I like to develop different Python scripts and programs for my enjoyment, and I'm starting basic Socket and Network programming.Thank you
_________________________________________________________________
Put your friends on the big screen with Windows Vista? + Windows Live?.
http://www.microsoft.com/windows/shop/specialoffers.mspx?ocid=TXT_TAGLM_CPC_MediaCtr_bigscreen_012008
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080109/8978f4ea/attachment.htm 

From mlangford.cs03 at gtalumni.org  Wed Jan  9 23:44:44 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 9 Jan 2008 17:44:44 -0500
Subject: [Tutor] Windowss sidebar gadgets with Python?
In-Reply-To: <BAY140-W3070F8E0B4AFEBCA8BCB4F89490@phx.gbl>
References: <BAY140-W3070F8E0B4AFEBCA8BCB4F89490@phx.gbl>
Message-ID: <82b4f5810801091444l1b93c84dla85a4fa57ca9325a@mail.gmail.com>

The answer is "Sort of" or "Not really" depending on how you define "in python".

http://microsoftgadgets.com/Sidebar/DevelopmentOverview.aspx
and
http://msdn2.microsoft.com/en-us/library/bb508513.aspx

are the apropos pieces of documentation. You can call a python program
via the System.Shell.execute function in your sidebar script, and have
it change the html files (or better yet, an xml file) that the toolbar
app uses. After it completes, you update the UI via reloading the XML
file.

It's not the least roundabout way to do something I've ever seen, but
it looks possible.

        --Michael

PS: I've had notes on this for awhile, but haven't had the time to
try. If it works, let me know.


On 1/9/08, Timothy Sikes <trs164 at hotmail.com> wrote:
>
> Hello all.
>
> I have been working with Python for a couple years off and on, and am
> currently enrolled in a java class. Python was my first language, and I
> think it's probably my favorite. But anyway, I was wondering about whether a
> Windows SideBar application could be built with Python.  I'm not completely
> sure how they work, as honestly, HTML just confuses me.... I know you can
> use JavaScript, but I don't know if you can apply it with Python.  I'll
> probably be back with more questions, as I like to develop different Python
> scripts and programs for my enjoyment, and I'm starting basic Socket and
> Network programming.
>
> Thank you
> ________________________________
> Put your friends on the big screen with Windows Vista(R) + Windows Live?.
> Start now!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From varsha.purohit at gmail.com  Thu Jan 10 02:17:47 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 9 Jan 2008 17:17:47 -0800
Subject: [Tutor] [tutor] Zoom in and zoom out capability
In-Reply-To: <fm39t2$ke2$1@ger.gmane.org>
References: <c2157c790801091140j615f942cxcf615a655b7bb8ce@mail.gmail.com>
	<fm39t2$ke2$1@ger.gmane.org>
Message-ID: <c2157c790801091717l3d16d35fkb2a1c527008c3ba5@mail.gmail.com>

Hi Alan,
     Yeah i read about them. i tried using the resize function but i was
having difficulty with clarity of the image. I had asked similar thing in
another post. I didnt get any satisfying answer for that. Tried
imagefilter<http://www.pythonware.com/library/pil/handbook/imagefilter.htm>even
thats not workin out properly. :(

Well in my application i need to make a button which when pressed should
zoom in the image so i was wondering how can i implement it i mean how
should i present the image with more size in a fixed size image panel. Any
ideas.. i am even plannin to implement a slider which will zoom in and out
the image accordingly..



-
Varsha

On Jan 9, 2008 12:11 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>
> > I want to implement zoom in and zoom out functions using wxpython
> > and PIL. I
> > am tryin to find in PIL if there is any functionality like that.
>
> A few minutes browsing the PIL documentation leads
> me to think there are. Try reading about crop and resize and
> maybe thumbnail.
>
> Between them these should just about cover your needs I think.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080109/fd44a786/attachment-0001.htm 

From keridee at jayco.net  Wed Jan  9 22:03:53 2008
From: keridee at jayco.net (Tiger12506)
Date: Wed, 9 Jan 2008 16:03:53 -0500
Subject: [Tutor] how to open a file using os.system
References: <bfb67a4d0801090224k65d632chba4cd8fea475df3a@mail.gmail.com>
Message-ID: <000201c85327$99c6ed40$175ae104@jslaptop>

> hi
>
> i am developing a GUI application using TKINTER
>
> i want to open a file from the askopenfile(which is a tkFileDialog) using
> OS.SYSTEM.
>
> i have already created the file open dilog using
> tkFileDialog.askopenfile(parent=root,mode='rb',title='choose a file')
> Now i want to open a file from this dialog using OS.SYSTEM

I am not completely familiar with tkFileDialog but I would bet that it 
returns the file you choose as a string. Try this.

fn = tkFileDialog.askopenfile(parent=root,mode='rb',title='choose a file')
os.system(fn)

Note: This means open a file as explorer.exe would open a file, such as an 
executable 


From goldwamh at slu.edu  Thu Jan 10 04:09:50 2008
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Wed, 9 Jan 2008 21:09:50 -0600
Subject: [Tutor] Scope and elegance revisited
In-Reply-To: <478530A6.5010508@tds.net>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8B6B@ex1.Fuel.Ott>
	<478530A6.5010508@tds.net>
Message-ID: <18309.35966.426743.695181@euclid.slu.edu>



On Wednesday January 9, 2008, Kent Johnson wrote: 

>    James Newton wrote:
>    > Hi Python Purists!
>    > 
>    > I want all instances of a given class to share a piece of information,
>    > but I want to set that information on the fly.  I have found that this
>    > works:
>    > 
>    > 
>    >   class Foo(object):
>    >       # class_variable = None # There is no real need to declare this 
>    > 
>    >       def __init__(self):
>    >           print self.__class__.class_variable
>    
>    could be just self.class_variable, attributes are looked up in the class 
>    if not found in the instance (that's how method access works, e.g.).

Though Kent is correct that the class namespace will be searched when
the variable is not found in the instance namespace, I still prefer to
use the syntax  Foo.class_variable in this context as it makes the
code more legible in regard to this being a class variable.

The only reason I can imagine using the self.__class__ syntax would be
if you expect subclasses to be defined and intentionally want to rely
on the subclass namespace rather than Foo.


>    >   def main():
>    >       Foo.class_variable = "Done"
>    >       Foo()

Notice the above change matches the style you are using in main().

Michael


From allen.fowler at yahoo.com  Thu Jan 10 06:41:20 2008
From: allen.fowler at yahoo.com (Allen Fowler)
Date: Wed, 9 Jan 2008 21:41:20 -0800 (PST)
Subject: [Tutor] run in "deamon" mode?
Message-ID: <848599.87160.qm@web45608.mail.sp1.yahoo.com>

Hello,

How can a make a python script run in "deamon mode"? (on a linux box)

That is, I want to run the program via "python myfile.py" and have it drop me back to the command line.  The program should continue running until I kill it via it's PID, the machine shuts down, or the program itself decides to shutdown.   It should _not_  die when I simply log-out, etc.

Is there a standard library module to help with this?

-- Thank you





      ____________________________________________________________________________________
Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  http://tools.search.yahoo.com/newsearch/category.php?category=shopping


From alan.gauld at btinternet.com  Thu Jan 10 09:06:24 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 08:06:24 -0000
Subject: [Tutor] [tutor] Zoom in and zoom out capability
References: <c2157c790801091140j615f942cxcf615a655b7bb8ce@mail.gmail.com><fm39t2$ke2$1@ger.gmane.org>
	<c2157c790801091717l3d16d35fkb2a1c527008c3ba5@mail.gmail.com>
Message-ID: <fm4jps$4fg$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>     Yeah i read about them. i tried using the resize function but i 
> was
> having difficulty with clarity of the image.

I remeber. That was because you were trying to zoom into
a small JPG image. You can't put more detail into an image
than is there to start with. Zooming into a small JPG will
always give you resolution problems.

Alan G. 



From alan.gauld at btinternet.com  Thu Jan 10 09:10:05 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 08:10:05 -0000
Subject: [Tutor] run in "deamon" mode?
References: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
Message-ID: <fm4k0q$52p$1@ger.gmane.org>


"Allen Fowler" <allen.fowler at yahoo.com> wrote

> How can a make a python script run in "deamon mode"? (on a linux 
> box)

ISTR that there is a recipe for this on the ActiveState cookbook site?

> That is, I want to run the program via "python myfile.py"
> and have it drop me back to the command line.

Simply running in background achioeves this - add ampersand (&)
after the command.

> The program should continue running until I kill it via it's PID,
> the machine shuts down, or the program itself decides to
> shutdown.   It should _not_  die when I simply log-out, etc.

OK, That needs more work - although I think running it from
sudo would do the trick if thats an option. Otherwise its
the cookbook recipe I think.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From aditya.n.lal at gmail.com  Thu Jan 10 09:29:20 2008
From: aditya.n.lal at gmail.com (Aditya Lal)
Date: Thu, 10 Jan 2008 13:59:20 +0530
Subject: [Tutor] run in "deamon" mode?
In-Reply-To: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
References: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
Message-ID: <5df213700801100029xf370949o5e0efd726b741310@mail.gmail.com>

On Jan 10, 2008 11:11 AM, Allen Fowler <allen.fowler at yahoo.com> wrote:

> Hello,
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>
> That is, I want to run the program via "python myfile.py" and have it drop
> me back to the command line.  The program should continue running until I
> kill it via it's PID, the machine shuts down, or the program itself decides
> to shutdown.   It should _not_  die when I simply log-out, etc.
>
> Is there a standard library module to help with this?
>
> -- Thank you
>
>
>
>
The simplest way to achieve this is as follows :
$ nohup python myfile.py &
Otherwise you need to become daemon from inside the program. fork(),
setsid(), etc. - the normal C language method for becoming a daemon..

-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080110/3d1ea4d5/attachment.htm 

From remco at gerlich.nl  Thu Jan 10 09:31:18 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 10 Jan 2008 09:31:18 +0100
Subject: [Tutor] run in "deamon" mode?
In-Reply-To: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
References: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
Message-ID: <7ae3ca10801100031j19474ec4pe0f788a378bd40ba@mail.gmail.com>

Hi,

A few days ago, someone posted a "daemon.py" to Reddit, that's supposed to
do everything needed. Haven't used it myself, but here it is:
http://hathawaymix.org/Software/Sketches/daemon.py

Remco

On Jan 10, 2008 6:41 AM, Allen Fowler <allen.fowler at yahoo.com> wrote:

> Hello,
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>
> That is, I want to run the program via "python myfile.py" and have it drop
> me back to the command line.  The program should continue running until I
> kill it via it's PID, the machine shuts down, or the program itself decides
> to shutdown.   It should _not_  die when I simply log-out, etc.
>
> Is there a standard library module to help with this?
>
> -- Thank you
>
>
>
>
>
>
>  ____________________________________________________________________________________
> Looking for last minute shopping deals?
> Find them fast with Yahoo! Search.
> http://tools.search.yahoo.com/newsearch/category.php?category=shopping
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080110/eda764e5/attachment.htm 

From hieu.d.hoang at gmail.com  Thu Jan 10 09:34:05 2008
From: hieu.d.hoang at gmail.com (=?UTF-8?Q?Hi=E1=BA=BFu_Ho=C3=A0ng?=)
Date: Thu, 10 Jan 2008 15:34:05 +0700
Subject: [Tutor] run in "deamon" mode?
In-Reply-To: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
References: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
Message-ID: <4f12b0dd0801100034j2fb92aceva03394499f4f2761@mail.gmail.com>

On Jan 10, 2008 12:41 PM, Allen Fowler <allen.fowler at yahoo.com> wrote:
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>

<http://blog.ianbicking.org/daemon-best-practices.html>
The comments on this post sum up a lot of daemonizing modules. I
haven't tried any of them out if they run after you logged out, and
Aditya's "nohup" way looks quickest.

Hi?u

From brindly at gmail.com  Thu Jan 10 09:45:14 2008
From: brindly at gmail.com (brindly sujith)
Date: Thu, 10 Jan 2008 14:15:14 +0530
Subject: [Tutor] how to run a timer in window using TKINTER
Message-ID: <bfb67a4d0801100045n23ca6905lfd3b70e09ca9193e@mail.gmail.com>

i want to run a timer in a window

plz guide me how to do this

after some 5 seconds i want to close the  same window automatically

send me the Tkinter code for this
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080110/71ea167b/attachment.htm 

From timmichelsen at gmx-topmail.de  Thu Jan 10 10:11:50 2008
From: timmichelsen at gmx-topmail.de (Timmie)
Date: Thu, 10 Jan 2008 09:11:50 +0000 (UTC)
Subject: [Tutor] getting filen basename without extension
Message-ID: <loom.20080110T090805-609@post.gmane.org>

Hello,
I would like to get the name of a file without it's extension/suffix.

What is the easiest and fastes way to get the basename
of a file wihout extension?

What I found is this:
import os
myfile_name_with_path = 'path/to/my/testfile.txt'
basename = os.path.basename(myfile_with_path)
filename = os.path.splitext(basename)
myfile_name_without_suffix = filename[0]

Can this be done with less code?

Thanks and kind regards,
Timmie


From alan.gauld at btinternet.com  Thu Jan 10 10:34:19 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 09:34:19 -0000
Subject: [Tutor] how to run a timer in window using TKINTER
References: <bfb67a4d0801100045n23ca6905lfd3b70e09ca9193e@mail.gmail.com>
Message-ID: <fm4ouo$jte$1@ger.gmane.org>


"brindly sujith" <brindly at gmail.com> wrote

>i want to run a timer in a window
> 
> plz guide me how to do this

There is a timer facility in Tkinter for this.

In your window constructor add a call to self.after()
Add a callback function/lambda that closes the window.

> send me the Tkinter code for this
##############
from Tkinter import *

tk = Tk()
L =Label(tk, text="Wait for it!")
L.pack()
L.after(5000, tk.quit  )  # quit after 5000ms

tk.mainloop()
###############
Is the shortest I could think of...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From finalyugi at sapo.pt  Thu Jan 10 11:40:17 2008
From: finalyugi at sapo.pt (Rolando Pereira)
Date: Thu, 10 Jan 2008 10:40:17 +0000
Subject: [Tutor] getting filen basename without extension
In-Reply-To: <loom.20080110T090805-609@post.gmane.org>
References: <loom.20080110T090805-609@post.gmane.org>
Message-ID: <4785F611.7030107@sapo.pt>

Timmie wrote:
> Hello,
> I would like to get the name of a file without it's extension/suffix.
> 
> What is the easiest and fastes way to get the basename
> of a file wihout extension?
> 
> What I found is this:
> import os
> myfile_name_with_path = 'path/to/my/testfile.txt'
> basename = os.path.basename(myfile_with_path)
> filename = os.path.splitext(basename)
> myfile_name_without_suffix = filename[0]
> 
> Can this be done with less code?
> 
> Thanks and kind regards,
> Timmie
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

I did something like this:

import os
path = 'path/to/file.ext'
filename = path.split(".")[0].split("/")[-1]
print filename
>>> file

The only problem I see is if the file has some "." character besides the
one before the extention.

-- 
                       _
ASCII ribbon campaign ( )
 - against HTML email  X
             & vCards / \

From alan.gauld at btinternet.com  Thu Jan 10 14:07:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 13:07:09 -0000
Subject: [Tutor] getting filen basename without extension
References: <loom.20080110T090805-609@post.gmane.org>
Message-ID: <fm55dq$ul2$1@ger.gmane.org>


"Timmie" <timmichelsen at gmx-topmail.de> wrote 

> What is the easiest and fastes way to get the basename
> of a file wihout extension?
> 
> What I found is this:
> import os
> myfile_name_with_path = 'path/to/my/testfile.txt'
> basename = os.path.basename(myfile_with_path)
> filename = os.path.splitext(basename)
> myfile_name_without_suffix = filename[0]

The last two can be easily combined as:

> myfile_name_without_suffix = os.path.splitext(basename)[0]

without much loss of clarity.
You could combine the basename call as well of course, 
but that is getting too messy for my liking.

But otherwise you are using the "correct" mechanism if 
you want a reliable result.

Alan G.


From timmichelsen at gmx-topmail.de  Thu Jan 10 14:33:01 2008
From: timmichelsen at gmx-topmail.de (Timmie)
Date: Thu, 10 Jan 2008 13:33:01 +0000 (UTC)
Subject: [Tutor] getting filen basename without extension
References: <loom.20080110T090805-609@post.gmane.org>
	<fm55dq$ul2$1@ger.gmane.org>
Message-ID: <loom.20080110T133121-740@post.gmane.org>

> > What I found is this:
> > import os
> > myfile_name_with_path = 'path/to/my/testfile.txt'
> > basename = os.path.basename(myfile_with_path)
> > filename = os.path.splitext(basename)
> > myfile_name_without_suffix = filename[0]
> 
> The last two can be easily combined as:
> 
> > myfile_name_without_suffix = os.path.splitext(basename)[0]
> 
> But otherwise you are using the "correct" mechanism if 
> you want a reliable result.
Thanks for this confirmation.

I am happy to have made some tiny progress in my python learings...

Kind regards,
Timmie


From reed at reedobrien.com  Thu Jan 10 15:00:51 2008
From: reed at reedobrien.com (Reed O'Brien)
Date: Thu, 10 Jan 2008 09:00:51 -0500
Subject: [Tutor] run in "deamon" mode?
In-Reply-To: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
References: <848599.87160.qm@web45608.mail.sp1.yahoo.com>
Message-ID: <499F9845-90AE-4F60-AFDB-8122585AE523@reedobrien.com>

On Jan 10, 2008, at 12:41 AM, Allen Fowler wrote:

> Hello,
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>
> That is, I want to run the program via "python myfile.py" and have  
> it drop me back to the command line.  The program should continue  
> running until I kill it via it's PID, the machine shuts down, or  
> the program itself decides to shutdown.   It should _not_  die when  
> I simply log-out, etc.
>
> Is there a standard library module to help with this?

Something I have thrown into scripts to daemonize them. NOTE: this is  
probably not the `best` way.  but it works...

import os
import sys

def daemonize():
	"""Become a daemon, seperate from the terminal and redirect IO"""
	if os.fork(): os._exit(0)
	os.setuid(1) # set user to  daemon
	os.setsid()
	sys.stdin  = sys.__stdin__  = open('/dev/null','r')
	sys.stdout = sys.__stdout__ = open('/dev/null','w')
	sys.stdout = sys.__stderr__ = sys.stdout


Then when you start your program in say main()

call daemonize()

From jnewton at fuelindustries.com  Thu Jan 10 17:23:17 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Thu, 10 Jan 2008 11:23:17 -0500
Subject: [Tutor] Opening a window to fit an image
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8B6B@ex1.Fuel.Ott>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8CB5@ex1.Fuel.Ott>

Hi Python Pros,

I want to create a window to fit an image that I read in on the fly.
I'm using pygame to load images and to create the window.  I find I have
to use pygame.display.set_mode() twice: once to allow me to use
pygame.image.loadfile(), and once to reset the window size after I have
been able to determine the size of the loaded image.

Does this have any undesired side-effects?  Is there a better way of
doing this?

Here's the relevant extract of my script.


import os
import pygame


def main():
    pygame.init()
    
    # You must use display.set_mode() before you can use image.load
    # If you don't, you get an "error: No video mode has been set"
    screen     = pygame.display.set_mode((1, 1))

    # Now we can load an image file and find out its size
    vFile      = 'image.bmp' # in same folder as script
    background = pygame.image.load(vFile).convert()
    vRect      = background.get_rect()

    # Reset the display mode to fit the image
    screen     = pygame.display.set_mode((vRect[2], vRect[3]))

    # Show the image in the window
    screen.blit(background, (0, 0))
    pygame.display.update()

    # <SNIP: code to make application exit gracefully>

main()


Thanks in advance for your help,

James

From warewerks at verizon.net  Thu Jan 10 17:39:10 2008
From: warewerks at verizon.net (Andrew Volmensky)
Date: Thu, 10 Jan 2008 08:39:10 -0800
Subject: [Tutor]  import sys; sys.exit()
In-Reply-To: <fm55dq$ul2$1@ger.gmane.org>
References: <loom.20080110T090805-609@post.gmane.org>
	<fm55dq$ul2$1@ger.gmane.org>
Message-ID: <D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>



I am going through the tutorial "Simple Sequences" here: http:// 
www.freenetpages.co.uk/hp/alan.gauld/

...and get an error. I have tried saving as exit.py from the editor  
and trying to run it and also entering the commands directly into the  
shell. My understanding is that this is supposed to exit the program,  
but that does not appear to be happening.

This is with MacPython 2.4 - Thanks!

IDLE 1.1.4
 >>> ================================ RESTART  
================================
 >>>

Traceback (most recent call last):
   File "/Users/andrew/python/exit.py", line 2, in -toplevel-
     sys.exit( )
SystemExit


 >>> import sys
 >>> sys.exit()

Traceback (most recent call last):
   File "<pyshell#1>", line 1, in -toplevel-
     sys.exit()
SystemExit
 >>>


From alan.gauld at btinternet.com  Thu Jan 10 18:33:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 17:33:09 -0000
Subject: [Tutor] import sys; sys.exit()
References: <loom.20080110T090805-609@post.gmane.org><fm55dq$ul2$1@ger.gmane.org>
	<D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
Message-ID: <fm5l0i$sm6$1@ger.gmane.org>

"Andrew Volmensky" <warewerks at verizon.net> wrote

> I am going through the tutorial "Simple Sequences" here: http://
> www.freenetpages.co.uk/hp/alan.gauld/

Good choice ;-)

> ...and get an error. I have tried saving as exit.py from the editor
> and trying to run it

How are you running it?
You need to run it from the Terminal application.
If you are using an IDE environment like IDLE the tool will
catch the attempt to exit and display a warning - which
is what you appear to be seeing.

> and also entering the commands directly into the
> shell.

Again if the shell is the one you get by typing python
at the Terminal prompt it should work and exit python.
But if you are using an IDE prompt such as IDLE then
IDLE will catch the attempt to exit.

> This is with MacPython 2.4 - Thanks!
>
> IDLE 1.1.4
> >>> ================================ RESTART
> ================================
> >>>
>
> Traceback (most recent call last):
>   File "/Users/andrew/python/exit.py", line 2, in -toplevel-
>     sys.exit( )
> SystemExit
>
>
> >>> import sys
> >>> sys.exit()
>
> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in -toplevel-
>     sys.exit()
> SystemExit
> >>>

This looks like the expected behaviour inside IDLE.

I'll add a note to that effect to the web page, thanks for
pointing it out.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From kvander11 at gmail.com  Thu Jan 10 19:25:27 2008
From: kvander11 at gmail.com (Kirk Vander Meulen)
Date: Thu, 10 Jan 2008 12:25:27 -0600
Subject: [Tutor] replacing CreateProcess command for Vista compatibility?
Message-ID: <2d0c08ca0801101025o4f8ba252w7b9f5c11c65c8b46@mail.gmail.com>

Hi, I'm running the program Pymol (written in python) on Windows Vista, and
in trying to run one of its plugins, I em encountering the following error:

Error: 3
WindowsError Exception in Tk callback
  Function: <function <lambda> at 0x027C6DF0> (type: <type 'function'>)
  Args: ()
Traceback (innermost last):
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\Pmw\Pmw_1_2\lib\PmwBase.py", line 1747,
in __call__
    return apply(self.func, args)
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\Pmw\Pmw_1_2\lib\PmwDialog.py", line
153, in <lambda>
    command=lambda self=self, name=name: self._doCommand(name))
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\Pmw\Pmw_1_2\lib\PmwDialog.py", line
132, in _doCommand
    return command(name)
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\pmg_tk\startup\apbs_tools.py", line
1136, in execute
    good = self.generatePdb2pqrPqrFile()
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\pmg_tk\startup\apbs_tools.py", line
1683, in generatePdb2pqrPqrFile
    (retval,progout) = run(self.pdb2pqr.getvalue(),args)
  File "C:\Program
Files\DeLanoScientific\PyMOL/modules\pmg_tk\startup\apbs_tools.py", line
362, in run
    retcode = subprocess.call(args,stdout=output_file.fileno(),stderr=
subprocess.STDOUT)
  File "C:\Program Files\DeLanoScientific\PyMOL\py24\lib\subprocess.py",
line 413, in call
    return Popen(*args, **kwargs).wait()
  File "C:\Program Files\DeLanoScientific\PyMOL\py24\lib\subprocess.py",
line 543, in __init__
    errread, errwrite)
  File "C:\Program Files\DeLanoScientific\PyMOL\py24\lib\subprocess.py",
line 706, in _execute_child
    startupinfo)
WindowsError: [Errno 193] %1 is not a valid Win32 application


Probably not all of that is relevant, but I thought I'd at least lay it out
there in case there's something obvious there.  In doing crazy amounts of
googling, I *think* the problem is that the python file uses a command
called "createprocess()", and, while this may work ok in XP, it does not in
Vista (something to do with how the security setup has changed).  The
software is not guaranteed fully Vista-proof, so it seems like a possible
explantion.

So I'm hoping, although not very optimistically, that I can tweak this
command and regain compatibility with Vista.  One site I found suggests
using either "ShellExecute()" or "ShellExecuteEx()" in lieu of
"createprocess()".  Would this be a simple fix- how much would I have to
change?  Here is the relevant call:

                hp, ht, pid, tid = CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         # must inherit handles to pass std
                                         # handles
                                         1,
                                         creationflags,
                                         env,
                                         cwd,
                                         startupinfo)

Thanks for any help,

Kirk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080110/d8a0e0c2/attachment.htm 

From kent37 at tds.net  Thu Jan 10 19:35:42 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 10 Jan 2008 13:35:42 -0500
Subject: [Tutor] import sys; sys.exit()
In-Reply-To: <D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
References: <loom.20080110T090805-609@post.gmane.org>	<fm55dq$ul2$1@ger.gmane.org>
	<D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
Message-ID: <4786657E.5060407@tds.net>

Andrew Volmensky wrote:

> ...and get an error. I have tried saving as exit.py from the editor  
> and trying to run it and also entering the commands directly into the  
> shell. My understanding is that this is supposed to exit the program,  
> but that does not appear to be happening.

sys.exit() doesn't do what you might think - it doesn't force an exit 
from the current process. All it does is raise a SystemExit exception. 
How this is handled depends on the context - SystemExit can be caught by 
an enclosing except handler just like any other exception.

If you are running a program directly, SystemExit will probably 
propagate to the interpreter and cause the program to exit, just as any 
other uncaught exception would.

Running in IDLE or another shell, the exception is caught and logged but 
it doesn't abort the process.

Kent

> This is with MacPython 2.4 - Thanks!
> 
> IDLE 1.1.4
>  >>> ================================ RESTART  
> ================================
>  >>>
> 
> Traceback (most recent call last):
>    File "/Users/andrew/python/exit.py", line 2, in -toplevel-
>      sys.exit( )
> SystemExit
> 
> 
>  >>> import sys
>  >>> sys.exit()
> 
> Traceback (most recent call last):
>    File "<pyshell#1>", line 1, in -toplevel-
>      sys.exit()
> SystemExit
>  >>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From keridee at jayco.net  Thu Jan 10 21:42:26 2008
From: keridee at jayco.net (Tiger12506)
Date: Thu, 10 Jan 2008 15:42:26 -0500
Subject: [Tutor] replacing CreateProcess command for Vista compatibility?
References: <2d0c08ca0801101025o4f8ba252w7b9f5c11c65c8b46@mail.gmail.com>
Message-ID: <002e01c853c9$5301add0$3efce004@jslaptop>

> WindowsError: [Errno 193] %1 is not a valid Win32 application

This line says that %1 is not a valid application. Windows uses %1 to mean 
the first argument on the command line to the program. Without seeing any 
code, it would be difficult to tell where this is being introduced, but the 
explanation is that someone somewhere (it may be you, it may be the 
libraries) is putting in %1 instead of the actual filename that %1 refers 
to. 


From warewerks at verizon.net  Thu Jan 10 22:17:20 2008
From: warewerks at verizon.net (Andrew Volmensky)
Date: Thu, 10 Jan 2008 13:17:20 -0800
Subject: [Tutor] import sys; sys.exit()
In-Reply-To: <fm5l0i$sm6$1@ger.gmane.org>
References: <loom.20080110T090805-609@post.gmane.org><fm55dq$ul2$1@ger.gmane.org>
	<D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
	<fm5l0i$sm6$1@ger.gmane.org>
Message-ID: <62AD46E3-9D12-4443-9A2C-BF3C043FBD12@verizon.net>

Thanks Alan,

When typing the commands [statements?] in the terminal I get this:

Last login: Sat Jan  5 22:20:44 on ttyp2
Welcome to Darwin!
warewerks-01:~ andrew$ python
Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys
 >>> sys.exit()
warewerks-01:~ andrew$

Does that behavior look correct? Apparently I have exit out of the  
Python interpreter; yes?


Kent - also thank you! I hope "exceptions" are covered in a following  
tutorial!

> ...and get an error. I have tried saving as exit.py from the  
> editor  and trying to run it and also entering the commands  
> directly into the  shell. My understanding is that this is supposed  
> to exit the program,  but that does not appear to be happening.
>

sys.exit() doesn't do what you might think - it doesn't force an exit  
from the current process. All it does is raise a SystemExit  
exception. How this is handled depends on the context - SystemExit  
can be caught by an enclosing except handler just like any other  
exception.

If you are running a program directly, SystemExit will probably  
propagate to the interpreter and cause the program to exit, just as  
any other uncaught exception would.

Running in IDLE or another shell, the exception is caught and logged  
but it doesn't abort the process.

Kent


On Jan 10, 2008, at 9:33 AM, Alan Gauld wrote:

> "Andrew Volmensky" <warewerks at verizon.net> wrote
>
>> I am going through the tutorial "Simple Sequences" here: http://
>> www.freenetpages.co.uk/hp/alan.gauld/
>
> Good choice ;-)
>
>> ...and get an error. I have tried saving as exit.py from the editor
>> and trying to run it
>
> How are you running it?
> You need to run it from the Terminal application.
> If you are using an IDE environment like IDLE the tool will
> catch the attempt to exit and display a warning - which
> is what you appear to be seeing.
>
>> and also entering the commands directly into the
>> shell.
>
> Again if the shell is the one you get by typing python
> at the Terminal prompt it should work and exit python.
> But if you are using an IDE prompt such as IDLE then
> IDLE will catch the attempt to exit.
>
>> This is with MacPython 2.4 - Thanks!
>>
>> IDLE 1.1.4
>>>>> ================================ RESTART
>> ================================
>>>>>
>>
>> Traceback (most recent call last):
>>   File "/Users/andrew/python/exit.py", line 2, in -toplevel-
>>     sys.exit( )
>> SystemExit
>>
>>
>>>>> import sys
>>>>> sys.exit()
>>
>> Traceback (most recent call last):
>>   File "<pyshell#1>", line 1, in -toplevel-
>>     sys.exit()
>> SystemExit
>>>>>
>
> This looks like the expected behaviour inside IDLE.
>
> I'll add a note to that effect to the web page, thanks for
> pointing it out.
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From brunson at brunson.com  Thu Jan 10 22:22:02 2008
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 10 Jan 2008 14:22:02 -0700
Subject: [Tutor] import sys; sys.exit()
In-Reply-To: <4786657E.5060407@tds.net>
References: <loom.20080110T090805-609@post.gmane.org>	<fm55dq$ul2$1@ger.gmane.org>	<D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
	<4786657E.5060407@tds.net>
Message-ID: <47868C7A.4070506@brunson.com>

Kent Johnson wrote:
> Andrew Volmensky wrote:
>
>   
>> ...and get an error. I have tried saving as exit.py from the editor  
>> and trying to run it and also entering the commands directly into the  
>> shell. My understanding is that this is supposed to exit the program,  
>> but that does not appear to be happening.
>>     
>
> sys.exit() doesn't do what you might think - it doesn't force an exit 
> from the current process. All it does is raise a SystemExit exception. 
> How this is handled depends on the context - SystemExit can be caught by 
> an enclosing except handler just like any other exception.
>
> If you are running a program directly, SystemExit will probably 
> propagate to the interpreter and cause the program to exit, just as any 
> other uncaught exception would.
>
> Running in IDLE or another shell, the exception is caught and logged but 
> it doesn't abort the process.
>   


FWIW, and in no way contradictory to what Kent said above, I find it 
more pythonic to simply raise SystemExit.  It doesn't require an import 
and when used in a program, if you raise SystemExit() with no 
parameters, the program will exit with no error.  Raising SystemExit( 
'some error message' ) will print the error message and exit with a 
non-zero status.


> Kent
>
>   
>> This is with MacPython 2.4 - Thanks!
>>
>> IDLE 1.1.4
>>  >>> ================================ RESTART  
>> ================================
>>  >>>
>>
>> Traceback (most recent call last):
>>    File "/Users/andrew/python/exit.py", line 2, in -toplevel-
>>      sys.exit( )
>> SystemExit
>>
>>
>>  >>> import sys
>>  >>> sys.exit()
>>
>> Traceback (most recent call last):
>>    File "<pyshell#1>", line 1, in -toplevel-
>>      sys.exit()
>> SystemExit
>>  >>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>     
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From steve at alchemy.com  Thu Jan 10 22:32:11 2008
From: steve at alchemy.com (Steve Willoughby)
Date: Thu, 10 Jan 2008 13:32:11 -0800
Subject: [Tutor] import sys; sys.exit()
In-Reply-To: <62AD46E3-9D12-4443-9A2C-BF3C043FBD12@verizon.net>
References: <D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net>
	<fm5l0i$sm6$1@ger.gmane.org>
	<62AD46E3-9D12-4443-9A2C-BF3C043FBD12@verizon.net>
Message-ID: <20080110213211.GC7064@dragon.alchemy.com>

On Thu, Jan 10, 2008 at 01:17:20PM -0800, Andrew Volmensky wrote:
> When typing the commands [statements?] in the terminal I get this:
> 
> Last login: Sat Jan  5 22:20:44 on ttyp2
> Welcome to Darwin!
> warewerks-01:~ andrew$ python
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import sys
>  >>> sys.exit()
> warewerks-01:~ andrew$
> 
> Does that behavior look correct? Apparently I have exit out of the  
> Python interpreter; yes?

Yes.

In a running program, a SystemExit exception will, unless some part 
of your program is specfically watching to intercept it, terminate
your program.  In your example above, you are exiting the interpreter.

If you were in IDLE instead of a terminal window, the GUI would 
catch it and ask you if you wanted to exit IDLE or just go back
to an interactive Python interpreter prompt.

> Kent - also thank you! I hope "exceptions" are covered in a following  
> tutorial!

Exceptions are something you should have at least basic familiarity
with (as a general concept, not necessarily a lot of detail) fairly 
soon upon starting to learn Python.  At least this much:

An exception is an error event raised by some part of your program
which ran into trouble trying to carry out an operation.  Normally,
the exception is printed out with some amount of relevant information
like "Division by zero error!" or "Permission denied opening foo.txt"
and your program will exit.

An uncaught exception raised in a function will immediately terminate
that function, and if the calling function wasn't set up to catch that
exception, then it's terminated too, and so on up the levels of the
call stack until something deals with that issue or you run out of 
levels to exit and you fall out of your program completely.

If you want to have Python try to run a block of code but let you
handle any exceptions which occur, you can do this:

  try:
    (insert your code here...)
  except:
    (the code here is run if anything in
    the "try" block failed...)

If you want to handle a specific exception only, you can do
something like in this example:

  try:
    spam = int(message_qty)
  except ValueError:
    spam = 0
    print "Warning:", message_qty, "is not a valid-looking number"
    print "proceeding with a value of 0 instead."

If the int() function raises a ValueError, the code here will 
deal gracefully with that, and carry on.  Any other exception
will still be handled normally.

There's a lot more detail, but that's the basic gist of it.

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

From alan.gauld at btinternet.com  Thu Jan 10 23:03:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 10 Jan 2008 22:03:32 -0000
Subject: [Tutor] import sys; sys.exit()
References: <loom.20080110T090805-609@post.gmane.org><fm55dq$ul2$1@ger.gmane.org><D3AD12A5-5A08-4EAB-91CF-73A5A4461D1D@verizon.net><fm5l0i$sm6$1@ger.gmane.org>
	<62AD46E3-9D12-4443-9A2C-BF3C043FBD12@verizon.net>
Message-ID: <fm64rh$mvq$1@ger.gmane.org>


"Andrew Volmensky" <warewerks at verizon.net> wrote

> warewerks-01:~ andrew$ python
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more 
> information.
> >>> import sys
> >>> sys.exit()
> warewerks-01:~ andrew$
>
> Does that behavior look correct? Apparently I have exit out of the
> Python interpreter; yes?

Yes thats absolutely correct.

> Kent - also thank you! I hope "exceptions" are covered in a 
> following
> tutorial!

Indeed they are under Error handling.

Alan G.



From cappy2112 at gmail.com  Thu Jan 10 19:37:38 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Thu, 10 Jan 2008 10:37:38 -0800
Subject: [Tutor] shutils.copytree
Message-ID: <8249c4ac0801101037i58f3595fke7fa35dbd550de80@mail.gmail.com>

I'm using shutils for the first time, and I've un into a problem.
The docs for copytree are pretty sparse and don't mention any problem situations

Under WinXP, I'm trying to copy a directory tree to a USB device using
copytree, but copytree doesn't like a drive letter as a destination.

copytree('C:\\testdir', 'g:\\')

OsError: Permission denied was displayed

However, when I changed the call to copytree('C:\\testdir', 'g:\\junk')

copytree worked.

Why is the root directory '\\' not a valid destination?

From kent37 at tds.net  Fri Jan 11 02:30:46 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 10 Jan 2008 20:30:46 -0500
Subject: [Tutor] shutils.copytree
In-Reply-To: <8249c4ac0801101037i58f3595fke7fa35dbd550de80@mail.gmail.com>
References: <8249c4ac0801101037i58f3595fke7fa35dbd550de80@mail.gmail.com>
Message-ID: <4786C6C6.9070300@tds.net>

Tony Cappellini wrote:
> I'm using shutils for the first time, and I've un into a problem.
> The docs for copytree are pretty sparse and don't mention any problem situations
> 
> Under WinXP, I'm trying to copy a directory tree to a USB device using
> copytree, but copytree doesn't like a drive letter as a destination.
> 
> copytree('C:\\testdir', 'g:\\')

The source for copytree says, "The destination directory must not 
already exist." I suppose that is why you have a problem but I don't 
know the specific cause. Did you get a traceback?

The source also says, "Consider this example code rather than the 
ultimate tool" so maybe you should just copy it and make a version that 
does what you want. See shutil.py in your Python lib directory.

Kent

From allen.fowler at yahoo.com  Fri Jan 11 05:36:38 2008
From: allen.fowler at yahoo.com (Allen Fowler)
Date: Thu, 10 Jan 2008 20:36:38 -0800 (PST)
Subject: [Tutor] run in "deamon" mode?
Message-ID: <237595.95931.qm@web45611.mail.sp1.yahoo.com>

Thank you for all the great tips... I'll try a few and see what works.

I must say that I'm a bit surprised that the Python Std library does not have a module for this.  Are all python scripts expected to be small user-mode utilities?
 




      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs


From brunson at brunson.com  Fri Jan 11 05:58:05 2008
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 10 Jan 2008 21:58:05 -0700
Subject: [Tutor] run in "deamon" mode?
In-Reply-To: <237595.95931.qm@web45611.mail.sp1.yahoo.com>
References: <237595.95931.qm@web45611.mail.sp1.yahoo.com>
Message-ID: <4786F75D.5020207@brunson.com>

Allen Fowler wrote:
> Thank you for all the great tips... I'll try a few and see what works.
>
> I must say that I'm a bit surprised that the Python Std library does not have a module for this.  Are all python scripts expected to be small user-mode utilities?
>   
I really agree with you on that.  I have a daemonize.py I based on an 
ActiveState recipe that I've been using for several years.  I think it 
would be a great addition to the standard library.

From brindly at gmail.com  Fri Jan 11 09:39:08 2008
From: brindly at gmail.com (brindly sujith)
Date: Fri, 11 Jan 2008 14:09:08 +0530
Subject: [Tutor] how to remove window borders
Message-ID: <bfb67a4d0801110039n1163b8b8lc15af712cd2cb94e@mail.gmail.com>

hi

i am developing a  GUI application using TKINTER

in my applicaton i dont want the window title bar(including MAX,MIN and
CLOSE)

how to do this

plz send me the code for this
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080111/5540796d/attachment-0001.htm 

From mail at timgolden.me.uk  Fri Jan 11 10:02:49 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 11 Jan 2008 09:02:49 +0000
Subject: [Tutor] shutils.copytree
In-Reply-To: <4786C6C6.9070300@tds.net>
References: <8249c4ac0801101037i58f3595fke7fa35dbd550de80@mail.gmail.com>
	<4786C6C6.9070300@tds.net>
Message-ID: <478730B9.9000904@timgolden.me.uk>

Kent Johnson wrote:
> Tony Cappellini wrote:
>> I'm using shutils for the first time, and I've un into a problem.
>> The docs for copytree are pretty sparse and don't mention any problem situations
>>
>> Under WinXP, I'm trying to copy a directory tree to a USB device using
>> copytree, but copytree doesn't like a drive letter as a destination.
>>
>> copytree('C:\\testdir', 'g:\\')
> 
> The source for copytree says, "The destination directory must not 
> already exist." I suppose that is why you have a problem but I don't 
> know the specific cause. Did you get a traceback?
> 
> The source also says, "Consider this example code rather than the 
> ultimate tool" so maybe you should just copy it and make a version that 
> does what you want. See shutil.py in your Python lib directory.

Also -- vaguely -- have a look at my notes on file copying
under windows to consider alternatives:

http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

TJG

From alan.gauld at btinternet.com  Fri Jan 11 10:10:53 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 09:10:53 -0000
Subject: [Tutor] run in "deamon" mode?
References: <237595.95931.qm@web45611.mail.sp1.yahoo.com>
Message-ID: <fm7buq$ok2$1@ger.gmane.org>

"Allen Fowler" <allen.fowler at yahoo.com> wrote

> I must say that I'm a bit surprised that the Python Std 
> library does not have a module for this.  

To be honest I've never used a language that does have 
a special library for turning programs/processes into 
daemons. The tools are in the modules and its only 
a few lines of code. Most of the time you don't even need 
that since if you want a long running server you can 
just arrange to start it in the init files when the machine 
starts up.

Also because Python is cross platform the rules for 
writing daemons are quite different on Windows/VMS/Unix 
etc So I'm guessing that nobody has gotten round to doing 
a cross platform daemonize function - although it probably 
isn't impossible!

> Are all python scripts expected to be small user-mode utilities?

Definitely not, but equally, I guess most Python programs 
are not daemons either. If somebody gets a good daemon 
module written and submitted I'm sure it would be considered 
for inclusion, it just looks like nobody has had to scratch 
that itch enough yet.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at btinternet.com  Fri Jan 11 10:20:48 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 09:20:48 -0000
Subject: [Tutor] how to remove window borders
References: <bfb67a4d0801110039n1163b8b8lc15af712cd2cb94e@mail.gmail.com>
Message-ID: <fm7che$qjr$1@ger.gmane.org>


"brindly sujith" <brindly at gmail.com> wrote

> i am developing a  GUI application using TKINTER
>
> in my applicaton i dont want the window title bar(including MAX,MIN 
> and
> CLOSE)

I can't see a way to do this and it doesn't really surprise me because
it varies so much between GUI systems.

On X Windows(Linux/Unix) you control it via the Window Manager
and each WindowManager has ways of removing title bars.

On MacOS you would need to interact with Quartz or Cocoa to
control the icon bar

On MS Windows you can use the Windows API to remove the
bar and that can be accessed via ctypes(non trivial)

So for Tk to provide a riss platform solution would be tricky I guess.
But it might be possible, although I don't know the key if it is.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From lefevrol at yahoo.com  Fri Jan 11 12:26:29 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Fri, 11 Jan 2008 12:26:29 +0100
Subject: [Tutor] Suppressing output in interactive mode
Message-ID: <fm7jpg$j86$1@ger.gmane.org>

This is stupid but my python is rusty I can neither
remember nor find out anew how to enter an expression
that returns a value w/o being seeing the result printed.
I would have expected something
    expr;
as opposed to
    exp
to do the trick but no dice and I haven't had any luck
with Google or the docs. Can it be done? Note that I
don't necessarily want to suppress all output, just
just for certain expressions (e.g., within a loop,
so as not to get flooded).

Thx much,

-- O.L.


From andre.roberge at gmail.com  Fri Jan 11 12:55:07 2008
From: andre.roberge at gmail.com (Andre Roberge)
Date: Fri, 11 Jan 2008 07:55:07 -0400
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm7jpg$j86$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org>
Message-ID: <7528bcdd0801110355p59ef6bc1qca88b10f66bcb1e7@mail.gmail.com>

You may want to check here:
http://mail.python.org/pipermail/edu-sig/2007-August/008154.html

Andr?

On Jan 11, 2008 7:26 AM, Olivier Lefevre <lefevrol at yahoo.com> wrote:
> This is stupid but my python is rusty I can neither
> remember nor find out anew how to enter an expression
> that returns a value w/o being seeing the result printed.
> I would have expected something
>     expr;
> as opposed to
>     exp
> to do the trick but no dice and I haven't had any luck
> with Google or the docs. Can it be done? Note that I
> don't necessarily want to suppress all output, just
> just for certain expressions (e.g., within a loop,
> so as not to get flooded).
>
> Thx much,
>
> -- O.L.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Fri Jan 11 13:35:40 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 07:35:40 -0500
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm7jpg$j86$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org>
Message-ID: <4787629C.8090003@tds.net>

Olivier Lefevre wrote:
> This is stupid but my python is rusty I can neither
> remember nor find out anew how to enter an expression
> that returns a value w/o being seeing the result printed.

If you assign the expression to a variable, the value will not be printed.

Kent

From cappy2112 at gmail.com  Fri Jan 11 14:44:29 2008
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Fri, 11 Jan 2008 05:44:29 -0800
Subject: [Tutor] shutils.copytree
Message-ID: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>

> The source for copytree says, "The destination directory must not
> already exist." I suppose that is why you have a problem but I don't
> know the specific cause. Did you get a traceback?
>
> The source also says, "Consider this example code rather than the
> ultimate tool" so maybe you should just copy it and make a version that
> does what you want. See shutil.py in your Python lib directory.

Yes, I did read that and was shocked. Is everything in python that
iffy? I believe there was a traceback, I'll have to look again when I
am back at work tomorrow.
The problem with that concept of "modifying the distribution as you
go" is that those changes must be moved to every system where your
program will run, and whenever python is updated, you have to remember
to save the changes before uninstalling the current version. The
shutils in the new python dist may not be compatible with your old
changes and may require more work. Bad idea. How did that ever get
approved to be in the standard distribution?

>>Also -- vaguely -- have a look at my notes on file copying
>>under windows to consider alternatives:
>>http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

I had started doing xcopy, but it became unreliable but I don't know
why yet, so I decided to try shutil.
I am doing the file copies in a thread, but that shouldn't matter.
I will look at your other file copy suggestions.

Thansk for both replies


Message: 1
Date: Fri, 11 Jan 2008 09:02:49 +0000
From: Tim Golden <mail at timgolden.me.uk>
Subject: Re: [Tutor] shutils.copytree
Cc: Tutor Python <tutor at python.org>
Message-ID: <478730B9.9000904 at timgolden.me.uk>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

From lefevrol at yahoo.com  Fri Jan 11 14:48:40 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Fri, 11 Jan 2008 14:48:40 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <7528bcdd0801110355p59ef6bc1qca88b10f66bcb1e7@mail.gmail.com>
References: <fm7jpg$j86$1@ger.gmane.org>
	<7528bcdd0801110355p59ef6bc1qca88b10f66bcb1e7@mail.gmail.com>
Message-ID: <fm7s44$gpr$1@ger.gmane.org>

Thanks for both suggestions. The displayhook trick would
be OK if there was a way to retrieve what _would_ have
been printed last if the display had not been changed:
something like a modified '_'. As it stands, it's a bit
radical.

-- O.L.


From kent37 at tds.net  Fri Jan 11 15:02:19 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 09:02:19 -0500
Subject: [Tutor] shutils.copytree
In-Reply-To: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>
References: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>
Message-ID: <478776EB.8060908@tds.net>

Tony Cappellini wrote:
>> The source also says, "Consider this example code rather than the
>> ultimate tool" so maybe you should just copy it and make a version that
>> does what you want. See shutil.py in your Python lib directory.
> 
> Yes, I did read that and was shocked. Is everything in python that
> iffy? 

If by 'iffy' you mean buggy, unreliable or incomplete, I don't read it 
that way. I think they are just saying, there are lots of reasonable 
possibilities for what a copytree() function could do. They haven't 
tried to cover all the bases. Instead they have given a reasonable 
starting point, that works for some cases, and invited you to make your 
own if it doesn't do what you want.

> The problem with that concept of "modifying the distribution as you
> go" is that those changes must be moved to every system where your
> program will run...

You don't have to modify shutils. I suggested that you *copy* copytree() 
and modify it to do what you want. The copy would be included with the 
program that needs it, not added to shutil.

Kent

From mail at timgolden.me.uk  Fri Jan 11 15:03:23 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 11 Jan 2008 14:03:23 +0000
Subject: [Tutor] shutils.copytree
In-Reply-To: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>
References: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>
Message-ID: <4787772B.3030404@timgolden.me.uk>

Tony Cappellini wrote:
>> The source for copytree says, "The destination directory must not
>> already exist." I suppose that is why you have a problem but I don't
>> know the specific cause. Did you get a traceback?
>>
>> The source also says, "Consider this example code rather than the
>> ultimate tool" so maybe you should just copy it and make a version that
>> does what you want. See shutil.py in your Python lib directory.
> 
> The problem with that concept of "modifying the distribution as you
> go" 

I don't think that's the idea; rather that you cut-and-paste
the code (it's not huge), make it work for you, and add it to
your project's own "utils" module or whatever. Still a bit hackish,
but not the DIY-distro you're suggesting here.

TJG

From alan.gauld at btinternet.com  Fri Jan 11 15:08:06 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 14:08:06 -0000
Subject: [Tutor] shutils.copytree
References: <8249c4ac0801110544r20c30ea0i4bb358b3dbecfe74@mail.gmail.com>
Message-ID: <fm7tc3$lng$1@ger.gmane.org>


"Tony Cappellini" <cappy2112 at gmail.com> wrote

>> The source also says, "Consider this example code rather than the
>> ultimate tool" so maybe you should just copy it and make a version 
>> that
>> does what you want. See shutil.py in your Python lib directory.
>
> Yes, I did read that and was shocked. Is everything in python that
> iffy?

No, thats why thee is a comment on that bit! :-)

> The problem with that concept of "modifying the distribution as you
> go" is that those changes must be moved to every system where your
> program will run,

Correct, one big advantage of using classes.modules.
So you should create your code in a module and then it is
no different to the rest of your application.

> and whenever python is updated, you have to remember
> to save the changes before uninstalling the current version.

Its always wise to have your local code somewhere other
than in the system space IMHO. I habe Python in

C:\python25

and my projects/modules on

D:\Projects\Python

This also helps if you want to run multiple copies of Python
Just set the PYTHONPATH environment variable to point at
the projects directory.

HTH,

Alan G. 



From andre.roberge at gmail.com  Fri Jan 11 15:10:30 2008
From: andre.roberge at gmail.com (Andre Roberge)
Date: Fri, 11 Jan 2008 10:10:30 -0400
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm7s44$gpr$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org>
	<7528bcdd0801110355p59ef6bc1qca88b10f66bcb1e7@mail.gmail.com>
	<fm7s44$gpr$1@ger.gmane.org>
Message-ID: <7528bcdd0801110610s45476cf6sdf4f81ab37cb8d48@mail.gmail.com>

On Jan 11, 2008 9:48 AM, Olivier Lefevre <lefevrol at yahoo.com> wrote:
> Thanks for both suggestions. The displayhook trick would
> be OK if there was a way to retrieve what _would_ have
> been printed last if the display had not been changed:
> something like a modified '_'. As it stands, it's a bit
> radical.

If you follow the discussion thread look through the link I provided,
I believe this is addressed a bit later.

Andr?

>
> -- O.L.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From lefevrol at yahoo.com  Fri Jan 11 16:14:42 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Fri, 11 Jan 2008 16:14:42 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <7528bcdd0801110610s45476cf6sdf4f81ab37cb8d48@mail.gmail.com>
References: <fm7jpg$j86$1@ger.gmane.org>	<7528bcdd0801110355p59ef6bc1qca88b10f66bcb1e7@mail.gmail.com>	<fm7s44$gpr$1@ger.gmane.org>
	<7528bcdd0801110610s45476cf6sdf4f81ab37cb8d48@mail.gmail.com>
Message-ID: <fm815e$42c$1@ger.gmane.org>

> If you follow the discussion thread look through the link I provided,
> I believe this is addressed a bit later.

Yes and no. They do discuss possible hooks a bit further in
http://mail.python.org/pipermail/edu-sig/2007-August/008161.html
but merely to suggest toggling between echo and no-echo. It gave
me the idea of trying

    def f(value):
       global _
       _ = value

i.e., assign _ without printing, but that doesn't work.

-- O.L.


From jfabiani at yolo.com  Fri Jan 11 17:26:25 2008
From: jfabiani at yolo.com (johnf)
Date: Fri, 11 Jan 2008 08:26:25 -0800
Subject: [Tutor] preventing SQL injection
Message-ID: <200801110826.26004.jfabiani@yolo.com>

Hi,
I was recently told I was doing something wrong with my python sql statements.
I was doing
tempCursor.execute("Select pg_get_serial_sequence('%s','%s') as seq ?
 " % ('public.arcust','pkid'))

and should be doing
tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as ?
seq", ( 'public.arcust', 'pkid' ) )

which prevented SQL injection.

But the above does not work when I use variables instead of strings as in

tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as ?
seq", ( tableName, fieldName ) )

So how am I suppose to prevent SQL injections?????
-- 
John Fabiani

From jnewton at fuelindustries.com  Fri Jan 11 17:53:35 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Fri, 11 Jan 2008 11:53:35 -0500
Subject: [Tutor] Iterating backwards
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F8FDE@ex1.Fuel.Ott>

Hi Pygamers,

I have created a series of pygame sprites.  Visually, these sprites
represent counters and may overlap.  I want to determine which sprite
the user clicked on.

This seems to me to be a fairly standard feature of a game interface, so
I imagine that there is already a standard technique for achieving it. 

My current implementation (see below) is to use a "for" statement on the
pygame.sprite group that contains the sprites.  This means that I have
to test all the sprites to determine the top-most sprite that is under
the mouse.

The sprites are blitted to the screen in the order they were added to
the sprite group, so the sprite that appears on top is the last one in
the group.  I'd like to start at the top-most sprite and work backwards
through the sprites in the group, and then use "break" to stop as soon
as I find a sprite whose rect collides with the mouse position.

In my code below, I've tried replacing the line...

    for vCounter in counters: # the pygame.sprite.RenderPlain() group

... with:

    vRange = range(len(counters))
    vRange.reverse()
    for ii in vRange:
        vCounter = counters[ii]

However this results in an error:

    #TypeError: 'Group' object is unindexable


Is there a way to iterate backwards through a pygame sprite group?  Or
can you recommend an alternative method to achieve the same ends?

My overall aim is to make the sprite the user clicks on jump to the top,
so the order of the sprites in the group will change over time.

Thanks in advance,

James


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


Here's my barebones code.  It assumes that there are three 64 x 64 pixel
image files named Counter_1.png through Counter_3.png in a subfolder
named data.


import os
import pygame
# Add QUIT, KEYDOWN and other event names to module namespace
from pygame.locals import *



# <COUNTER
class Counter(pygame.sprite.Sprite):
    """ Creates a counter sprite from an image and
        places it in a tiled pattern relative to
        other counters
    """

    def __init__(self, aIndex):
        pygame.sprite.Sprite.__init__(self)

        self.index = aIndex

        # Create a "surface" that we need to name "image" to overwrite
        # the Sprite's own .image property, which remains as None
        vFileName  = "Counter_"+str(aIndex + 1)+".png"
        vPath      = os.path.join('data', vFileName)
        self.image = pygame.image.load(vPath).convert()
        self.rect  = self.image.get_rect()

        # Scatter the counters so they overlap
        self.rect.move_ip(aIndex * 24, aIndex * 24)

    def is_opaque_at(self, x, y):
        if self.rect.collidepoint(x, y):
            return True

        return False
# COUNTER>


# <MAIN
def main():
    """ Demonstrates the use of pygames RenderUpdates
        sprite group
    """

    # Initialization
    pygame.init()
    
    clock      = pygame.time.Clock()
    screen     = pygame.display.set_mode((120, 120))
 
    counters   = pygame.sprite.RenderPlain()
    for i in range(0, 3):
        vCounter = Counter(i)
        vCounter.add(counters)
     
    # <Infinite loop
    while True:
        clock.tick(5) # 5 frames per second is quite sufficient

        for event in pygame.event.get():
            if event.type in (QUIT, KEYDOWN):
                pygame.quit()
                return

            elif event.type == MOUSEBUTTONDOWN:
                vPos   = pygame.mouse.get_pos()

                vIndex = None
                for vCounter in counters:
                    vClicked = vCounter.is_opaque_at(*vPos)
                    if vClicked:
                        vIndex = vCounter.index
                        print "Sprite "+str(vIndex)+" is under the
mouse"
                        #break  # Uncomment to return the *lowest*
sprite

                if vIndex != None:
                    print vIndex
 
        counters.draw(screen)
        pygame.display.update()
   # Infinite loop>
# MAIN>



if __name__ == '__main__': main()

From kent37 at tds.net  Fri Jan 11 17:55:25 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 11:55:25 -0500
Subject: [Tutor] preventing SQL injection
In-Reply-To: <200801110826.26004.jfabiani@yolo.com>
References: <200801110826.26004.jfabiani@yolo.com>
Message-ID: <47879F7D.5070307@tds.net>

johnf wrote:
> Hi,
> I was recently told I was doing something wrong with my python sql statements.
> I was doing
> tempCursor.execute("Select pg_get_serial_sequence('%s','%s') as seq  
>  " % ('public.arcust','pkid'))
> 
> and should be doing
> tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as  
> seq", ( 'public.arcust', 'pkid' ) )
> 
> which prevented SQL injection.

Yes, good advice.

> But the above does not work when I use variables instead of strings as in
> 
> tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as  
> seq", ( tableName, fieldName ) )

That should work, can you show us a bit more code? What is in tableName 
and fieldName?

If this works:
tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as
seq", ( 'public.arcust', 'pkid' ) )

Then so should this:
tableName = 'public.arcust'
fieldName = 'pkid'
tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as
seq", (tableName , fieldName) )

Kent

From simozack at yahoo.it  Fri Jan 11 18:14:25 2008
From: simozack at yahoo.it (Simone)
Date: Fri, 11 Jan 2008 18:14:25 +0100
Subject: [Tutor] preventing SQL injection
In-Reply-To: <200801110826.26004.jfabiani@yolo.com>
References: <200801110826.26004.jfabiani@yolo.com>
Message-ID: <4787A3F1.4080002@yahoo.it>

johnf ha scritto:

> But the above does not work when I use variables instead of strings as in
> 
> tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as  
> seq", ( tableName, fieldName ) )
> 
> So how am I suppose to prevent SQL injections?????

Try tu use '?' instead of %s, like this:

tempCursor.execute ( "Select pg_get_serial_sequence ( ?, ? ) as seq", ( 
tableName, fieldName ) )

For further information see PEP 249 
(http://www.python.org/dev/peps/pep-0249/)

HTH!

Simone
Chiacchiera con i tuoi amici in tempo reale! 
 http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com 

From kent37 at tds.net  Fri Jan 11 18:22:07 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 12:22:07 -0500
Subject: [Tutor] Iterating backwards
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD24010F8FDE@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD24010F8FDE@ex1.Fuel.Ott>
Message-ID: <4787A5BF.40204@tds.net>

James Newton wrote:

> I have created a series of pygame sprites.  Visually, these sprites
> represent counters and may overlap.  I want to determine which sprite
> the user clicked on.
> 
> This seems to me to be a fairly standard feature of a game interface, so
> I imagine that there is already a standard technique for achieving it. 

I would think so too, but a quick look at the docs and tutorials didn't 
turn up anything....

> I'd like to start at the top-most sprite and work backwards
> through the sprites in the group, and then use "break" to stop as soon
> as I find a sprite whose rect collides with the mouse position.
> 
> In my code below, I've tried replacing the line...
> 
>     for vCounter in counters: # the pygame.sprite.RenderPlain() group
> 
> ... with:
> 
>     vRange = range(len(counters))
>     vRange.reverse()
>     for ii in vRange:
>         vCounter = counters[ii]
> 
> However this results in an error:
> 
>     #TypeError: 'Group' object is unindexable

I guess counters is iterable but not a sequence. Try this:
   for vCounter in reversed(list(counters)):

Kent

From jfabiani at yolo.com  Fri Jan 11 18:30:16 2008
From: jfabiani at yolo.com (johnf)
Date: Fri, 11 Jan 2008 09:30:16 -0800
Subject: [Tutor] preventing SQL injection
In-Reply-To: <4787A3F1.4080002@yahoo.it>
References: <200801110826.26004.jfabiani@yolo.com> <4787A3F1.4080002@yahoo.it>
Message-ID: <200801110930.16111.jfabiani@yolo.com>

On Friday 11 January 2008 09:14:25 am Simone wrote:
> johnf ha scritto:
> > But the above does not work when I use variables instead of strings as in
> >
> > tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as
> > seq", ( tableName, fieldName ) )
> >
> > So how am I suppose to prevent SQL injections?????
>
> Try tu use '?' instead of %s, like this:
>
> tempCursor.execute ( "Select pg_get_serial_sequence ( ?, ? ) as seq", (
> tableName, fieldName ) )
>
> For further information see PEP 249
> (http://www.python.org/dev/peps/pep-0249/)
>
> HTH!
>
> Simone

Thanks I think I see the issue.  The Qmark etc.. was the clue.



-- 
John Fabiani

From jnewton at fuelindustries.com  Fri Jan 11 18:36:38 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Fri, 11 Jan 2008 12:36:38 -0500
Subject: [Tutor] Iterating backwards
In-Reply-To: <4787A5BF.40204@tds.net>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD24010F9011@ex1.Fuel.Ott>

Kent Johnson wrote: 
>I guess counters is iterable but not a sequence. Try this:
>   for vCounter in reversed(list(counters)):

Hi Kent,

Thanks for your help.  This solves my problem:

    vPos = pygame.mouse.get_pos()
    for vCounter in reversed(list(counters)):
        if vCounter.rect.collidepoint(*vPos):
            # vCounter now points to the sprite we want to treat
            break

:-)

James

From alan.gauld at btinternet.com  Fri Jan 11 19:17:39 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 18:17:39 -0000
Subject: [Tutor] Suppressing output in interactive mode
References: <fm7jpg$j86$1@ger.gmane.org>
Message-ID: <fm8c00$cmp$1@ger.gmane.org>

"Olivier Lefevre" <lefevrol at yahoo.com> wrote

> This is stupid but my python is rusty I can neither
> remember nor find out anew how to enter an expression
> that returns a value w/o being seeing the result printed.

I don;t understand the question.
Are you talking about the >>> prompt? 
That is the only place I can think of where expression values 
are displayed without an explicit print statement. In a normal 
script unassigned expressions are evaluated but the result 
is discarded (except for the magic _ variable which is not 
displayed)

> don't necessarily want to suppress all output, just
> just for certain expressions (e.g., within a loop,
> so as not to get flooded).

But if you refer to a loop when would you ever be evaluating 
expressions inside a loop without assigning them?

Can you give an example of the problem and what your like 
to see? I don;t understand what you are trying to do, or 
where the problem lies.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Fri Jan 11 19:20:13 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 18:20:13 -0000
Subject: [Tutor] preventing SQL injection
References: <200801110826.26004.jfabiani@yolo.com>
Message-ID: <fm8c4q$d7m$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote 

> and should be doing
> tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as 
> seq", ( 'public.arcust', 'pkid' ) )
> 
> which prevented SQL injection.

The syntax of the execute statement varies by database
Which DB are you using. For example SQLite uses ? 
instead of %s indicators.

Could that be the issue? Have you checked the DB-API 
guide for your database?

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From jfabiani at yolo.com  Fri Jan 11 19:28:59 2008
From: jfabiani at yolo.com (johnf)
Date: Fri, 11 Jan 2008 10:28:59 -0800
Subject: [Tutor] preventing SQL injection
In-Reply-To: <fm8c4q$d7m$1@ger.gmane.org>
References: <200801110826.26004.jfabiani@yolo.com> <fm8c4q$d7m$1@ger.gmane.org>
Message-ID: <200801111028.59246.jfabiani@yolo.com>

On Friday 11 January 2008 10:20:13 am Alan Gauld wrote:
> "johnf" <jfabiani at yolo.com> wrote
>
> > and should be doing
> > tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as
> > seq", ( 'public.arcust', 'pkid' ) )
> >
> > which prevented SQL injection.
>
> The syntax of the execute statement varies by database
> Which DB are you using. For example SQLite uses ?
> instead of %s indicators.
>
> Could that be the issue? Have you checked the DB-API
> guide for your database?
>
> HTH,

all's working now - thanks

-- 
John Fabiani

From jfabiani at yolo.com  Fri Jan 11 19:56:19 2008
From: jfabiani at yolo.com (johnf)
Date: Fri, 11 Jan 2008 10:56:19 -0800
Subject: [Tutor] preventing SQL injection
In-Reply-To: <fm8c4q$d7m$1@ger.gmane.org>
References: <200801110826.26004.jfabiani@yolo.com> <fm8c4q$d7m$1@ger.gmane.org>
Message-ID: <200801111056.19436.jfabiani@yolo.com>

On Friday 11 January 2008 10:20:13 am Alan Gauld wrote:
> "johnf" <jfabiani at yolo.com> wrote
>
> > and should be doing
> > tempCursor.execute ( "Select pg_get_serial_sequence ( %s, %s ) as
> > seq", ( 'public.arcust', 'pkid' ) )
> >
> > which prevented SQL injection.
>
> The syntax of the execute statement varies by database
> Which DB are you using. For example SQLite uses ?
> instead of %s indicators.
>
> Could that be the issue? Have you checked the DB-API
> guide for your database?
>
> HTH,

I spoke to soon.  Where can I find the DB-API for postgres?  Because the only 
way I can get this to work is using ('%s') and it does not work with (%s).

BTW where I'm doing my testing is with a SELECT statement.

below does not work
mySQL= "Select fieldname from tableName where str_field = %s" % (myVar,)

but this works
mySQL= "Select fieldname from tableName where str_field = '%s' " % (myVar,)

-- 
John Fabiani

From kent37 at tds.net  Fri Jan 11 20:19:43 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 14:19:43 -0500
Subject: [Tutor] preventing SQL injection
In-Reply-To: <200801111056.19436.jfabiani@yolo.com>
References: <200801110826.26004.jfabiani@yolo.com> <fm8c4q$d7m$1@ger.gmane.org>
	<200801111056.19436.jfabiani@yolo.com>
Message-ID: <4787C14F.6020803@tds.net>

johnf wrote:
> I spoke to soon.  Where can I find the DB-API for postgres?  Because the only 
> way I can get this to work is using ('%s') and it does not work with (%s).

What module are you using to connect to postgres? That module should 
implement DB-API as documented here:
http://www.python.org/dev/peps/pep-0249/

The module itself should have a paramstyle attribute that shows what 
kind of parameter passing it expects:
In [5]: import psycopg2
In [6]: psycopg2.paramstyle
Out[6]: 'pyformat'

The meaning of the paramstyle is documented (somewhat) in PEP 249.

> BTW where I'm doing my testing is with a SELECT statement.
> 
> below does not work
> mySQL= "Select fieldname from tableName where str_field = %s" % (myVar,)
> 
> but this works
> mySQL= "Select fieldname from tableName where str_field = '%s' " % (myVar,)

Can you post a small, complete program containing both the working and 
non-working variants and show the complete output of the program?

Kent

From lefevrol at yahoo.com  Fri Jan 11 20:30:52 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Fri, 11 Jan 2008 20:30:52 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm8c00$cmp$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org> <fm8c00$cmp$1@ger.gmane.org>
Message-ID: <fm8g5p$rmd$1@ger.gmane.org>

> Are you talking about the >>> prompt? 

Yes.

> But if you refer to a loop when would you ever be evaluating 
> expressions inside a loop without assigning them?

Some method calls return a value that you may not be interested
in but which will still be printed, e.g., Set.add in Java (if
you are using jython, this is relevant).

-- O.L.


From jfabiani at yolo.com  Fri Jan 11 20:33:00 2008
From: jfabiani at yolo.com (johnf)
Date: Fri, 11 Jan 2008 11:33:00 -0800
Subject: [Tutor] preventing SQL injection
In-Reply-To: <4787C14F.6020803@tds.net>
References: <200801110826.26004.jfabiani@yolo.com>
	<200801111056.19436.jfabiani@yolo.com> <4787C14F.6020803@tds.net>
Message-ID: <200801111133.00102.jfabiani@yolo.com>

On Friday 11 January 2008 11:19:43 am you wrote:
> johnf wrote:
> > I spoke to soon.  Where can I find the DB-API for postgres?  Because the
> > only way I can get this to work is using ('%s') and it does not work with
> > (%s).
>
> What module are you using to connect to postgres? That module should
> implement DB-API as documented here:
> http://www.python.org/dev/peps/pep-0249/
>
> The module itself should have a paramstyle attribute that shows what
> kind of parameter passing it expects:
> In [5]: import psycopg2
> In [6]: psycopg2.paramstyle
> Out[6]: 'pyformat'
>
> The meaning of the paramstyle is documented (somewhat) in PEP 249.
>
> > BTW where I'm doing my testing is with a SELECT statement.
> >
> > below does not work
> > mySQL= "Select fieldname from tableName where str_field = %s" % (myVar,)
> >
> > but this works
> > mySQL= "Select fieldname from tableName where str_field = '%s' " %
> > (myVar,)
>
> Can you post a small, complete program containing both the working and
> non-working variants and show the complete output of the program?
>
> Kent

Sure:
localTableName = 'arcust'
cursor.KeyField = 'pkid'
localSchemaName = 'public'

mysql="""
SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128) 
FROM pg_attrdef d 
WHERE d.adrelid = a.attrelid  AND d.adnum = a.attnum  AND a.atthasdef) 
FROM 'nextval[^'']*''([^'']*)') 
FROM pg_attribute a 
LEFT JOIN pg_class c ON c.oid = a.attrelid 
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND 
a.atthasdef 
LEFT JOIN pg_namespace n ON c.relnamespace = n.oid WHERE (c.relname = '%s') 
AND a.attname = '%s' and n.nspname='%s' AND NOT a.attisdropped AND a.attnum > 
0 AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%%' 
""" %(localTableName, cursor.KeyField,localSchemaName)

tempCursor.execute(mysql)

without the single qoutes I get 
column "arcust" does not exist

What the statement wants to see is something like

c.relname = 'arcust'

and not

c.relname = arcust

- 
John Fabiani

From kent37 at tds.net  Fri Jan 11 20:45:36 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 14:45:36 -0500
Subject: [Tutor] preventing SQL injection
In-Reply-To: <200801111133.00102.jfabiani@yolo.com>
References: <200801110826.26004.jfabiani@yolo.com>
	<200801111056.19436.jfabiani@yolo.com> <4787C14F.6020803@tds.net>
	<200801111133.00102.jfabiani@yolo.com>
Message-ID: <4787C760.1000506@tds.net>

johnf wrote:
> On Friday 11 January 2008 11:19:43 am you wrote:

>> Can you post a small, complete program containing both the working and
>> non-working variants and show the complete output of the program?

Jeez, you might want to try to get this to work with something simple!

This is still not a complete program - where are the imports? There are 
at least four different DB-API compliant modules that talk to Postgres. 
Am I supposed to guess which one you are using?

Where does tempCursor come from? You just show the working version. 
Should I guess what the failing version looks like?

I'm trying to help but you aren't giving me much to work with and I'm 
getting tired of guessing. Show me the code!

> Sure:
> localTableName = 'arcust'
> cursor.KeyField = 'pkid'
> localSchemaName = 'public'
> 
> mysql="""
> SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128) 
> FROM pg_attrdef d 
> WHERE d.adrelid = a.attrelid  AND d.adnum = a.attnum  AND a.atthasdef) 
> FROM 'nextval[^'']*''([^'']*)') 
> FROM pg_attribute a 
> LEFT JOIN pg_class c ON c.oid = a.attrelid 
> LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND 
> a.atthasdef 
> LEFT JOIN pg_namespace n ON c.relnamespace = n.oid WHERE (c.relname = '%s') 
> AND a.attname = '%s' and n.nspname='%s' AND NOT a.attisdropped AND a.attnum > 
> 0 AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%%' 
> """ %(localTableName, cursor.KeyField,localSchemaName)

       ^
       ^
------^-----

Are you leaving that % in when you take out the quotes? Don't.

Kent
> 
> tempCursor.execute(mysql)
> 
> without the single qoutes I get 
> column "arcust" does not exist
> 
> What the statement wants to see is something like
> 
> c.relname = 'arcust'
> 
> and not
> 
> c.relname = arcust
> 
> - 
> John Fabiani
> 


From brunson at brunson.com  Fri Jan 11 20:49:48 2008
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 11 Jan 2008 12:49:48 -0700
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm8g5p$rmd$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org> <fm8c00$cmp$1@ger.gmane.org>
	<fm8g5p$rmd$1@ger.gmane.org>
Message-ID: <4787C85C.4070403@brunson.com>

Olivier Lefevre wrote:
>> Are you talking about the >>> prompt? 
>>     
>
> Yes.
>
>   
>> But if you refer to a loop when would you ever be evaluating 
>> expressions inside a loop without assigning them?
>>     
>
> Some method calls return a value that you may not be interested
> in but which will still be printed, e.g., Set.add in Java (if
> you are using jython, this is relevant).
>
>   

Then assign the return value to a variable and never use it.

I don't see the problem.



From alan.gauld at btinternet.com  Fri Jan 11 21:11:31 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 11 Jan 2008 20:11:31 -0000
Subject: [Tutor] Suppressing output in interactive mode
References: <fm7jpg$j86$1@ger.gmane.org> <fm8c00$cmp$1@ger.gmane.org>
	<fm8g5p$rmd$1@ger.gmane.org>
Message-ID: <fm8ilg$4oe$1@ger.gmane.org>


"Olivier Lefevre" <lefevrol at yahoo.com> wrote 

>> But if you refer to a loop when would you ever be evaluating 
>> expressions inside a loop without assigning them?
> 
> Some method calls return a value that you may not be interested
> in but which will still be printed, e.g., Set.add in Java (if
> you are using jython, this is relevant).

OK, I see. Interestingly default retuirn values are not printed:

>>> def f(n): return
...
>>> for n in range(5):
...     f(n)
...
>>>


But if they return printable values then yes you would see them.
In that case I'd just assign to a dummy variable.

But usually in the >>>> prompt I don't care, if there were so 
many lines inside a loop I'd probably create a test file for the 
code because its easier to edit changes.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From kent37 at tds.net  Fri Jan 11 21:34:14 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 11 Jan 2008 15:34:14 -0500
Subject: [Tutor] preventing SQL injection
In-Reply-To: <200801111214.36929.jfabiani@yolo.com>
References: <200801110826.26004.jfabiani@yolo.com>
	<200801111133.00102.jfabiani@yolo.com> <4787C760.1000506@tds.net>
	<200801111214.36929.jfabiani@yolo.com>
Message-ID: <4787D2C6.5090106@tds.net>

johnf wrote:
> On Friday 11 January 2008 11:45:36 am you wrote:
> Let's start over!

Thank you.

> import psycopg2
> 
> conn = psycopg2.connect("host='192.168.1.201' dbname='aName' user ='UserName' 
> password ='******'")
> tempCursor= conn.cursor()
> custnum = 'ABC123'
> mysql ="Select ccustno from public.arcust where ccustno =%s" % (custnum,)
> tempCursor.execute(mysql)
> 
> The above statement will return an error from postgres
> column "ABC123" does not exist

Right, you are not calling execute correctly. The whole point is *not* 
to use string interpolation to put the parameters into the sql. The 
params are passed to execute() as a separate argument. Try this:

mysql ="Select ccustno from public.arcust where ccustno =%s"
tempCursor.execute(mysql, (custnum,))

If that doesn't work then you probably need a different paramstyle. I 
think ? works with psycopg2 but it says it wants pyformat style which 
would be something like

mysql ="Select ccustno from public.arcust where ccustno =%(custnum)s"
tempCursor.execute(mysql, dict(custnum=custnum))

Kent

> 
> However, if change the statement to:
> 
> mysql ="Select ccustno from public.arcust where ccustno ='%s' " % (custnum,)
> 
> it works.
> 
> Because the select statement wants to see 
> ccustno = 'ABC123'
> 
> not
> ccustno=ABC123
> 
> 
> 


From keridee at jayco.net  Fri Jan 11 22:36:11 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 11 Jan 2008 16:36:11 -0500
Subject: [Tutor] getting filen basename without extension
References: <loom.20080110T090805-609@post.gmane.org><fm55dq$ul2$1@ger.gmane.org>
	<loom.20080110T133121-740@post.gmane.org>
Message-ID: <005901c85499$ffd640e0$7afce004@jslaptop>

I would always use the os functions to find the basename, but
You could exploit the fact that Windows considers the extension to be 
whatever is after the last "." character.

fn = fn[:fn.rfind(".")]

>> > What I found is this:
>> > import os
>> > myfile_name_with_path = 'path/to/my/testfile.txt'
>> > basename = os.path.basename(myfile_with_path)
>> > filename = os.path.splitext(basename)
>> > myfile_name_without_suffix = filename[0]
>>
>> The last two can be easily combined as:
>>
>> > myfile_name_without_suffix = os.path.splitext(basename)[0]
>>
>> But otherwise you are using the "correct" mechanism if
>> you want a reliable result.
> Thanks for this confirmation.
>
> I am happy to have made some tiny progress in my python learings...
>
> Kind regards,
> Timmie
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From lefevrol at yahoo.com  Fri Jan 11 22:49:14 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Fri, 11 Jan 2008 22:49:14 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <4787C85C.4070403@brunson.com>
References: <fm7jpg$j86$1@ger.gmane.org>
	<fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org>
	<4787C85C.4070403@brunson.com>
Message-ID: <fm8o8q$nbh$1@ger.gmane.org>

> Then assign the return value to a variable and never use it.

That feels obfuscated; definitely not an elegant solution.
When I'm done with interactive development and save the
substance to a script I'd have to chase these bogus
assignments to junk variables and remove them; not a
smooth workflow.

-- O.L.


From brunson at brunson.com  Fri Jan 11 23:42:30 2008
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 11 Jan 2008 15:42:30 -0700
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm8o8q$nbh$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org>	<fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org>	<4787C85C.4070403@brunson.com>
	<fm8o8q$nbh$1@ger.gmane.org>
Message-ID: <4787F0D6.3060209@brunson.com>

Olivier Lefevre wrote:
>> Then assign the return value to a variable and never use it.
>>     
>
> That feels obfuscated; definitely not an elegant solution.
> When I'm done with interactive development and save the
> substance to a script I'd have to chase these bogus
> assignments to junk variables and remove them; not a
> smooth workflow.
>
>   

Sounds like you need a better interactive development tool.  You should 
try emacs.  :-)



From lefevrol at yahoo.com  Sat Jan 12 01:49:08 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Sat, 12 Jan 2008 01:49:08 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <4787F0D6.3060209@brunson.com>
References: <fm7jpg$j86$1@ger.gmane.org>	<fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org>	<4787C85C.4070403@brunson.com>	<fm8o8q$nbh$1@ger.gmane.org>
	<4787F0D6.3060209@brunson.com>
Message-ID: <fm92q4$kma$1@ger.gmane.org>

> Sounds like you need a better interactive development tool.
> You should try emacs.  :-)

With jython the options are limited: even readline is a luxury,
but I'll look into it.

-- O.L.


From alan.gauld at btinternet.com  Sat Jan 12 01:54:45 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jan 2008 00:54:45 -0000
Subject: [Tutor] Suppressing output in interactive mode
References: <fm7jpg$j86$1@ger.gmane.org><fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org><4787C85C.4070403@brunson.com>
	<fm8o8q$nbh$1@ger.gmane.org>
Message-ID: <fm938i$lv3$1@ger.gmane.org>

"Olivier Lefevre" <lefevrol at yahoo.com> wrote

>> Then assign the return value to a variable and never use it.
> 
> That feels obfuscated; definitely not an elegant solution.
> When I'm done with interactive development and save the
> substance to a script I'd have to chase these bogus
> assignments to junk variables and remove them; not a
> smooth workflow.

Why remove them? They shouldn't hurt performance 
and you only need one re-used for each expression.

However I'm curious how you save your interactive sesssion 
to a script? I normally only write fragments at the >>> prompt 
and retype them into my script - there would be so much 
tweaking needed that its just as fast I think.
(I tend to use single letter variables etc at the >>> whereas 
real scripts will have longer names and comments and 
spacing and more error handling etc)

How are you using the prompt?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From lefevrol at yahoo.com  Sat Jan 12 02:09:42 2008
From: lefevrol at yahoo.com (Olivier Lefevre)
Date: Sat, 12 Jan 2008 02:09:42 +0100
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm938i$lv3$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org><fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org><4787C85C.4070403@brunson.com>	<fm8o8q$nbh$1@ger.gmane.org>
	<fm938i$lv3$1@ger.gmane.org>
Message-ID: <fm940n$nrg$1@ger.gmane.org>

Alan Gauld wrote:
> Why remove them? 
I think they might be confusing; unless perhaps you gave
them special names.

> How are you using the prompt?
I tend to cut and paste individual lines.

Incidentally the lack of readline is the reason why large
amounts of output are such a big deal.

I think we should close this thread: apparently there is no
way to do quite what I wanted as you would, say, in MatLab
(compare '1+2' and '1+2;') so it's just a matter of finding
a workaround I can live with.

-- O.L.



From brindly at gmail.com  Sat Jan 12 11:56:08 2008
From: brindly at gmail.com (brindly sujith)
Date: Sat, 12 Jan 2008 16:26:08 +0530
Subject: [Tutor] how to disable MIN,MAX and CLOSE options using tkinter
Message-ID: <bfb67a4d0801120256n3e8d1a6fobe16a720508d83f5@mail.gmail.com>

hi

in my application i dont want MIN,MAX,CLOSE options in window
i need to disable these options
how to do this in tkinter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080112/08a04399/attachment.htm 

From fiveholiday55 at hotmail.com  Sat Jan 12 14:00:39 2008
From: fiveholiday55 at hotmail.com (Evans Anyokwu)
Date: Sat, 12 Jan 2008 13:00:39 -0000
Subject: [Tutor] how to disable MIN,MAX and CLOSE options using tkinter
References: <bfb67a4d0801120256n3e8d1a6fobe16a720508d83f5@mail.gmail.com>
Message-ID: <BAY142-DAV7D0238586726BD0423F70AD440@phx.gbl>

Hi Brindly,

I remember Alan answering this question yesterday.
Please look at the suggestions he made and see if they are of any help.

However, I don't think its possible in Python's Tkinter; the only thing close to what you want is in Java, its called JWindow.

Sorry never have to disable those options in Tkinter before.

--
Evans

----- Original Message ----- 
  From: brindly sujith 
  To: tutor at python.org 
  Sent: Saturday, January 12, 2008 10:56 AM
  Subject: [Tutor] how to disable MIN,MAX and CLOSE options using tkinter


  hi
   
  in my application i dont want MIN,MAX,CLOSE options in window
  i need to disable these options
  how to do this in tkinter 


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


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080112/48e89b03/attachment.htm 

From kent37 at tds.net  Sat Jan 12 14:09:08 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 12 Jan 2008 08:09:08 -0500
Subject: [Tutor] Suppressing output in interactive mode
In-Reply-To: <fm8o8q$nbh$1@ger.gmane.org>
References: <fm7jpg$j86$1@ger.gmane.org>	<fm8c00$cmp$1@ger.gmane.org>	<fm8g5p$rmd$1@ger.gmane.org>	<4787C85C.4070403@brunson.com>
	<fm8o8q$nbh$1@ger.gmane.org>
Message-ID: <4788BBF4.1020009@tds.net>

Olivier Lefevre wrote:
>> Then assign the return value to a variable and never use it.
> 
> That feels obfuscated; definitely not an elegant solution.
> When I'm done with interactive development and save the
> substance to a script I'd have to chase these bogus
> assignments to junk variables and remove them; not a
> smooth workflow.

FWIW I do most development in an editor and save the interpreter for 
small snippets and interactive exploration. Many editors can be set up 
to execute Python code with a keystroke and show the results in another 
window.

Unit tests help with incremental development too - a unit test can 
exercise the code you are working on.

Kent

From alan.gauld at btinternet.com  Sat Jan 12 18:18:11 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Jan 2008 17:18:11 -0000
Subject: [Tutor] how to disable MIN,MAX and CLOSE options using tkinter
References: <bfb67a4d0801120256n3e8d1a6fobe16a720508d83f5@mail.gmail.com>
	<BAY142-DAV7D0238586726BD0423F70AD440@phx.gbl>
Message-ID: <fmassh$97b$1@ger.gmane.org>


"Evans Anyokwu" <fiveholiday55 at hotmail.com> wrote

> I remember Alan answering this question yesterday.

To be fair it was a slightly different question but the principles 
are the same.

These things are controlled by the Window Manager 
or the OS or the GUI system depending on the platform.

On X you can communicate with the Window Manager
(and Tkinter lets you ask which it is) and on Windows 
you can use the Win32 API via ctypes to set the icons.

I assume on MacOs you would use Cocoa from MacPython.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From earlylightpublishing at yahoo.com  Sat Jan 12 22:44:32 2008
From: earlylightpublishing at yahoo.com (earlylight publishing)
Date: Sat, 12 Jan 2008 13:44:32 -0800 (PST)
Subject: [Tutor] Why Won't My Pizza Fall?
Message-ID: <184430.18650.qm@web45107.mail.sp1.yahoo.com>

Hey There Everyone,
   
  I'm following an example in a book and I can't find the error that's preventing this program from running.  It's just an example of how to get a sprite moving.  The images are all in the right folder.  I can run the program and get a stationary sprite to appear.  The trouble seems to come up when I add "dx" and "dy"  Here's the code.
   
   
  from livewires import games
   
  SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
   
  class Pizza(games.Sprite):
    """A falling pizza."""
    def __init__(self, screen, x, y, image, dx, dy):
        """Initialize pizza object."""
        self.init_sprite(screen = screen, x = x, y = y, image = image,
                             dx = dx, dy = dy)
   
  #main
my_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT)
  wall_image = games.load_image("skywall.png", transparent = False)
my_screen.set_background(wall_image)
  pizza_image = games.load_image("pizza.png")
Pizza(screen = my_screen, x = SCREEN_WIDTH/2, y = SCREEN_HEIGHT/2,
          image = pizza_image, dx = 0, dy = 1)
   
  my_screen.mainloop()
   
  ___________
   
   
  Here's the error message:
  
 
  Traceback (most recent call last):
  File "C:/Python25/Chapter 11/movingsprite.py", line 25, in <module>
    image = pizza_image, dx = 0, dy =1)
  File "C:/Python25/Chapter 11/movingsprite.py", line 15, in __init__
    dx = dx, dy = dy)
TypeError: init_sprite() got an unexpected keyword argument 'dx'
   
   
  Thanks in advance for any help you can give me.  :-)

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080112/2a2bbdda/attachment.htm 

From keridee at jayco.net  Sun Jan 13 01:05:26 2008
From: keridee at jayco.net (Tiger12506)
Date: Sat, 12 Jan 2008 19:05:26 -0500
Subject: [Tutor] Why Won't My Pizza Fall?
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>
Message-ID: <003f01c85578$297a8170$7efce004@jslaptop>

> Hey There Everyone,
>
>  I'm following an example in a book and I can't find the error that's 
> preventing this program from running.  It's just an example of how to get 
> a sprite moving.  The images are all in the right folder.  I can run the 
> program and get a stationary sprite to appear.  The trouble seems to come 
> up when I add "dx" and "dy"  Here's the code.

I thank you for sending your error messages and the code! It made this very 
simple.


>  from livewires import games
>
>  SCREEN_WIDTH = 640
> SCREEN_HEIGHT = 480
>
>  class Pizza(games.Sprite):
>    """A falling pizza."""
>    def __init__(self, screen, x, y, image, dx, dy):
>        """Initialize pizza object."""
>        self.init_sprite(screen = screen, x = x, y = y, image = image,
>                             dx = dx, dy = dy)
>
>  #main
> my_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT)
>  wall_image = games.load_image("skywall.png", transparent = False)
> my_screen.set_background(wall_image)
>  pizza_image = games.load_image("pizza.png")
> Pizza(screen = my_screen, x = SCREEN_WIDTH/2, y = SCREEN_HEIGHT/2,
>          image = pizza_image, dx = 0, dy = 1)
>
>  my_screen.mainloop()
>
>  ___________
>
>
>  Here's the error message:
>
>
>  Traceback (most recent call last):
>  File "C:/Python25/Chapter 11/movingsprite.py", line 25, in <module>
>    image = pizza_image, dx = 0, dy =1)
>  File "C:/Python25/Chapter 11/movingsprite.py", line 15, in __init__
>    dx = dx, dy = dy)
> TypeError: init_sprite() got an unexpected keyword argument 'dx'

Ok. This last line says that init_sprite (which is the function you call 
within your Pizza.__init__ will not accept the dx argument. (I would also 
expect that it won't accept dy either).

This is an easy fix. I'm sure you are aware that dx and dy are short for 
"change in x", "change in y" and all you have to do therefore is this.

def __init__(self, screen, x, y, image, dx, dy):
    """Initialize pizza object."""
    x += dx
    y += dy
    self.init_sprite(screen = screen, x = x, y = y, image = image)

I will warn you that this probably could be structured a little better. It 
is better, I believe, to keep your dx and your dy out of your class 
altogether and handle all of the repositioning code in your application 
(before you create a Pizza object) and let the Pizza object handle just it's 
state, not it's change in state. This is entirely stylistic however i think 
you will agree eventually.


From alan.gauld at btinternet.com  Sun Jan 13 02:05:08 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Jan 2008 01:05:08 -0000
Subject: [Tutor] Why Won't My Pizza Fall?
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>
	<003f01c85578$297a8170$7efce004@jslaptop>
Message-ID: <fmbo81$k3m$1@ger.gmane.org>

"Tiger12506" <keridee at jayco.net> wrote

> I thank you for sending your error messages and the code! It made 
> this very
> simple.

I totally agree and the answer is correct however...

> I will warn you that this probably could be structured a little 
> better. It
> is better, I believe, to keep your dx and your dy out of your class
> altogether and handle all of the repositioning code in your 
> application

I strongly disagree with this bit :-)

> (before you create a Pizza object) and let the Pizza object handle 
> just it's
> state, not it's change in state.

Objects manage their own state, any change to the state of
an object should be made by the object itself (via a method)
It is extremely bad OOP practice to have other objects (or
the "main" programme) determining the internal state of
another object. (This is why blanket getter/setter methods
are such a bad idea from an OOP point of view)

However, I do agree that an init method is probably the wrong
place to have a dx/dy pair since we should, I would ex[pect,
be positioning the object initially before trying to move it.
Thus I'd expect a move metjod someplasce that took the
dx and dy. Something like:

  class Pizza(games.Sprite):
    """A falling pizza."""
    def __init__(self, screen, x, y, image):
        """Initialize pizza object."""
        self.init_sprite(screen = screen, x = x, y = y, image = image)
        self.x = x
        self.y = y

    def fall(self, dx=0,dy=0):
        self.x += dx
        self.y += dy
        self.delete_sprite()    # clear the old
        self.init_sprite(self.x, self.y) # draw the new

However since in re-reading the description I think this Pizza
is supposed to fall automatically the default drop could be
passed in to the init, but we should try to arrange for the fall
to be called periodically(by mainloop?)

But in either case the calculation of the new x and y values
should be done by the object itself. If it isn't supposed to
know where it is then what does?

Alan G.



From eric at abrahamsen.com  Sun Jan 13 09:52:28 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Sun, 13 Jan 2008 16:52:28 +0800
Subject: [Tutor] PIL: preserving exif data
Message-ID: <EAA48A89-40D4-48E4-956E-AC86B3F1F1D5@abrahamsen.com>

Can any PIL people out there tell me if it's possible to save a jpeg  
image with exif data? I'm opening an image file, making changes to it,  
and then resaving it: apparently calling save() chops off its exif  
data, and there doesn't appear to be a way to re-attach it via a  
parameter to the save function. Has anyone run into this problem before?

Thanks,
Eric

From hendrikverlinden89 at hotmail.com  Sun Jan 13 16:24:14 2008
From: hendrikverlinden89 at hotmail.com (Hendrik Verlinden)
Date: Sun, 13 Jan 2008 16:24:14 +0100
Subject: [Tutor] Pyhon Mac/Pc
Message-ID: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>


Is the programming language for windows and mac the same? I use a python script in Blender (3d program) to export it as a DOF-format. I get a dof-file but I can't do anything with it. When I use a dof-file from windows (made the same way) it works. Perhaps I have to change some characters in the python document. (I don't know nothing about Python language:) )

Thanks

_________________________________________________________________
Een gelukkig nieuwjaar vanwege Windows Live...Download het nu gratis!
http://get.live.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080113/d664ef97/attachment.htm 

From kent37 at tds.net  Sun Jan 13 16:57:11 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 13 Jan 2008 10:57:11 -0500
Subject: [Tutor] Pyhon Mac/Pc
In-Reply-To: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>
References: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>
Message-ID: <478A34D7.9040002@tds.net>

Hendrik Verlinden wrote:
> Is the programming language for windows and mac the same?

The language is the same. There are some differences between the 
platforms. Well-written Python programs can be portable across platforms.

One difference between platforms is the default line ending. Windows 
uses carriage return / line feed (two characters). Linux and Mac OS X 
use just line feed; Mac OS 9 and earlier use carriage return.

> I use a python 
> script in Blender (3d program) to export it as a DOF-format.

What is 'it' (that is being exported)? What is DOF format?

> I get a 
> dof-file but I can't do anything with it. When I use a dof-file from 
> windows (made the same way) it works. Perhaps I have to change some 
> characters in the python document.

The details aren't too clear here. It sounds like you
- export a file from Blender on a non-windows computer
- copy the file to windows
- it doesn't work

but
- export a file from Blender on a windows computer
- use the file to windows
- it works

Is that right? If so, my guess is that the DOF files are not portable. 
You may have to tranlate the line endings from what is used on the 
source platform to the CRLF used on Windows, or change the non-Windows 
program to output CRLF.

Hmm. A little googling comes up with this:
http://relro.net/racer/dofexport.html

Is that what you are using?

Kent

From ian505 at gmail.com  Sun Jan 13 21:17:21 2008
From: ian505 at gmail.com (Ian Egland)
Date: Sun, 13 Jan 2008 15:17:21 -0500
Subject: [Tutor] New 2 Python- Script 'kill' function/Ubuntu File Browser
	hide hidden files
Message-ID: <fd42efd50801131217x2d18b126ja00d7a30a65a9d2d@mail.gmail.com>

Hello, I am new to Python (and OO programming in general) and I have a
script that I made through a tutorial.

# -*- coding: utf-8 -*-
# Copyright (C) 2007-2008 Ian Egland
# From the Non-Programmer's Guide to Python By Josh Cogliati
# 5.3 Exercise 1
# Modify the 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."


tries = 3
password = "What is the password?"
while password != "thepassword":
    print "You have", tries, "remaining."
    print "What is the password?"
    password = raw_input("> ")
    if password == "thepassword":
        print "You got the password in only", 3 - tries, "tries!"
    else:
        tries = tries - 1
        if tries == 0:
            print "Sorry... but that was wrong. (again) Your not as smart as
I thought..."
        else:
            print "I am sorry, that was incorrect. Please try again."
            quit

Now I cant see anything wrong with it... except that I don't think that quit
is the right function as when I run it this happens.

Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "copyright", "credits" or "license()" for more information.

    ****************************************************************
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface.  This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    ****************************************************************

IDLE 1.2.1      ==== No Subprocess ====
>>>
You have 3 remaining.
What is the password?
> is this it?
I am sorry, that was incorrect. Please try again.
You have 2 remaining.
What is the password?
> really?
I am sorry, that was incorrect. Please try again.
You have 1 remaining.
What is the password?
> omg one more left
Sorry... but that was wrong. (again) Your not as smart as I thought...
You have 0 remaining.
What is the password?
> ...huh?
I am sorry, that was incorrect. Please try again.
You have -1 remaining.
What is the password?
> lol
I am sorry, that was incorrect. Please try again.
You have -2 remaining.
What is the password?
>


I am using the while function, so I know that it will loop the script
forever unless I kill the application, but I don't know the command to kill
it.

Also, I am doing this in Ubuntu linux and hidden files are defined as
.filename. However, they are displayed in IDLE- so I have to scroll past
about 5 columns of hidden folders till I get to the 'visible' ones, which
contain my scripts. Any ideas on how to get IDLE not to reconize any
file/folders with the prefix '.'?

Thanks a million. I really am a nooB.

-- 
-Ian
My Website: http://www.64digits.net/
My Signature Page: http://www.64digits.net/signature/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080113/9743a722/attachment.htm 

From bgailer at alum.rpi.edu  Sun Jan 13 21:58:16 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sun, 13 Jan 2008 15:58:16 -0500
Subject: [Tutor] New 2 Python- Script 'kill' function/Ubuntu File
 Browser hide hidden files
In-Reply-To: <fd42efd50801131217x2d18b126ja00d7a30a65a9d2d@mail.gmail.com>
References: <fd42efd50801131217x2d18b126ja00d7a30a65a9d2d@mail.gmail.com>
Message-ID: <478A7B68.4040101@alum.rpi.edu>

Ian Egland wrote:
> Hello, I am new to Python (and OO programming in general) and I have a 
> script that I made through a tutorial.
>
> # -*- coding: utf-8 -*-
> # Copyright (C) 2007-2008 Ian Egland
> # From the Non-Programmer's Guide to Python By Josh Cogliati
> # 5.3 Exercise 1
> # Modify the 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."
>
>
> tries = 3
> password = "What is the password?"
> while password != "thepassword":
>     print "You have", tries, "remaining."
>     print "What is the password?"
>     password = raw_input("> ")
>     if password == "thepassword":
>         print "You got the password in only", 3 - tries, "tries!"
>     else:
>         tries = tries - 1
>         if tries == 0:
>             print "Sorry... but that was wrong. (again) Your not as 
> smart as I thought..."
>         else:
>             print "I am sorry, that was incorrect. Please try again."
>             quit
>
> Now I cant see anything wrong with it... except that I don't think 
> that quit is the right function as when I run it this happens.
quit is a function. The line above is a reference to the function rather 
than a call to the function. To call a function you must always add () 
e.g. quit().

Your goal here is to break out of the while loop. You can accomplish 
that with the break statement in place of the quit function call.

I'd code this differently, to take advantage of the for loop and to 
reduce redundant code. I also corrected spelling, introduced a 
"constant" and enhanced things so try is singular or plural as needed.

MAXTRY = 3
for tries in range(MAXTRY, 0, -1):
    if tries == 1:
        print "You have 1 try remaining."
    else:
        print "You have", tries, "tries remaining."
    print "What is the password?"
    password = raw_input("> ")
    if password == "thepassword":
        attempts = MAXTRY - tries + 1
        if attempts == 1:
            print "You got the password in only 1 try!"
        else:
            print "You got the password in only", attempts, "tries!"
        break
    elif tries > 1:
        print "I am sorry, that was incorrect. Please try again."
    else:
        print "Sorry... but that was wrong. (again) You're not as smart 
as I thought..."

That is more than you requested, and I hope it all helps your learning.

[snip]

From ian505 at gmail.com  Sun Jan 13 22:04:11 2008
From: ian505 at gmail.com (Ian Egland)
Date: Sun, 13 Jan 2008 16:04:11 -0500
Subject: [Tutor] New 2 Python- Script 'kill' function/Ubuntu File
	Browser hide hidden files
In-Reply-To: <478A7B68.4040101@alum.rpi.edu>
References: <fd42efd50801131217x2d18b126ja00d7a30a65a9d2d@mail.gmail.com>
	<478A7B68.4040101@alum.rpi.edu>
Message-ID: <fd42efd50801131304n5f9a4dbfhe98b514218b66a4@mail.gmail.com>

Thanks, you helped more than you know.

-Ian

On Jan 13, 2008 3:58 PM, bob gailer <bgailer at alum.rpi.edu> wrote:

> Ian Egland wrote:
> > Hello, I am new to Python (and OO programming in general) and I have a
> > script that I made through a tutorial.
> >
> > # -*- coding: utf-8 -*-
> > # Copyright (C) 2007-2008 Ian Egland
> > # From the Non-Programmer's Guide to Python By Josh Cogliati
> > # 5.3 Exercise 1
> > # Modify the 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."
> >
> >
> > tries = 3
> > password = "What is the password?"
> > while password != "thepassword":
> >     print "You have", tries, "remaining."
> >     print "What is the password?"
> >     password = raw_input("> ")
> >     if password == "thepassword":
> >         print "You got the password in only", 3 - tries, "tries!"
> >     else:
> >         tries = tries - 1
> >         if tries == 0:
> >             print "Sorry... but that was wrong. (again) Your not as
> > smart as I thought..."
> >         else:
> >             print "I am sorry, that was incorrect. Please try again."
> >             quit
> >
> > Now I cant see anything wrong with it... except that I don't think
> > that quit is the right function as when I run it this happens.
> quit is a function. The line above is a reference to the function rather
> than a call to the function. To call a function you must always add ()
> e.g. quit().
>
> Your goal here is to break out of the while loop. You can accomplish
> that with the break statement in place of the quit function call.
>
> I'd code this differently, to take advantage of the for loop and to
> reduce redundant code. I also corrected spelling, introduced a
> "constant" and enhanced things so try is singular or plural as needed.
>
> MAXTRY = 3
> for tries in range(MAXTRY, 0, -1):
>    if tries == 1:
>        print "You have 1 try remaining."
>    else:
>        print "You have", tries, "tries remaining."
>    print "What is the password?"
>    password = raw_input("> ")
>    if password == "thepassword":
>        attempts = MAXTRY - tries + 1
>        if attempts == 1:
>            print "You got the password in only 1 try!"
>        else:
>            print "You got the password in only", attempts, "tries!"
>        break
>    elif tries > 1:
>        print "I am sorry, that was incorrect. Please try again."
>    else:
>        print "Sorry... but that was wrong. (again) You're not as smart
> as I thought..."
>
> That is more than you requested, and I hope it all helps your learning.
>
> [snip]
>



-- 
-Ian
My Website: http://www.64digits.net/
My Signature Page: http://www.64digits.net/signature/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080113/9652b462/attachment.htm 

From kent37 at tds.net  Sun Jan 13 23:03:22 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 13 Jan 2008 17:03:22 -0500
Subject: [Tutor] Pyhon Mac/Pc
In-Reply-To: <BAY137-W40ECBD68FB76C6C1B2BCDEDC450@phx.gbl>
References: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>
	<478A34D7.9040002@tds.net>
	<BAY137-W40ECBD68FB76C6C1B2BCDEDC450@phx.gbl>
Message-ID: <478A8AAA.2020704@tds.net>

Hendrik Verlinden wrote:
> Yes I'm using the files from this link  
> http://relro.net/racer/dofexport.html :) 
> <http://relro.net/racer/dofexport.html>
> Do you now what the problem is with these files on a mac?
> Otherwise how do I have to change the carriage return or line feed?

Looking at the files, they seem to be in a binary format so my guess 
about line endings is probably not correct.

The DOFfile module does seem to take pains to write integers in 
little-endian format but does not do the same for floats. You could try 
adding '<' to the beginning of the format specifiers for floats, for 
example in writeFloat() change 'f' to '<f' and so forth.

Beyond that, I suggest you contact the author of the module for help, 
his email is in the readme.

This list is primarily for helping people who want to learn Python, not 
people having trouble with someone else's Python program, so I am not 
going to dig too far into this.

HTH,
Kent

PS Please use Reply All to keep the discussion on the list.

Kent

From ricaraoz at gmail.com  Mon Jan 14 03:37:26 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 13 Jan 2008 23:37:26 -0300
Subject: [Tutor] Why Won't My Pizza Fall?
In-Reply-To: <fmbo81$k3m$1@ger.gmane.org>
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>	<003f01c85578$297a8170$7efce004@jslaptop>
	<fmbo81$k3m$1@ger.gmane.org>
Message-ID: <478ACAE6.7080501@bigfoot.com>

Alan Gauld wrote:

> However, I do agree that an init method is probably the wrong
> place to have a dx/dy pair since we should, I would ex[pect,
> be positioning the object initially before trying to move it.
> Thus I'd expect a move metjod someplasce that took the
> dx and dy. Something like:
> 
>   class Pizza(games.Sprite):
>     """A falling pizza."""
>     def __init__(self, screen, x, y, image):
>         """Initialize pizza object."""
>         self.init_sprite(screen = screen, x = x, y = y, image = image)
>         self.x = x
>         self.y = y
> 
>     def fall(self, dx=0,dy=0):
>         self.x += dx
>         self.y += dy
>         self.delete_sprite()    # clear the old
>         self.init_sprite(self.x, self.y) # draw the new
> 
> However since in re-reading the description I think this Pizza
> is supposed to fall automatically the default drop could be
> passed in to the init, but we should try to arrange for the fall
> to be called periodically(by mainloop?)
> 
> But in either case the calculation of the new x and y values
> should be done by the object itself. If it isn't supposed to
> know where it is then what does?
> 
> Alan G.
> 

Anyway Alan, what do you think about Pizza as a class? It has two
properties, (x, y) that express it's position, but with respect to what?
Pizza cannot exist by itself, it has a strong dependency on another
object that will give context to Pizza.x and Pizza.y and in giving
context then it would modify Pizza's behavior (for instance, what
happens and where is the floor). So Pizza is tightly coupled with
another object. Isn't that questionable? I don't have an answer. What do
you think?


From ricaraoz at gmail.com  Mon Jan 14 03:39:47 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sun, 13 Jan 2008 23:39:47 -0300
Subject: [Tutor] Pyhon Mac/Pc
In-Reply-To: <478A8AAA.2020704@tds.net>
References: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>	<478A34D7.9040002@tds.net>	<BAY137-W40ECBD68FB76C6C1B2BCDEDC450@phx.gbl>
	<478A8AAA.2020704@tds.net>
Message-ID: <478ACB73.80200@bigfoot.com>

Kent Johnson wrote:
> Hendrik Verlinden wrote:
>> Yes I'm using the files from this link  
>> http://relro.net/racer/dofexport.html :) 
>> <http://relro.net/racer/dofexport.html>
>> Do you now what the problem is with these files on a mac?
>> Otherwise how do I have to change the carriage return or line feed?
> 
> Looking at the files, they seem to be in a binary format so my guess 
> about line endings is probably not correct.
> 
> The DOFfile module does seem to take pains to write integers in 
> little-endian format but does not do the same for floats. You could try 
> adding '<' to the beginning of the format specifiers for floats, for 
> example in writeFloat() change 'f' to '<f' and so forth.
> 
> Beyond that, I suggest you contact the author of the module for help, 
> his email is in the readme.
> 
> This list is primarily for helping people who want to learn Python, not 
> people having trouble with someone else's Python program, so I am not 
> going to dig too far into this.
> 
> HTH,
> Kent
> 
> PS Please use Reply All to keep the discussion on the list.
> 

Are you reading/writing the files in binary mode?



From bill.wws at gmail.com  Mon Jan 14 05:08:13 2008
From: bill.wws at gmail.com (bill.wu)
Date: Mon, 14 Jan 2008 12:08:13 +0800
Subject: [Tutor] new guy problem, what's wrong with this program.
Message-ID: <DreamMail__120813_50007182127@smtp.gmail.com>



mumber = 23
running = Ture
while running:
    guess = int(raw_input('Enter an integer :'))
    
    if guess == number:
        print 'congratulations, you guessed it.'
        running = False
    elif guess < number:
        print 'no, it is a little higher than that'
    else:
        print 'no, it is a little lower than that'
else:
    print 'the while loop is over.'
print 'done'


when i run it, interactive window show:

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run
    exec cmd in globals, locals
  File "C:\Documents and Settings\asus\??\while.py", line 2, in <module>
    running = Ture
NameError: name 'Ture' is not defined



how to solve. thanks 

____________________________________________________________________
DreamMail - ??????????????????? www.dreammail.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/d6892bc1/attachment.htm 

From eric at abrahamsen.com  Mon Jan 14 05:13:28 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Mon, 14 Jan 2008 12:13:28 +0800
Subject: [Tutor] new guy problem, what's wrong with this program.
In-Reply-To: <DreamMail__120813_50007182127@smtp.gmail.com>
References: <DreamMail__120813_50007182127@smtp.gmail.com>
Message-ID: <F27BFC4B-3A29-4274-BB60-112F4240B257@abrahamsen.com>


> mumber = 23
> running = Ture

Both these lines have spelling errors: 'mumber' should be 'number',  
and 'Ture' should be 'True'.

You can see where the problem is coming from by the end of your  
traceback:

> NameError: name 'Ture' is not defined

A NameError with something being 'not defined' nine times of ten means  
you've spelled something wrong.

Good luck!

Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/35f6c65a/attachment.htm 

From john at fouhy.net  Mon Jan 14 05:15:16 2008
From: john at fouhy.net (John Fouhy)
Date: Mon, 14 Jan 2008 17:15:16 +1300
Subject: [Tutor] new guy problem, what's wrong with this program.
In-Reply-To: <DreamMail__120813_50007182127@smtp.gmail.com>
References: <DreamMail__120813_50007182127@smtp.gmail.com>
Message-ID: <5e58f2e40801132015x288a538ax2c5d634623058497@mail.gmail.com>

On 14/01/2008, bill.wu <bill.wws at gmail.com> wrote:
> mumber = 23
> running = Ture
[...]
> when i run it, interactive window show:
>
> Traceback (most recent call last):
[...]
> NameError: name 'Ture' is not defined

Hi Bill,

The error message means that python doesn't know what "Ture" is.  In
this case, I suspect you have misspelt "True".  Programming languages
are quite picky about correct spelling!

-- 
John.

From mlangford.cs03 at gtalumni.org  Mon Jan 14 06:15:37 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 00:15:37 -0500
Subject: [Tutor] new guy problem, what's wrong with this program.
In-Reply-To: <5e58f2e40801132015x288a538ax2c5d634623058497@mail.gmail.com>
References: <DreamMail__120813_50007182127@smtp.gmail.com>
	<5e58f2e40801132015x288a538ax2c5d634623058497@mail.gmail.com>
Message-ID: <82b4f5810801132115m7c4f7717wa3c6b194b4815fa@mail.gmail.com>

I suggest using pychecker. It helps if you have spelling issues like I do:

pychecker.sourceforge.net/

Its sorta like lint for python.

        --Michael

On 1/13/08, John Fouhy <john at fouhy.net> wrote:
> On 14/01/2008, bill.wu <bill.wws at gmail.com> wrote:
> > mumber = 23
> > running = Ture
> [...]
> > when i run it, interactive window show:
> >
> > Traceback (most recent call last):
> [...]
> > NameError: name 'Ture' is not defined
>
> Hi Bill,
>
> The error message means that python doesn't know what "Ture" is.  In
> this case, I suspect you have misspelt "True".  Programming languages
> are quite picky about correct spelling!
>
> --
> John.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From mobiledreamers at gmail.com  Mon Jan 14 06:51:20 2008
From: mobiledreamers at gmail.com (mobiledreamers at gmail.com)
Date: Sun, 13 Jan 2008 21:51:20 -0800
Subject: [Tutor] Recieving emails in python
Message-ID: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>

I m trying to create something simple a mailing list similar to yahoo groups
I m stumbling at the part where the python recieves messages via say
python at yahoogroups.com

how to make python recieve emails and process it
after that it is straight forward processing in python inserting in db etc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080113/90104f7f/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Jan 14 07:24:31 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 01:24:31 -0500
Subject: [Tutor] Recieving emails in python
In-Reply-To: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
References: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
Message-ID: <82b4f5810801132224s256ec1e0pcc71fc21fda64889@mail.gmail.com>

It depends.

If you're trying to write a MTA, think about looking at and stealing
parts of mailmain and smtpd.py

Mailman: http://www.gnu.org/software/mailman/index.html
Smtpd:http://barry.warsaw.us/software/Code/smtpd.py

If you're going to use someone else as a MTA then just use IMAP or POP
to get the mail out, there are IMAP and POP libraries

imap: http://docs.python.org/lib/module-imaplib.html
pop: http://docs.python.org/lib/module-poplib.html

Else, if you're writing this all from scratch, whip out the RFC and
start hacking:
http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt

         --Michael

PS: What's the tutor policy on cross posting?


On 1/14/08, mobiledreamers at gmail.com <mobiledreamers at gmail.com> wrote:
> I m trying to create something simple a mailing list similar to yahoo groups
> I m stumbling at the part where the python recieves messages via say
> python at yahoogroups.com
>
>  how to make python recieve emails and process it
> after that it is straight forward processing in python inserting in db etc
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From law.bar at hotmail.co.uk  Mon Jan 14 07:48:36 2008
From: law.bar at hotmail.co.uk (Lawrence Barrott)
Date: Mon, 14 Jan 2008 06:48:36 +0000
Subject: [Tutor] Daemonizing Scripts
In-Reply-To: <fm7buq$ok2$1@ger.gmane.org>
References: <237595.95931.qm@web45611.mail.sp1.yahoo.com>
	<fm7buq$ok2$1@ger.gmane.org>
Message-ID: <BAY122-W2176464883DE0FC918E0BDB7460@phx.gbl>

>>Hello,>>>>How can a make a python script run in "deamon mode"? (on a linux box)>>>>That is, I want to run the program via "python myfile.py" and have it drop me back to the command line.  The program should continue running until I kill it via it's PID, the machine shuts >>down, or the program itself decides to shutdown.   It should _not_  die when I simply log-out, etc.>> >>Is there a standard library module to help with this?>>>>-- Thank you I have read through the rest of the replies for this problem and was wondering if something similar could be done in Windows (XP).Unfortunately it seems the Linux and Windows os and sys modules differ too much so the suggested approach does not work. Any help would be greatly appreciated
_________________________________________________________________
Telly addicts unite!
http://www.searchgamesbox.com/tvtown.shtml
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/9ebdfc61/attachment-0001.htm 

From mobiledreamers at gmail.com  Mon Jan 14 07:49:39 2008
From: mobiledreamers at gmail.com (mobiledreamers at gmail.com)
Date: Sun, 13 Jan 2008 22:49:39 -0800
Subject: [Tutor] Recieving emails in python
In-Reply-To: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
References: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
Message-ID: <c1870d60801132249k1760dd73vde50522484d7ca04@mail.gmail.com>

ok i dont want to write an mta
i want to use another mta
to recieve emails on say -

python at mygrouplist.com

so can i start reading the emails to python from that mta

How to set this up to read messages from the mta

sending out email
we are using sendmail so we ll continue using that for now
thanks
It depends.

If you're trying to write a MTA, think about looking at and stealing
parts of mailmain and smtpd.py

Mailman: http://www.gnu.org/software/mailman/index.html
Smtpd:http://barry.warsaw.us/software/Code/smtpd.py

If you're going to use someone else as a MTA then just use IMAP or POP
to get the mail out, there are IMAP and POP libraries

imap: http://docs.python.org/lib/module-imaplib.html
pop: http://docs.python.org/lib/module-poplib.html

Else, if you're writing this all from scratch, whip out the RFC and
start hacking:
http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt

        --Michael
On 1/13/08, mobiledreamers at gmail.com <mobiledreamers at gmail.com> wrote:
>
> I m trying to create something simple a mailing list similar to yahoo
> groups
> I m stumbling at the part where the python recieves messages via say
> python at yahoogroups.com
>
> how to make python recieve emails and process it
> after that it is straight forward processing in python inserting in db etc
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080113/b789cf98/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Jan 14 07:52:01 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 01:52:01 -0500
Subject: [Tutor] Daemonizing Scripts
In-Reply-To: <BAY122-W2176464883DE0FC918E0BDB7460@phx.gbl>
References: <237595.95931.qm@web45611.mail.sp1.yahoo.com>
	<fm7buq$ok2$1@ger.gmane.org>
	<BAY122-W2176464883DE0FC918E0BDB7460@phx.gbl>
Message-ID: <82b4f5810801132252k3c57a9den9939080901b58bb9@mail.gmail.com>

I've had this work before: http://support.microsoft.com/kb/251192

Cygwin also has a service maker, but I'm unaware of the details of using it.

       --Michael

On 1/14/08, Lawrence Barrott <law.bar at hotmail.co.uk> wrote:
>
> >>Hello,
> >>
> >>How can a make a python script run in "deamon mode"? (on a linux box)
> >>
> >>That is, I want to run the program via "python myfile.py" and have it drop
> me back to the command line.  The program should continue running until I
> kill it via it's PID, the machine shuts >>down, or the program itself
> decides to shutdown.   It should _not_  die when I simply log-out, etc.
> >>
> >>Is there a standard library module to help with this?
> >>
> >>-- Thank you
>
> I have read through the rest of the replies for this problem and was
> wondering if something similar could be done in Windows (XP).
> Unfortunately it seems the Linux and Windows os and sys modules differ too
> much so the suggested approach does not work.
>
> Any help would be greatly appreciated
>
> ________________________________
> Messenger on the move. Text MSN to 63463 now!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From mlangford.cs03 at gtalumni.org  Mon Jan 14 07:57:04 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 01:57:04 -0500
Subject: [Tutor] Recieving emails in python
In-Reply-To: <c1870d60801132248o5330d9dfx2fcfed922733a439@mail.gmail.com>
References: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
	<82b4f5810801132224s256ec1e0pcc71fc21fda64889@mail.gmail.com>
	<c1870d60801132248o5330d9dfx2fcfed922733a439@mail.gmail.com>
Message-ID: <82b4f5810801132257l4442d5dcs39c1b2ada75c0467@mail.gmail.com>

imap: http://docs.python.org/lib/module-imaplib.html
pop: http://docs.python.org/lib/module-poplib.html
or
mbox: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157437

Milters also look like they might be apropos:
http://www.bmsi.com/python/milter.html

     --Michael

On 1/14/08, mobiledreamers at gmail.com <mobiledreamers at gmail.com> wrote:
> ok i dont want to write an mta
> i want to use another mta
> to recieve emails on say -
>
> python at mygrouplist.com
>
> so can i start reading the emails to python from that mta
>
> How to set this up to read messages from the mta
>
> sending out email
> we are using sendmail so we ll continue using that for now
> thanks
>
>
>
> On 1/13/08, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
> > It depends.
> >
> > If you're trying to write a MTA, think about looking at and stealing
> > parts of mailmain and smtpd.py
> >
> > Mailman: http://www.gnu.org/software/mailman/index.html
> > Smtpd:http://barry.warsaw.us/software/Code/smtpd.py
> >
> > If you're going to use someone else as a MTA then just use IMAP or POP
> > to get the mail out, there are IMAP and POP libraries
> >
> > imap: http://docs.python.org/lib/module-imaplib.html
> > pop: http://docs.python.org/lib/module-poplib.html
> >
> > Else, if you're writing this all from scratch, whip out the RFC and
> > start hacking:
> >
> http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt
> >
> >          --Michael
> >
> > PS: What's the tutor policy on cross posting?
> >
> >
> > On 1/14/08, mobiledreamers at gmail.com < mobiledreamers at gmail.com> wrote:
> > > I m trying to create something simple a mailing list similar to yahoo
> groups
> > > I m stumbling at the part where the python recieves messages via say
> > > python at yahoogroups.com
> > >
> > >  how to make python recieve emails and process it
> > > after that it is straight forward processing in python inserting in db
> etc
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> >
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From alan.gauld at btinternet.com  Mon Jan 14 09:09:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Jan 2008 08:09:59 -0000
Subject: [Tutor] Daemonizing Scripts
References: <237595.95931.qm@web45611.mail.sp1.yahoo.com><fm7buq$ok2$1@ger.gmane.org>
	<BAY122-W2176464883DE0FC918E0BDB7460@phx.gbl>
Message-ID: <fmf5gm$31r$1@ger.gmane.org>


"Lawrence Barrott" <law.bar at hotmail.co.uk> wrote 

> Thank you I have read through the rest of the replies 
> for this problem and was wondering if something similar 
> could be done in Windows (XP).

The equivalent to a daemon on XP is a service.
If you do a bit of googling you should find an Active|State 
cookbook recipe for making a python script into a service

HTH,

Alan G.


From alan.gauld at btinternet.com  Mon Jan 14 09:18:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Jan 2008 08:18:25 -0000
Subject: [Tutor] Why Won't My Pizza Fall?
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>	<003f01c85578$297a8170$7efce004@jslaptop><fmbo81$k3m$1@ger.gmane.org>
	<478ACAE6.7080501@bigfoot.com>
Message-ID: <fmf60g$4f2$1@ger.gmane.org>


"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote

> Anyway Alan, what do you think about Pizza as a class? It has two
> properties, (x, y) that express it's position, but with respect to 
> what?

Any cartesian coordinate system.

> Pizza cannot exist by itself, it has a strong dependency on another
> object that will give context to Pizza.x and Pizza.y and in giving
> context then it would modify Pizza's behavior

Providing context does not necessarily imply modifying core
behaviour.

> happens and where is the floor). So Pizza is tightly coupled with
> another object. Isn't that questionable? I don't have an answer. 
> What do
> you think?

It is coupled in that it receives the x,y from an outside agency.
But it does not depend on that agency once intialised. The
coordinate system could be an 80x24 character display or
a 1024x768 GUI screen or a 40000x60000 virtuyal screen
or a purely conceptual mathematical model. Pizza doesn't
care it just knows where it is now and how to "fall". The only
context it needs is the initial x,y and the dx,dy values that
govern its fall rate.

If some other factor were to determine its behhaviour more
closely - such as determining whether the Pizza was within
the coordinate boundaries or in collision with another Pizza
then that could be implemented via a message protocol.
Thus the context object should respond to some message
from Pizza and in this case the Pizza should hold a reference
to its context manager(probably a screen or grid of some sort).
The context manager is responsible for tracking the objects
being managed, but the objects remain responsible for
managing their own state.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Mon Jan 14 09:22:00 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Jan 2008 08:22:00 -0000
Subject: [Tutor] Pyhon Mac/Pc
References: <BAY137-W16965CDA4E0D82B584BE4ADC450@phx.gbl>	<478A34D7.9040002@tds.net>	<BAY137-W40ECBD68FB76C6C1B2BCDEDC450@phx.gbl><478A8AAA.2020704@tds.net>
	<478ACB73.80200@bigfoot.com>
Message-ID: <fmf676$506$1@ger.gmane.org>


"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote
>> Hendrik Verlinden wrote:
>>> Yes I'm using the files from this link
>>> http://relro.net/racer/dofexport.html :)
>>> <http://relro.net/racer/dofexport.html>
>>> Do you now what the problem is with these files on a mac?
>>> Otherwise how do I have to change the carriage return or line 
>>> feed?
>>
>> Looking at the files, they seem to be in a binary format so my 
>> guess
>> about line endings is probably not correct.
> Are you reading/writing the files in binary mode?

Since the OP is not a Python programmer and doesn't know
how to modify the carriage return then I doubt he will know if
he is using binary mode. I think Kent's suggestion is best that
he contact the supplier - blind tinkering is more likely to cause
more damage than help.

The alternative suggestion is for the OP to learn Python
I suppose! :-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From zebra05 at gmail.com  Mon Jan 14 12:10:04 2008
From: zebra05 at gmail.com (OkaMthembo)
Date: Mon, 14 Jan 2008 13:10:04 +0200
Subject: [Tutor] YouTube Python web framework
Message-ID: <c7c6f3bc0801140310m7eb91b65od1d71e2481de61ee@mail.gmail.com>

Dear Friends,

Does anybody know what Python web framework e.g. Webware or Web.py, etc
YouTube is built on/in?

Kind Regards,

-- 
Sithembewena Lloyd Dube

"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/ce805111/attachment.htm 

From sgeiger at ncee.net  Mon Jan 14 07:53:41 2008
From: sgeiger at ncee.net (Shane Geiger)
Date: Mon, 14 Jan 2008 00:53:41 -0600
Subject: [Tutor] Recieving emails in python
In-Reply-To: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
References: <c1870d60801132151u28fe977alda6c854a019bfef7@mail.gmail.com>
Message-ID: <478B06F5.40801@ncee.net>

mobiledreamers at gmail.com wrote:
> I m trying to create something simple a mailing list similar to yahoo
> groups
> I m stumbling at the part where the python recieves messages via say
> python at yahoogroups.com <mailto:python at yahoogroups.com>
>
> how to make python recieve emails and process it
> after that it is straight forward processing in python inserting in db etc

Can you use POP to access Yahoo groups?

If so, this script will get you started:

#!/usr/bin/python
"""
Redirect the output to a file to capture the contents of the mailbox.
"""
host = 'foo.com'
account = 'jennyjenny'
password = '8675309'

import getpass, poplib
M = poplib.POP3(host)
#M.user(getpass.getuser())
#M.pass_(getpass.getpass())
M.user(account)
M.pass_(password)
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print j



-- 
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy


From fkayhan at rcstr.com  Mon Jan 14 09:17:47 2008
From: fkayhan at rcstr.com (Ferruh KAYHAN)
Date: Mon, 14 Jan 2008 10:17:47 +0200
Subject: [Tutor] Read protection of python files for Abaqus
Message-ID: <698FE3B0F09C344DAA29AE014A926432E0DAF1@rozmasm.rozmas.com.tr>

Dear Sirs;
Good morning.
I do not like abaqus users will read my python file codes.  How can I
protect my codes from reading ans still workable by Abaqus import??
 
Best Regards
Ferruh Kayhan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/e9e3551a/attachment.htm 

From kent37 at tds.net  Mon Jan 14 13:09:11 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Jan 2008 07:09:11 -0500
Subject: [Tutor] YouTube Python web framework
In-Reply-To: <c7c6f3bc0801140310m7eb91b65od1d71e2481de61ee@mail.gmail.com>
References: <c7c6f3bc0801140310m7eb91b65od1d71e2481de61ee@mail.gmail.com>
Message-ID: <478B50E7.90700@tds.net>

OkaMthembo wrote:
> Dear Friends,
> 
> Does anybody know what Python web framework e.g. Webware or Web.py, etc 
> YouTube is built on/in?

There is a little info here, perhaps the referenced video has more details:
http://highscalability.com/youtube-architecture

Kent

From kent37 at tds.net  Mon Jan 14 13:13:01 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Jan 2008 07:13:01 -0500
Subject: [Tutor] Read protection of python files for Abaqus
In-Reply-To: <698FE3B0F09C344DAA29AE014A926432E0DAF1@rozmasm.rozmas.com.tr>
References: <698FE3B0F09C344DAA29AE014A926432E0DAF1@rozmasm.rozmas.com.tr>
Message-ID: <478B51CD.5070504@tds.net>

Ferruh KAYHAN wrote:
> Dear Sirs;
> Good morning.
> I do not like abaqus users will read my python file codes.  How can I 
> protect my codes from reading ans still workable by Abaqus import??

You can ship .pyc files instead of .py files, that will discourage 
casual readers.

I don't think there is anything you can do to stop a determined reader 
from understanding your code.

Kent

From zebra05 at gmail.com  Mon Jan 14 13:32:46 2008
From: zebra05 at gmail.com (OkaMthembo)
Date: Mon, 14 Jan 2008 14:32:46 +0200
Subject: [Tutor] YouTube Python web framework
In-Reply-To: <478B50E7.90700@tds.net>
References: <c7c6f3bc0801140310m7eb91b65od1d71e2481de61ee@mail.gmail.com>
	<478B50E7.90700@tds.net>
Message-ID: <c7c6f3bc0801140432s17f5c23blf1a11c074be1fc46@mail.gmail.com>

Thanks Kent :)

On Jan 14, 2008 2:09 PM, Kent Johnson <kent37 at tds.net> wrote:

> OkaMthembo wrote:
> > Dear Friends,
> >
> > Does anybody know what Python web framework e.g. Webware or Web.py, etc
> > YouTube is built on/in?
>
> There is a little info here, perhaps the referenced video has more
> details:
> http://highscalability.com/youtube-architecture
>
> Kent
>



-- 
Sithembewena Lloyd Dube

"The Stupidry Foundry"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/a3de9dc9/attachment.htm 

From bhaaluu at gmail.com  Mon Jan 14 14:25:11 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Mon, 14 Jan 2008 08:25:11 -0500
Subject: [Tutor] Read protection of python files for Abaqus
In-Reply-To: <698FE3B0F09C344DAA29AE014A926432E0DAF1@rozmasm.rozmas.com.tr>
References: <698FE3B0F09C344DAA29AE014A926432E0DAF1@rozmasm.rozmas.com.tr>
Message-ID: <ea979d70801140525t3cd41e80va782952914242f0a@mail.gmail.com>

Greetings,
On Jan 14, 2008 3:17 AM, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> Dear Sirs;
> Good morning.
> I do not like abaqus users will read my python file codes.  How can I
> protect my codes from reading ans still workable by Abaqus import??
>
> Best Regards
> Ferruh Kayhan

<quote source=wikipedia?ABAQUS>
Abaqus is widely used in the automotive, aerospace, and industrial
products industries. The package is very popular with academic and
research institutions
...
These software products, especially Abaqus/CAE, extensively use the
open-source scripting language Python for scripting and customization.
</quote>

Don't academics and researchers thrive on sharing information?
Also, this forum is geared towards learning Python, and sharing
source code is encouraged in order to obtain help.

Also, "many eyes" can find and fix bugs in your scripts,
as well as, others may find the scripts useful: ie. research
can advance more quickly.

Is there a particular reason why you don't want others to see your
Abaqus Python scripts?

Just curious.
-- 
b h a a l u u at g m a i l dot c o m

From fkayhan at rcstr.com  Mon Jan 14 14:01:30 2008
From: fkayhan at rcstr.com (Ferruh KAYHAN)
Date: Mon, 14 Jan 2008 15:01:30 +0200
Subject: [Tutor] Read protection of python files for Abaqus
Message-ID: <698FE3B0F09C344DAA29AE014A926432E0DBA7@rozmasm.rozmas.com.tr>

Thank you very much for your reply. 

-----Original Message-----
From: Kent Johnson [mailto:kent37 at tds.net] 
Sent: Monday, January 14, 2008 2:13 PM
To: Ferruh KAYHAN
Cc: tutor at python.org
Subject: Re: [Tutor] Read protection of python files for Abaqus

Ferruh KAYHAN wrote:
> Dear Sirs;
> Good morning.
> I do not like abaqus users will read my python file codes.  How can I 
> protect my codes from reading ans still workable by Abaqus import??

You can ship .pyc files instead of .py files, that will discourage
casual readers.

I don't think there is anything you can do to stop a determined reader
from understanding your code.

Kent

From fkayhan at rcstr.com  Mon Jan 14 15:24:46 2008
From: fkayhan at rcstr.com (Ferruh KAYHAN)
Date: Mon, 14 Jan 2008 16:24:46 +0200
Subject: [Tutor] Read protection of python files for Abaqus
Message-ID: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>

Dear Sir;
Thank you for your reply.  Oftenly, especially in industrial companies,
codes are becoming very valuable and owner of the company likes to keep
that value as confidential in order to protect the company
competitivness.  Somr times, professionals are leaving companies and
starting new jobs in competitor companies.  Therefore, protecting some
codes are becoming important.

So in our case, we are not trying to stop anybody learning python
language but we are trying to protect what we are doing with python.

I hope my reply is sufficient.

Regards 

-----Original Message-----
From: bhaaluu [mailto:bhaaluu at gmail.com] 
Sent: Monday, January 14, 2008 3:25 PM
To: Ferruh KAYHAN
Cc: tutor at python.org
Subject: Re: [Tutor] Read protection of python files for Abaqus

Greetings,
On Jan 14, 2008 3:17 AM, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> Dear Sirs;
> Good morning.
> I do not like abaqus users will read my python file codes.  How can I 
> protect my codes from reading ans still workable by Abaqus import??
>
> Best Regards
> Ferruh Kayhan

<quote source=wikipedia?ABAQUS>
Abaqus is widely used in the automotive, aerospace, and industrial
products industries. The package is very popular with academic and
research institutions ...
These software products, especially Abaqus/CAE, extensively use the
open-source scripting language Python for scripting and customization.
</quote>

Don't academics and researchers thrive on sharing information?
Also, this forum is geared towards learning Python, and sharing source
code is encouraged in order to obtain help.

Also, "many eyes" can find and fix bugs in your scripts, as well as,
others may find the scripts useful: ie. research can advance more
quickly.

Is there a particular reason why you don't want others to see your
Abaqus Python scripts?

Just curious.
--
b h a a l u u at g m a i l dot c o m

From mlangford.cs03 at gtalumni.org  Mon Jan 14 16:32:43 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 10:32:43 -0500
Subject: [Tutor] Read protection of python files for Abaqus
In-Reply-To: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>
Message-ID: <82b4f5810801140732i4b1692abx2d65cea28978ffd8@mail.gmail.com>

I know there are a lot of people who are very much for code openness
in all cases. I'm from a couple worlds that's not even something you'd
think about doing (military software, where people die if the other
side gets your code, and embedded software, where a company in china
copies your design and puts you out of business), so you have to work
within this sometimes. That said, many companies *vastly* overvalue
their code base, especially the great balance of it, when really 4-10
modules are the only valuable parts.

There are obfuscators that generally work for python and then only
shipping .pyc files (as someone suggested above) helps as well.

If the code really is that valuable, I doubt you're going to be able
to hide it well enough a determined, an attacker with a skill level
equal to many of the people on this list, couldn't extract your
algorithms. I'm am not saying .NET is any more secure in that than
python is either. Just introspective languages (Java too), have this
issue where they're quite a bit easier to reverse engineer.

Assuming its only moderately valuable, then the steps above should be enough.

You may think about isolating the highly valuable algorithm in a C
module then highly optimizing it and running a stripper on it. Then
connect it up to your python code with SWIG. That will defeat the
introspection attacks (they'll only be able to see the interface of
the C module), and the high levels of optimization in the C code
(which you should strip) will hide the algorithm further.

Another possibility is refactoring your algorithm into a code
generating utility which you don't let leave your facility. The
generated code will work, but is not reverse engineerable, as its just
something like a massive lookup table, or a series of decomposed
functions.

I've been the guy attacking code before. It all boils down to the
safe/lock issue: Locks and safes aren't there to keep people out
forever, every good lock and safe has an amount of time they expect to
keep people out. You have to have a security guard or something else
at that point to safeguard your valuables. Pick locks that are good
enough, and try to remove the incentives and abilities to break in
other ways.

            --Michael

PS: I would like to point out. These other people will be able to
*call* your highly proprietary code no matter what you do. So if
nothing else, a determined attacker can just call your code again
without understanding it.
-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com


On 1/14/08, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> Dear Sir;
> Thank you for your reply.  Oftenly, especially in industrial companies,
> codes are becoming very valuable and owner of the company likes to keep
> that value as confidential in order to protect the company
> competitivness.  Somr times, professionals are leaving companies and
> starting new jobs in competitor companies.  Therefore, protecting some
> codes are becoming important.
>
> So in our case, we are not trying to stop anybody learning python
> language but we are trying to protect what we are doing with python.
>
> I hope my reply is sufficient.
>
> Regards
>
> -----Original Message-----
> From: bhaaluu [mailto:bhaaluu at gmail.com]
> Sent: Monday, January 14, 2008 3:25 PM
> To: Ferruh KAYHAN
> Cc: tutor at python.org
> Subject: Re: [Tutor] Read protection of python files for Abaqus
>
> Greetings,
> On Jan 14, 2008 3:17 AM, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> > Dear Sirs;
> > Good morning.
> > I do not like abaqus users will read my python file codes.  How can I
> > protect my codes from reading ans still workable by Abaqus import??
> >
> > Best Regards
> > Ferruh Kayhan
>
> <quote source=wikipedia?ABAQUS>
> Abaqus is widely used in the automotive, aerospace, and industrial
> products industries. The package is very popular with academic and
> research institutions ...
> These software products, especially Abaqus/CAE, extensively use the
> open-source scripting language Python for scripting and customization.
> </quote>
>
> Don't academics and researchers thrive on sharing information?
> Also, this forum is geared towards learning Python, and sharing source
> code is encouraged in order to obtain help.
>
> Also, "many eyes" can find and fix bugs in your scripts, as well as,
> others may find the scripts useful: ie. research can advance more
> quickly.
>
> Is there a particular reason why you don't want others to see your
> Abaqus Python scripts?
>
> Just curious.
> --
> b h a a l u u at g m a i l dot c o m
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From brindly at gmail.com  Mon Jan 14 16:55:52 2008
From: brindly at gmail.com (brindly sujith)
Date: Mon, 14 Jan 2008 21:25:52 +0530
Subject: [Tutor] how to change the values of keyboard keys in TKINTER
Message-ID: <bfb67a4d0801140755q6d213065s473b8b0118e2999e@mail.gmail.com>

hi

i want to know how to change the values of keyboard keys(for example:
I want to set alt+f4 to enter)

do we have any modules in tkinter for doing this...

plz tell me how we can do this
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/500aac86/attachment.htm 

From ceasar102 at yahoo.com  Mon Jan 14 17:43:46 2008
From: ceasar102 at yahoo.com (ammar azif)
Date: Mon, 14 Jan 2008 08:43:46 -0800 (PST)
Subject: [Tutor] Document Control System
In-Reply-To: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>
Message-ID: <123975.197.qm@web56801.mail.re3.yahoo.com>

Hello,

Is python suitable in developing web based document control system ? I was thinking of using python and mysql to create such system. Users can download latest document as well as upload drafts. Is this possible or i should use PHP instead?

       
---------------------------------
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080114/c308e426/attachment.htm 

From mlangford.cs03 at gtalumni.org  Mon Jan 14 18:03:37 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Mon, 14 Jan 2008 12:03:37 -0500
Subject: [Tutor] Document Control System
In-Reply-To: <123975.197.qm@web56801.mail.re3.yahoo.com>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>
	<123975.197.qm@web56801.mail.re3.yahoo.com>
Message-ID: <82b4f5810801140903p26f8fc41j841397590526d96e@mail.gmail.com>

There are several ready made ones. Plone for instance: http://plone.org/
It's a very customizable zope project.

Look at Paste as well in building up your stack: http://pythonpaste.org/

I also suggest opting for use of  the WSGI interface for your
application (a python web-app interface which allows easy
collaboration between apps). There is mod_wsgi for apache deployment
and you can use numerous web servers for a development standard. I
really think it is the simplest thing available now, and the way of
the future.
http://www.wsgi.org/wsgi/Learn_WSGI
http://code.google.com/p/modwsgi/

I'm porting my mod_python stuff over....


          --Michael

On Jan 14, 2008 11:43 AM, ammar azif <ceasar102 at yahoo.com> wrote:
> Hello,
>
> Is python suitable in developing web based document control system ? I was
> thinking of using python and mysql to create such system. Users can download
> latest document as well as upload drafts. Is this possible or i should use
> PHP instead?
>
>
>  ________________________________
> Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it
> now.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From kent37 at tds.net  Mon Jan 14 18:10:53 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 14 Jan 2008 12:10:53 -0500
Subject: [Tutor] Document Control System
In-Reply-To: <123975.197.qm@web56801.mail.re3.yahoo.com>
References: <123975.197.qm@web56801.mail.re3.yahoo.com>
Message-ID: <478B979D.2030706@tds.net>

ammar azif wrote:
> Hello,
> 
> Is python suitable in developing web based document control system ? I 
> was thinking of using python and mysql to create such system. Users can 
> download latest document as well as upload drafts. Is this possible or i 
> should use PHP instead?

Document control can mean many things but it should be possible using 
Python. You might be interested in these:
http://www.python.org/about/success/ezro/
http://www.python.org/about/success/st-andrews/

Zope and Plone also might be of interest. Or maybe you want a 
revision-control system like Subversion (not in Python) (google them).

Kent

From alan.gauld at btinternet.com  Mon Jan 14 19:08:52 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Jan 2008 18:08:52 -0000
Subject: [Tutor] how to change the values of keyboard keys in TKINTER
References: <bfb67a4d0801140755q6d213065s473b8b0118e2999e@mail.gmail.com>
Message-ID: <fmg8jj$95c$1@ger.gmane.org>

"brindly sujith" <brindly at gmail.com> wrote

> i want to know how to change the values of keyboard keys(for 
> example:
> I want to set alt+f4 to enter)

Can you be more specific?
Do you want to change Alt-F4 for every application on the
computer permanently or only on a single application?
Do you want Alt-F4 to become the Enter key or just to
act like one in a specific scenario?

> do we have any modules in tkinter for doing this...

Not specifically but some of it can be faked.
See my event driven programming topic in my tutorial
for example code for reading the keys - including Alt-F4.

However its worth pointing out that this kind of stuff, and
the other things that you are posting are really well outside
what Tk was designed for.

The Tool Control Language(Tcl) was intended to be an
embedded macro language for various lab tools. Similar
to Python in that it is a scripting language which can easily
interface with other languages and be embedded in them.

The Tcl Toolkit (Tcl/Tk) was intended to allow a simple
GUI front end to be added to Tcl projects. It was never
really intended for writing complex GUI applications, it
provides basic GUI capability in a very easy to use package.

Tkinter is a thin Python wrapper around Tcl/Tk and has
much the same purpose - to provide basic GUI wrapper
capability in an easy to use package. It is not a fully
featured GUI system like MS Windows or X windows.

If you want to do lots of low level control of a GUI you
would be better advised to look at toolkits like PyQt or
GTK. Even wxPython struggles to provide the low level
detailed control that you are looking for.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From dkuhlman at rexx.com  Mon Jan 14 19:20:24 2008
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Mon, 14 Jan 2008 10:20:24 -0800
Subject: [Tutor] Document Control System
In-Reply-To: <123975.197.qm@web56801.mail.re3.yahoo.com>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>
	<123975.197.qm@web56801.mail.re3.yahoo.com>
Message-ID: <20080114182024.GB47507@cutter.rexx.com>

On Mon, Jan 14, 2008 at 08:43:46AM -0800, ammar azif wrote:
> Hello,
> 

> Is python suitable in developing web based document control
> system ? I was thinking of using python and mysql to create such
> system. Users can download latest document as well as upload
> drafts. Is this possible or i should use PHP instead?

Also look at Silva:

    http://infrae.com/products/silva

Silva, as well as Plone (http://plone.org), are intended for
*content* management.  They use workflow rules to control the
movement of on-line documents through the system.  Document
management, in contrast with content management might mean
something slightly different to you.

- Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman

From keridee at jayco.net  Tue Jan 15 01:52:42 2008
From: keridee at jayco.net (Tiger12506)
Date: Mon, 14 Jan 2008 19:52:42 -0500
Subject: [Tutor] Why Won't My Pizza Fall?
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>	<003f01c85578$297a8170$7efce004@jslaptop><fmbo81$k3m$1@ger.gmane.org><478ACAE6.7080501@bigfoot.com>
	<fmf60g$4f2$1@ger.gmane.org>
Message-ID: <007e01c85711$19072ba0$e058e104@jslaptop>

[Background from Alan]
> If some other factor were to determine its behhaviour more
> closely - such as determining whether the Pizza was within
> the coordinate boundaries or in collision with another Pizza
> then that could be implemented via a message protocol.
> Thus the context object should respond to some message
> from Pizza and in this case the Pizza should hold a reference
> to its context manager(probably a screen or grid of some sort).


[disclaimer]
This email has particularly strong personal opinions about coding practices. 
I do not wish to personally offend anyone, and if you feel that you have 
been offended as such, or that you disagree, please do not bother emailing 
this list to tell me, excepting that you provide an excellent case promoting 
your views that someone may be able to apply to make their code more 
intuitive/sensible. This email was provided for just such a reason.
[/disclaimer]


> The context manager is responsible for tracking the objects
> being managed, but the objects remain responsible for
> managing their own state.

[rant]
This phrase right here is a dead giveaway to me that Pizza should have 
little control over how it moves. A Pizza must be completely aware of its 
current position (being part of its state) and at the very *most* a set of 
rules governing general falling behaviour. I like the idea of a context 
manager that is perhaps a container for Pizzas that oversees their behavior, 
but I dislike the idea that a Pizza knows specifics about its rules for 
positioning such as collisions or etc. that it has to communicate to the 
context manager and/or other Pizzas. Maybe I am becoming too used to lower 
level languages, not fully siding with abstraction. I just see that we have 
suddenly introduced to new levels of redirection to achieve the same result, 
like a company that must use interdepartmental communication by messages 
through possibly more than one department instead of just simply 
communicating directly. Or like the elements of a list changing each other, 
instead of the list changing the elements. Definite benefits for messaging 
models, but this /feels/ akin to filling out tax forms so that the 
government can tell you how you filled them out incorrectly.

A similar somewhat questionably connected problem involves my dealings with 
the Render method of the IPicture interface. Sure, you can directly apply 
the picture to the device context or if you like we have a Render method 
that will automatically change the coordinates so that you have to convert 
them back to display it. Abstraction isn't everything.
[/rant] 


From washakie at gmail.com  Tue Jan 15 10:59:45 2008
From: washakie at gmail.com (John)
Date: Tue, 15 Jan 2008 10:59:45 +0100
Subject: [Tutor] MySQLdb install issue
Message-ID: <aaf235960801150159l1ada2ea7hbd2aa802d44f881c@mail.gmail.com>

Hello,

Does anyone know how to install MySQLdb into a python installation when the
machine you are working on does not have MySQL installed? I.E. the MySQL
installation is on a different server, but the site.cfg file for the MySQLdb
installation asks for the location of the mysql_config:


"
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
#mysql_config = /usr/local/bin/mysql_config

"

Thanks!

-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080115/3929be0e/attachment.htm 

From fkayhan at rcstr.com  Tue Jan 15 09:31:58 2008
From: fkayhan at rcstr.com (Ferruh KAYHAN)
Date: Tue, 15 Jan 2008 10:31:58 +0200
Subject: [Tutor] Read protection of python files for Abaqus
Message-ID: <698FE3B0F09C344DAA29AE014A926432E0DCB5@rozmasm.rozmas.com.tr>

Dear Sir;
Thank you very much for the information.  After I read your e-mail, I
have started to think that our codes are not highly but moderately
valuable.  Therefore, I am satisfied, by using .pyc files.  I am not
very affraid of determined hackers from outside because they will not
understand the usage of my application and a hardcopy of the codes will
always be in my handbag.

Best Regards
Ferruh Kayhan 

-----Original Message-----
From: michael.langford at gmail.com [mailto:michael.langford at gmail.com] On
Behalf Of Michael Langford
Sent: Monday, January 14, 2008 5:33 PM
To: Ferruh KAYHAN
Cc: tutor at python.org
Subject: Re: [Tutor] Read protection of python files for Abaqus

I know there are a lot of people who are very much for code openness in
all cases. I'm from a couple worlds that's not even something you'd
think about doing (military software, where people die if the other side
gets your code, and embedded software, where a company in china copies
your design and puts you out of business), so you have to work within
this sometimes. That said, many companies *vastly* overvalue their code
base, especially the great balance of it, when really 4-10 modules are
the only valuable parts.

There are obfuscators that generally work for python and then only
shipping .pyc files (as someone suggested above) helps as well.

If the code really is that valuable, I doubt you're going to be able to
hide it well enough a determined, an attacker with a skill level equal
to many of the people on this list, couldn't extract your algorithms.
I'm am not saying .NET is any more secure in that than python is either.
Just introspective languages (Java too), have this issue where they're
quite a bit easier to reverse engineer.

Assuming its only moderately valuable, then the steps above should be
enough.

You may think about isolating the highly valuable algorithm in a C
module then highly optimizing it and running a stripper on it. Then
connect it up to your python code with SWIG. That will defeat the
introspection attacks (they'll only be able to see the interface of the
C module), and the high levels of optimization in the C code (which you
should strip) will hide the algorithm further.

Another possibility is refactoring your algorithm into a code generating
utility which you don't let leave your facility. The generated code will
work, but is not reverse engineerable, as its just something like a
massive lookup table, or a series of decomposed functions.

I've been the guy attacking code before. It all boils down to the
safe/lock issue: Locks and safes aren't there to keep people out
forever, every good lock and safe has an amount of time they expect to
keep people out. You have to have a security guard or something else at
that point to safeguard your valuables. Pick locks that are good enough,
and try to remove the incentives and abilities to break in other ways.

            --Michael

PS: I would like to point out. These other people will be able to
*call* your highly proprietary code no matter what you do. So if nothing
else, a determined attacker can just call your code again without
understanding it.
--
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com


On 1/14/08, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> Dear Sir;
> Thank you for your reply.  Oftenly, especially in industrial
companies,
> codes are becoming very valuable and owner of the company likes to
keep
> that value as confidential in order to protect the company
> competitivness.  Somr times, professionals are leaving companies and
> starting new jobs in competitor companies.  Therefore, protecting some
> codes are becoming important.
>
> So in our case, we are not trying to stop anybody learning python
> language but we are trying to protect what we are doing with python.
>
> I hope my reply is sufficient.
>
> Regards
>
> -----Original Message-----
> From: bhaaluu [mailto:bhaaluu at gmail.com]
> Sent: Monday, January 14, 2008 3:25 PM
> To: Ferruh KAYHAN
> Cc: tutor at python.org
> Subject: Re: [Tutor] Read protection of python files for Abaqus
>
> Greetings,
> On Jan 14, 2008 3:17 AM, Ferruh KAYHAN <fkayhan at rcstr.com> wrote:
> > Dear Sirs;
> > Good morning.
> > I do not like abaqus users will read my python file codes.  How can
I
> > protect my codes from reading ans still workable by Abaqus import??
> >
> > Best Regards
> > Ferruh Kayhan
>
> <quote source=wikipedia?ABAQUS>
> Abaqus is widely used in the automotive, aerospace, and industrial
> products industries. The package is very popular with academic and
> research institutions ...
> These software products, especially Abaqus/CAE, extensively use the
> open-source scripting language Python for scripting and customization.
> </quote>
>
> Don't academics and researchers thrive on sharing information?
> Also, this forum is geared towards learning Python, and sharing source
> code is encouraged in order to obtain help.
>
> Also, "many eyes" can find and fix bugs in your scripts, as well as,
> others may find the scripts useful: ie. research can advance more
> quickly.
>
> Is there a particular reason why you don't want others to see your
> Abaqus Python scripts?
>
> Just curious.
> --
> b h a a l u u at g m a i l dot c o m
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From brunson at brunson.com  Tue Jan 15 18:10:02 2008
From: brunson at brunson.com (Eric Brunson)
Date: Tue, 15 Jan 2008 10:10:02 -0700
Subject: [Tutor] MySQLdb install issue
In-Reply-To: <aaf235960801150159l1ada2ea7hbd2aa802d44f881c@mail.gmail.com>
References: <aaf235960801150159l1ada2ea7hbd2aa802d44f881c@mail.gmail.com>
Message-ID: <478CE8EA.7050407@brunson.com>


There is at least on client library that the mysql package needs to link 
against.  You either need to install the libraries on the client machine 
or else build the package statically linked on the server machine and 
move it over prebuilt.

John wrote:
> Hello,
>  
> Does anyone know how to install MySQLdb into a python installation 
> when the machine you are working on does not have MySQL installed? 
> I.E. the MySQL installation is on a different server, but the site.cfg 
> file for the MySQLdb installation asks for the location of the 
> mysql_config:
>  
>  
> "
> # The path to mysql_config.
> # Only use this if mysql_config is not on your PATH, or you have some 
> weird
> # setup that requires it.
> #mysql_config = /usr/local/bin/mysql_config
>  
> "
>  
> Thanks!
>
> -- 
> Configuration
> ``````````````````````````
> Plone 2.5.3-final,
> CMF-1.6.4,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 
> 4.1.1-51)],
> PIL 1.1.6
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From dineshbvadhia at hotmail.com  Tue Jan 15 18:12:35 2008
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Tue, 15 Jan 2008 09:12:35 -0800
Subject: [Tutor] A faster x in S
Message-ID: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>

For some significant data pre-processing we have to perform the following simple process:

Is the integer x in a list of 13K sorted integers.  That's it except this has to be done >100m times with different x's (multiple times).  Yep, a real pain!  

I've put the 13K integers in a list S and am using the is 'x in S' function.

I was wondering if there is anything faster?

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080115/ceeee28e/attachment.htm 

From work at infomaniak.ch  Tue Jan 15 17:18:18 2008
From: work at infomaniak.ch (cedric briner)
Date: Tue, 15 Jan 2008 17:18:18 +0100
Subject: [Tutor] tree/node class/module
Message-ID: <478CDCCA.7060606@infomaniak.ch>

hello,

I'm wanting to do a GUI for to help people using rsync, du, tar . it 
will provide the --exclude and --include of them.

And I thought that the best way to store data relative to the hierarchy 
filesystem was to store them in a tree structure. But after browsing 
ages on the web, I didn't found any class/modules which implements 
trees, with some comments, and small examples.

Am I just blind ???

I'm looking for a tree of object which will give me stuff like:
  - sibling
  - parent
  - children
  - find
  - insert

Do you have any pointers ??

Ced.

-- 

Cedric BRINER
Geneva - Switzerland

From kent37 at tds.net  Tue Jan 15 18:38:40 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jan 2008 12:38:40 -0500
Subject: [Tutor] A faster x in S
In-Reply-To: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>
References: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>
Message-ID: <478CEFA0.4020109@tds.net>

Dinesh B Vadhia wrote:
> For some significant data pre-processing we have to perform the 
> following simple process:
>  
> Is the integer x in a list of 13K sorted integers.  That's it except 
> this has to be done >100m times with different x's (multiple times).  
> Yep, a real pain! 
>  
> I've put the 13K integers in a list S and am using the is 'x in S' function.
>  
> I was wondering if there is anything faster?

Yes. Put the integers in a set and test for membership there. If for 
some reason the integers have to be in a list, and the list is sorted, 
use the bisect module to do a binary search, rather than the linear 
search used by 'x in S'.
http://docs.python.org/lib/module-bisect.html

Kent

From lechtlr at yahoo.com  Tue Jan 15 21:26:29 2008
From: lechtlr at yahoo.com (lechtlr)
Date: Tue, 15 Jan 2008 12:26:29 -0800 (PST)
Subject: [Tutor] Reading Input Data
Message-ID: <920791.67864.qm@web57905.mail.re3.yahoo.com>

I want to read an input file (file.csv) that has two columns. I want to read 2nd column and assign variables that are strings and floats. Currently, I use the following split() function to read from the input file and create a list, and then assign each element to a variable. 

I am wondering there is any other easier (and elegant) way of doing this ?

data = []
for line in open("file.csv"):
     columns = line.split(',')
     data.append([columns[1]])

This script returns, say:
data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]

Then, I assign to a set of variables, say:

x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn = data[-1][0] 


Thanks,
Lex







       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080115/92788f4f/attachment.htm 

From titleistfour at gmail.com  Tue Jan 15 21:34:15 2008
From: titleistfour at gmail.com (jay)
Date: Tue, 15 Jan 2008 14:34:15 -0600
Subject: [Tutor] Reading Input Data
In-Reply-To: <920791.67864.qm@web57905.mail.re3.yahoo.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
Message-ID: <7c25bb490801151234l7fbdba12r9c68006bdac834df@mail.gmail.com>

Python has a cvs module that will make this slightly more elegant

http://docs.python.org/lib/module-csv.html

j

On Jan 15, 2008 2:26 PM, lechtlr <lechtlr at yahoo.com> wrote:

> I want to read an input file (file.csv) that has two columns. I want to
> read 2nd column and assign variables that are strings and floats. Currently,
> I use the following split() function to read from the input file and create
> a list, and then assign each element to a variable.
>
> I am wondering there is any other easier (and elegant) way of doing this ?
>
> data = []
> for line in open("file.csv"):
>      columns = line.split(',')
>      data.append([columns[1]])
>
> This script returns, say:
> data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50'
> ]]
>
> Then, I assign to a set of variables, say:
>
> x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> data[-1][0]
>
>
> Thanks,
> Lex
>
>
>
>
>
>
> ------------------------------
> Never miss a thing. Make Yahoo your homepage.<http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080115/5692df7a/attachment.htm 

From kent37 at tds.net  Tue Jan 15 21:44:16 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jan 2008 15:44:16 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <920791.67864.qm@web57905.mail.re3.yahoo.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
Message-ID: <478D1B20.4000407@tds.net>

lechtlr wrote:
> I want to read an input file (file.csv) that has two columns. I want to 
> read 2nd column and assign variables that are strings and floats. 
> Currently, I use the following split() function to read from the input 
> file and create a list, and then assign each element to a variable.
> 
> I am wondering there is any other easier (and elegant) way of doing this ?

Hmm. Are the strings and floats in a repeating pattern, or randomly 
sprinkled around, or what?

Assigning a bunch of variables like this may not be the best way to 
handle the data. Perhaps you could just keep them in a list?

Why are you doing this? How many lines are in the data file?

> data = []
> for line in open("file.csv"):
>      columns = line.split(',')
>      data.append([columns[1]])

This could be
   data.append(columns[1])
there is no need to make a nested list.

> 
> This script returns, say:
> data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
> 
> Then, I assign to a set of variables, say:
> 
> x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn = 
> data[-1][0]

Without the extra nesting it would be
   x1 = float(data[0]); etc.

Kent

> 
> 
> Thanks,
> Lex
> 
> 
> 
> 
> 
> 
> ------------------------------------------------------------------------
> Never miss a thing. Make Yahoo your homepage. 
> <http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From mlangford.cs03 at gtalumni.org  Tue Jan 15 21:47:53 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Tue, 15 Jan 2008 15:47:53 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <920791.67864.qm@web57905.mail.re3.yahoo.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
Message-ID: <82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>

for subscript,line in enumerate(file("file.csv")):
     s = line.split(",")[1]
     try:
	     f = float(s)
	     locals()["x%i" % subscript]=f
     except:
	     locals()["x%i" % subscript]=s

print x1
print x

On Jan 15, 2008 3:26 PM, lechtlr <lechtlr at yahoo.com> wrote:
> I want to read an input file (file.csv) that has two columns. I want to read
> 2nd column and assign variables that are strings and floats. Currently, I
> use the following split() function to read from the input file and create a
> list, and then assign each element to a variable.
>
> I am wondering there is any other easier (and elegant) way of doing this ?
>
> data = []
> for line in open("file.csv"):
>      columns = line.split(',')
>      data.append([columns[1]])
>
> This script returns, say:
> data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
>
> Then, I assign to a set of variables, say:
>
> x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> data[-1][0]
>
>
> Thanks,
> Lex
>
>
>
>
>
>
>
>
>  ________________________________
> Never miss a thing. Make Yahoo your homepage.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From mlangford.cs03 at gtalumni.org  Tue Jan 15 21:50:35 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Tue, 15 Jan 2008 15:50:35 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
	<82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>
Message-ID: <82b4f5810801151250m11670feam437425936d88db76@mail.gmail.com>

Accidentally cut off a 0 there...
Think about using ConfigParser instead of your csv. Doug Hellman wrote
a good article on that:
http://blog.doughellmann.com/2007/04/pymotw-configparser.html

But if you really want to load your data this way, this will work:

for subscript,line in enumerate(file("file.csv")):
     s = line.split(",")[1]
     try:
	     f = float(s)
	     locals()["x%i" % subscript]=f
     except:
	     locals()["x%i" % subscript]=s

print x1
print x0

On Jan 15, 2008 3:47 PM, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
> for subscript,line in enumerate(file("file.csv")):
>      s = line.split(",")[1]
>      try:
>              f = float(s)
>              locals()["x%i" % subscript]=f
>      except:
>              locals()["x%i" % subscript]=s
>
> print x1
> print x
>
> On Jan 15, 2008 3:26 PM, lechtlr <lechtlr at yahoo.com> wrote:
>
> > I want to read an input file (file.csv) that has two columns. I want to read
> > 2nd column and assign variables that are strings and floats. Currently, I
> > use the following split() function to read from the input file and create a
> > list, and then assign each element to a variable.
> >
> > I am wondering there is any other easier (and elegant) way of doing this ?
> >
> > data = []
> > for line in open("file.csv"):
> >      columns = line.split(',')
> >      data.append([columns[1]])
> >
> > This script returns, say:
> > data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
> >
> > Then, I assign to a set of variables, say:
> >
> > x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> > data[-1][0]
> >
> >
> > Thanks,
> > Lex
> >
> >
> >
> >
> >
> >
> >
> >
> >  ________________________________
> > Never miss a thing. Make Yahoo your homepage.
>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From kent37 at tds.net  Tue Jan 15 22:25:09 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jan 2008 16:25:09 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
	<82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>
Message-ID: <478D24B5.8060800@tds.net>

Michael Langford wrote:
> for subscript,line in enumerate(file("file.csv")):
>      s = line.split(",")[1]
>      try:
> 	     f = float(s)
> 	     locals()["x%i" % subscript]=f
>      except:
> 	     locals()["x%i" % subscript]=s

Don't do this!

For one thing, writing to locals() doesn't always work. Specifically, 
writing to locals() inside a function does *not* affect the local namespace:
In [28]: def foo():
    ....:     locals()['x'] = 1
    ....:     print x
    ....:
    ....:
In [29]: foo()
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
   File "<ipython console>", line 3, in foo
<type 'exceptions.NameError'>: global name 'x' is not defined


Writing to globals() might be marginally better but not much. (When not 
in a function, locals() is actually the same as globals() and the above 
code will work.)

In most cases where someone is trying to assign a bunch of names like 
this, a better solution is to use a dictionary (or possibly a list) to 
hold the data.

Kent

From ricaraoz at gmail.com  Tue Jan 15 23:30:45 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Tue, 15 Jan 2008 19:30:45 -0300
Subject: [Tutor] Input
In-Reply-To: <20080114182024.GB47507@cutter.rexx.com>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com>
	<20080114182024.GB47507@cutter.rexx.com>
Message-ID: <478D3415.4080907@bigfoot.com>

Last week someone had an issue with raw_input() and how to get input for
a number. So I remembered my CP/M times and got to think of a little
function I had there. The function is lost and my time is scarce but I
made a little effort and here you have the results. It has loads of room
for improvement and probably a few bugs but it's a starting point, and
it should guarantee that you get the input you need.
You just define your mask and the functions checks the input
accordingly, it returns a string.
You might improve it by displaying the mask, e.g. for mask = '9999.99'
you might see in the screen ____.__ or for mask = '999-AAA::9999' you'd
see ___-___::___ so the user will know the format of what's expected of
him, also a beep on incorrect entry might prove nice.

HTH

-----------------------------------------------------------------------
import msvcrt

_validChars = {
                'X' :
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
                , '9' : '1234567890'
                , '-' : '-1234567890'
                , 'A' :
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
                , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
_validKeys = _validChars.keys()

def maskInput(mask, separators = True) :
    lmask = list(mask)
    lmask.reverse()
    usedMask = []
    retInput = ''
    c = ''
    maskChar = lmask.pop()
    try :
        while maskChar not in _validKeys :
            if separators :
                retInput += maskChar
            msvcrt.putch(maskChar)
            maskChar = lmask.pop()
    except IndexError : pass

    c = msvcrt.getch()
    while c != chr(13) :
        if maskChar and maskChar not in _validKeys and c in
_validChars[lmask[-1]] :
            if separators :
                retInput += maskChar
            msvcrt.putch(maskChar)
            usedMask.append(maskChar)
            maskChar = lmask.pop()
        if usedMask and c == '\b' :
            try :
                if maskChar :
                    lmask.append(maskChar)
                maskChar = usedMask.pop()
                retInput = retInput[:-1]
                msvcrt.putch(c)
                msvcrt.putch(' ')
                msvcrt.putch(c)
                while usedMask[-1] not in _validKeys :
                    if maskChar :
                        lmask.append(maskChar)
                    maskChar = usedMask.pop()
                    if separators :
                        retInput = retInput[:-1]
                    msvcrt.putch(c)
                    msvcrt.putch(' ')
                    msvcrt.putch(c)
            except IndexError : pass
        elif maskChar and c in _validChars[maskChar] :
            retInput += c
            msvcrt.putch(c)
            try :
                usedMask.append(maskChar)
                maskChar = lmask.pop()
              #  while maskChar not in _validKeys :
            except IndexError :
                maskChar = ''
        c = msvcrt.getch()
    return retInput

if __name__ == '__main__' :
    invar = maskInput('-9999.99')
    print
    print invar

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

From bgailer at alum.rpi.edu  Tue Jan 15 22:31:06 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 15 Jan 2008 16:31:06 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <920791.67864.qm@web57905.mail.re3.yahoo.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
Message-ID: <478D261A.9000004@alum.rpi.edu>

lechtlr wrote:
> I want to read an input file (file.csv) that has two columns. I want 
> to read 2nd column and assign variables that are strings and floats. 
> Currently, I use the following split() function to read from the input 
> file and create a list, and then assign each element to a variable.
In addition to Jay (it's csv module not cvs) and Michael's responses I add:

It is rarely a good idea to assign a bunch of variables (x1...xn).

What's the reason you're doing this?

You can just create another list holding the floated values. If you 
assign this list to x then you can refer to x[0], x[1], ...x[n].

Also you have created lists within your list, to no apparent purpose;

Consider:

x = [float(line.split(',')[1]) for line in open("file.csv")]

Bob

From bgailer at alum.rpi.edu  Tue Jan 15 23:03:47 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 15 Jan 2008 17:03:47 -0500
Subject: [Tutor] tree/node class/module
In-Reply-To: <478CDCCA.7060606@infomaniak.ch>
References: <478CDCCA.7060606@infomaniak.ch>
Message-ID: <478D2DC3.7020300@alum.rpi.edu>

cedric briner wrote:
> hello,
>
> I'm wanting to do a GUI for to help people using rsync, du, tar . it 
> will provide the --exclude and --include of them.
>
> And I thought that the best way to store data relative to the hierarchy 
> filesystem was to store them in a tree structure. But after browsing 
> ages on the web, I didn't found any class/modules which implements 
> trees, with some comments, and small examples.
>   
Some googling led to:

http://www.velocityreviews.com/forums/t355467-tree-and-graph-structures-in-python.html

I have not looked up the links therein but the titles sound promising.

We could roll our own if all else fails.

[snip]

Bob

From bgailer at alum.rpi.edu  Tue Jan 15 23:03:59 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 15 Jan 2008 17:03:59 -0500
Subject: [Tutor] A faster x in S
In-Reply-To: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>
References: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>
Message-ID: <478D2DCF.2080100@alum.rpi.edu>

Dinesh B Vadhia wrote:
> For some significant data pre-processing we have to perform the 
> following simple process:
>  
> Is the integer x in a list of 13K sorted integers.  That's it except 
> this has to be done >100m times with different x's (multiple times).  
> Yep, a real pain! 
>  
> I've put the 13K integers in a list S and am using the is 'x in S' 
> function.
>  
> I was wondering if there is anything faster?
I agree with Kent.

 >>> l = range(13000)
 >>> s=set(l)
 >>> d=dict(enumerate(l))
 >>> import time
 >>> def f(lookupVal, times, values):
...     st=time.time()
...     for i in range(times):
...         z = lookupVal in values
...     return time.time()-st   
 >>> f(6499,1000,l)
0.31299996376037598
 >>> f(6499,1000000,s)
0.31200003623962402

So set is 1000 times faster than list!

 >>> f(6499,1000000,d)
0.31300020217895508

And dict is (as expected) about the same as set.

So 100,000,000 lookups should take about 30 seconds. Not bad, eh?

Let's explore another angle. What range are the integers in (min and max)?

Bob

From mlangford.cs03 at gtalumni.org  Tue Jan 15 23:50:10 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Tue, 15 Jan 2008 17:50:10 -0500
Subject: [Tutor] Reading Input Data
In-Reply-To: <82b4f5810801151250m11670feam437425936d88db76@mail.gmail.com>
References: <920791.67864.qm@web57905.mail.re3.yahoo.com>
	<82b4f5810801151247u701903ap7db99b2aa8a014b4@mail.gmail.com>
	<82b4f5810801151250m11670feam437425936d88db76@mail.gmail.com>
Message-ID: <82b4f5810801151450n28c65033w13db43bff4ae7394@mail.gmail.com>

I'd like to be clear, this isn't a clean thing for the middle of a big
program. I was thinking the entire time I was testing it "I wonder why
anyone would need to do this...."

But if you have a python program you'd probably call a script, used
for one simple task, it can be appropriate (with Kent's catch on the
globals/local thing). I assumed you were using your approach for
something like that. (would you tell us what you're doing this for
btw? The suspense ... :o))

If you're doing something like multivariable analysis or something
else that you would do in software like maple, this approach can
greatly simplify the notation over the list/dict approach.

If you're not using python as a huge substitute for a math solver,
then avoid what I said like the plague and use a dict.

          --Michael

On 1/15/08, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
> Accidentally cut off a 0 there...
> Think about using ConfigParser instead of your csv. Doug Hellman wrote
> a good article on that:
> http://blog.doughellmann.com/2007/04/pymotw-configparser.html
>
> But if you really want to load your data this way, this will work:
>
> for subscript,line in enumerate(file("file.csv")):
>      s = line.split(",")[1]
>      try:
>              f = float(s)
>              locals()["x%i" % subscript]=f
>      except:
>              locals()["x%i" % subscript]=s
>
> print x1
> print x0
>
> On Jan 15, 2008 3:47 PM, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
> > for subscript,line in enumerate(file("file.csv")):
> >      s = line.split(",")[1]
> >      try:
> >              f = float(s)
> >              locals()["x%i" % subscript]=f
> >      except:
> >              locals()["x%i" % subscript]=s
> >
> > print x1
> > print x
> >
> > On Jan 15, 2008 3:26 PM, lechtlr <lechtlr at yahoo.com> wrote:
> >
> > > I want to read an input file (file.csv) that has two columns. I want to read
> > > 2nd column and assign variables that are strings and floats. Currently, I
> > > use the following split() function to read from the input file and create a
> > > list, and then assign each element to a variable.
> > >
> > > I am wondering there is any other easier (and elegant) way of doing this ?
> > >
> > > data = []
> > > for line in open("file.csv"):
> > >      columns = line.split(',')
> > >      data.append([columns[1]])
> > >
> > > This script returns, say:
> > > data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
> > >
> > > Then, I assign to a set of variables, say:
> > >
> > > x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> > > data[-1][0]
> > >
> > >
> > > Thanks,
> > > Lex
> > >
> > >
> > >
> > >
> > >
> > >
> > >
> > >
> > >  ________________________________
> > > Never miss a thing. Make Yahoo your homepage.
> >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From keridee at jayco.net  Wed Jan 16 00:04:27 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 15 Jan 2008 18:04:27 -0500
Subject: [Tutor] Input
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com><20080114182024.GB47507@cutter.rexx.com>
	<478D3415.4080907@bigfoot.com>
Message-ID: <007201c857ca$fe0415b0$68fce004@jslaptop>

Try regular expressions in the re module. This should make this code below 
much much simpler. Downside is you have to learn a slightly different 
syntax. Upside is - regular expressions are very powerful.



> Last week someone had an issue with raw_input() and how to get input for
> a number. So I remembered my CP/M times and got to think of a little
> function I had there. The function is lost and my time is scarce but I
> made a little effort and here you have the results. It has loads of room
> for improvement and probably a few bugs but it's a starting point, and
> it should guarantee that you get the input you need.
> You just define your mask and the functions checks the input
> accordingly, it returns a string.
> You might improve it by displaying the mask, e.g. for mask = '9999.99'
> you might see in the screen ____.__ or for mask = '999-AAA::9999' you'd
> see ___-___::___ so the user will know the format of what's expected of
> him, also a beep on incorrect entry might prove nice.
>
> HTH
>
> -----------------------------------------------------------------------
> import msvcrt
>
> _validChars = {
>                'X' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>                , '9' : '1234567890'
>                , '-' : '-1234567890'
>                , 'A' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>                , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
> _validKeys = _validChars.keys()
>
> def maskInput(mask, separators = True) :
>    lmask = list(mask)
>    lmask.reverse()
>    usedMask = []
>    retInput = ''
>    c = ''
>    maskChar = lmask.pop()
>    try :
>        while maskChar not in _validKeys :
>            if separators :
>                retInput += maskChar
>            msvcrt.putch(maskChar)
>            maskChar = lmask.pop()
>    except IndexError : pass
>
>    c = msvcrt.getch()
>    while c != chr(13) :
>        if maskChar and maskChar not in _validKeys and c in
> _validChars[lmask[-1]] :
>            if separators :
>                retInput += maskChar
>            msvcrt.putch(maskChar)
>            usedMask.append(maskChar)
>            maskChar = lmask.pop()
>        if usedMask and c == '\b' :
>            try :
>                if maskChar :
>                    lmask.append(maskChar)
>                maskChar = usedMask.pop()
>                retInput = retInput[:-1]
>                msvcrt.putch(c)
>                msvcrt.putch(' ')
>                msvcrt.putch(c)
>                while usedMask[-1] not in _validKeys :
>                    if maskChar :
>                        lmask.append(maskChar)
>                    maskChar = usedMask.pop()
>                    if separators :
>                        retInput = retInput[:-1]
>                    msvcrt.putch(c)
>                    msvcrt.putch(' ')
>                    msvcrt.putch(c)
>            except IndexError : pass
>        elif maskChar and c in _validChars[maskChar] :
>            retInput += c
>            msvcrt.putch(c)
>            try :
>                usedMask.append(maskChar)
>                maskChar = lmask.pop()
>              #  while maskChar not in _validKeys :
>            except IndexError :
>                maskChar = ''
>        c = msvcrt.getch()
>    return retInput
>
> if __name__ == '__main__' :
>    invar = maskInput('-9999.99')
>    print
>    print invar
>
> ------------------------------------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From ricaraoz at gmail.com  Wed Jan 16 02:24:51 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Tue, 15 Jan 2008 22:24:51 -0300
Subject: [Tutor] Input
In-Reply-To: <007201c857ca$fe0415b0$68fce004@jslaptop>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com><20080114182024.GB47507@cutter.rexx.com>	<478D3415.4080907@bigfoot.com>
	<007201c857ca$fe0415b0$68fce004@jslaptop>
Message-ID: <478D5CE3.9000109@bigfoot.com>

Tiger12506 wrote:
> Try regular expressions in the re module. This should make this code below 
> much much simpler. Downside is you have to learn a slightly different 
> syntax. Upside is - regular expressions are very powerful.
> 

Of course I know and use reg. exps., the point of the function is not to
validate input but to force the proper input.

From bill.wws at gmail.com  Wed Jan 16 03:01:49 2008
From: bill.wws at gmail.com (bill.wu)
Date: Wed, 16 Jan 2008 10:01:49 +0800
Subject: [Tutor] Rs: help, thanks very much.
Message-ID: <DreamMail__100149_79688485706@smtp.gmail.com>


i am new guy.
i ask a easy question.

why the first one have"x",the second one doesn't have "x". what is different? when write "x",when don't write "x".

in my point,the second one don't def variable.

(1)

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x (2)

def func():
    global x

    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x 

____________________________________________________________________
DreamMail - ??????????????????? www.dreammail.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/e4e7f082/attachment.htm 

From brunson at brunson.com  Wed Jan 16 03:36:16 2008
From: brunson at brunson.com (Eric Brunson)
Date: Tue, 15 Jan 2008 19:36:16 -0700
Subject: [Tutor] Rs: help, thanks very much.
In-Reply-To: <DreamMail__100149_79688485706@smtp.gmail.com>
References: <DreamMail__100149_79688485706@smtp.gmail.com>
Message-ID: <478D6DA0.4010800@brunson.com>


Did you read the entire discussion at
http://www.ibiblio.org/g2swap/byteofpython/read/local-variables.html?

What did you understand and not understand?

Sincerely,
e.

bill.wu wrote:
> i am new guy.
> i ask a easy question.
> why the first one have"x",the second one doesn't have "x". what is
> different? when write "x",when don't write "x".
> in my point,the second one don't def variable.
> (1)
> def |func||*(x)*:|
> | print ||'x is'||, x|
> | x = ||2|
> | print ||'Changed local x to'||, x|
>
> |x = ||50|
> |func*(x)*|
> |print ||'x is still'||, x|
> 	
> (2)
> def |func||*()*:|
> | global ||x|
>
> | print ||'x is'||, x|
> | x = ||2|
> | print ||'Changed local x to'||, x|
>
> |x = ||50|
> |func*()*|
> |print ||'Value of x is'||, x|
>
> ____________________________________________________________________
> /*DreamMail*/ - ???????????????????
> www.dreammail.org <http://www.dreammail.org>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From kent37 at tds.net  Wed Jan 16 03:47:34 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 15 Jan 2008 21:47:34 -0500
Subject: [Tutor] Input
In-Reply-To: <478D3415.4080907@bigfoot.com>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com>	<20080114182024.GB47507@cutter.rexx.com>
	<478D3415.4080907@bigfoot.com>
Message-ID: <478D7046.1060107@tds.net>

Ricardo Ar?oz wrote:

> _validChars = {
>                 'X' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>                 , '9' : '1234567890'
>                 , '-' : '-1234567890'
>                 , 'A' :
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>                 , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
> _validKeys = _validChars.keys()

<snip>
>         while maskChar not in _validKeys :

There is no need to make _validKeys, you can write
   while maskChar not in _validChars
which is actually more efficient, in general, because it is a hash table 
lookup instead of searching a list.

Kent

From keridee at jayco.net  Wed Jan 16 04:01:42 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 15 Jan 2008 22:01:42 -0500
Subject: [Tutor] Input
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com><20080114182024.GB47507@cutter.rexx.com>	<478D3415.4080907@bigfoot.com>
	<007201c857ca$fe0415b0$68fce004@jslaptop>
	<478D5CE3.9000109@bigfoot.com>
Message-ID: <001f01c857ec$46a70b30$61fce004@jslaptop>

> Of course I know and use reg. exps., the point of the function is not to
> validate input but to force the proper input.

So? Are you going to try to tell me that you can force particular input 
without actually determining if its valid or not first? ;-)

Just a thought. 


From dyoo at cs.wpi.edu  Wed Jan 16 03:56:44 2008
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Tue, 15 Jan 2008 21:56:44 -0500 (EST)
Subject: [Tutor] A faster x in S
Message-ID: <Pine.LNX.4.63.0801152146040.29760@cs.wpi.edu>

Kent and Bob,

Are you thinking of the first problem in Bentley's Programming Pearls? 
The original poster's questions sounds like it could be in that domain.

     http://netlib.bell-labs.com/cm/cs/pearls/cto.html

So I agree: the next questions we probably should ask the original poster:

    * Why are you trying to search for a number in those sorted integers?


    * Is there anything characteristic about those sorted integers that
      might be peculiar or useful?  Do the numbers have "streaks"?  Are the
      integers large or small?

From bill.wws at gmail.com  Wed Jan 16 02:31:07 2008
From: bill.wws at gmail.com (bill.wu)
Date: Wed, 16 Jan 2008 09:31:07 +0800
Subject: [Tutor] help, thanks very much.
Message-ID: <DreamMail__093107_25082062226@smtp.gmail.com>


i am new guy.
i ask a easy question.
 
why the first one have"x",the second one doesn't have "x". what is different? when write "x",when don't write "x".

in my point,the second one don't def variable.

(1)

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x (2)

def func():
    global x

    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/220cd6f2/attachment.htm 

From hokkakada at khmeros.info  Wed Jan 16 05:58:17 2008
From: hokkakada at khmeros.info (Kakada)
Date: Wed, 16 Jan 2008 11:58:17 +0700
Subject: [Tutor] get_python_lib()
Message-ID: <200801161158.17972.hokkakada@khmeros.info>

Hi list,

I was just wondering why the below function return different location on 
different machine?

import distutils.sysconfig
distutils.sysconfig.get_python_lib()

On my computer:
'/usr/lib/python2.5/site-packages'
On my friend's computer:
'/usr/local/lib/python2.5/site-packages'

What is the difference between these two?
Note: I have both location on my filestem.

Thanks for your input.

dada



From brendan.rankin at gmail.com  Wed Jan 16 05:58:27 2008
From: brendan.rankin at gmail.com (Brendan Rankin)
Date: Wed, 16 Jan 2008 04:58:27 +0000 (UTC)
Subject: [Tutor] help, thanks very much.
References: <DreamMail@smtp.gmail.com>
Message-ID: <loom.20080116T045603-326@post.gmane.org>

bill.wu <bill.wws <at> gmail.com> writes:

> 
> 
>  
> i am new guy.
> i ask a easy question.
>  
> why the first one have"x",the second one doesn't have "x". what 
> is different? when write "x",when don't write "x".
>  
> in my point,the second one don't def variable.
>  
> 

Variable scope.  By declaring the x as "global", any changes to x in func() will
affect x outside the function, as well.



From shriphanip at gmail.com  Wed Jan 16 07:32:58 2008
From: shriphanip at gmail.com (Shriphani Palakodety)
Date: Wed, 16 Jan 2008 12:02:58 +0530
Subject: [Tutor] parsing html.
Message-ID: <80f9e6490801152232l567bce71j91bdd676f95c966f@mail.gmail.com>

Hello,
I have a html document here which goes like this:

<A name=4></a><b>Table of Contents</b>
.........
<A name=5></a><b>Preface</b>

Can someone tell me how I can get the string between the <b> tag for
an a tag for a given value of the name attribute.

Thanks,
Shriphani Palakodety

From vishnu at montalvosystems.com  Wed Jan 16 07:16:34 2008
From: vishnu at montalvosystems.com (Vishnu Mohan)
Date: Wed, 16 Jan 2008 11:46:34 +0530
Subject: [Tutor] get_python_lib()
In-Reply-To: <200801161158.17972.hokkakada@khmeros.info>
References: <200801161158.17972.hokkakada@khmeros.info>
Message-ID: <478DA142.5020403@montalvosystems.com>

Kakada wrote:
> Hi list,
>
> I was just wondering why the below function return different location on 
> different machine?
>
> import distutils.sysconfig
> distutils.sysconfig.get_python_lib()
> On my computer:
> '/usr/lib/python2.5/site-packages'
> On my friend's computer:
> '/usr/local/lib/python2.5/site-packages'
>
> What is the difference between these two? Note: I have both location on my filestem.
>   

Most of the packages will install itself, by default, into 
/usr/local/lib/python$VER/site-packages/(third-party).
But most distibutions will put their software into 
/usr/lib/python$VER/site-packages/. May be your friend might
have changed $PYTHONHOME like env's so that it is pointing to /usr/local 
or while installing the python he might have
set --prefix to the /usr/local/....

-VishnuMohan, Montalvo Systems.

From work at infomaniak.ch  Wed Jan 16 08:22:47 2008
From: work at infomaniak.ch (cedric briner)
Date: Wed, 16 Jan 2008 08:22:47 +0100
Subject: [Tutor] tree/node class/module
In-Reply-To: <478D2DC3.7020300@alum.rpi.edu>
References: <478CDCCA.7060606@infomaniak.ch> <478D2DC3.7020300@alum.rpi.edu>
Message-ID: <478DB0C7.10004@infomaniak.ch>

usefull page

> http://www.velocityreviews.com/forums/t355467-tree-and-graph-structures-in-python.html 

thanks again

Ced.
	
-- 

Cedric BRINER
Geneva - Switzerland

From alan.gauld at btinternet.com  Wed Jan 16 09:13:10 2008
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 16 Jan 2008 08:13:10 +0000 (GMT)
Subject: [Tutor] how to change the values of keyboard keys in TKINTER
Message-ID: <353164.29281.qm@web86711.mail.ird.yahoo.com>

> i dont want to change alt+f4 for every application on the computer permanently...
> i just want to change it a particular area
> do we have any options for this

In that case all you need to do is to bind the key to the same action as the 
Enter key. Enter usually is a default action so you will likely have to work 
out what that ,means in your context but it should not be too hard.

An alternative might be to write a handler that posts a message onto the Tk 
event queue that looks like it comes from the Enter key, this would then get 
picked up by the mainloop and processed as if Enter had been pressed. 
I think Tk does have a way to do this but I can't remember how and 
don't have time to research it just now.

HTH,

Alan G




-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/c0190236/attachment.htm 

From alan.gauld at btinternet.com  Wed Jan 16 09:18:30 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 08:18:30 -0000
Subject: [Tutor] Input
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com><20080114182024.GB47507@cutter.rexx.com>	<478D3415.4080907@bigfoot.com><007201c857ca$fe0415b0$68fce004@jslaptop><478D5CE3.9000109@bigfoot.com>
	<001f01c857ec$46a70b30$61fce004@jslaptop>
Message-ID: <fmkekn$crt$1@ger.gmane.org>

"Tiger12506" <keridee at jayco.net> wrote
>> Of course I know and use reg. exps., the point of the function is 
>> not to
>> validate input but to force the proper input.
>
> So? Are you going to try to tell me that you can force particular 
> input
> without actually determining if its valid or not first? ;-)

regex is great for testing strings but the function posted tests
each character as it is input. Using regex you would need to
test the complete string after it was entered before getting
a reliable result.

I think thats the difference.

Alan G.




From ricaraoz at gmail.com  Wed Jan 16 10:18:57 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 16 Jan 2008 06:18:57 -0300
Subject: [Tutor] Input
In-Reply-To: <001f01c857ec$46a70b30$61fce004@jslaptop>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com><20080114182024.GB47507@cutter.rexx.com>	<478D3415.4080907@bigfoot.com>	<007201c857ca$fe0415b0$68fce004@jslaptop>	<478D5CE3.9000109@bigfoot.com>
	<001f01c857ec$46a70b30$61fce004@jslaptop>
Message-ID: <478DCC01.5010500@bigfoot.com>

Tiger12506 wrote:
>> Of course I know and use reg. exps., the point of the function is not to
>> validate input but to force the proper input.
> 
> So? Are you going to try to tell me that you can force particular input 
> without actually determining if its valid or not first? ;-)
> 
> Just a thought. 
> 


Are you going to try to tell me that it is better to check if ONE
character is valid with a reg.exp. that with a simple 'in' statement?

The purpose of the code is not to check input but to force it a
character at a time according to an input mask, it's a common enough
concept. Just do a bunch of raw_inputs inscribed in while loops with
their validations, then do it with this function and check the
readability of your code (not to talk about the length). Anyway it was
presented as a help for those who want it and as an exercise program to
be improved and learn from.



From ricaraoz at gmail.com  Wed Jan 16 10:20:26 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 16 Jan 2008 06:20:26 -0300
Subject: [Tutor] Input
In-Reply-To: <478D7046.1060107@tds.net>
References: <698FE3B0F09C344DAA29AE014A926432E0DBE0@rozmasm.rozmas.com.tr>	<123975.197.qm@web56801.mail.re3.yahoo.com>	<20080114182024.GB47507@cutter.rexx.com>
	<478D3415.4080907@bigfoot.com> <478D7046.1060107@tds.net>
Message-ID: <478DCC5A.70109@bigfoot.com>

Kent Johnson wrote:
> Ricardo Ar?oz wrote:
> 
>> _validChars = {
>>                 'X' :
>> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>>                 , '9' : '1234567890'
>>                 , '-' : '-1234567890'
>>                 , 'A' :
>> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>                 , '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
>> _validKeys = _validChars.keys()
> 
> <snip>
>>         while maskChar not in _validKeys :
> 
> There is no need to make _validKeys, you can write
>   while maskChar not in _validChars
> which is actually more efficient, in general, because it is a hash table
> lookup instead of searching a list.
> 
> Kent
> 

Thanks Kent, I'll wait to see if there are more corrections and re-post
the corrected code.



From alan.gauld at btinternet.com  Wed Jan 16 09:34:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 08:34:32 -0000
Subject: [Tutor] help, thanks very much.
References: <DreamMail__100149_79688485706@smtp.gmail.com>
Message-ID: <fmkfip$fdv$1@ger.gmane.org>


"bill.wu" <bill.wws at gmail.com> wrote 

> i ask a easy question.
> 
> why the first one have"x",the second one 
> doesn't have "x". what is different? 

The first is using x as the name of a parameter
of the function and is only used inside the function.
The second one takes no parameter and relies on 
explicit knowlege that an variable called x 
exists in the global namespace.

The second form is considered bad practice 
unless you have a very good reason to use it
since it forces the function to know about 
things outside its control.

> when write "x",when don't write "x".

Using a parameter (usually called something 
more meaningful than x!) is normally the best 
way. Version 2 should be avoided if possible.

> in my point,the second one don't def variable.

Corect it uses the global variable defined 
at the module level. That is why the global 
statement is used.

> (1)
> 
> def func(x):
>    print 'x is', x
>    x = 2
>    print 'Changed local x to', x
> 
> x = 50
> func(x)
> print 'x is still', x (2)

This defines a global x with value 50.
It then calls func passing in the value 
50 to the parameter x which acts like a 
local variable, only seen inside the 
function.
The func internally assigns a value 
of 2 to that local x which does not 
affect the global x. It then prints 
the local value and exits
The next line of code then prints 
the global x to show that it has 
not changed.

If a different name had been used for the 
parameter it would be much clearer but 
I assume the author is trying to demonstrate 
how names are controlled.

def func(y):
   print 'y =',y
   y = 2
   print 'y =',y

x = 50
func(x)
print 'x =',x

The code here is identical in function 
to the first version but because we 
chose y as the parameter name it is 
obvious that they are different variables.

> def func():
>    global x
> 
>    print 'x is', x
>    x = 2
>    print 'Changed local x to', x

This function has no local variables and 
instead acts on the global x. It could 
be better written with a parameter like this:

def func(y)
    print 'y =',y
    y = 2
    print 'y=',y
    return y    # allows it to affect the global
 
> x = 50
> func()

And this line becomes

x = func(x)

> print 'Value of x is', x 

Now x will reflect the changes made by func()

You will find more about namespaces in the 
"Whats in a name?" topic of my tutorial.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Wed Jan 16 09:40:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 08:40:09 -0000
Subject: [Tutor] parsing html.
References: <80f9e6490801152232l567bce71j91bdd676f95c966f@mail.gmail.com>
Message-ID: <fmkfta$gbq$1@ger.gmane.org>


"Shriphani Palakodety" <shriphanip at gmail.com> wrote in

> I have a html document here which goes like this:
>
> <A name=4></a><b>Table of Contents</b>
> .........
> <A name=5></a><b>Preface</b>
>
> Can someone tell me how I can get the string between the <b> tag for
> an a tag for a given value of the name attribute.

Heres an example using the standard library HTML parser
(from an unfinished topic in tutorial...). You could also
use BeautifulSoup and I recommend that if your needs get
any more complex...

----------------------------------------------
In practice we usually want to extract more specific data from a page, 
maybe the content of a particular row in a table or similar. For that 
we need to use the handle_starttag() and handle_endtag() methods. As 
an example let's extract the text of the second H1 level header:
html = '''
<html><head><title>Test page</title></head>
<body>
<center>
<h1>Here is the first heading</h1>
</center>
<p>A short paragraph
<h1>A second heading</h1>
<p>A paragraph containing a
<a href="www.google.com">hyperlink to google</a>
</body></html>
'''

from HTMLParser import HTMLParser

class H1Parser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.h1_count = 0
        self.isHeading = False

    def handle_starttag(self,tag,attributes=None):
        if tag == 'h1':
            self.h1_count += 1
            self.isHeading = True

    def handle_endtag(self,tag):
        if tag == 'h1':
            self.isHeading = False

    def handle_data(self,data):
        if self.isHeading and self.h1_count == 2:
            print "Second Header contained: ", data

parser = H1Parser()
parser.feed(html)
parser.close()
------------------------------Hopefully you can see how to alter that 
pattern to suit your scenario.-- Alan GauldAuthor of the Learn to 
Program web sitehttp://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Wed Jan 16 10:06:16 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 09:06:16 -0000
Subject: [Tutor] Why Won't My Pizza Fall?
References: <184430.18650.qm@web45107.mail.sp1.yahoo.com>	<003f01c85578$297a8170$7efce004@jslaptop><fmbo81$k3m$1@ger.gmane.org><478ACAE6.7080501@bigfoot.com><fmf60g$4f2$1@ger.gmane.org>
	<007e01c85711$19072ba0$e058e104@jslaptop>
Message-ID: <fmkhe9$kot$1@ger.gmane.org>


"Tiger12506" <keridee at jayco.net> wrote>
>> [Background from Alan]
>> ... Thus the context object should respond to some message
>> from Pizza and in this case the Pizza should hold a reference
>> to its context manager(probably a screen or grid of some sort).
>
> [disclaimer]
> This email has particularly strong personal opinions about coding 
> practices.
> I do not wish to personally offend anyone, and if you feel that you 
> have
> been offended as such, or that you disagree, please do not bother 
> emailing
> this list to tell me, excepting that you provide an excellent case 
> promoting
> your views that someone may be able to apply to make their code more
> intuitive/sensible. This email was provided for just such a reason.
> [/disclaimer]

Noted :-)

>> The context manager is responsible for tracking the objects
>> being managed, but the objects remain responsible for
>> managing their own state.
>
> [rant]
> This phrase right here is a dead giveaway to me that Pizza should 
> have
> little control over how it moves. A Pizza must be completely aware 
> of its
> current position (being part of its state) and at the very *most* a 
> set of
> rules governing general falling behaviour. I like the idea of a 
> context
> manager that is perhaps a container for Pizzas that oversees their 
> behavior,
> but I dislike the idea that a Pizza knows specifics about its rules 
> for
> positioning such as collisions or etc. that it has to communicate to 
> the
> context manager and/or other Pizzas.

I'm confused about what you dislike about this. You agree that
the Pizza shouldn't know about other Pizzas and is thus unable
to do its own collision monitoring. But if the Pizza is, as I 
surmised,
a Pizza that falls under its own control as implied by the description
"a Falling Pizza", then without it notifying the context manager 
(screen,
board, collection or whatever) how will the thing that does know
about the context be able to determine whether a collision has
occured - assuming that it needs to.

> Maybe I am becoming too used to lower
> level languages, not fully siding with abstraction.

That's possible :-). OOP was introduced to add abstraction
to lower level concepts and sometimes that abstraction hits
performance and requires extra code at the micro level,
but usually does so by simplifying design at the macro
level. This is one reason that true OOP(as opposed to using
objects) is rarely used on small programs and classes in those
problems tend to be used more as data containers somewhat
like an old fashioned C struct or Pascal record.

> I just see that we have suddenly introduced to new levels
> of redirection to achieve the same result,

Not entirely, by using indirection we have decoupled the class
from the solution thus increased reusability. If you will never
need to reuse a FallingPizza then of course it may be just
as effective to use direct intervention but in doing so you
break one of the fundamental principles of OOP. (And my
comments were explicitly concerned with good OOP style)

> instead of the list changing the elements. Definite benefits for 
> messaging
> models, but this /feels/ akin to filling out tax forms so that the
> government can tell you how you filled them out incorrectly.

The messaging overhead in Python (as in most OOP languages)
is not onerous and if dealing with lots of different Pizza objects
might even save code due to the potential to remove if/elif
constructs by relying on polymorphism. It would be different
if we were talking about setting the objects up in different
processes and communicating via an ORB but in practice
its only a couple of function calls. (Of course if we did later
need to split the objects over proceesses the messaging
solution is much easier to adapt to using an ORB...)

> A similar somewhat questionably connected problem involves my 
> dealings with
> the Render method of the IPicture interface. Sure, you can directly 
> apply
> the picture to the device context or if you like we have a Render 
> method
> that will automatically change the coordinates so that you have to 
> convert
> them back to display it. Abstraction isn't everything.

No, I agree, abstaction isn't everything and occasionally for
performance reasons you need to break down an abstraction layer.
But in my experience I've only had to do that a couple of times.
And Abstraction does give huge benefits. For example in the Picture
example if you follow the protocol approach its trivial to swap device
contexts from screen to printer to terminal to braille panel etc etc.
But rendering by hand will usuially involve completely rewriting the
renderer for each new device. If you know you will only ever have
one device then direct rendering is a valid option.

One of the interesting things about engineering (any branch, not
just software) is that "rules" are there for guidance and engineering
skill and experience tells us when it will be safe to break them.
The smaller and more specific the task at hand the more likely
that rules can be broken. But broken rules increase risk that you
will incur extra cost later if assumptions change.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From fiyawerx at gmail.com  Wed Jan 16 12:28:36 2008
From: fiyawerx at gmail.com (Fiyawerx)
Date: Wed, 16 Jan 2008 06:28:36 -0500
Subject: [Tutor] Programming Ideas, need some focus
Message-ID: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>

I've been over google for hours now, and I'm sort of at a lull in my
learning, as I don't really have a current "goal". I know I could set some
easy goal like to learn a specific function or feature, but I still have a
hard time with that approach also. I was wondering if anyone knows of any
sites where people might request "projects" almost like rentacoder, but for
free stuff and/or just for fun. Almost an 'It would be nice if I had a
program that did this.. " type of thing to give me some direction. Or does
anyone else have any ideas for some types of programs that might actually
prove useful to people for beginners to work on?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/c32ec1fd/attachment.htm 

From kent37 at tds.net  Wed Jan 16 12:46:35 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jan 2008 06:46:35 -0500
Subject: [Tutor] parsing html.
In-Reply-To: <80f9e6490801152232l567bce71j91bdd676f95c966f@mail.gmail.com>
References: <80f9e6490801152232l567bce71j91bdd676f95c966f@mail.gmail.com>
Message-ID: <478DEE9B.7090801@tds.net>

Shriphani Palakodety wrote:
> Hello,
> I have a html document here which goes like this:
> 
> <A name=4></a><b>Table of Contents</b>
> .........
> <A name=5></a><b>Preface</b>
> 
> Can someone tell me how I can get the string between the <b> tag for
> an a tag for a given value of the name attribute.

In [30]: from BeautifulSoup import BeautifulSoup
In [31]: text = '''<A name=4></a><b>Table of Contents</b>
    ....: .........
    ....: <A name=5></a><b>Preface</b>'''
In [32]: soup = BeautifulSoup(text)
In [40]: soup.find('a', dict(name='5'))
Out[40]: <a name="5"></a>
In [41]: soup.find('a', dict(name='5')).next
Out[41]: <b>Preface</b>
In [42]: soup.find('a', dict(name='5')).next.string
Out[42]: u'Preface'

Note BeautifulSoup lower-cases the tag name.
http://www.crummy.com/software/BeautifulSoup/

Kent

From kent37 at tds.net  Wed Jan 16 13:52:02 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jan 2008 07:52:02 -0500
Subject: [Tutor] help, thanks very much.
In-Reply-To: <DreamMail__093107_25082062226@smtp.gmail.com>
References: <DreamMail__093107_25082062226@smtp.gmail.com>
Message-ID: <478DFDF2.1040500@tds.net>

bill.wu wrote:
>  
> i am new guy.
> i ask a easy question.

There is no need to ask twice.

Please post messages in plain-text, not HTML.

Kent

From mlangford.cs03 at gtalumni.org  Wed Jan 16 14:29:40 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 16 Jan 2008 08:29:40 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>

There are programming contests you can enter. I don't know of any more
still running past these two (but would love to hear of more):

Sphere Online Judge:
http://www.spoj.pl/problems/classical/

Topcoder's Development Contests:
http://www.topcoder.com/tc?module=ViewActiveContests&ph=113

       --Michael


On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
> I've been over google for hours now, and I'm sort of at a lull in my
> learning, as I don't really have a current "goal". I know I could set some
> easy goal like to learn a specific function or feature, but I still have a
> hard time with that approach also. I was wondering if anyone knows of any
> sites where people might request "projects" almost like rentacoder, but for
> free stuff and/or just for fun. Almost an 'It would be nice if I had a
> program that did this.. " type of thing to give me some direction. Or does
> anyone else have any ideas for some types of programs that might actually
> prove useful to people for beginners to work on?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From ptmcg at austin.rr.com  Wed Jan 16 14:39:31 2008
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Wed, 16 Jan 2008 07:39:31 -0600
Subject: [Tutor] parsing html.
In-Reply-To: <mailman.2274.1200324767.894.tutor@python.org>
References: <mailman.2274.1200324767.894.tutor@python.org>
Message-ID: <001d01c85845$3922d170$1200a8c0@AWA2>

Here is a pyparsing approach to your question.  I've added some comments to
walk you through the various steps.  By using pyparsing's makeHTMLTags
helper method, it is easy to write short programs to skim selected data tags
from out of an HTML page.

-- Paul


from pyparsing import makeHTMLTags, SkipTo

html = """
<A name=4></a><b>Table of Contents</b>
.........
<A name=5></a><b>Preface</b>
"""

# define the pattern to search for, using pyparsing makeHTMLTags helper
# makeHTMLTags constructs a very tolerant mini-pattern, to match HTML
# tags with the given tag name:
# - caseless matching on the tag name
# - embedded whitespace is handled
# - detection of empty tags (opening tags that end in "/")
# - detection of tag attributes
# - returning parsed data using results names for attribute values
# makeHTMLTags actually returns two patterns, one for the opening tag
# and one for the closing tag
aStart,aEnd = makeHTMLTags("A")
bStart,bEnd = makeHTMLTags("B")
pattern = aStart + aEnd + bStart + SkipTo(bEnd)("text") + bEnd

# search the input string - dump matched structure for each match
for pp in pattern.searchString(html):
    print pp.dump()
    print pp.startA.name, pp.text
    
# parse input and build a dict using the results
nameDict = dict( (pp.startA.name,pp.text) for pp in
pattern.searchString(html) )
print nameDict


The last line of the output is the dict that is created:

{'5': 'Preface', '4': 'Table of Contents'}





From eric at abrahamsen.com  Wed Jan 16 15:10:05 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Wed, 16 Jan 2008 22:10:05 +0800
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
Message-ID: <E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>

Hey, on this topic, I spent some time this afternoon googling the One  
Laptop Per Child (OLPC) project (the GUI is done with Python and  
PyGTK), to see if there were any collaborative open-source projects I  
could contribute to. Seems like a perfect opportunity to get a little  
more Python experience and actually do something useful. I found lots  
of noble exhortations to help, but very little in the way of  
specifics. Does anyone know of any ongoing projects that could use  
volunteers? Of the middling-capable range?

Eric

On Jan 16, 2008, at 9:29 PM, Michael Langford wrote:

> There are programming contests you can enter. I don't know of any more
> still running past these two (but would love to hear of more):
>
> Sphere Online Judge:
> http://www.spoj.pl/problems/classical/
>
> Topcoder's Development Contests:
> http://www.topcoder.com/tc?module=ViewActiveContests&ph=113
>
>       --Michael
>
>
> On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
>> I've been over google for hours now, and I'm sort of at a lull in my
>> learning, as I don't really have a current "goal". I know I could  
>> set some
>> easy goal like to learn a specific function or feature, but I still  
>> have a
>> hard time with that approach also. I was wondering if anyone knows  
>> of any
>> sites where people might request "projects" almost like rentacoder,  
>> but for
>> free stuff and/or just for fun. Almost an 'It would be nice if I  
>> had a
>> program that did this.. " type of thing to give me some direction.  
>> Or does
>> anyone else have any ideas for some types of programs that might  
>> actually
>> prove useful to people for beginners to work on?
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
> -- 
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From mlangford.cs03 at gtalumni.org  Wed Jan 16 15:13:53 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 16 Jan 2008 09:13:53 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
	<E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
Message-ID: <82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>

No, but this is quite useful for getting it up and going on your PC:
http://wiki.laptop.org/go/OS_images_for_emulation

I was looking at Metropolis (the non-TM version of SimCity) as its gui
is all written in python....

          --Michael



On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
> Hey, on this topic, I spent some time this afternoon googling the One
> Laptop Per Child (OLPC) project (the GUI is done with Python and
> PyGTK), to see if there were any collaborative open-source projects I
> could contribute to. Seems like a perfect opportunity to get a little
> more Python experience and actually do something useful. I found lots
> of noble exhortations to help, but very little in the way of
> specifics. Does anyone know of any ongoing projects that could use
> volunteers? Of the middling-capable range?
>
> Eric
>
> On Jan 16, 2008, at 9:29 PM, Michael Langford wrote:
>
> > There are programming contests you can enter. I don't know of any more
> > still running past these two (but would love to hear of more):
> >
> > Sphere Online Judge:
> > http://www.spoj.pl/problems/classical/
> >
> > Topcoder's Development Contests:
> > http://www.topcoder.com/tc?module=ViewActiveContests&ph=113
> >
> >       --Michael
> >
> >
> > On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
> >> I've been over google for hours now, and I'm sort of at a lull in my
> >> learning, as I don't really have a current "goal". I know I could
> >> set some
> >> easy goal like to learn a specific function or feature, but I still
> >> have a
> >> hard time with that approach also. I was wondering if anyone knows
> >> of any
> >> sites where people might request "projects" almost like rentacoder,
> >> but for
> >> free stuff and/or just for fun. Almost an 'It would be nice if I
> >> had a
> >> program that did this.. " type of thing to give me some direction.
> >> Or does
> >> anyone else have any ideas for some types of programs that might
> >> actually
> >> prove useful to people for beginners to work on?
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >>
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From noufal at nibrahim.net.in  Wed Jan 16 13:53:43 2008
From: noufal at nibrahim.net.in (Noufal Ibrahim)
Date: Wed, 16 Jan 2008 18:23:43 +0530
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <478DFE57.8030200@nibrahim.net.in>

Fiyawerx wrote:
> I've been over google for hours now, and I'm sort of at a lull in my 
> learning, as I don't really have a current "goal". I know I could set 
> some easy goal like to learn a specific function or feature, but I still 
> have a hard time with that approach also. I was wondering if anyone 
> knows of any sites where people might request "projects" almost like 
> rentacoder, but for free stuff and/or just for fun. Almost an 'It would 
> be nice if I had a program that did this.. " type of thing to give me 
> some direction. Or does anyone else have any ideas for some types of 
> programs that might actually prove useful to people for beginners to 
> work on?

You can check out http://projecteuler.net/


-- 
~noufal
http://nibrahim.net.in/

From eric at abrahamsen.com  Wed Jan 16 15:26:35 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Wed, 16 Jan 2008 22:26:35 +0800
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
	<E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
	<82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>
Message-ID: <33FCDADA-9D47-4FD9-85B4-694B6A055969@abrahamsen.com>

I'm on a Mac, and it seems the current advice for Sugar emulation on  
the Mac is "come back next year, or the year after"... I did get PyGTK  
working, tho.


On Jan 16, 2008, at 10:13 PM, Michael Langford wrote:

> No, but this is quite useful for getting it up and going on your PC:
> http://wiki.laptop.org/go/OS_images_for_emulation
>
> I was looking at Metropolis (the non-TM version of SimCity) as its gui
> is all written in python....
>
>          --Michael
>
>
>
> On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
>> Hey, on this topic, I spent some time this afternoon googling the One
>> Laptop Per Child (OLPC) project (the GUI is done with Python and
>> PyGTK), to see if there were any collaborative open-source projects I
>> could contribute to. Seems like a perfect opportunity to get a little
>> more Python experience and actually do something useful. I found lots
>> of noble exhortations to help, but very little in the way of
>> specifics. Does anyone know of any ongoing projects that could use
>> volunteers? Of the middling-capable range?
>>
>> Eric
>>
>> On Jan 16, 2008, at 9:29 PM, Michael Langford wrote:
>>
>>> There are programming contests you can enter. I don't know of any  
>>> more
>>> still running past these two (but would love to hear of more):
>>>
>>> Sphere Online Judge:
>>> http://www.spoj.pl/problems/classical/
>>>
>>> Topcoder's Development Contests:
>>> http://www.topcoder.com/tc?module=ViewActiveContests&ph=113
>>>
>>>      --Michael
>>>
>>>
>>> On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
>>>> I've been over google for hours now, and I'm sort of at a lull in  
>>>> my
>>>> learning, as I don't really have a current "goal". I know I could
>>>> set some
>>>> easy goal like to learn a specific function or feature, but I still
>>>> have a
>>>> hard time with that approach also. I was wondering if anyone knows
>>>> of any
>>>> sites where people might request "projects" almost like rentacoder,
>>>> but for
>>>> free stuff and/or just for fun. Almost an 'It would be nice if I
>>>> had a
>>>> program that did this.. " type of thing to give me some direction.
>>>> Or does
>>>> anyone else have any ideas for some types of programs that might
>>>> actually
>>>> prove useful to people for beginners to work on?
>>>>
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>>
>>>
>>>
>>> --
>>> Michael Langford
>>> Phone: 404-386-0495
>>> Consulting: http://www.RowdyLabs.com
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> -- 
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>


From kent37 at tds.net  Wed Jan 16 15:49:21 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jan 2008 09:49:21 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <478E1971.70407@tds.net>

Fiyawerx wrote:
> I've been over google for hours now, and I'm sort of at a lull in my 
> learning, as I don't really have a current "goal". I know I could set 
> some easy goal like to learn a specific function or feature, but I still 
> have a hard time with that approach also. I was wondering if anyone 
> knows of any sites where people might request "projects" almost like 
> rentacoder, but for free stuff and/or just for fun. Almost an 'It would 
> be nice if I had a program that did this.. " type of thing to give me 
> some direction. Or does anyone else have any ideas for some types of 
> programs that might actually prove useful to people for beginners to 
> work on?

This is a common question here; you might want to look at some previous 
answers:
http://search.gmane.org/?query=project+ideas&group=gmane.comp.python.tutor

You might look for a Python project at Google Code or SourceForge that 
interests you and work on that:
http://code.google.com/hosting/search?q=label%3aPython
http://sourceforge.net/search/?type_of_search=soft&type_of_search=soft&words=python

If you are in high school you might like to participate in the Google 
Highly Open Participation Contest:
http://code.google.com/p/google-highly-open-participation-psf/

Even if you are not in high school, the list of GHOP Python tasks shows 
you some projects that are actively looking for help:
http://code.google.com/p/google-highly-open-participation-psf/issues/list

Kent

From mlangford.cs03 at gtalumni.org  Wed Jan 16 16:29:37 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 16 Jan 2008 10:29:37 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <33FCDADA-9D47-4FD9-85B4-694B6A055969@abrahamsen.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
	<E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
	<82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>
	<33FCDADA-9D47-4FD9-85B4-694B6A055969@abrahamsen.com>
Message-ID: <82b4f5810801160729r614efa78qe2c3011b3d7bbf99@mail.gmail.com>

First off OLPC still needs help with:
http://wiki.laptop.org/go/Journal
http://wiki.laptop.org/go/Bitfrost
http://wiki.laptop.org/go/School_Server

Secondly: To start playing with python on the OLPC, click pippy the python :o)

Lastly, you can emulate the build on most computers, Mac/Win/Linux:
Qemu is cross platform.  And OLPC is cool to mess around with for
python people. Its like what windows would be if all of the API's were
in python (and they were made simple enough a child could use it).

To run OLPC on mac, you need qemu for mac:
http://www.kju-app.org/kju/

For you windows people:
http://www.h7.dion.ne.jp/~qemu-win/
and
http://www.davereyn.co.uk/qem/source.zip for the nice GUI

For you linux people:
Well, you probably get if from your package manager

Download the latest (.img.bz2) file from:
http://xs-dev.laptop.org/cscott/olpc/streams/ship.2/latest/devel_ext3/

Unzip it using bzcat (which you mac guys get via Fink if its not
natively available or you can't unzip some other way). Unzip it to a
file called olpc.img

bzcat whatevertheycalledthe.bz2.img > olpc.img

Then you run it the same way the linux people do:
qemu -redir tcp:2211::22 -soundhw es1370 -net user -net
nic,model=rtl8139 -hda olpc.img

If you're in windows, use the command line inside the launcher or on
the command line.

(The command line stuff is about stuff inside the emulator, not about
your setup).

If I get someone to test my instructions, I'll happily update the OLPC
emulation page for Windows and Mac OS X.

Any takers? Eric on the mac side? Some other windows user on the
windows side? I guarantee OLPC will be running on your computer by the
end of this.

       --Michael

On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
> I'm on a Mac, and it seems the current advice for Sugar emulation on
> the Mac is "come back next year, or the year after"... I did get PyGTK
> working, tho.
>
>
> On Jan 16, 2008, at 10:13 PM, Michael Langford wrote:
>
> > No, but this is quite useful for getting it up and going on your PC:
> > http://wiki.laptop.org/go/OS_images_for_emulation
> >
> > I was looking at Metropolis (the non-TM version of SimCity) as its gui
> > is all written in python....
> >
> >          --Michael
> >
> >
> >
> > On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
> >> Hey, on this topic, I spent some time this afternoon googling the One
> >> Laptop Per Child (OLPC) project (the GUI is done with Python and
> >> PyGTK), to see if there were any collaborative open-source projects I
> >> could contribute to. Seems like a perfect opportunity to get a little
> >> more Python experience and actually do something useful. I found lots
> >> of noble exhortations to help, but very little in the way of
> >> specifics. Does anyone know of any ongoing projects that could use
> >> volunteers? Of the middling-capable range?
> >>
> >> Eric
> >>
> >> On Jan 16, 2008, at 9:29 PM, Michael Langford wrote:
> >>
> >>> There are programming contests you can enter. I don't know of any
> >>> more
> >>> still running past these two (but would love to hear of more):
> >>>
> >>> Sphere Online Judge:
> >>> http://www.spoj.pl/problems/classical/
> >>>
> >>> Topcoder's Development Contests:
> >>> http://www.topcoder.com/tc?module=ViewActiveContests&ph=113
> >>>
> >>>      --Michael
> >>>
> >>>
> >>> On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
> >>>> I've been over google for hours now, and I'm sort of at a lull in
> >>>> my
> >>>> learning, as I don't really have a current "goal". I know I could
> >>>> set some
> >>>> easy goal like to learn a specific function or feature, but I still
> >>>> have a
> >>>> hard time with that approach also. I was wondering if anyone knows
> >>>> of any
> >>>> sites where people might request "projects" almost like rentacoder,
> >>>> but for
> >>>> free stuff and/or just for fun. Almost an 'It would be nice if I
> >>>> had a
> >>>> program that did this.. " type of thing to give me some direction.
> >>>> Or does
> >>>> anyone else have any ideas for some types of programs that might
> >>>> actually
> >>>> prove useful to people for beginners to work on?
> >>>>
> >>>> _______________________________________________
> >>>> Tutor maillist  -  Tutor at python.org
> >>>> http://mail.python.org/mailman/listinfo/tutor
> >>>>
> >>>>
> >>>
> >>>
> >>> --
> >>> Michael Langford
> >>> Phone: 404-386-0495
> >>> Consulting: http://www.RowdyLabs.com
> >>> _______________________________________________
> >>> Tutor maillist  -  Tutor at python.org
> >>> http://mail.python.org/mailman/listinfo/tutor
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From lechtlr at yahoo.com  Wed Jan 16 16:36:37 2008
From: lechtlr at yahoo.com (lechtlr)
Date: Wed, 16 Jan 2008 07:36:37 -0800 (PST)
Subject: [Tutor] Reading Input Data
In-Reply-To: <82b4f5810801151450n28c65033w13db43bff4ae7394@mail.gmail.com>
Message-ID: <337385.4439.qm@web57915.mail.re3.yahoo.com>

  Thank you all for your suggestions.
    The purpose of this script to read values for initialization of a class that calls functions from another software program for chemically reacting flows (www.cantera.org). I have around 25 input variables with distinct variable names (don?t follow any patterns) with 5 strings (i.e., last five variables that contain chemical species names). Currently, I use a csv file to provide the initial values.  I hope this answers your questions.
  Lex

Michael Langford <mlangford.cs03 at gtalumni.org> wrote: I'd like to be clear, this isn't a clean thing for the middle of a big
program. I was thinking the entire time I was testing it "I wonder why
anyone would need to do this...."

But if you have a python program you'd probably call a script, used
for one simple task, it can be appropriate (with Kent's catch on the
globals/local thing). I assumed you were using your approach for
something like that. (would you tell us what you're doing this for
btw? The suspense ... :o))

If you're doing something like multivariable analysis or something
else that you would do in software like maple, this approach can
greatly simplify the notation over the list/dict approach.

If you're not using python as a huge substitute for a math solver,
then avoid what I said like the plague and use a dict.

          --Michael

On 1/15/08, Michael Langford  wrote:
> Accidentally cut off a 0 there...
> Think about using ConfigParser instead of your csv. Doug Hellman wrote
> a good article on that:
> http://blog.doughellmann.com/2007/04/pymotw-configparser.html
>
> But if you really want to load your data this way, this will work:
>
> for subscript,line in enumerate(file("file.csv")):
>      s = line.split(",")[1]
>      try:
>              f = float(s)
>              locals()["x%i" % subscript]=f
>      except:
>              locals()["x%i" % subscript]=s
>
> print x1
> print x0
>
> On Jan 15, 2008 3:47 PM, Michael Langford  wrote:
> > for subscript,line in enumerate(file("file.csv")):
> >      s = line.split(",")[1]
> >      try:
> >              f = float(s)
> >              locals()["x%i" % subscript]=f
> >      except:
> >              locals()["x%i" % subscript]=s
> >
> > print x1
> > print x
> >
> > On Jan 15, 2008 3:26 PM, lechtlr  wrote:
> >
> > > I want to read an input file (file.csv) that has two columns. I want to read
> > > 2nd column and assign variables that are strings and floats. Currently, I
> > > use the following split() function to read from the input file and create a
> > > list, and then assign each element to a variable.
> > >
> > > I am wondering there is any other easier (and elegant) way of doing this ?
> > >
> > > data = []
> > > for line in open("file.csv"):
> > >      columns = line.split(',')
> > >      data.append([columns[1]])
> > >
> > > This script returns, say:
> > > data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
> > >
> > > Then, I assign to a set of variables, say:
> > >
> > > x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> > > data[-1][0]
> > >
> > >
> > > Thanks,
> > > Lex
> > >
> > >
> > >
> > >
> > >
> > >
> > >
> > >
> > >  ________________________________
> > > Never miss a thing. Make Yahoo your homepage.
> >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
> >
> >
> > --
> > Michael Langford
> > Phone: 404-386-0495
> > Consulting: http://www.RowdyLabs.com
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com


       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/199fa384/attachment.htm 

From jnewton at fuelindustries.com  Wed Jan 16 17:19:08 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Wed, 16 Jan 2008 11:19:08 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD2401153BC3@ex1.Fuel.Ott>

Eric Abrahamsen wrote
> I spent some time this afternoon googling the One Laptop Per Child
> (OLPC) project (the GUI is done with Python and PyGTK), to see if 
> there were any collaborative open-source projects I could contribute 
> to. Seems like a perfect opportunity to get a little more Python 
> experience and actually do something useful. I found lots of noble 
> exhortations to help, but very little in the way of specifics. Does 
> anyone know of any ongoing projects that could use volunteers? Of the 
> middling-capable range?

Hi Eric,

I've got a project that I could use help on :-)

I'm a long-time game developer, but a newbie to Python.  I'm currently
working on a Snakes and Ladders game, as I see this as a good way for
young children to learn:

* Putting numbers in the right order
* Associating a value with the name of a number
* fFamiliarity with written numbers
* Taking turns
* ... and a whole range of concepts associated with numeracy.

You can find my latest build at:
  <http://olpc-dev.fuelindustries.com/snakes_080116.zip>.


Things that need to be done:

* Distribute counters evenly if there are more than one on
  the same square
* Set up a multi-user environment, so that players can join
  a game hosted on a different machine
* Provide a system for selecting the voice-over language
  and other preferences
* Tweak the game play
* Ensure that the activity is as miserly with CPU-time and
  disk space as possible
* ...

Nice to have:
* Allow users to select their own graphics (created in a
  different activity) for the background, dice and counters
* Add an arrow or a pointing finger to indicate which
  square to click on next
* Advanced mode using:
  - two dice
  - drag and drop to move the counter to its final square
* Choice of writing system for the numbers
* ...

I've just received a couple of XO machines from the Give One Get One
initiative, and am currently looking into getting the game to run on the
laptop.

I have a number of other game ideas that I want to bring to the XO:

* Matching images (more flexible than the built-in Memorize game)
* Drawing Letters
* Abacus Shapes
* Black boxes (a game to develop mental imagery)
* Picture Book Reader

I also have plans for an activity that helps children to understand
musical notation, without having to learn the theory or the practice
first.  But that is currently way out of my depth, as far as my Python
abilities are concerned. 

I'm based in Ottawa, Canada.

Do Snakes and Ladders (or any of the other ideas) inspire you?

James

From dineshbvadhia at hotmail.com  Wed Jan 16 18:01:24 2008
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Wed, 16 Jan 2008 09:01:24 -0800
Subject: [Tutor] A faster x in S
References: <BAY109-DAV7C6EE109661A17801446BA3470@phx.gbl>
	<478D2DCF.2080100@alum.rpi.edu>
Message-ID: <BAY109-DAV115EDF5FD8F4939B5CDD64A3400@phx.gbl>

I used the s.intersection(t) function in the set type as it was the most appropriate.  The performance was phenomenal.  Thank-you!

Dinesh


----- Original Message ----- 
From: bob gailer 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Tuesday, January 15, 2008 2:03 PM
Subject: Re: [Tutor] A faster x in S


Dinesh B Vadhia wrote:
> For some significant data pre-processing we have to perform the 
> following simple process:
>  
> Is the integer x in a list of 13K sorted integers.  That's it except 
> this has to be done >100m times with different x's (multiple times).  
> Yep, a real pain! 
>  
> I've put the 13K integers in a list S and am using the is 'x in S' 
> function.
>  
> I was wondering if there is anything faster?
I agree with Kent.

 >>> l = range(13000)
 >>> s=set(l)
 >>> d=dict(enumerate(l))
 >>> import time
 >>> def f(lookupVal, times, values):
..     st=time.time()
..     for i in range(times):
..         z = lookupVal in values
..     return time.time()-st   
 >>> f(6499,1000,l)
0.31299996376037598
 >>> f(6499,1000000,s)
0.31200003623962402

So set is 1000 times faster than list!

 >>> f(6499,1000000,d)
0.31300020217895508

And dict is (as expected) about the same as set.

So 100,000,000 lookups should take about 30 seconds. Not bad, eh?

Let's explore another angle. What range are the integers in (min and max)?

Bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/090d0053/attachment-0001.htm 

From bgailer at alum.rpi.edu  Wed Jan 16 18:46:52 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Wed, 16 Jan 2008 12:46:52 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <478E430C.4030907@alum.rpi.edu>

Yet one more offering: en.wikipedia.org/wiki/Python_Pipelines

This is my project - and a way you could help is:

I'd give you the specification of a "stage" and you'd develop a python 
function or class that would implement that stage. The first stages 
would be fairly simple, then things would get more involved.

I'd give you a testing framework in which to test a stage.

So the task would look like:

Specification of stage "foo": print the length of the input and if the 
length is less that 10 send the input to the output.

The simplest solution you could code is:

def run(input, output, spec=None):
    print len(input) # input is a character string of arbitrary length
    if len(input) < 10:
        output(input) # output is a function that sends its argument to 
"the output".

Then you'd test it thusly:

import pipetest
pipetest.test("Short")
pipetest.test("Longer than 10")

Running the above should display:

5
Short
14

Is that clear? Is that interesting? There are a lot of stages to be 
developed; many of them are much more complex, so this could provide for 
a step-by-step evolution of your skills.

Let me know one way or the other or ask clarifying questions.

Bob Gailer



From garry.bettle at gmail.com  Wed Jan 16 19:07:49 2008
From: garry.bettle at gmail.com (Garry Bettle)
Date: Wed, 16 Jan 2008 18:07:49 +0000
Subject: [Tutor] Pycron - Does anyone have experience with this?
Message-ID: <f8d7009c0801161007k51afc272y863aadfacae40a77@mail.gmail.com>

Howdy all,

Hope this finds everyone well - roll on the weekend.

I've been using pycron for months now with no trouble at all.

It's a great scheduling program.

I'm now trying to schedule a file copy from a network share.

However, Pycron chokes, as it requires the share to fully qualified.

Instead of:

s:\subdir1\subdir2\file.ext

it wants:

\\servername\share\subdir1\subdir2\file.ext

But no matter how I try to do the file copy - batch file, WSH and
Win32API calls - it still refuses to run.

It seems a shame to have to look for another scheduling solution.

Can anyone help?

Many thanks!

Cheers,

Garry

From vlad_lad at yahoo.com  Wed Jan 16 19:12:18 2008
From: vlad_lad at yahoo.com (Roger Maxwell)
Date: Wed, 16 Jan 2008 10:12:18 -0800 (PST)
Subject: [Tutor] Program Specification Request
Message-ID: <666332.91553.qm@web45908.mail.sp1.yahoo.com>

Hi all:
   1st post! Have been lurker 4 some time. Thanks to
all.
   I am new to Python and a former DOS Clipper
programmer.
   I would like to learn and teach my 2 girls a mini
database GUI program in Python and ????
   They are Girl Scouts (and advanced MS & HS
students)
   It is, almost, (19 January 2008)GS cookie time in
CA.
   Soooo.
   
   Question(s):
   Q01:  Is this a 'reasonable' first project?
   Q02:  We can use either MAC or WinXP but which? Or
both?
   Q03:  Is this the appropriate forum?

thanx.


      ____________________________________________________________________________________
Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 



From bba at inbox.com  Wed Jan 16 21:37:28 2008
From: bba at inbox.com (Ben Bartrum)
Date: Wed, 16 Jan 2008 12:37:28 -0800
Subject: [Tutor] Program Specification Request
In-Reply-To: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
Message-ID: <653B085FA8C.0000083Cbba@inbox.com>

>    Question(s):
>    Q01:  Is this a 'reasonable' first project?

Yes.  But I'd say do it in 2 phases.  First do a command-line version, then do the GUI.

>    Q02:  We can use either MAC or WinXP but which? Or both?

It realy doesn't matter

>    Q03:  Is this the appropriate forum?

Yes

____________________________________________________________
GET FREE SMILEYS FOR YOUR IM & EMAIL - Learn more at http://www.inbox.com/smileys
Works with AIM?, MSN? Messenger, Yahoo!? Messenger, ICQ?, Google Talk? and most webmails

From bhaaluu at gmail.com  Wed Jan 16 21:52:28 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 16 Jan 2008 15:52:28 -0500
Subject: [Tutor] Program Specification Request
In-Reply-To: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
References: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
Message-ID: <ea979d70801161252i3149cddcq69b67865a3dcae6e@mail.gmail.com>

Greetings,

Take a look at this page:

http://davidbau.com/python/learning.html

and also this one (by the same programmer):

http://davidbau.com/archives/2005/07/29/haaarg_world.html

Not only are these interesting reads, but also give a glimpse
into what it takes to teach kids computer programming using
the Python Programming language.

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html


On Jan 16, 2008 1:12 PM, Roger Maxwell <vlad_lad at yahoo.com> wrote:
> Hi all:
>    1st post! Have been lurker 4 some time. Thanks to
> all.
>    I am new to Python and a former DOS Clipper
> programmer.
>    I would like to learn and teach my 2 girls a mini
> database GUI program in Python and ????
>    They are Girl Scouts (and advanced MS & HS
> students)
>    It is, almost, (19 January 2008)GS cookie time in
> CA.
>    Soooo.
>
>    Question(s):
>    Q01:  Is this a 'reasonable' first project?
>    Q02:  We can use either MAC or WinXP but which? Or
> both?
>    Q03:  Is this the appropriate forum?
>
> thanx.
>
>
>       ____________________________________________________________________________________
> Be a better friend, newshound, and
> know-it-all with Yahoo! Mobile.  Try it now.  http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From amonroe at columbus.rr.com  Wed Jan 16 23:10:39 2008
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed, 16 Jan 2008 17:10:39 -0500
Subject: [Tutor] Program Specification Request
In-Reply-To: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
References: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
Message-ID: <106151905778.20080116171039@columbus.rr.com>


>    I would like to learn and teach my 2 girls a mini
> database GUI program in Python and ????
>    They are Girl Scouts (and advanced MS & HS
> students)

http://davidbau.com/archives/2005/07/29/haaarg_world.html

Alan


From alan.gauld at btinternet.com  Wed Jan 16 23:44:25 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 22:44:25 -0000
Subject: [Tutor] Program Specification Request
References: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
Message-ID: <fmm1ca$o1l$1@ger.gmane.org>


"Roger Maxwell" <vlad_lad at yahoo.com> wrote 

>   I would like to learn and teach my 2 girls a mini
> database GUI program in Python and ????

Since sqlite is included in the standard distribution 
of Pythn 2.5 you might as well use that. It is easy to administer 
and uses a simplified version of standard SQL.

>   It is, almost, (19 January 2008)GS cookie time in
> CA.

Coming from Scotland I have no idea what that means! :-)

>   Q01:  Is this a 'reasonable' first project?

Maybe but as someone else said a command line 
version first will be easier, GUIs are slightly arcane 
in Python due to the lack of a good visual GUI builder.

>   Q02:  We can use either MAC or WinXP but which? Or
> both?

Either or both Python is very portable.

>   Q03:  Is this the appropriate forum?

Yes

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From jfabiani at yolo.com  Thu Jan 17 00:05:41 2008
From: jfabiani at yolo.com (johnf)
Date: Wed, 16 Jan 2008 15:05:41 -0800
Subject: [Tutor] Program Specification Request
In-Reply-To: <fmm1ca$o1l$1@ger.gmane.org>
References: <666332.91553.qm@web45908.mail.sp1.yahoo.com>
	<fmm1ca$o1l$1@ger.gmane.org>
Message-ID: <200801161505.41671.jfabiani@yolo.com>

On Wednesday 16 January 2008 02:44:25 pm Alan Gauld wrote:
> > ? It is, almost, (19 January 2008)GS cookie time in
> > CA.
>
> Coming from Scotland I have no idea what that means!

What no Girl Scout cookies in Scotland???:-)

-- 
John Fabiani

From kent37 at tds.net  Wed Jan 16 20:12:32 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jan 2008 14:12:32 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <82b4f5810801160729r614efa78qe2c3011b3d7bbf99@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>	<E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>	<82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>	<33FCDADA-9D47-4FD9-85B4-694B6A055969@abrahamsen.com>
	<82b4f5810801160729r614efa78qe2c3011b3d7bbf99@mail.gmail.com>
Message-ID: <478E5720.5020302@tds.net>

Michael Langford wrote:

> To run OLPC on mac, you need qemu for mac:
> http://www.kju-app.org/kju/

This gets the main page for Q, a native Mac port of qemu. I downloaded 
the stable build.

> Download the latest (.img.bz2) file from:
> http://xs-dev.laptop.org/cscott/olpc/streams/ship.2/latest/devel_ext3/

olpc-redhat-stream-ship.2-build-656-20080102_1619-devel_ext3.img.bz2
or
olpc-redhat-stream-ship.2-devel_ext3.img.bz2
? I got the first

> Unzip it using bzcat (which you mac guys get via Fink if its not
> natively available or you can't unzip some other way). Unzip it to a
> file called olpc.img
> 
> bzcat whatevertheycalledthe.bz2.img > olpc.img

I used BOMArchiveHelper which seems to be included with Mac OS X 10.4 
and (as Archive Utility) 10.5.

> Then you run it the same way the linux people do:
> qemu -redir tcp:2211::22 -soundhw es1370 -net user -net
> nic,model=rtl8139 -hda olpc.img

This is a bit of a mystery as there is no obvious command line for Q.
 From the qemu docs I find
`-redir [tcp|udp]:host-port:[guest-host]:guest-port'
     When using the user mode network stack, redirect incoming TCP or 
UDP connections to the host port host-port to the guest guest-host on 
guest port guest-port.
-redir tcp:2211::22 seems to correspond most closely to enabling Remote 
Login in the Network preferences though that maps port 2200 to port 22.

-soundhw es1370 I guess means to enable ENSONIQ AudioPCI ES 1370 in the 
Hardware prefs.

-net user ?? can't find a setting for this

  -net nic,model=rtl8139
Set Network card to rtl8139 PCI network adapter in Hardware prefs

-hda olpc.img
Choose the downloaded disk image in Hard disk popup in Hardware pref.

Click the start button, it is booting...

OK, seems to more or less work. It's very slow on my Mac (2.33 GHz Intel 
core 2 duo) and pretty buggy, though I have no way of knowing if that is 
the emulator or the OLPC software. Lots of screen refresh problems. The 
mouse is too sensitive, don't see a way to adjust that offhand.

Ah, looking again at the prefs I see there is a box for "QEMU Arguments" 
in the Advanced panel. No time to try it now though. I guess I'm getting 
pretty far off-topic too :-)

Kent

> If I get someone to test my instructions, I'll happily update the OLPC
> emulation page for Windows and Mac OS X.

From alan.gauld at btinternet.com  Thu Jan 17 00:29:09 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Jan 2008 23:29:09 -0000
Subject: [Tutor] Program Specification Request
References: <666332.91553.qm@web45908.mail.sp1.yahoo.com><fmm1ca$o1l$1@ger.gmane.org>
	<200801161505.41671.jfabiani@yolo.com>
Message-ID: <fmm406$ol$1@ger.gmane.org>


"johnf" <jfabiani at yolo.com> wrote

> > Coming from Scotland I have no idea what that means!
>
> What no Girl Scout cookies in Scotland???:-)

Well we have girls and we have scouts and we have girls
who are in the scouts equivalent for girls - the brownies.
Brownies are a kind of cookie aren't they?

Is that the same thing? ;-)

Alan G



From eric at abrahamsen.com  Thu Jan 17 02:41:41 2008
From: eric at abrahamsen.com (Eric Abrahamsen)
Date: Thu, 17 Jan 2008 09:41:41 +0800
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <82b4f5810801160729r614efa78qe2c3011b3d7bbf99@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<82b4f5810801160529x6d6a1a87vb671e25c5302c085@mail.gmail.com>
	<E2573555-400C-4E91-9F6D-3687524D1AEC@abrahamsen.com>
	<82b4f5810801160613q75ae28d9ge8f74b3ed72fd0a7@mail.gmail.com>
	<33FCDADA-9D47-4FD9-85B4-694B6A055969@abrahamsen.com>
	<82b4f5810801160729r614efa78qe2c3011b3d7bbf99@mail.gmail.com>
Message-ID: <5E2C3202-F09D-4B4F-96BF-F1B618631B88@abrahamsen.com>

> Any takers? Eric on the mac side? Some other windows user on the
> windows side? I guarantee OLPC will be running on your computer by the
> end of this.

I'll give this a shot this Saturday ? I ought to be an ideal test  
candidate since I'm more or less an installation/configuration idjit.  
I'll let you know how it goes. Will it conflict with an existing pyGTK  
installation?

Both Snakes and Ladders and the pipelines thing sound potentially  
interesting, I'll get back to you guys in a couple days...

Thanks!
Eric


>
>
>       --Michael
>
> On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
>> I'm on a Mac, and it seems the current advice for Sugar emulation on
>> the Mac is "come back next year, or the year after"... I did get  
>> PyGTK
>> working, tho.
>>
>>
>> On Jan 16, 2008, at 10:13 PM, Michael Langford wrote:
>>
>>> No, but this is quite useful for getting it up and going on your PC:
>>> http://wiki.laptop.org/go/OS_images_for_emulation
>>>
>>> I was looking at Metropolis (the non-TM version of SimCity) as its  
>>> gui
>>> is all written in python....
>>>
>>>         --Michael
>>>
>>>
>>>
>>> On 1/16/08, Eric Abrahamsen <eric at abrahamsen.com> wrote:
>>>> Hey, on this topic, I spent some time this afternoon googling the  
>>>> One
>>>> Laptop Per Child (OLPC) project (the GUI is done with Python and
>>>> PyGTK), to see if there were any collaborative open-source  
>>>> projects I
>>>> could contribute to. Seems like a perfect opportunity to get a  
>>>> little
>>>> more Python experience and actually do something useful. I found  
>>>> lots
>>>> of noble exhortations to help, but very little in the way of
>>>> specifics. Does anyone know of any ongoing projects that could use
>>>> volunteers? Of the middling-capable range?
>>>>
>>>> Eric
>>>>
>>>> On Jan 16, 2008, at 9:29 PM, Michael Langford wrote:
>>>>
>>>>> There are programming contests you can enter. I don't know of any
>>>>> more
>>>>> still running past these two (but would love to hear of more):
>>>>>
>>>>> Sphere Online Judge:
>>>>> http://www.spoj.pl/problems/classical/
>>>>>
>>>>> Topcoder's Development Contests:
>>>>> http://www.topcoder.com/tc?module=ViewActiveContests&ph=113
>>>>>
>>>>>     --Michael
>>>>>
>>>>>
>>>>> On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
>>>>>> I've been over google for hours now, and I'm sort of at a lull in
>>>>>> my
>>>>>> learning, as I don't really have a current "goal". I know I could
>>>>>> set some
>>>>>> easy goal like to learn a specific function or feature, but I  
>>>>>> still
>>>>>> have a
>>>>>> hard time with that approach also. I was wondering if anyone  
>>>>>> knows
>>>>>> of any
>>>>>> sites where people might request "projects" almost like  
>>>>>> rentacoder,
>>>>>> but for
>>>>>> free stuff and/or just for fun. Almost an 'It would be nice if I
>>>>>> had a
>>>>>> program that did this.. " type of thing to give me some  
>>>>>> direction.
>>>>>> Or does
>>>>>> anyone else have any ideas for some types of programs that might
>>>>>> actually
>>>>>> prove useful to people for beginners to work on?
>>>>>>
>>>>>> _______________________________________________
>>>>>> Tutor maillist  -  Tutor at python.org
>>>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>>>
>>>>>>
>>>>>
>>>>>
>>>>> --
>>>>> Michael Langford
>>>>> Phone: 404-386-0495
>>>>> Consulting: http://www.RowdyLabs.com
>>>>> _______________________________________________
>>>>> Tutor maillist  -  Tutor at python.org
>>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>
>>>
>>> --
>>> Michael Langford
>>> Phone: 404-386-0495
>>> Consulting: http://www.RowdyLabs.com
>>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> -- 
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>


From varsha.purohit at gmail.com  Thu Jan 17 03:47:58 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Wed, 16 Jan 2008 18:47:58 -0800
Subject: [Tutor] [tutor] Comparing two images using PIL
Message-ID: <c2157c790801161847w5e557ab3n79d118fce49092de@mail.gmail.com>

Hello Everyone,
        I have an application where i am comparing two images(jpg) which are
almost identical but have little difference. I wanted to mark the difference
with a different colour to highlight the region which is different from 1st
image. Can you tell me if there is any image funciton in PIL which will help
me to calculate the differences between two different JPEG images.

-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080116/54ed294a/attachment.htm 

From kent37 at tds.net  Thu Jan 17 03:59:47 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 16 Jan 2008 21:59:47 -0500
Subject: [Tutor] [tutor] Comparing two images using PIL
In-Reply-To: <c2157c790801161847w5e557ab3n79d118fce49092de@mail.gmail.com>
References: <c2157c790801161847w5e557ab3n79d118fce49092de@mail.gmail.com>
Message-ID: <478EC4A3.6050108@tds.net>

Varsha Purohit wrote:
> Hello Everyone,
>         I have an application where i am comparing two images(jpg) which 
> are almost identical but have little difference. I wanted to mark the 
> difference with a different colour to highlight the region which is 
> different from 1st image. Can you tell me if there is any image funciton 
> in PIL which will help me to calculate the differences between two 
> different JPEG images.

The ImageChops and ImageMath modules look like they might be helpful.

Kent

From Andy.cheesman at bristol.ac.uk  Thu Jan 17 11:39:34 2008
From: Andy.cheesman at bristol.ac.uk (Andy Cheesman)
Date: Thu, 17 Jan 2008 10:39:34 +0000
Subject: [Tutor] Saving Objects
Message-ID: <478F3066.7010006@bristol.ac.uk>

Hi people

I've written a complex program in python/numpy/scipy which creates a 
dictionary of objects(which takes a while to create). I am hoping to 
save these objects to disk and then access them using a different 
session, thus bypassing the time to create the objects.

My initial tests using pickle and a simple class system (shown below) 
have failed. The method shown below fails with a AttributeError: 
'FakeModule' object has no attribute 'Spod', so when I create a
an empty class Spod in the new session, it generates an IndexError:(list 
index out of range)

Is there a better way to do this?

Andy

class Spod:
     def __init__(self, name):
         self.name=name

fish = Spod("andy")
file = open("test.pickle","w")
pickle.dump(fish, file)

# New session
file = open("test.pickle","r")
pickle.load(file)






From ptmcg at austin.rr.com  Thu Jan 17 14:44:22 2008
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Thu, 17 Jan 2008 07:44:22 -0600
Subject: [Tutor] Saving Objects
In-Reply-To: <mailman.59.1200567621.20660.tutor@python.org>
References: <mailman.59.1200567621.20660.tutor@python.org>
Message-ID: <005001c8590f$11573ad0$1200a8c0@AWA2>

>>>
My initial tests using pickle and a simple class system (shown below) have
failed. The method shown below fails with a AttributeError: 
'FakeModule' object has no attribute 'Spod', so when I create a an empty
class Spod in the new session, it generates an IndexError:(list index out of
range)

Is there a better way to do this?
>>>

I'm assuming that "# New session" marks the beginning of a separate Python
file.  The problem is that the Spod class definition is not included in the
pickle file, so you must import that as well, before loading back the
pickled fish object.  Do this;

1. Put Spod in its own module, let's call it spod.py.  (While you are at it,
have Spod derive from object, so that you get a new-style class.)
2. Create test1.py to pickle a Spod.  Have test1.py import spod, and then
have your code that creates spod.Spod("andy") and pickles it to test.pickle.
3. Create test2.py to unpickle a Spod.  Have test2.py *also* import spod,
and then have the rest of your code that follows "# New session".  Modify
the pickle.load statement to save the result to a variable, and then you can
verify that its name is "andy", type is "Spod", etc.

-- Paul



From Andy.cheesman at bristol.ac.uk  Thu Jan 17 15:15:59 2008
From: Andy.cheesman at bristol.ac.uk (Andy Cheesman)
Date: Thu, 17 Jan 2008 14:15:59 +0000
Subject: [Tutor] Saving Objects
In-Reply-To: <005001c8590f$11573ad0$1200a8c0@AWA2>
References: <mailman.59.1200567621.20660.tutor@python.org>
	<005001c8590f$11573ad0$1200a8c0@AWA2>
Message-ID: <478F631F.7030508@bristol.ac.uk>

That's great and it works too, thank you!

My only arising question is why should i
"derive from object, so that you get a new-style class."

I've looked online and found this 
(http://www.geocities.com/foetsch/python/new_style_classes.htm) but I 
not sure it tells why I would want to do this this way.

Thanks again for your help

Andy

Paul McGuire wrote:
> My initial tests using pickle and a simple class system (shown below) have
> failed. The method shown below fails with a AttributeError: 
> 'FakeModule' object has no attribute 'Spod', so when I create a an empty
> class Spod in the new session, it generates an IndexError:(list index out of
> range)
>
> Is there a better way to do this?
>   
>
> I'm assuming that "# New session" marks the beginning of a separate Python
> file.  The problem is that the Spod class definition is not included in the
> pickle file, so you must import that as well, before loading back the
> pickled fish object.  Do this;
>
> 1. Put Spod in its own module, let's call it spod.py.  (While you are at it,
> have Spod derive from object, so that you get a new-style class.)
> 2. Create test1.py to pickle a Spod.  Have test1.py import spod, and then
> have your code that creates spod.Spod("andy") and pickles it to test.pickle.
> 3. Create test2.py to unpickle a Spod.  Have test2.py *also* import spod,
> and then have the rest of your code that follows "# New session".  Modify
> the pickle.load statement to save the result to a variable, and then you can
> verify that its name is "andy", type is "Spod", etc.
>
> -- Paul
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

From marc.tompkins at gmail.com  Thu Jan 17 20:48:43 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 17 Jan 2008 11:48:43 -0800
Subject: [Tutor] Saving Objects
In-Reply-To: <478F631F.7030508@bristol.ac.uk>
References: <mailman.59.1200567621.20660.tutor@python.org>
	<005001c8590f$11573ad0$1200a8c0@AWA2> <478F631F.7030508@bristol.ac.uk>
Message-ID: <40af687b0801171148h53dfec29wf48333cecc2e6c49@mail.gmail.com>

On Jan 17, 2008 6:15 AM, Andy Cheesman <Andy.cheesman at bristol.ac.uk> wrote:

> My only arising question is why should i
> "derive from object, so that you get a new-style class."
>

This list discussed this topic a couple of weeks ago.  Recklessly
simplifying, it boils down to this: By using new-style classes, your objects
inherit a number of pre-defined methods and properties which you would
otherwise have to write yourself.  Ceteris paribus, a new-style class takes
up less memory than the equivalent old-style class (there was some wild
surmise about why that should be, but it's not important now.)  Finally, it
appears that Python 3000 will require new-style classes, so you might as
well get used to them now.

For your program, the only difference is that instead of defining a class
like this:

class Thingy():
    pass

you would write this:

class Thingy(object):
    pass

Not much downside, I'd say.


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080117/25b078d3/attachment.htm 

From bill.wws at gmail.com  Fri Jan 18 03:41:33 2008
From: bill.wws at gmail.com (bill.wu)
Date: Fri, 18 Jan 2008 10:41:33 +0800
Subject: [Tutor] the tutor list has been strangely silent for a few days.
	Anyone know
Message-ID: <DreamMail__104133_68706260525@smtp.gmail.com>



the tutor list has been strangely silent for a few days.  Anyone know 
what has happened? why? 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080118/bb007f81/attachment.htm 

From rabidpoobear at gmail.com  Fri Jan 18 03:45:44 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 17 Jan 2008 20:45:44 -0600
Subject: [Tutor] the tutor list has been strangely silent for a few
 days. Anyone know
In-Reply-To: <DreamMail__104133_68706260525@smtp.gmail.com>
References: <DreamMail__104133_68706260525@smtp.gmail.com>
Message-ID: <479012D8.9080508@gmail.com>

bill.wu wrote:
> the tutor list has been strangely silent for a few days. Anyone know
> what has happened? why?
I got about 20 e-mails from the list yesterday.
Do you consider this slient?
or do you maybe have a problem receiving messages?
> ____________________________________________________________________
> /*DreamMail*/ - ???????????????????
> www.dreammail.org <http://www.dreammail.org>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From rdmoores at gmail.com  Fri Jan 18 06:22:02 2008
From: rdmoores at gmail.com (Dick Moores)
Date: Thu, 17 Jan 2008 21:22:02 -0800
Subject: [Tutor] the tutor list has been strangely silent for a few
	days. Anyone know
Message-ID: <d71c7ed60801172122m33e4ad20iec1814c9692bd3bb@mail.gmail.com>

At 06:41 PM 1/17/2008, bill.wu wrote:

>the tutor list has been strangely silent for a few days.  Anyone know
>what has happened? why?

FYI I see 34 messages in my Eudora Tutor mailbox, dated 1/16 Pacific
Time (Eudora converts the datetimes to my time zone, PT).

Here's a screenshot of that mailbox:
<http://www.rcblue.com/Misc/Jan16TutorMessages.png>

If you're missing some, you can read them here:
<http://mail.python.org/pipermail/tutor/>

Dick Moores

From vimes656 at gmail.com  Fri Jan 18 11:19:07 2008
From: vimes656 at gmail.com (Danny Navarro)
Date: Fri, 18 Jan 2008 15:49:07 +0530
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <af173d400801180219k4dec1da2hcf718ff96ac9dac5@mail.gmail.com>

http://www.pythonchallenge.com/ is a great way to learn Python.

Danny

On Jan 16, 2008 4:58 PM, Fiyawerx <fiyawerx at gmail.com> wrote:

> I've been over google for hours now, and I'm sort of at a lull in my
> learning, as I don't really have a current "goal". I know I could set some
> easy goal like to learn a specific function or feature, but I still have a
> hard time with that approach also. I was wondering if anyone knows of any
> sites where people might request "projects" almost like rentacoder, but for
> free stuff and/or just for fun. Almost an 'It would be nice if I had a
> program that did this.. " type of thing to give me some direction. Or does
> anyone else have any ideas for some types of programs that might actually
> prove useful to people for beginners to work on?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080118/388a16e6/attachment.htm 

From sruiz at canterburyschool.org  Fri Jan 18 16:46:12 2008
From: sruiz at canterburyschool.org (=?ISO-8859-1?Q?=22Sim=F3n_A=2E_Ruiz=22?=)
Date: Fri, 18 Jan 2008 10:46:12 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <af173d400801180219k4dec1da2hcf718ff96ac9dac5@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<af173d400801180219k4dec1da2hcf718ff96ac9dac5@mail.gmail.com>
Message-ID: <4790C9C4.6060902@canterburyschool.org>

I'll second that.

It's quite an interesting mental gymnastics challenge, and will get you 
familiar with a lot of the modules. They also have helpful forums for 
when you get stuck.

Sim?n

Danny Navarro wrote:
> http://www.pythonchallenge.com/ is a great way to learn Python.
> 
> Danny
> 
> On Jan 16, 2008 4:58 PM, Fiyawerx < fiyawerx at gmail.com 
> <mailto:fiyawerx at gmail.com>> wrote:
> 
>     I've been over google for hours now, and I'm sort of at a lull in my
>     learning, as I don't really have a current "goal". I know I could
>     set some easy goal like to learn a specific function or feature, but
>     I still have a hard time with that approach also. I was wondering if
>     anyone knows of any sites where people might request "projects"
>     almost like rentacoder, but for free stuff and/or just for fun.
>     Almost an 'It would be nice if I had a program that did this.. "
>     type of thing to give me some direction. Or does anyone else have
>     any ideas for some types of programs that might actually prove
>     useful to people for beginners to work on?
> 
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
>     <http://mail.python.org/mailman/listinfo/tutor>
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From alejck at gmail.com  Fri Jan 18 20:06:26 2008
From: alejck at gmail.com (Alexander)
Date: Fri, 18 Jan 2008 14:06:26 -0500
Subject: [Tutor] data structure question
Message-ID: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>

Hi all,

I'm trying to write a small todo list/task manager and I'm having
trouble creating the right data structure to hold the tasks. The
program should have a command line interface.

This is what I want it to do:

* A list of tasks, where each task has a number of attributes.
Each task should be able to have subtasks.

* Persistence.

* A way to display all the tasks, with subtasks indented.

* A way to filter/search on the attributes of the tasks.

What I've tried so far is something like this:

<snip>
class Task(object):
	def __init__(self, cargo, children=[]):
		self.cargo = cargo
		self.children = children
	
	def __str__(self):
		s = '\t'.join(self.cargo)
		return s
	
	def add_child(self,child):
		self.children = self.children + [child]

<snip>

cargo is a list of the attributes of the task, such as task text,
status, deadline etc

What I'm having trouble with is:

* What data structure should all the Task instances be held in?

* How to traverse all the tasks, both with recursion into the subtasks
and not. I need the traversal both to create a nice string with the
task information for printing (here I need level-aware indentation),
and to be able to search the tasks by their attributes.

I suspect what I need is a tree, but I want one with multiple roots. I
only envision having <100 tasks at any one time so I don't need a
database backend. Persistence I think I've solved by having the
container data structure dump/load itself using pickle.

Best regards,

Alexander

From kent37 at tds.net  Fri Jan 18 20:35:07 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Jan 2008 14:35:07 -0500
Subject: [Tutor] data structure question
In-Reply-To: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
Message-ID: <4790FF6B.8030803@tds.net>

Alexander wrote:

> * A list of tasks, where each task has a number of attributes.
> Each task should be able to have subtasks.

Sounds like you should keep the Task objects in a list :-)
Possibly just the top-level tasks should be in the list...

> * A way to filter/search on the attributes of the tasks.
> 
> What I've tried so far is something like this:
> 
> <snip>
> class Task(object):
> 	def __init__(self, cargo, children=[]):

Don't use mutable objects as default arguments! See
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
for an explanation.

Kent

From jnewton at fuelindustries.com  Fri Jan 18 21:07:57 2008
From: jnewton at fuelindustries.com (James Newton)
Date: Fri, 18 Jan 2008 15:07:57 -0500
Subject: [Tutor] Teach-yourself game design site... for Python?
Message-ID: <1861F7D138B8034FAAB4BF433EBCAD240115429D@ex1.Fuel.Ott>

Hi folks,

I've just come across this article on the BBC site:

<http://news.bbc.co.uk/2/hi/technology/7189694.stm>

You can see some of the games that are either created collaboratively or
designed to be improved collaboratively at:

<http://www.myglife.org/usa/Boulder-GameDev/en/play/othergames>

Here's the home page for the My G-Life site:

<http://www.myglife.org/>


So my question is: is there something similar in the Python community?

James



From kent37 at tds.net  Fri Jan 18 21:23:15 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 18 Jan 2008 15:23:15 -0500
Subject: [Tutor] Teach-yourself game design site... for Python?
In-Reply-To: <1861F7D138B8034FAAB4BF433EBCAD240115429D@ex1.Fuel.Ott>
References: <1861F7D138B8034FAAB4BF433EBCAD240115429D@ex1.Fuel.Ott>
Message-ID: <47910AB3.5020508@tds.net>

James Newton wrote:
> Hi folks,
> 
> I've just come across this article on the BBC site:
> 
> <http://news.bbc.co.uk/2/hi/technology/7189694.stm>

> So my question is: is there something similar in the Python community?

I don't know of a collaborative, teaching community like that. There are 
a couple of frameworks for creating games in Python (pygame, pyglet) and 
the PyWeek challenge http://www.pyweek.org/ encourages game development 
and sharing.

Kent

From bhaaluu at gmail.com  Fri Jan 18 22:21:29 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Fri, 18 Jan 2008 16:21:29 -0500
Subject: [Tutor] Teach-yourself game design site... for Python?
In-Reply-To: <47910AB3.5020508@tds.net>
References: <1861F7D138B8034FAAB4BF433EBCAD240115429D@ex1.Fuel.Ott>
	<47910AB3.5020508@tds.net>
Message-ID: <ea979d70801181321ye9c72e6ye9404cbea26fc078@mail.gmail.com>

Greetings,
There are several beginning tutorials at the PyGame site:
http://pygame.org/news.html
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html

On Jan 18, 2008 3:23 PM, Kent Johnson <kent37 at tds.net> wrote:
> James Newton wrote:
> > Hi folks,
> >
> > I've just come across this article on the BBC site:
> >
> > <http://news.bbc.co.uk/2/hi/technology/7189694.stm>
>
> > So my question is: is there something similar in the Python community?
>
> I don't know of a collaborative, teaching community like that. There are
> a couple of frameworks for creating games in Python (pygame, pyglet) and
> the PyWeek challenge http://www.pyweek.org/ encourages game development
> and sharing.
>
> Kent

From tjampman at gmail.com  Fri Jan 18 22:28:25 2008
From: tjampman at gmail.com (Ole Jensen)
Date: Fri, 18 Jan 2008 22:28:25 +0100
Subject: [Tutor] Converting binary file date into a file?
Message-ID: <2fbed1fd0801181328y708c3a31h4bd5ff77ea8d0722@mail.gmail.com>

Hi

I made a small python program at home and tried to send by email attachments
to my studymates.
The attachment however shows up as a strange text

the first lines look like this:

M1F]R<_AG(#(@+2 R(&=E;F5R871O<F5R("T at 1$<R#0H@"5!I"0E08 at D)4"!O
M;&EE<'5M<&4)4"!V86YD<'5M<&4)4"!F<FEK=&EO;@EB97)E9VYE="!08 at T*
M5&EM92 P( DS-C4Q-3 at N-30T-#0T( DS-C(S-C N," ),3(R,BXR,C(R,C(R
M,B ),30V-"XP.#@X...<http://groups.google.com/groups/unlock?msg=c42d7058ff6b0c28&hl=en&_done=/group/gruppe-b1/browse_thread/thread/23a5c2bfae647d8b%3Fhl%3Den>
@X.2 ),3$R+C(S,S,S,S,S,R ),S0Y,3,T+C$W,S at U
M,PT*5&EM92 Q( DS-3 at P.#4N-CDT-#0T( DS-34S-# N," ),3(R,BXR,C(R

I was thinking that it might be the binary representation of my .py files?
(the files were not compresses, just basic .py-files)
If so is there anyways its possible to convert it back into an ordinary text
file? through either Python og Windows?

I ain'tt gonna be back to my own PC for the rest of the weekend so some of
the study work requires me to decode the attachments.

All help highly appriciated
Best regards

Ole Jensen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080118/6ea327be/attachment.htm 

From brunson at brunson.com  Fri Jan 18 22:42:10 2008
From: brunson at brunson.com (Eric Brunson)
Date: Fri, 18 Jan 2008 14:42:10 -0700
Subject: [Tutor] Converting binary file date into a file?
In-Reply-To: <2fbed1fd0801181328y708c3a31h4bd5ff77ea8d0722@mail.gmail.com>
References: <2fbed1fd0801181328y708c3a31h4bd5ff77ea8d0722@mail.gmail.com>
Message-ID: <47911D32.2020604@brunson.com>

Ole Jensen wrote:
> Hi
>  
> I made a small python program at home and tried to send by email 
> attachments to my studymates.
> The attachment however shows up as a strange text
>  
> the first lines look like this:
>  
> M1F]R<_AG(#(@+2 R(&=E;F5R871O<F5R("T at 1$<R#0H@"5!I"0E08 at D)4"!O
> M;&EE<'5M<&4)4"!V86YD<'5M<&4)4"!F<FEK=&EO;@EB97)E9VYE="!08 at T*
> M5&EM92 P( DS-C4Q-3 at N-30T-#0T( DS-C(S-C N," ),3(R,BXR,C(R,C(R
> M,B ),30V-"XP.#@X ... 
> <http://groups.google.com/groups/unlock?msg=c42d7058ff6b0c28&hl=en&_done=/group/gruppe-b1/browse_thread/thread/23a5c2bfae647d8b%3Fhl%3Den>@X.2 
> ),3$R+C(S,S,S,S,S,R ),S0Y,3,T+C$W,S at U
> M,PT*5&EM92 Q( DS-3 at P.#4N-CDT-#0T( DS-34S-# N," ),3(R,BXR,C(R
>  
> I was thinking that it might be the binary representation of my .py 
> files? (the files were not compresses, just basic .py-files)
> If so is there anyways its possible to convert it back into an 
> ordinary text file? through either Python og Windows?

Your email application attached the files using a standard called MIME 
(Multipurpose Internet Mail Extensions, see: 
http://www.faqs.org/rfcs/rfc2045.html

Part of the standards involves the choice of using a base64 encoding to 
ensure the attachment is 7-bit clean to properly transfer over SMTP, 
that's what you're seeing is the encoded attachment.

Several things may have happened.  1) the program you used to send the 
mail didn't perform the MIME attaching correctly and didn't include the 
proper information for the receiver to decode, 2) something corrupted 
the email in transit or 3) the email client reading the email doesn't 
know how to handle MIME.

If the problem is not 2 then you could open the email with a different 
mail application or you could save the raw email to a file and try to 
use python or other tools to extract the content.

Check out http://docs.python.org/lib/module-email.html for details on 
extracting MIME from email messages or simply look at 
http://docs.python.org/lib/module-base64.html for info on decoding the 
attachment after you've manually extracted the encoded text from the file.

Hope that's at least a little bit of help,
e.

>  
> I ain'tt gonna be back to my own PC for the rest of the weekend so 
> some of the study work requires me to decode the attachments.
>  
> All help highly appriciated
> Best regards
>  
> Ole Jensen
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From keridee at jayco.net  Fri Jan 18 22:47:09 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 18 Jan 2008 16:47:09 -0500
Subject: [Tutor] data structure question
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
Message-ID: <001001c85a1b$b0d19080$81fde004@jslaptop>

> <snip>
> class Task(object):
> def __init__(self, cargo, children=[]):
> self.cargo = cargo
> self.children = children
>
> def __str__(self):
> s = '\t'.join(self.cargo)
> return s
>
> def add_child(self,child):
> self.children = self.children + [child]

This is an excellent start.
self.children = self.children +[child]
can be
self.children.append(child)

Building on your concept and Kent's suggestions, I wish to list some things 
that will
help me to organize this...

* Each task is a container for other tasks (children)  (Essentially a *list* 
of other tasks)
* Each task has 'cargo' which is a string
* Each task can print it's direct contents, or a full recursive print is 
available

This helps, I think.

So the answer is -> when you add a child to self.children, make it an 
instance of Task
Oh ~ and ~

class Task(object):
   ...
    def recursive_print(self, level=0):
        print "\t"*level + self.cargo
        for x in self.children:
          recursive_print(x,level+1)

should take care of the recursive printing with level control 


From keridee at jayco.net  Fri Jan 18 22:56:20 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 18 Jan 2008 16:56:20 -0500
Subject: [Tutor] Converting binary file date into a file?
References: <2fbed1fd0801181328y708c3a31h4bd5ff77ea8d0722@mail.gmail.com>
Message-ID: <004301c85a1c$f966ff00$81fde004@jslaptop>

Many email clients encode attachments in base-64. I think there are standard 
modules in python which should be able to decode this.

> Hi
>
> I made a small python program at home and tried to send by email 
> attachments
> to my studymates.
> The attachment however shows up as a strange text
>
> the first lines look like this:
>
> M1F]R<_AG(#(@+2 R(&=E;F5R871O<F5R("T at 1$<R#0H@"5!I"0E08 at D)4"!O
> M;&EE<'5M<&4)4"!V86YD<'5M<&4)4"!F<FEK=&EO;@EB97)E9VYE="!08 at T*
> M5&EM92 P( DS-C4Q-3 at N-30T-#0T( DS-C(S-C N," ),3(R,BXR,C(R,C(R
> M,B ),30V-"XP.#@X...<http://groups.google.com/groups/unlock?msg=c42d7058ff6b0c28&hl=en&_done=/group/gruppe-b1/browse_thread/thread/23a5c2bfae647d8b%3Fhl%3Den>
> @X.2 ),3$R+C(S,S,S,S,S,R ),S0Y,3,T+C$W,S at U
> M,PT*5&EM92 Q( DS-3 at P.#4N-CDT-#0T( DS-34S-# N," ),3(R,BXR,C(R
>
> I was thinking that it might be the binary representation of my .py files?
> (the files were not compresses, just basic .py-files)
> If so is there anyways its possible to convert it back into an ordinary 
> text
> file? through either Python og Windows?
>
> I ain'tt gonna be back to my own PC for the rest of the weekend so some of
> the study work requires me to decode the attachments.
>
> All help highly appriciated
> Best regards
>
> Ole Jensen
>


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


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


From keridee at jayco.net  Fri Jan 18 23:04:04 2008
From: keridee at jayco.net (Tiger12506)
Date: Fri, 18 Jan 2008 17:04:04 -0500
Subject: [Tutor] data structure question
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
	<001001c85a1b$b0d19080$81fde004@jslaptop>
Message-ID: <000601c85a1e$0dbedcb0$81fde004@jslaptop>

>    def recursive_print(self, level=0):
>        print "\t"*level + self.cargo
>        for x in self.children:
>          recursive_print(x,level+1)

Whoops. should be

for x in self.children:
    x.recursive_print(level+1)

From mlangford.cs03 at gtalumni.org  Fri Jan 18 23:25:31 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Fri, 18 Jan 2008 17:25:31 -0500
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
Message-ID: <82b4f5810801181425o310f3822w252073335d37bf87@mail.gmail.com>

For those of you interested in hacking on the OLPC, IBM is putting up
a tutorial that goes through all the stuff with Qemu etc:

http://www.ibm.com/developerworks/linux/edu/l-dw-linux-xo-python-i.html?S_TACT=105AGX03&S_CMP=HP%3Cbr%3E

On 1/16/08, Fiyawerx <fiyawerx at gmail.com> wrote:
> I've been over google for hours now, and I'm sort of at a lull in my
> learning, as I don't really have a current "goal". I know I could set some
> easy goal like to learn a specific function or feature, but I still have a
> hard time with that approach also. I was wondering if anyone knows of any
> sites where people might request "projects" almost like rentacoder, but for
> free stuff and/or just for fun. Almost an 'It would be nice if I had a
> program that did this.. " type of thing to give me some direction. Or does
> anyone else have any ideas for some types of programs that might actually
> prove useful to people for beginners to work on?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From carroll at tjc.com  Sat Jan 19 00:52:26 2008
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 18 Jan 2008 15:52:26 -0800 (PST)
Subject: [Tutor] data structure question
In-Reply-To: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0801181548480.3974-100000@violet.rahul.net>

On Fri, 18 Jan 2008, Alexander wrote:

> I'm trying to write a small todo list/task manager...

Hi, Alexander.  Not to derail your actual question, but have you looked at 
Task Coach? It's a small todo list/task manager, written in Python using 
wxPython.

It does much, perhaps all, of what you're looking for, and it's open 
source.  You might be able to take it and either use it as-is, or modify 
it to meet your needs.  (And donate back the changes, if you feel 
generous.)

http://www.taskcoach.org/
http://sourceforge.net/projects/taskcoach/


From alan.gauld at btinternet.com  Sat Jan 19 02:06:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Jan 2008 01:06:17 -0000
Subject: [Tutor] data structure question
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
	<001001c85a1b$b0d19080$81fde004@jslaptop>
Message-ID: <fmrieb$ug3$1@ger.gmane.org>


"Tiger12506" <keridee at jayco.net> wrote

> class Task(object):
>   ...
>    def recursive_print(self, level=0):
>        print "\t"*level + self.cargo
>        for x in self.children:
>          recursive_print(x,level+1)

             x.recursive_print(level+1)

Is what you meant I think :-)

Alan G.


From alan.gauld at btinternet.com  Sat Jan 19 02:07:17 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Jan 2008 01:07:17 -0000
Subject: [Tutor] data structure question
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com><001001c85a1b$b0d19080$81fde004@jslaptop>
	<000601c85a1e$0dbedcb0$81fde004@jslaptop>
Message-ID: <fmrig8$ujo$1@ger.gmane.org>


"Tiger12506" <keridee at jayco.net> wrote in message 
news:000601c85a1e$0dbedcb0$81fde004 at jslaptop...
>>    def recursive_print(self, level=0):
>>        print "\t"*level + self.cargo
>>        for x in self.children:
>>          recursive_print(x,level+1)
>
> Whoops. should be
>
> for x in self.children:
>    x.recursive_print(level+1)

Ah, you already caught it, my gmane feed ruinning a bit slow...

Alan G 



From varsha.purohit at gmail.com  Sat Jan 19 03:09:30 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Fri, 18 Jan 2008 18:09:30 -0800
Subject: [Tutor] interview questions
Message-ID: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>

Hello All,
       I have an interview in python program development. Can i know some
interview questions in python ? If you know any website where i can refer
that would be helpful.

thanks,
-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080118/ca3f8b25/attachment.htm 

From varsha.purohit at gmail.com  Sat Jan 19 03:10:14 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Fri, 18 Jan 2008 18:10:14 -0800
Subject: [Tutor] [tutor] Interview questions in python and wxpython
Message-ID: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>

Hello All,
       I have an interview in python program development. Can i know some
interview questions in python ? If you know any website where i can refer
that would be helpful.

thanks,

-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080118/7236588e/attachment.htm 

From alan.gauld at btinternet.com  Sat Jan 19 10:15:55 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Jan 2008 09:15:55 -0000
Subject: [Tutor] interview questions
References: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
Message-ID: <fmsf4e$k9g$1@ger.gmane.org>

"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>       I have an interview in python program development. Can i know 
> some
> interview questions in python ? If you know any website where i can 
> refer
> that would be helpful.

Interview styles vary enormously but in my experience the
language specific bits of an interview will only take up 10-20%
of the interview. The bulk of the interview time would be spent
trying to understand how you approach problem solving in
general, how well you understand the dynamics of a project
and team working, maybe a bit on management issues
to see if you have long term potential.

Language specifics range from showing buggy code and
asking you to find the faults, asking you to suggest a
design approach to a problem, maybe some specific
questions about toolkits and known issues with the language.

But you could wind up with something completely different
depending on the organisations style and culture as well
as the individual interviewer. One of my old bosses loved
asking really off the ball  questions like" what is the most
enjoyable aspect of winter?" or "how well would you cope
on a 3 month submarine trip?" and stuff like that.

Another common technique is to "drill down" until they
hit bottom. In other words just keep on asking more and
more specific questions till you finally run out of answers.

And another is to stick to actual experience: Tell me
about a time when YOU did so and so... What did you do?,
What was the result, What would you do differently,
etc.

Its always hard to say how an interview will go, the most
important thing is to answer professionally and honestly.

Alan G. 



From connorsml at gmail.com  Sat Jan 19 12:07:05 2008
From: connorsml at gmail.com (Michael Connors)
Date: Sat, 19 Jan 2008 12:07:05 +0100
Subject: [Tutor] interview questions
In-Reply-To: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
References: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
Message-ID: <d9e7db140801190307y6ed80856wf277212a610b15f0@mail.gmail.com>

On 19/01/2008, Varsha Purohit <varsha.purohit at gmail.com> wrote:
>
> Hello All,
>        I have an interview in python program development. Can i know some
> interview questions in python ? If you know any website where i can refer
> that would be helpful.
>
> thanks,
> --
> Varsha Purohit,
> Graduate Student
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
If the company is developing in Python they must think its better than other
languages.
You should be prepared to answer "Why do you want to work with Python?" and
have a clear picture of its pros and cons.

The job is probably not all about Python, so don't forget to prepare the
other areas you mentioned on your CV.

-- 
Michael Connors
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/cd0e8195/attachment.htm 

From cissi85 at gmail.com  Sat Jan 19 12:37:22 2008
From: cissi85 at gmail.com (Cecilia Grahn)
Date: Sat, 19 Jan 2008 12:37:22 +0100
Subject: [Tutor] random.choice function
Message-ID: <FDA6D07E-39E3-4C46-8290-A068C0096372@gmail.com>

Hi,
this is my first mail and I apologize if I got something wrong =)
I am trying to make a script which returns a random string:

#hello.py
# Get the user's name and print a friendly hello
import random, string
name = raw_input("Your name please:")
ch = "So good to see you!","How are you?","Everything good  
today?","Glad you're here!".split(" ")
x = random.choice(ch)
print "Hello", name, x

everything works pretty much as I want it to, except when the last  
string is returned. It looks like this:

 >>> ================================ RESTART  
================================
 >>>
Your name please:Cece
Hello Cece ['Glad', "you're", 'here!']
 >>>

What is it I have missed or am I using  random.choice wrong?


/CeCe

From remco at gerlich.nl  Sat Jan 19 12:38:08 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Sat, 19 Jan 2008 12:38:08 +0100
Subject: [Tutor] interview questions
In-Reply-To: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
References: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
Message-ID: <7ae3ca10801190338n7b929a5bob0c707e5a5801c1a@mail.gmail.com>

Hi.

I've interviewed people for a project in which we used Perl. Most of us
already on the team hadn't used Perl before that project, but we learned it
pretty quickly, so we knew that that was quite possible. Before the
interview we would have seen their CV, and decided we wanted to speak to
them, so any language specific questions in the interview (or programming
questions generally) would be to check if they really had the level they
claimed.

Some people said in their letter, I don't know Perl yet but I do know X and
Y, I can program, and I expect to be able to learn Perl. That was fine by
us, we did ask them things about how they'd do things in X and Y, and
general problems of Web programming, how would they go about learning a
language - but we didn't grill them on their Perl.

Then there were those who claimed they were good at Perl. Even though we
weren't specifically looking for great Perl programmers, if they claim to be
great... these very often failed at pretty simple stuff, they really were
just beginners. Not actually worse at Perl than the other candidates, but
they had claimed more.

So, be honest :-) Then it doesn't matter much what they ask, since you have
the level of Python knowledge that you claimed.

Remco Gerlich

On Jan 19, 2008 3:09 AM, Varsha Purohit <varsha.purohit at gmail.com> wrote:

> Hello All,
>        I have an interview in python program development. Can i know some
> interview questions in python ? If you know any website where i can refer
> that would be helpful.
>
> thanks,
> --
> Varsha Purohit,
> Graduate Student
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/e6b7d2c6/attachment.htm 

From alan.gauld at btinternet.com  Sat Jan 19 12:56:16 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Jan 2008 11:56:16 -0000
Subject: [Tutor] random.choice function
References: <FDA6D07E-39E3-4C46-8290-A068C0096372@gmail.com>
Message-ID: <fmsoh3$ajb$1@ger.gmane.org>


"Cecilia Grahn" <cissi85 at gmail.com> wrote

> I am trying to make a script which returns a random string:
>
> ch = "So good to see you!","How are you?","Everything good
> today?","Glad you're here!".split(" ")

To python this line has 4 expressions which Pyhon will
assign as a tuple to ch. The first 3 expressions are literal
strings. The fourth is a string which is being split to
form 3 words contained in a list.

So ch winds up containing 3 strings and a list of 3 short
strings.

> everything works pretty much as I want it to, except when the last
> string is returned. It looks like this:
>
> Your name please:Cece
> Hello Cece ['Glad', "you're", 'here!']

So it returns a list of strings as you see here.
In other words you don't need the split operation.

> What is it I have missed or am I using  random.choice wrong?

No, you are using split wrongly.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From remco at gerlich.nl  Sat Jan 19 13:02:48 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Sat, 19 Jan 2008 13:02:48 +0100
Subject: [Tutor] random.choice function
In-Reply-To: <FDA6D07E-39E3-4C46-8290-A068C0096372@gmail.com>
References: <FDA6D07E-39E3-4C46-8290-A068C0096372@gmail.com>
Message-ID: <7ae3ca10801190402t459e09e0ha9244b5a20a43c36@mail.gmail.com>

Hi,

This line:

ch = "So good to see you!","How are you?","Everything good
today?","Glad you're here!".split(" ")

Creates a tuple with 4 elements:

1. "So good to see you!"
2. "How are you?"
3. "Everything good today?"
and
4. "Glad you're here!".split(" "), which is equal to ["Glad","you're",
"here"].

So it would seem that you just need to remove the .split(" "). It's probably
there from a previous try? What it does is break the string into a list,
splitting at every space.

Also, I'd recommend adding ( and ) around the tuple for readability, so
you'd get this:
ch = ("So good to see you!",
      "How are you?",
      "Everything good today?",
      "Glad you're here!",
)

Also a last ',' so it's easier to add new lines, move them around, delete
lines etc without accidently forgetting the comma. But these things are just
a matter of taste.

Remco


On Jan 19, 2008 12:37 PM, Cecilia Grahn <cissi85 at gmail.com> wrote:

> Hi,
> this is my first mail and I apologize if I got something wrong =)
> I am trying to make a script which returns a random string:
>
> #hello.py
> # Get the user's name and print a friendly hello
> import random, string
> name = raw_input("Your name please:")
> ch = "So good to see you!","How are you?","Everything good
> today?","Glad you're here!".split(" ")
> x = random.choice(ch)
> print "Hello", name, x
>
> everything works pretty much as I want it to, except when the last
> string is returned. It looks like this:
>
>  >>> ================================ RESTART
> ================================
>  >>>
> Your name please:Cece
> Hello Cece ['Glad', "you're", 'here!']
>  >>>
>
> What is it I have missed or am I using  random.choice wrong?
>
>
> /CeCe
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/70210311/attachment.htm 

From brindly at gmail.com  Sat Jan 19 14:09:48 2008
From: brindly at gmail.com (brindly sujith)
Date: Sat, 19 Jan 2008 18:39:48 +0530
Subject: [Tutor] how to bind a event to a application in tkinter
Message-ID: <bfb67a4d0801190509l7450bfbvf507bff856e85d1b@mail.gmail.com>

hi

how to bind a event to a application

consider i m opening  openoffice using

os.system("openoffice")...

i want to bind a event on openoffice...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/01c0b7e2/attachment.htm 

From bgailer at alum.rpi.edu  Sat Jan 19 15:40:03 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 19 Jan 2008 09:40:03 -0500
Subject: [Tutor] Interview questions in python and wxpython
In-Reply-To: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>
Message-ID: <47920BC3.6000708@alum.rpi.edu>

Varsha Purohit wrote:
> Hello All,
>        I have an interview in python program development. Can i know 
> some interview questions in python ? If you know any website where i 
> can refer that would be helpful.
My first engineering job interview went thus:

"We need someone to help us design antennas."

"I know nothing about antennas."

"Here's your desk and books. Start reading. You have 3 weeks to get up 
to speed."


An associate of mine interviewing at MS was given the a"lien railroad 
car" problem to check out his analytical skills and problem solving 
techniques. My version of this problem is:

Two railroad cars drop from space. Parachutes assist them to land at 
random points on a linear railroad track of infinite length. The chutes 
detach and lay next to the track beside the cars.

Each car is equipped with a rudimentary computer that can move the car 
and notice when it is next to a parachute. Both cars have the same 
program. The program starts once the parachute has detached. There is no 
communication between cars.

Each program line begins with an optional label followed by a command. 
Commands are:

Move one car's length left
Move one car's length right
Do nothing
Goto label
If car is next to a parachute Goto label

Each car will respond to move commands, and can tell when it is next to 
a parachute. Moving one car's length takes it out of parachute observing 
range.

Your mission is to write a program that will run (independently of 
course) on both computers. The goal is to get the cars to meet. We don't 
care what happens after that.

Your meta-mission is to propose ideas, state assumptions and ask questions.

I request of any of us who wants to tackle this to not reveal the 
solution for a while so some discussion can take place.

From alan.gauld at btinternet.com  Sat Jan 19 22:27:24 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Jan 2008 21:27:24 -0000
Subject: [Tutor] how to bind a event to a application in tkinter
References: <bfb67a4d0801190509l7450bfbvf507bff856e85d1b@mail.gmail.com>
Message-ID: <fmtpvv$9b8$1@ger.gmane.org>


"brindly sujith" <brindly at gmail.com> wrote

> how to bind a event to a application
> 
> consider i m opening  openoffice using
> 
> os.system("openoffice")...
> 
> i want to bind a event on openoffice...

Sorry, I'm still not clear what you want to do, 
can you be more specific?

Also which OS?

Are you running OpenOdffice and want to catch an event 
in OO and send it to your Python program?

Or are you running a python program and want to notify 
OO of some event in your program?

Running OO from os.system will make the task much 
harder whichever one you mean, consider using the 
sub-process module instead.

Alan G.


From ricaraoz at gmail.com  Sun Jan 20 00:14:30 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 19 Jan 2008 20:14:30 -0300
Subject: [Tutor] Interview questions in python and wxpython
In-Reply-To: <47920BC3.6000708@alum.rpi.edu>
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>
	<47920BC3.6000708@alum.rpi.edu>
Message-ID: <47928456.80708@bigfoot.com>

bob gailer wrote:
> Varsha Purohit wrote:
>> Hello All,
>>        I have an interview in python program development. Can i know 
>> some interview questions in python ? If you know any website where i 
>> can refer that would be helpful.
> My first engineering job interview went thus:
> 
> "We need someone to help us design antennas."
> 
> "I know nothing about antennas."
> 
> "Here's your desk and books. Start reading. You have 3 weeks to get up 
> to speed."
> 
> 
> An associate of mine interviewing at MS was given the a"lien railroad 
> car" problem to check out his analytical skills and problem solving 
> techniques. My version of this problem is:
> 
> Two railroad cars drop from space. Parachutes assist them to land at 
> random points on a linear railroad track of infinite length. The chutes 
> detach and lay next to the track beside the cars.
> 
> Each car is equipped with a rudimentary computer that can move the car 
> and notice when it is next to a parachute. Both cars have the same 
> program. The program starts once the parachute has detached. There is no 
> communication between cars.
> 
> Each program line begins with an optional label followed by a command. 
> Commands are:
> 
> Move one car's length left
> Move one car's length right
> Do nothing
> Goto label
> If car is next to a parachute Goto label
> 
> Each car will respond to move commands, and can tell when it is next to 
> a parachute. Moving one car's length takes it out of parachute observing 
> range.
> 
> Your mission is to write a program that will run (independently of 
> course) on both computers. The goal is to get the cars to meet. We don't 
> care what happens after that.
> 
> Your meta-mission is to propose ideas, state assumptions and ask questions.
> 
> I request of any of us who wants to tackle this to not reveal the 
> solution for a while so some discussion can take place.


Ok, I'll bite.
First, the instructions make no sense. There is no left and right! In a
railroad there is forward and backwards, and these are relative to the
directions the cars dropped at which I assume will be random. So "move
fwd" has the same meaning as "move bck" as there is no common reference
system (at least you mentioned none).

Anyway the program is obvious:

label1
Move one car's length fwd
If car is next to a parachute Goto label2
do nothing
goto label1

label2
Move one car's length fwd
goto label2


This will give you 75% probability that the cars meet (they will never
meet if they land facing opposite ways).






From jeff at drinktomi.com  Sat Jan 19 23:56:06 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Sat, 19 Jan 2008 14:56:06 -0800
Subject: [Tutor] Interview questions in python and wxpython
In-Reply-To: <47920BC3.6000708@alum.rpi.edu>
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>
	<47920BC3.6000708@alum.rpi.edu>
Message-ID: <ADE5DFD6-8E1C-4E0D-BCD8-CD7E8C4911C1@drinktomi.com>

> Your meta-mission is to propose ideas, state assumptions and ask  
> questions.

Is the track infinite in the sense that it resides on an infinite  
plane, or is it infinite
in the sense that it is circular, wrapping around the entire planet  
and meeting with
itself?

-jeff

From bgailer at alum.rpi.edu  Sun Jan 20 00:06:18 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 19 Jan 2008 18:06:18 -0500
Subject: [Tutor] Interview questions in python and wxpython
In-Reply-To: <ADE5DFD6-8E1C-4E0D-BCD8-CD7E8C4911C1@drinktomi.com>
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>	<47920BC3.6000708@alum.rpi.edu>
	<ADE5DFD6-8E1C-4E0D-BCD8-CD7E8C4911C1@drinktomi.com>
Message-ID: <4792826A.5090002@alum.rpi.edu>

Jeff Younker wrote:
>> Your meta-mission is to propose ideas, state assumptions and ask  
>> questions.
>>     
>
> Is the track infinite in the sense that it resides on an infinite  
> plane
yes
> , or is it infinite
> in the sense that it is circular, wrapping around the entire planet  
> and meeting with
> itself?
>
> -jeff
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


From bgailer at alum.rpi.edu  Sun Jan 20 00:10:36 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Sat, 19 Jan 2008 18:10:36 -0500
Subject: [Tutor] Interview questions in python and wxpython
In-Reply-To: <47928456.80708@bigfoot.com>
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com>	<47920BC3.6000708@alum.rpi.edu>
	<47928456.80708@bigfoot.com>
Message-ID: <4792836C.5030602@alum.rpi.edu>

Ricardo Ar?oz wrote:
>
> Ok, I'll bite.
> First, the instructions make no sense. There is no left and right! In a
> railroad there is forward and backwards, and these are relative to the
> directions the cars dropped at which I assume will be random. So "move
> fwd" has the same meaning as "move bck" as there is no common reference
> system (at least you mentioned none).
>
> Anyway the program is obvious:
>
> label1
> Move one car's length fwd
> If car is next to a parachute Goto label2
> do nothing
> goto label1
>
> label2
> Move one car's length fwd
> goto label2
>
>
> This will give you 75% probability that the cars meet (they will never
> meet if they land facing opposite ways).
>
>   
When the problem was posed to me there was a diagram in which left and 
right made sense. Your observation is also good.

The program is obvious - well eventually. It took me several iterations 
before I was able to see the obvious.

My preferred solution is the one Michael Langford offered as this makes 
no assumptions about execution time:

#Same assumptions as 1, but assumes:
# NO-OP takes no time to execute
# so we have to move the car around more
# to slow it down
#Approach: Two steps forward, one step back,
# until we're sure we're the chasing car
PROG2:  GO LEFT
        GO LEFT
    GO RIGHT
    IF AT PARACHUTE GOTO FASTER
    GOTO PROG2
FASTER: GO LEFT
    GOTO FASTER

From varsha.purohit at gmail.com  Sun Jan 20 00:24:38 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 19 Jan 2008 15:24:38 -0800
Subject: [Tutor] interview questions
In-Reply-To: <7ae3ca10801190338n7b929a5bob0c707e5a5801c1a@mail.gmail.com>
References: <c2157c790801181809p48de490apd460680940897ab9@mail.gmail.com>
	<7ae3ca10801190338n7b929a5bob0c707e5a5801c1a@mail.gmail.com>
Message-ID: <c2157c790801191524l1bc4bbf8s3bf1c2618b4fa360@mail.gmail.com>

Thanks for the input. ACtualy i just started programming in python since aug
2007 and i m doing my masters research on it. So i learnt python in quite
less amount of time. But otherwise i am good in c and c++. I am giving my
first interview in python so i dont know what kind of questions they might
ask me. So i wanted to have some list of quiestions which would give me an
idea as how should i prepare for python and wxpython.

On Jan 19, 2008 3:38 AM, Remco Gerlich <remco at gerlich.nl> wrote:

> Hi.
>
> I've interviewed people for a project in which we used Perl. Most of us
> already on the team hadn't used Perl before that project, but we learned it
> pretty quickly, so we knew that that was quite possible. Before the
> interview we would have seen their CV, and decided we wanted to speak to
> them, so any language specific questions in the interview (or programming
> questions generally) would be to check if they really had the level they
> claimed.
>
> Some people said in their letter, I don't know Perl yet but I do know X
> and Y, I can program, and I expect to be able to learn Perl. That was fine
> by us, we did ask them things about how they'd do things in X and Y, and
> general problems of Web programming, how would they go about learning a
> language - but we didn't grill them on their Perl.
>
> Then there were those who claimed they were good at Perl. Even though we
> weren't specifically looking for great Perl programmers, if they claim to be
> great... these very often failed at pretty simple stuff, they really were
> just beginners. Not actually worse at Perl than the other candidates, but
> they had claimed more.
>
> So, be honest :-) Then it doesn't matter much what they ask, since you
> have the level of Python knowledge that you claimed.
>
> Remco Gerlich
>
> On Jan 19, 2008 3:09 AM, Varsha Purohit < varsha.purohit at gmail.com> wrote:
>
> > Hello All,
> >        I have an interview in python program development. Can i know
> > some interview questions in python ? If you know any website where i can
> > refer that would be helpful.
> >
> > thanks,
> > --
> > Varsha Purohit,
> > Graduate Student
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>


-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/0c4d3c83/attachment.htm 

From alan.gauld at btinternet.com  Sun Jan 20 01:49:12 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Jan 2008 00:49:12 -0000
Subject: [Tutor] Interview questions in python and wxpython
References: <c2157c790801181810o788239bfx919b8bc3ccee413b@mail.gmail.com><47920BC3.6000708@alum.rpi.edu>
	<47928456.80708@bigfoot.com>
Message-ID: <fmu5qb$8jr$1@ger.gmane.org>


"Ricardo Ar?oz" <ricaraoz at gmail.com> wrote

> Anyway the program is obvious:

Not to me :-)

> label1
> Move one car's length fwd
> If car is next to a parachute Goto label2
> do nothing
> goto label1
>
> label2
> Move one car's length fwd
> goto label2

Very clever, but in the interests of readability I'd change
the labels and structure slightly:

GoSlow: move right
             do nothing
             if car next to 'chute goto GoFast
             goto GoSlow

GoFast: move right
             goto GoFast

Interesting example, thanks Bob.

Alan G.



From deliberatus at verizon.net  Sun Jan 20 03:40:31 2008
From: deliberatus at verizon.net (Kirk Bailey)
Date: Sat, 19 Jan 2008 21:40:31 -0500
Subject: [Tutor] Obssfurcatedpuytthonlessons nneeded
Message-ID: <4792B49F.1040103@verizon.net>

I  aam  writing some software which calls for some  unreadable code in 
it to let me secretly  set a registration key- it is to be shareware.

I know this can be done, but have not the foggiest clue of how todo it. 
Any links, articles, pointers?

-- 
Salute!
	-Kirk Bailey
           Think
          +-----+
          | BOX |
          +-----+
           knihT

Fnord.

From keridee at jayco.net  Sun Jan 20 04:32:46 2008
From: keridee at jayco.net (Tiger12506)
Date: Sat, 19 Jan 2008 22:32:46 -0500
Subject: [Tutor] Obssfurcatedpuytthonlessons nneeded
References: <4792B49F.1040103@verizon.net>
Message-ID: <000e01c85b15$517b6020$3dfce004@jslaptop>

>I  aam  writing some software which calls for some  unreadable code in
> it to let me secretly  set a registration key- it is to be shareware.
>
> I know this can be done, but have not the foggiest clue of how todo it.
> Any links, articles, pointers?

This is impossible to do completely, and while you work on it, you will 
always feel that the protection is not enough because you understand it, and 
could easily circumvent it.

Some possiblities:
1) Write registration validation in very clever and confusing C and then 
call with ctypes
2) At the very least, compile to pyc (IOW, don't distribute py, but the pyc 
that's generated when imported)
3) Use tricks... look for unreadable code and try to imitate it
4) Individual scenarios
  a) play with floats and strings, mix them, meld them, build sandcastles
  b) almost every good registration has a difficult to follow algorithm of 
arithmetic operations
  c) build hashes on certain times.
  d) Be creative

Here's something interesting.

#########
import time

def genkey(name):                                        #This is for you 
exclusively
  yr, mn, dy = time.localtime()[:3]
  ad = yr/5.0+6.0*mn%(dy+2)
  tsum=sum(ord(x) for x in name)
  return str(ad+tsum).replace(".",str(mn))


def chkkey(name,key,mn,dy,yr):
  ad = yr/5.0+6.0*mn%(dy+2)
  tsum=sum(ord(x) for x in name)
  ad = str(ad+tsum).replace(".",str(mn))
  return ad==key
#############


Not nearly creative enough I would think.

The best thing I can come up with right now is to use a preexisting function 
in your application to also process your key. That's difficult, yes, but it 
will help discourage people from say~ changing the last line of my chkkey to 
return True

Also, use obscure names. (Not that it will matter in pyc code) 


From varsha.purohit at gmail.com  Sun Jan 20 08:48:50 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sat, 19 Jan 2008 23:48:50 -0800
Subject: [Tutor] [tutor] Pointers in python ??
Message-ID: <c2157c790801192348k2c281aa9n5f11534d074c8814@mail.gmail.com>

Hello All,
        Does python has concept of pointers like c/cpp ?? If yes how.. can
anyone give me a small example to how we can use pointers in python.

thanks,
-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080119/70baeb9f/attachment-0001.htm 

From alan.gauld at btinternet.com  Sun Jan 20 09:38:31 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Jan 2008 08:38:31 -0000
Subject: [Tutor] Obssfurcatedpuytthonlessons nneeded
References: <4792B49F.1040103@verizon.net>
Message-ID: <fmv1aa$sh7$1@ger.gmane.org>

"Kirk Bailey" <deliberatus at verizon.net> wrote

>I  aam  writing some software which calls for some  unreadable code 
>in
> it to let me secretly  set a registration key- it is to be 
> shareware.

You don;t need to use a registration key for shareware.
Other much easier options are:
1) Rely on the honesty of your users.
2) Provide good quality documentation in pa[per only
format to buyers

Of course nothing is foolproof and whatever you do will be
hacked and free copies will become available so ultimately
you will always rely on honesty. That is the nature of
shareware...

> I know this can be done, but have not the foggiest clue of how todo 
> it.

There are lots of options, some dont even require you to
distribute a key since the key can be an encrypted form of
the users email address or user name (which is usually
obtainable via an environent variable...). Another option
is to use the checksum of the file itself, or the MAC id
of the computer.

Another option is to have an open key in the distribution and
your web site generate a secondary key based on the open
key and the users download credentials (a sequence number
and time usually). This is somewhat similar to public key
encryption protocols like RSA...

But there are many ways to do it which do not involve
writing obscure code which is probably the least secure
technique. But ultimately they can all be bypassed its
only a matter of time and effort..


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Sun Jan 20 09:41:44 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Jan 2008 08:41:44 -0000
Subject: [Tutor] [tutor] Pointers in python ??
References: <c2157c790801192348k2c281aa9n5f11534d074c8814@mail.gmail.com>
Message-ID: <fmv1gb$stk$1@ger.gmane.org>

"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>        Does python has concept of pointers like c/cpp ?? If yes 
> how.. can
> anyone give me a small example to how we can use pointers in python.

No, not really.

It does have the concept of C++ references however and in fact
thats how Pyhon variables work. They are all references. But
there is no real concept of a poibnter to a specific memory
location, and especially one that can be manipulated
arithmetically.

OTOH there is in practice little need for such a low level
approach in Python. What did you have in mind thast you
thought might need a pointer?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From varsha.purohit at gmail.com  Sun Jan 20 10:18:14 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 20 Jan 2008 01:18:14 -0800
Subject: [Tutor] [tutor] Calling python from a c program
Message-ID: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>

Hi,
   I just read about how to call python from a c program. This is the
function for that

int main()
{
     Py_Initialize();
    PyRun_SampleString("print 76");
    Py_Finalize();

    return 0;
}


But i am getting an error of header file. python.h not found. Can anybody
tell me where can i get this header file ?? And how can i call the python
interpreter screen from c program ??

-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080120/a85c6ade/attachment.htm 

From varsha.purohit at gmail.com  Sun Jan 20 10:33:20 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 20 Jan 2008 01:33:20 -0800
Subject: [Tutor] [tutor] Calling python from a c program
In-Reply-To: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>
References: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>
Message-ID: <c2157c790801200133m1bae8e28s985b7a809ff9f53b@mail.gmail.com>

I got the python.h file but i am getting linking errors for my program....

On Jan 20, 2008 1:18 AM, Varsha Purohit <varsha.purohit at gmail.com> wrote:

> Hi,
>    I just read about how to call python from a c program. This is the
> function for that
>
> int main()
> {
>      Py_Initialize();
>     PyRun_SampleString("print 76");
>     Py_Finalize();
>
>     return 0;
> }
>
>
> But i am getting an error of header file. python.h not found. Can anybody
> tell me where can i get this header file ?? And how can i call the python
> interpreter screen from c program ??
>
> --
> Varsha Purohit,
> Graduate Student




-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080120/2c31e290/attachment.htm 

From kent37 at tds.net  Sun Jan 20 15:24:51 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 20 Jan 2008 09:24:51 -0500
Subject: [Tutor] [tutor] Calling python from a c program
In-Reply-To: <c2157c790801200133m1bae8e28s985b7a809ff9f53b@mail.gmail.com>
References: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>
	<c2157c790801200133m1bae8e28s985b7a809ff9f53b@mail.gmail.com>
Message-ID: <479359B3.3010509@tds.net>

Varsha Purohit wrote:
> I got the python.h file but i am getting linking errors for my program....

It might help to tell us
- what platform you are using
- what compiler
- what link errors

Kent

> 
> On Jan 20, 2008 1:18 AM, Varsha Purohit <varsha.purohit at gmail.com 
> <mailto:varsha.purohit at gmail.com>> wrote:
> 
>     Hi,
>        I just read about how to call python from a c program. This is
>     the function for that
> 
>     int main()
>     {
>          Py_Initialize();
>         PyRun_SampleString("print 76");
>         Py_Finalize();
>        
>         return 0;
>     }
> 
> 
>     But i am getting an error of header file. python.h not found. Can
>     anybody tell me where can i get this header file ?? And how can i
>     call the python interpreter screen from c program ??
> 
>     -- 
>     Varsha Purohit,
>     Graduate Student 
> 
> 
> 
> 
> -- 
> Varsha Purohit,
> Graduate Student
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Sun Jan 20 16:16:49 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Jan 2008 15:16:49 -0000
Subject: [Tutor] [tutor] Calling python from a c program
References: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>
Message-ID: <fmvol5$rr2$1@ger.gmane.org>


"Varsha Purohit" <varsha.purohit at gmail.com> wrote

>   I just read about how to call python from a c program. 

Where did you read it? There are several sources of info 
on embedding Python in C, some better than others.

> And how can i call the python interpreter screen 
> from c program ??

You don't call the python interpreter screen
(ie the >>> prompt) from C you call the interpreter itself.
The interactive interpreter is a C program in its own right.

You could write your own fairly easily or you could use 
the PyShell GUI component that is part of the wxPython 
package.

But usually you just want to interpret some Python 
commands much as you did in your example.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From mlangford.cs03 at gtalumni.org  Sun Jan 20 16:19:41 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Sun, 20 Jan 2008 10:19:41 -0500
Subject: [Tutor] Obssfurcatedpuytthonlessons nneeded
In-Reply-To: <4792B49F.1040103@verizon.net>
References: <4792B49F.1040103@verizon.net>
Message-ID: <82b4f5810801200719t1ef72f28i9c711b636d189371@mail.gmail.com>

This is one of the few things I suggest going with a professional
software library for.

I remember reading about one in the sub $200 range you could also get
source for a little extra...but I've looked for 45 minutes and can't
find it.

They are called "License Managers" and many of them can just drop in
and handle all the forms of licenses you're used to.

         --Michael



On Jan 19, 2008 9:40 PM, Kirk Bailey <deliberatus at verizon.net> wrote:
> I  aam  writing some software which calls for some  unreadable code in
> it to let me secretly  set a registration key- it is to be shareware.
>
> I know this can be done, but have not the foggiest clue of how todo it.
> Any links, articles, pointers?
>
> --
> Salute!
>         -Kirk Bailey
>            Think
>           +-----+
>           | BOX |
>           +-----+
>            knihT
>
> Fnord.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From goldwamh at slu.edu  Sun Jan 20 16:45:36 2008
From: goldwamh at slu.edu (Michael H. Goldwasser)
Date: Sun, 20 Jan 2008 09:45:36 -0600
Subject: [Tutor] Pointers in python ??
In-Reply-To: <fmv1gb$stk$1@ger.gmane.org>
References: <c2157c790801192348k2c281aa9n5f11534d074c8814@mail.gmail.com>
	<fmv1gb$stk$1@ger.gmane.org>
Message-ID: <18323.27808.162317.881158@euclid.slu.edu>


On Sunday January 20, 2008, Alan Gauld wrote: 

>    "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>    
>    >        Does python has concept of pointers like c/cpp ?? If yes 
>    > how.. can
>    > anyone give me a small example to how we can use pointers in python.
>    
>    No, not really.
>    
>    It does have the concept of C++ references however and in fact
>    thats how Pyhon variables work. They are all references. But
>    there is no real concept of a poibnter to a specific memory
>    location, and especially one that can be manipulated
>    arithmetically.

You are correct in that Python has no concept of pointer arithmetic or
any direct access of memory based on a pointer value.

However I strongly disagree with your suggestion that Python's
variables work like C++ reference variables.  The issue is that a C++
reference variable must be initially bound to an existing object and
that association cannot henceforth be changed.  Consider the following
C++ example, presuming that we have a basic Point class (not shown
here).

Point a(0,0);
Point b(5,7);
Point& c = a;     // C++ reference variable

At this point there are two instances.  The names a and c are bound to
the same underlying instance and b is bound to a second instance.
Consider the following

c = b;       // reassigns the VALUE of c (aka a) to 5,7 but c is still bound to a
c.setX(3);   // notice that this has no effect on b;  c is not bound to b
cout << a;   // would output <3,7>
cout << b;   // would output <5,7>
cout << c;   // would output <3,7>

Translating these same seven command into Python would produce
different results, most notably because of the c=b assignment.

C++ When passing a parameter as a C++ reference, similar semantics are
used. The formal parameter is bound to the actual parameter upon
invocation of a function and from that point on assignments within the
body do not rebind the name but instead alter the value of the
underlying instance.

bool clear(Point& p) {
  p = Point(0,0);        // changes the actual parameter's value
}

As a final issue, notice that a C++ pointer can be assigned to null,
just as a Python variable can be assigned to None.  (C++ reference
variable cannot be null).

I should say that the SYNTAX of C++ pointers are different, as you
need to explicitly dereference them to access the underlying instance,
as in c->setX(3) rather than c.setX(3).

If you are comfortable with Java's syntax and semantics, it is easy to
explain.  The model for all data types in Python is the same as the
model used for non-primitive types in Java.

With regard,
Michael


       +-----------------------------------------------
       | Michael Goldwasser
       | Associate Professor
       | Dept. Mathematics and Computer Science
       | Saint Louis University
       | 220 North Grand Blvd.
       | St. Louis, MO 63103-2007


From alan.gauld at btinternet.com  Sun Jan 20 17:17:21 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Jan 2008 16:17:21 -0000
Subject: [Tutor] Pointers in python ??
References: <c2157c790801192348k2c281aa9n5f11534d074c8814@mail.gmail.com><fmv1gb$stk$1@ger.gmane.org>
	<18323.27808.162317.881158@euclid.slu.edu>
Message-ID: <fmvs6l$dfe$1@ger.gmane.org>

"Michael H. Goldwasser" <goldwamh at slu.edu> wrote

>>    It does have the concept of C++ references however and in fact
>>    thats how Pyhon variables work. They are all references.

> However I strongly disagree with your suggestion that Python's
> variables work like C++ reference variables.

You are quite correct, I overstated the similarity, especially
in saying that they "work like" C++ references. I was really
only refering to the fact that in both cases the references
are to other variables/objects rather than to memory
locations. But the underlying semantics are quite different.

> reference variable must be initially bound to an existing object and
> that association cannot henceforth be changed.

But I had actually forgotten that references could not be reassigned.
My C++ is pretty rusty, I haven't used C++ much in the last 7
or 8 years! :-)

Thanks for the clarification Michael.

Alan G. 



From varsha.purohit at gmail.com  Sun Jan 20 19:00:44 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Sun, 20 Jan 2008 10:00:44 -0800
Subject: [Tutor] [tutor] Calling python from a c program
In-Reply-To: <fmvol5$rr2$1@ger.gmane.org>
References: <c2157c790801200118m2aba1464r6d5b69810167aaf8@mail.gmail.com>
	<fmvol5$rr2$1@ger.gmane.org>
Message-ID: <c2157c790801201000r4417c349j55fb7ec66dff1aab@mail.gmail.com>

I am gettng following linking errors....

  [Linker error] undefined reference to `_imp__Py_Initialize'
  [Linker error] undefined reference to `PyRun_SampleString'
  [Linker error] undefined reference to `_imp__Py_Finalize'

I think i need to set the path to the linker... may be i need to pass
linking options of python to the c compiler... but wat are those options :(
??

On Jan 20, 2008 7:16 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> "Varsha Purohit" <varsha.purohit at gmail.com> wrote
>
> >   I just read about how to call python from a c program.
>
> Where did you read it? There are several sources of info
> on embedding Python in C, some better than others.
>
> > And how can i call the python interpreter screen
> > from c program ??
>
> You don't call the python interpreter screen
> (ie the >>> prompt) from C you call the interpreter itself.
> The interactive interpreter is a C program in its own right.
>
> You could write your own fairly easily or you could use
> the PyShell GUI component that is part of the wxPython
> package.
>
> But usually you just want to interpret some Python
> commands much as you did in your example.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080120/89bd43bb/attachment.htm 

From callethan at gmail.com  Sun Jan 20 23:16:18 2008
From: callethan at gmail.com (ethan s)
Date: Sun, 20 Jan 2008 17:16:18 -0500
Subject: [Tutor] Program Review: startup_user script -and-
	TimedMultiChoiceDialog class
Message-ID: <8473cfd90801201416v7ff6f0b3m62f9fc69c65be0e8@mail.gmail.com>

Hi folks. I'd love some feedback for two scripts.

  -startup_user: Intended to be called from a users logon script to
present a list of apps to launch. List items can be set to default on or
off. I run it from my system logon script like this:
if exist "c:\_utils\scripts\logon_%USERNAME%.py" pythonw
"c:\_utils\scripts\logon_%USERNAME%.py"

  -timedmultichoicedialog: A derivative of wx.MultiChoiceDialog. Added:
Timeout, statusbar countdown, default selected status of list items.

Prerequisites: wxPython
OS: Tested WinXP. Since only imports basically are wx.MultiChoiceDialog
and subprocess.Popen it they may/should work on on *nix.

Questions/Notes:

Left startup_user as simple script in line with simple nature of logon
scripts rather than do 'if __name__ == '__main__': Does that choice make
sense?

Script prints result info to stdout on theory that will run from pythonw or
redirect to NUL if want quiet. Could control with command line switch if
  implement a main. Again, good choice or does in rankle?

Could not get to/change message on dialog after setting it, so update
the dialogs titlebar instead. Acceptable? Better ideas? Know how to
change the message on a wx.MultiChoiceDialog when after ShowModal()?

Are these (after any fixes suggested) of use enough to submit wxPython
list for comment or otherwise publish?

----start startup_user.py----
#!/usr/bin/env python
# startup_user.py - default programs launcher GUI
# Author:      Ethan Shames - my.first.name NatO SPdogdiniAM.com
# Created:     2007-12-19
# last edit:   2008-01-19
# Version:     .8

# lessons learned:
#   Event incantations:
#      (D'oh)Event Binds must be to function w/o '()'s or function will
#      be __called__ when mentioned.
#      No parameter passing when Binding. (use self)
#      Event functions must be of form "def (self, event):" or they don't
work right.
#      Don't try to guess the event, get it from the docs.
#   Since this is a wx derived modal dialog, these changes to behavior
#   work. Not necessarily so if system derived like MessageBox

# TODO runas domain/user as LST parameter. Encode password.
# TODO 'save selections' button to remember on/off status of list item
# TODO program list maintenance

from wx import App, ID_OK
from subprocess import Popen
from timedmultichoicedialog import TimedMultiChoiceDialog

def launch(apps):
     #Launch a list of targets, return results
     results = []
     for app in apps:
         try:
             results.append(Popen(app))
         except WindowsError, e: # Not sure what error raised if *nix
             results.append(" subprocess.Popen: %s\n Starting File: %s" %
(e, app))
             continue
     return results

# List of items to launch. True/False flag sets default
# checked/unchecked status of item on list.
LST = [[True, r"C:\WINDOWS\system32\notepad.exe"],
        [True, r"C:\WINDOWS\system32\calc.exe"],
        [False, r"C:\you have fail.test"],
        ]

SELECTED = []
DELAY = 5000
MESSAGE = "Starting these in %s seconds. Click any item to stop timer" %
(DELAY/1000)
TITLE = "startup manager"

app = App()
dlg = TimedMultiChoiceDialog(message=MESSAGE, title=TITLE, lst=LST,
delay=DELAY)

# Clever idiom: ()calling ShowModal, which blocks processing until the
dialog dismissed,
# then check the return value for OK (vs. CANCEL)
if (dlg.ShowModal() == ID_OK):
     selections = dlg.GetSelections ()
     SELECTED = [LST[x][1] for x in selections]
     ##print("Selections: %s --> %s" % (selections, SELECTED))    #uncomment
to test

# Destroy dialog before moving on to launch selected items.
dlg.Destroy()    #Breakpoint here to test

results = launch(SELECTED)

for r in results:
     try:
         print(r.__dict__)
     except AttributeError:
         print(r)

----end startup_user.py----

----start timedmultichoicedialog.py----
#!/usr/bin/env python
# timedmultchoicedialog.py - multi-choice dialog box with timeout
# Author:      Ethan Shames - my.first.name NatO SPdogdiniAM.com
# Created:     2007-12-19
# last edit:   2008-01-19
# Version:     .8

# TODO Add group as parameter to lst; Create button for each unique
#      group to deselect/select group.
# TODO click anywhere to stop timer

import wx

class TimedMultiChoiceDialog(wx.MultiChoiceDialog):
     """
     MultiChoiceDialog with added timeout delay and countdown in titlebar.
Timer stops on change.

         lst: [[True|False, item], ...] True/False flag sets default
              checked/unchecked status of item on list.
         message: Message on header of dialog.
         title: Titlebar text.
         delay: Delay before timeout. Default value 10000ms.
         tic: Update titlebar text interval.
     """

     def __init__(self, message, lst, title=None, parent=None, delay=10000,
tic=1000):
         self.tic = tic          # timer tick interval
         self.timeout = delay    # init timeout for countdown
         if title == None: title = "TimedMultiChoiceDialog"
         self.title = title
         mytitle = '%s - "T-%ss"' % (title, delay/1000)
         items = [i[1] for i in lst]

         wx.MultiChoiceDialog.__init__(self, None, message, mytitle, items)
          self.SetWindowStyle(self.WindowStyle|wx.STAY_ON_TOP)

         selections = [i for i in range(len(lst)) if lst[i][0] == True]
         self.SetSelections(selections)

         self.Bind(wx.EVT_TIMER, self.countdown )
         # stop timer on change. would prefer on click, but no sus.
         self.Bind(wx.EVT_CHECKLISTBOX, self.on_change)

         self.t1 = wx.Timer(self)
         self.t1.Start(1000)

     def on_change(self, evt):
         # stop timer if item on list is changed.
         if self.t1.IsRunning():
             self.t1.Stop()
             self.SetLabel(self.title +" - timer stopped")

     def countdown(self, evt):
         # update titlebar with time remaining until launch
         # TODO Update header message text, not titlebar.
         # -There is no SetMessage(?) SetLabel, SetTitle change titlebar

          self.timeout -= self.tic

         if self.timeout > 0:
             title = '%s - "T-%ss"' % (self.title, self.timeout/1000)
             self.SetLabel(title)
             self.t1.Start (self.tic)
             return

         self.press_ok()

     def press_ok(self):
         # Create 'pushed OK' event, post it to dlg
         ok = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED , wx.ID_OK )
         wx.PostEvent(self, ok)

----end timedmultichoicedialog.py----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080120/cb5993b4/attachment-0001.htm 

From benjamin.eckenfels at gmx.de  Mon Jan 21 15:50:47 2008
From: benjamin.eckenfels at gmx.de (Benjamin Eckenfels)
Date: Mon, 21 Jan 2008 15:50:47 +0100
Subject: [Tutor] Programming Ideas, need some focus
In-Reply-To: <4790C9C4.6060902@canterburyschool.org>
References: <1b31ae500801160328m4525547fneb8c5caf02283a85@mail.gmail.com>
	<af173d400801180219k4dec1da2hcf718ff96ac9dac5@mail.gmail.com>
	<4790C9C4.6060902@canterburyschool.org>
Message-ID: <20080121145047.GA30638@firemoth>

On Fri, Jan 18, 2008 at 10:46:12AM -0500, "Sim?n A. Ruiz" wrote:
> I'll second that.


Me, too. Thanks for that hint. I currently have a great time with python 
challenge. I recommend it for everybody who like me has just finished 
the python basics an now is looking for an entertaining way to get 
familiar with the language and the most important modules.

Cheers
-- 
Benjamin Eckenfels

OpenPGP
Key id: CF56E489
Key fingerprint = 386D CBE1 0833 4C12 2871  F51E 839D 18EF CF56 E489
Public Key: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0xCF56E489

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20080121/20d2ef09/attachment.pgp 

From kent37 at tds.net  Mon Jan 21 17:59:29 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jan 2008 11:59:29 -0500
Subject: [Tutor] float_info
Message-ID: <4794CF71.60908@tds.net>

This is probably of interest to Dick Moores at least...
 From What's New in Python 2.6
http://docs.python.org/dev/whatsnew/2.6.html

[Note: A release date has not been set for Python 2.6]

A new variable in the sys module, float_info, is an object containing 
information about the platform?s floating-point support derived from the 
float.h file. Attributes of this object include mant_dig (number of 
digits in the mantissa), epsilon (smallest difference between 1.0 and 
the next largest value representable), and several others. (Contributed 
by Christian Heimes.)


Kent

From jrmorrisnc at gmail.com  Tue Jan 22 03:16:34 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 21:16:34 -0500
Subject: [Tutor] dictionaries, objects and scoping...
Message-ID: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>

class Foo:
  '''Represents a foo'''
  def __init__(self, name):
    '''Initializes the person's data'''
    self.name = name
    print '(Initializing %s)' % self.name
    self.ot = Bar(self.name)
    print '(After Other - %s)' % self.name

class Bar:
    def __init__(self, name):
        self.name = name
        print 'Other', self.name
        self.name.pop('srv')
        print 'Other (Changed)', self.name

dict = { "srv" : "why", "goo" : "sticky" }
foo = Foo(dict)
print foo.name


Why does the pop in the Bar class nuke the srv k & v from Foo.name as well?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/b709b641/attachment.htm 

From jrmorrisnc at gmail.com  Tue Jan 22 03:24:52 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 21:24:52 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
Message-ID: <6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>

Does it have something to do with:
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

And if so can anyone explain it a bit for me, I'm being slow tonight.

I thought each class got it's own namespace and this sharing of mutable
objects is confusing me.

Thanks.


On Jan 21, 2008 9:16 PM, John Morris <jrmorrisnc at gmail.com> wrote:

> class Foo:
>   '''Represents a foo'''
>   def __init__(self, name):
>     '''Initializes the person's data'''
>     self.name = name
>     print '(Initializing %s)' % self.name
>     self.ot = Bar(self.name)
>     print '(After Other - %s)' % self.name
>
> class Bar:
>     def __init__(self, name):
>         self.name = name
>         print 'Other', self.name
>         self.name.pop('srv')
>         print 'Other (Changed)', self.name
>
> dict = { "srv" : "why", "goo" : "sticky" }
> foo = Foo(dict)
> print foo.name
>
>
> Why does the pop in the Bar class nuke the srv k & v from Foo.name as
> well?
>
>


-- 
John Morris
jrmorrisnc at gmail.com
"Do nothing which is of no use." -- Miyamoto Musashi
<a href="http://profile.mygamercard.net/nerdality">
<img src="http://card.mygamercard.net/gbar/abyss/nerdality.gif" border=0>
</a>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/0cf99e0c/attachment.htm 

From kent37 at tds.net  Tue Jan 22 03:25:21 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jan 2008 21:25:21 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
Message-ID: <47955411.2030409@tds.net>

John Morris wrote:

> Why does the pop in the Bar class nuke the srv k & v from Foo.name 
> <http://Foo.name> as well?

Because they are both names for the same dict.

Assignment in Python does not copy values; it binds a name to a value. 
Some good references:
http://effbot.org/zone/python-objects.htm
http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/

Kent

From jrmorrisnc at gmail.com  Tue Jan 22 03:31:50 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 21:31:50 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <47955411.2030409@tds.net>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<47955411.2030409@tds.net>
Message-ID: <6216eba0801211831l4181281ap5e37edb06a0dea1f@mail.gmail.com>

Thanks,

so I could/should do

self.ot = Bar(self.name.copy()) instead


On Jan 21, 2008 9:25 PM, Kent Johnson <kent37 at tds.net> wrote:

> John Morris wrote:
>
> > Why does the pop in the Bar class nuke the srv k & v from Foo.name
> > <http://Foo.name> as well?
>
> Because they are both names for the same dict.
>
> Assignment in Python does not copy values; it binds a name to a value.
> Some good references:
> http://effbot.org/zone/python-objects.htm
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/
>
> Kent
>



-- 
John Morris
jrmorrisnc at gmail.com
"Do nothing which is of no use." -- Miyamoto Musashi
<a href="http://profile.mygamercard.net/nerdality">
<img src="http://card.mygamercard.net/gbar/abyss/nerdality.gif" border=0>
</a>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/c86b2d0e/attachment.htm 

From john at fouhy.net  Tue Jan 22 03:32:21 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 22 Jan 2008 15:32:21 +1300
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>
Message-ID: <5e58f2e40801211832u64e0d308u370b20416b84227@mail.gmail.com>

On 22/01/2008, John Morris <jrmorrisnc at gmail.com> wrote:
> I thought each class got it's own namespace and this sharing of mutable
> objects is confusing me.

Each class gets its own namespace, but names are different from
objects.  For example:

>>> x = [1, 2, 3]
>>> y = x
>>> y.append(4)
>>> x
[1, 2, 3, 4]

In this case, x and y are both different names for the same object.
Classes increase the name space, but they don't change the fact that
in python, assignment is just giving something a new name.

-- 
John.

From kent37 at tds.net  Tue Jan 22 03:35:14 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jan 2008 21:35:14 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>
Message-ID: <47955662.6060606@tds.net>

John Morris wrote:
> Does it have something to do with:
> http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
> 
> And if so can anyone explain it a bit for me, I'm being slow tonight.
> 
> I thought each class got it's own namespace and this sharing of mutable 
> objects is confusing me.

It has nothing to do with namespaces, it is the semantics of assignment 
that is your problem. What you have done is essentially the same as 
this, just obfuscated ;-)

In [1]: d = { "srv" : "why", "goo" : "sticky" }
In [2]: n = d
In [3]: n.pop('srv')
Out[3]: 'why'
In [4]: d
Out[4]: {'goo': 'sticky'}

Look at the references I sent (or wait for someone else with more energy 
than I to explain :-) )

Kent

From jrmorrisnc at gmail.com  Tue Jan 22 03:36:48 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 21:36:48 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <5e58f2e40801211832u64e0d308u370b20416b84227@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com>
	<5e58f2e40801211832u64e0d308u370b20416b84227@mail.gmail.com>
Message-ID: <6216eba0801211836n40485ed5s123e98d858081381@mail.gmail.com>

So this seems like it will make scope/namespaces a bit interesting...

Any good references on why this is this way?
I.e., why assignment passes across scopes instead of copy.
Or is it just explicit versus implicit?



On Jan 21, 2008 9:32 PM, John Fouhy <john at fouhy.net> wrote:

> On 22/01/2008, John Morris <jrmorrisnc at gmail.com> wrote:
> > I thought each class got it's own namespace and this sharing of mutable
> > objects is confusing me.
>
> Each class gets its own namespace, but names are different from
> objects.  For example:
>
> >>> x = [1, 2, 3]
> >>> y = x
> >>> y.append(4)
> >>> x
> [1, 2, 3, 4]
>
> In this case, x and y are both different names for the same object.
> Classes increase the name space, but they don't change the fact that
> in python, assignment is just giving something a new name.
>
> --
> John.
>



-- 
John Morris
jrmorrisnc at gmail.com
"Do nothing which is of no use." -- Miyamoto Musashi
<a href="http://profile.mygamercard.net/nerdality">
<img src="http://card.mygamercard.net/gbar/abyss/nerdality.gif" border=0>
</a>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/ee28e7d7/attachment-0001.htm 

From kent37 at tds.net  Tue Jan 22 03:45:07 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jan 2008 21:45:07 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211831l4181281ap5e37edb06a0dea1f@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>	<47955411.2030409@tds.net>
	<6216eba0801211831l4181281ap5e37edb06a0dea1f@mail.gmail.com>
Message-ID: <479558B3.3000305@tds.net>

John Morris wrote:
> Thanks,
> 
> so I could/should do
> 
> self.ot = Bar(self.name.copy()) instead

Yes, if you want a copy you have to ask for it.

Kent

From jrmorrisnc at gmail.com  Tue Jan 22 04:04:31 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 22:04:31 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
Message-ID: <6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>

Ahhh. so namespaces are scoped, not objects...
You have to keep your objects separate (and make copies when needed), Python
just keeps namespaces (names that refer to an object) scoped according to
it's rules:
http://docs.python.org/ref/naming.html

So if you create an object way up in terms of scope (global), then all
python does is handle what names are available in a given scope to refer to
it. If you want a separate object you have to take care of that yourself.
Efficient. Massive potential for gotchas, especially with some of python's
cleverness in terms of scoping rules.

Sort of. I see some light beginning to dawn ;).

On Jan 21, 2008 9:16 PM, John Morris <jrmorrisnc at gmail.com> wrote:

> class Foo:
>   '''Represents a foo'''
>   def __init__(self, name):
>     '''Initializes the person's data'''
>     self.name = name
>     print '(Initializing %s)' % self.name
>     self.ot = Bar(self.name)
>     print '(After Other - %s)' % self.name
>
> class Bar:
>     def __init__(self, name):
>         self.name = name
>         print 'Other', self.name
>         self.name.pop('srv')
>         print 'Other (Changed)', self.name
>
> dict = { "srv" : "why", "goo" : "sticky" }
> foo = Foo(dict)
> print foo.name
>
>
> Why does the pop in the Bar class nuke the srv k & v from Foo.name as
> well?
>
>


-- 
John Morris
jrmorrisnc at gmail.com
"Do nothing which is of no use." -- Miyamoto Musashi
<a href="http://profile.mygamercard.net/nerdality">
<img src="http://card.mygamercard.net/gbar/abyss/nerdality.gif" border=0>
</a>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/e7934afb/attachment.htm 

From john at fouhy.net  Tue Jan 22 04:18:18 2008
From: john at fouhy.net (John Fouhy)
Date: Tue, 22 Jan 2008 16:18:18 +1300
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>
Message-ID: <5e58f2e40801211918j3c705de6mb7406c283f0b90bf@mail.gmail.com>

On 22/01/2008, John Morris <jrmorrisnc at gmail.com> wrote:
> So if you create an object way up in terms of scope (global), then all
> python does is handle what names are available in a given scope to refer to
> it. If you want a separate object you have to take care of that yourself.
> Efficient. Massive potential for gotchas, especially with some of python's
> cleverness in terms of scoping rules.

There is potential for gotchas, but it's reduced by the fact that
integers and strings are both immutable.  For example:

>>> x = 'foo'
>>> y = x
>>> y is x   # this tests whether x and y are different names for the
same object
True
>>> y += 'bar'  # this is equivalent to: y = y + 'bar'
>>> y is x
False
>>> y, x
('foobar', 'foo')

(this is why there is no '.append()' method for strings)

-- 
John.

From kent37 at tds.net  Tue Jan 22 04:18:14 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 21 Jan 2008 22:18:14 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>
Message-ID: <47956076.7090701@tds.net>

John Morris wrote:
> Ahhh. so namespaces are scoped, not objects...

I would say names are scoped, but I guess namespaces are too.

> You have to keep your objects separate (and make copies when needed), 

Yes

> Python just keeps namespaces (names that refer to an object) scoped 
> according to it's rules:
> http://docs.python.org/ref/naming.html
> 
> So if you create an object way up in terms of scope (global), then all 
> python does is handle what names are available in a given scope to refer 
> to it. If you want a separate object you have to take care of that 
> yourself. Efficient. 

Yes. Assignment is not copying, it is name-binding.

> Massive potential for gotchas, especially with some 
> of python's cleverness in terms of scoping rules.

In my experience it is rare to actually need a copy of an object, and 
usually pretty clear when I do. The real hurdle is getting your mental 
model in sync with what Python is actually doing, rather than what you 
think it should be doing.

Kent

From jrmorrisnc at gmail.com  Tue Jan 22 04:28:07 2008
From: jrmorrisnc at gmail.com (John Morris)
Date: Mon, 21 Jan 2008 22:28:07 -0500
Subject: [Tutor] dictionaries, objects and scoping...
In-Reply-To: <47956076.7090701@tds.net>
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com>
	<6216eba0801211904qd720746hc0e00069076fa8cd@mail.gmail.com>
	<47956076.7090701@tds.net>
Message-ID: <6216eba0801211928r519fa50ataa87ebecec35474f@mail.gmail.com>

Thanks. I think this is understood better now.

Thanks to everyone for their help. I was running low on ways to express this
for clearer understanding.

Awesomeness once again from tutor at python.org.

- John

On Jan 21, 2008 10:18 PM, Kent Johnson <kent37 at tds.net> wrote:

> John Morris wrote:
> > Ahhh. so namespaces are scoped, not objects...
>
> I would say names are scoped, but I guess namespaces are too.
>
> > You have to keep your objects separate (and make copies when needed),
>
> Yes
>
> > Python just keeps namespaces (names that refer to an object) scoped
> > according to it's rules:
> > http://docs.python.org/ref/naming.html
> >
> > So if you create an object way up in terms of scope (global), then all
> > python does is handle what names are available in a given scope to refer
> > to it. If you want a separate object you have to take care of that
> > yourself. Efficient.
>
> Yes. Assignment is not copying, it is name-binding.
>
> > Massive potential for gotchas, especially with some
> > of python's cleverness in terms of scoping rules.
>
> In my experience it is rare to actually need a copy of an object, and
> usually pretty clear when I do. The real hurdle is getting your mental
> model in sync with what Python is actually doing, rather than what you
> think it should be doing.
>
> Kent
>



-- 
John Morris
jrmorrisnc at gmail.com
"Do nothing which is of no use." -- Miyamoto Musashi
<a href="http://profile.mygamercard.net/nerdality">
<img src="http://card.mygamercard.net/gbar/abyss/nerdality.gif" border=0>
</a>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080121/54242be0/attachment.htm 

From alan.gauld at btinternet.com  Tue Jan 22 09:27:57 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Jan 2008 08:27:57 -0000
Subject: [Tutor] dictionaries, objects and scoping...
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com><6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com><5e58f2e40801211832u64e0d308u370b20416b84227@mail.gmail.com>
	<6216eba0801211836n40485ed5s123e98d858081381@mail.gmail.com>
Message-ID: <fn49ei$ika$1@ger.gmane.org>

"John Morris" <jrmorrisnc at gmail.com> wrote

> So this seems like it will make scope/namespaces a bit 
> interesting...

namespaces in python are literally that, they are spaces
where *names* are visible. Objects are something else
entirely and assignment only pins a name to an object.

So in Python namespaces contriol where you can use a
name, not where you can use an object.

def f(y): return  y+1

x = 66
print f(x)

y is a name that is only visible inside f.
66 is a number object associated with x
and passed into f where it is associated
with y. The number object inside f is the
same object outside f only the name has
changed.The return value is a new number
object (67 in this case).

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From rdm at rcblue.com  Tue Jan 22 12:17:29 2008
From: rdm at rcblue.com (Dick Moores)
Date: Tue, 22 Jan 2008 03:17:29 -0800
Subject: [Tutor] float_info
In-Reply-To: <4794CF71.60908@tds.net>
References: <4794CF71.60908@tds.net>
Message-ID: <20080122112417.0FE681E4019@bag.python.org>

At 08:59 AM 1/21/2008, Kent Johnson wrote:
>This is probably of interest to Dick Moores at least...
>  From What's New in Python 2.6
>http://docs.python.org/dev/whatsnew/2.6.html
>
>[Note: A release date has not been set for Python 2.6]
>
>A new variable in the sys module, float_info, is an object containing
>information about the platform's floating-point support derived from the
>float.h file. Attributes of this object include mant_dig (number of
>digits in the mantissa), epsilon (smallest difference between 1.0 and
>the next largest value representable), and several others. (Contributed
>by Christian Heimes.)

Yes. Thanks, Kent.

Dick



From imonthejazz at googlemail.com  Wed Jan 23 00:10:18 2008
From: imonthejazz at googlemail.com (Damian Archer)
Date: Tue, 22 Jan 2008 23:10:18 +0000
Subject: [Tutor] Projects
Message-ID: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>

Guys and Gals,

Firstly 'Hi'. So I am new to Python have been learning it for about two
months now on and off between working and playing.....

Its the first language I have tried to learn, I am taking to it quite well
and enjoying it, which is always good.

The problem I am having is finding project ideas for beginners. I know I
should be looking at things I need, but quite honestly the level I am at I
think these will be beyond me. Plus I want to master the basics I've
learnt before I get ahead of myself.

So anyone have any good project ideas, perhaps projects that people have
undertaken before??

Thanks in advance!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080122/e6ecdaf9/attachment.htm 

From keridee at jayco.net  Wed Jan 23 00:58:03 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 22 Jan 2008 18:58:03 -0500
Subject: [Tutor] dictionaries, objects and scoping...
References: <6216eba0801211816u1a334b4bs8b35db550d3673fe@mail.gmail.com><6216eba0801211824i893a681k7b4bca3f284e9ea2@mail.gmail.com><5e58f2e40801211832u64e0d308u370b20416b84227@mail.gmail.com><6216eba0801211836n40485ed5s123e98d858081381@mail.gmail.com>
	<fn49ei$ika$1@ger.gmane.org>
Message-ID: <008b01c85d52$c8c4a0d0$06fce004@jslaptop>

Just a thought~

The built-in id() function can be useful in helping to sort out stuff. 
Returns a unique identifier for each object created so you can test whether 
a different name is a different object or just a different name for the same 
object. (This is what the  'is' operator does... Note: the 'is' operator and 
the '==' operator are not the same) 


From washakie at gmail.com  Wed Jan 23 10:42:11 2008
From: washakie at gmail.com (washakie)
Date: Wed, 23 Jan 2008 01:42:11 -0800 (PST)
Subject: [Tutor]  ssh script
Message-ID: <15038129.post@talk.nabble.com>


Hello, I'm trying to write a script which will allow me to create a reverse
tunnel from a remote machine using SSH -R

I know the reverse tunnel script works on it's own run from the shell, but I
don't want to leave it open always... does anyone have any ideas on how to
make this work? There seems to be something wrong with the subprocess call
such that it just hangs on the remote side...

#!/usr/bin/python

import os, time, subprocess
REMOTE_HOME='../'  #mounted drive to REMOTE_HOME from LOCAL_MACHINE

cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ; sleep
60; done'
while 1:
	while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'):
		proc=subprocess.call(cmd,shell='True')

	if proc: os.kill(proc.pid)

	if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'):
		break

-- 
View this message in context: http://www.nabble.com/ssh-script-tp15038129p15038129.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From benjamin.eckenfels at gmx.de  Wed Jan 23 10:57:03 2008
From: benjamin.eckenfels at gmx.de (Benjamin Eckenfels)
Date: Wed, 23 Jan 2008 10:57:03 +0100
Subject: [Tutor] Projects
In-Reply-To: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
References: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
Message-ID: <20080123095703.GC1248@firemoth>

On Tue, Jan 22, 2008 at 11:10:18PM +0000, Damian Archer wrote:
>    So anyone have any good project ideas, perhaps projects that people 
>    have
>    undertaken before??

I am in the same situation as you are. What I now did was doing 
something practical and some fun stuff: such as writing a statistic-tool 
for my mails, a script what automagically produces latex-letters and 
playing around with www.pythonchallenge.com 


-- 
Benjamin Eckenfels

OpenPGP
Key id: CF56E489
Key fingerprint = 386D CBE1 0833 4C12 2871  F51E 839D 18EF CF56 E489
Public Key: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0xCF56E489

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20080123/6d202f45/attachment.pgp 

From kent37 at tds.net  Wed Jan 23 13:22:21 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 23 Jan 2008 07:22:21 -0500
Subject: [Tutor] Projects
In-Reply-To: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
References: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
Message-ID: <4797317D.4040305@tds.net>

Damian Archer wrote:

> So anyone have any good project ideas, perhaps projects that people have 
> undertaken before??

This just came up on the list:
http://mail.python.org/pipermail/tutor/2008-January/059653.html

Kent

From tetsuo2k6 at web.de  Wed Jan 23 13:32:57 2008
From: tetsuo2k6 at web.de (tetsuo2k6 at web.de)
Date: Wed, 23 Jan 2008 13:32:57 +0100
Subject: [Tutor] csv.reader: bad argument type
Message-ID: <479733F9.6090508@web.de>

I don't get this.

I wrote a script that reads data from a .csv file and puts them into a 
MySQL database. It works fine on my machine.

Here's the relevant part:


<snip>
import csv
import MySQLdb
import sys

try:
         datei = sys.argv[1]
except:
         print("Usage: insert_into_db <.csv-file>")

# convert csv to list
reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar = "", 
quoting = csv.QUOTE_NONE)
</snip>

After copying it to the server, it says:

server1:/usr/local/sbin# ./insert_dgf_customers.py /usr/local/sbin/my.csv
Traceback (most recent call last):
   File "./insert_dgf_customers.py", line 27, in ?
     reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar = 
"", quoting = csv.QUOTE_NONE)
TypeError: bad argument type for built-in operation


The file my.csv is a test file and correctly formatted (it's the same 
file that worked on the other machine).
I thought the built-in operation meant here is open(), but without 
putting csv.reader() around it everything works fine... And I guess 
csv.reader is _not_ built-in, for it from the module - is that correct?

Any hints?

-paul

From agoldgod at gmail.com  Wed Jan 23 13:49:10 2008
From: agoldgod at gmail.com (goldgod a)
Date: Wed, 23 Jan 2008 18:19:10 +0530
Subject: [Tutor] Boost python
Message-ID: <105c9ccc0801230449l4947246fhc1ad54ef49af3d53@mail.gmail.com>

hi,
      I have hello.cpp and hello.py file. I want to access hello.cpp from
hello.py. How can I do that.
      I tried to find the solutions, I got Boost python. I saw the tutorial
I tried to do what they mentioned in the tutorial. I confused with "jamfile"
and "project-root". I am using debian I tried only the "bjam" method. I
installed bjam,boost-python. If any one familiar with this then help me.

-- 
Thanks & Regards,
goldgod
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080123/a46c86f3/attachment.htm 

From kent37 at tds.net  Wed Jan 23 14:04:46 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 23 Jan 2008 08:04:46 -0500
Subject: [Tutor] csv.reader: bad argument type
In-Reply-To: <479733F9.6090508@web.de>
References: <479733F9.6090508@web.de>
Message-ID: <47973B6E.60308@tds.net>

tetsuo2k6 at web.de wrote:

> import csv
> import MySQLdb
> import sys
> 
> try:
>          datei = sys.argv[1]
> except:
>          print("Usage: insert_into_db <.csv-file>")
> 
> # convert csv to list
> reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar = "", 
> quoting = csv.QUOTE_NONE)
> </snip>
> 
> After copying it to the server, it says:
> 
> server1:/usr/local/sbin# ./insert_dgf_customers.py /usr/local/sbin/my.csv
> Traceback (most recent call last):
>    File "./insert_dgf_customers.py", line 27, in ?
>      reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar = 
> "", quoting = csv.QUOTE_NONE)
> TypeError: bad argument type for built-in operation
> 
> 
> The file my.csv is a test file and correctly formatted (it's the same 
> file that worked on the other machine).

It doesn't seem to get as far as actually reading the file.

> I thought the built-in operation meant here is open(), but without 
> putting csv.reader() around it everything works fine... And I guess 
> csv.reader is _not_ built-in, for it from the module - is that correct?

csv.reader is not built-in, that is correct. But it is implemented in C 
so you won't get a good traceback into where the failure is actually 
occurring.

What version of Python is on the two machines?

A couple of things to try, maybe some hints will come out:
- print the value of datei just to make sure nothing funny there
- split the open to a separate line to make sure it is the call to 
reader that is the problem:
f = open(datei, "rb")
reader = csv.reader(f, delimiter = ";", quotechar = "", quoting = 
csv.QUOTE_NONE)

Kent

From tetsuo2k6 at web.de  Wed Jan 23 14:43:12 2008
From: tetsuo2k6 at web.de (tetsuo2k6 at web.de)
Date: Wed, 23 Jan 2008 14:43:12 +0100
Subject: [Tutor] csv.reader: bad argument type
In-Reply-To: <47973B6E.60308@tds.net>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
Message-ID: <47974470.5070005@web.de>

Kent Johnson schrieb:
> tetsuo2k6 at web.de wrote:
> 
>> import csv
>> import MySQLdb
>> import sys
>>
>> try:
>>          datei = sys.argv[1]
>> except:
>>          print("Usage: insert_into_db <.csv-file>")
>>
>> # convert csv to list
>> reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar = 
>> "", quoting = csv.QUOTE_NONE)
>> </snip>
>>
>> After copying it to the server, it says:
>>
>> server1:/usr/local/sbin# ./insert_dgf_customers.py /usr/local/sbin/my.csv
>> Traceback (most recent call last):
>>    File "./insert_dgf_customers.py", line 27, in ?
>>      reader = csv.reader(open(datei, "rb"), delimiter = ";", quotechar 
>> = "", quoting = csv.QUOTE_NONE)
>> TypeError: bad argument type for built-in operation
>>
>>
>> The file my.csv is a test file and correctly formatted (it's the same 
>> file that worked on the other machine).
> 
> It doesn't seem to get as far as actually reading the file.
> 
>> I thought the built-in operation meant here is open(), but without 
>> putting csv.reader() around it everything works fine... And I guess 
>> csv.reader is _not_ built-in, for it from the module - is that correct?
> 
> csv.reader is not built-in, that is correct. But it is implemented in C 
> so you won't get a good traceback into where the failure is actually 
> occurring.
> 
> What version of Python is on the two machines?

I guess that's it - my client has 2.5 while the server runs 2.4 ... I 
don't think any differences are mentioned in the library reference for 
csv but I'll have a second look.

> A couple of things to try, maybe some hints will come out:
> - print the value of datei just to make sure nothing funny there

Filename is alright - my.csv

> - split the open to a separate line to make sure it is the call to 
> reader that is the problem:
> f = open(datei, "rb")
> reader = csv.reader(f, delimiter = ";", quotechar = "", quoting = 
> csv.QUOTE_NONE)

Same result. Thanks nonetheless :)

> Kent
> 

- Paul

From kent37 at tds.net  Wed Jan 23 15:02:08 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 23 Jan 2008 09:02:08 -0500
Subject: [Tutor] csv.reader: bad argument type
In-Reply-To: <47974470.5070005@web.de>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de>
Message-ID: <479748E0.3050506@tds.net>

tetsuo2k6 at web.de wrote:
> I guess that's it - my client has 2.5 while the server runs 2.4 ... I 
> don't think any differences are mentioned in the library reference for 
> csv but I'll have a second look.

According to
http://www.python.org/doc/2.5/whatsnew/modules.html
"The csv module, which parses files in comma-separated value format, 
received several enhancements and a number of bugfixes."

FWIW the Python 2.5 change history for _csv.c is here:
http://svn.python.org/view/python/trunk/Modules/_csv.c?rev=59564&view=log

and for Python 2.4 here:
http://svn.python.org/view/python/branches/release24-maint/Modules/_csv.c?rev=52247&view=log

Nothing jumps out at me as the cause of your problem, though.

Kent

From jason.massey at gmail.com  Wed Jan 23 15:20:11 2008
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 23 Jan 2008 08:20:11 -0600
Subject: [Tutor] Projects
In-Reply-To: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
References: <c7cfa05e0801221510r241fdd65hcc874d4a56f1c74a@mail.gmail.com>
Message-ID: <7e3eab2c0801230620m4292033dsb35164f4ccf0a5f1@mail.gmail.com>

On Jan 22, 2008 5:10 PM, Damian Archer <imonthejazz at googlemail.com> wrote:

>   So anyone have any good project ideas, perhaps projects that people have
> undertaken before??
>
>

I'm taking a Java class this semester and our first program is a number
translator.  Here's the assignment:

*Below is a sample run:*

  Welcome to my number translator!

  Enter amount [0-999999.99; 0 to exit]: 1234.56
  Translation: one thousand two hundred thirty-four and 56/100



  Enter amount [0-999999.99; 0 to exit]: 17775
  Translation: seventeen thousand seven hundred seventy-five and 00/100


  Enter amount [0-999999.99; 0 to exit]: -45
  Enter amount [0-999999.99; 0 to exit]: 999999999.99

  Enter amount [0-999999.99; 0 to exit]: 22.95
  Translation: twenty-two and 95/100


  Enter amount [0-999999.99; 0 to exit]: 0.01
  Translation: zero and 01/100


  Enter amount [0-999999.99; 0 to exit]: 909909.99
  Translation: nine hundred nine thousand nine hundred nine and 99/100


  Enter amount [0-999999.99; 0 to exit]: 0
  Bye bye!

*Input*

You may assume that your input is in floating point format (no dollar signs
or commas or other special characters other than a single decimal point).  But
you will need to check to make sure your input satisfies the specs given
above.  (Although with exception handling it's not difficult to validate
that you have floating point format.)
---

An example routine to translate a number into it's english equivalent was
given (again, this is Java):
  static String convertDigitToEnglish(int d)  {
      switch ( d )
      {

         case 1: return "one";
         case 2: return "two";
         case 3: return "three";
         case 4: return "four";
         case 5: return "five";
         case 6: return "six";
         case 7: return "seven";
         case 8: return "eight";
         case 9: return "nine";
         default: return "\nFatal Error!\n"; // should I abort pgm?
      } // end of switch
  } // end of convertDigitToEnglish

In Python I'd just use a dictionary.

HTH,

jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080123/d277d350/attachment.htm 

From titleistfour at gmail.com  Wed Jan 23 16:15:00 2008
From: titleistfour at gmail.com (jay)
Date: Wed, 23 Jan 2008 09:15:00 -0600
Subject: [Tutor] ssh script
In-Reply-To: <15038129.post@talk.nabble.com>
References: <15038129.post@talk.nabble.com>
Message-ID: <7c25bb490801230715n1b62bd5btb95a2ac6fb985733@mail.gmail.com>

Have you looked into Paramiko?

http://www.lag.net/paramiko/

Its a port of the ssh2 protocol for python.  It might be easier to do this
using that that subprocess calls.  Paramiko is quite nice, I use it a lot at
work.  Just a suggestion....

J

On Jan 23, 2008 3:42 AM, washakie <washakie at gmail.com> wrote:

>
> Hello, I'm trying to write a script which will allow me to create a
> reverse
> tunnel from a remote machine using SSH -R
>
> I know the reverse tunnel script works on it's own run from the shell, but
> I
> don't want to leave it open always... does anyone have any ideas on how to
> make this work? There seems to be something wrong with the subprocess call
> such that it just hangs on the remote side...
>
> #!/usr/bin/python
>
> import os, time, subprocess
> REMOTE_HOME='../'  #mounted drive to REMOTE_HOME from LOCAL_MACHINE
>
> cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ;
> sleep
> 60; done'
> while 1:
>        while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'):
>                proc=subprocess.call(cmd,shell='True')
>
>        if proc: os.kill(proc.pid)
>
>        if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'):
>                break
>
> --
> View this message in context:
> http://www.nabble.com/ssh-script-tp15038129p15038129.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080123/fe670ac3/attachment-0001.htm 

From tetsuo2k6 at web.de  Wed Jan 23 17:01:28 2008
From: tetsuo2k6 at web.de (tetsuo2k6 at web.de)
Date: Wed, 23 Jan 2008 17:01:28 +0100
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related) (was: csv.reader:
 bad argument type)
In-Reply-To: <479748E0.3050506@tds.net>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>
Message-ID: <479764D8.5080307@web.de>

I decided to install Python2.5 on the server machine to save me the time 
for low-level debugging >;) but it doesn't find the MySQLdb module...

I searched through aptitude - the only thing I find is MySQLdb for Py2.4 
... What's happening here?

I have to say that the client PC (on which my script runs fine with 2.5) 
has Ubuntu installed - can it be that the MySQLdb module is behind in 
Debian?

Sorry for going off topic - if you guys don't want that here can move 
the problem to the Debian list - but maybe someone here knows about the 
status of the packages...?

- Paul

From titleistfour at gmail.com  Wed Jan 23 17:09:20 2008
From: titleistfour at gmail.com (jay)
Date: Wed, 23 Jan 2008 10:09:20 -0600
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related) (was:
	csv.reader: bad argument type)
In-Reply-To: <479764D8.5080307@web.de>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>
	<479764D8.5080307@web.de>
Message-ID: <7c25bb490801230809t663dbec5qe2bbb4fb20b3dbce@mail.gmail.com>

I run MySQLdb with Python 2.5.1, but I had to build it manually.  It was not
part of any prebuilt package on my RedHat box.  You should be able to do the
same.

J

On Jan 23, 2008 10:01 AM, <tetsuo2k6 at web.de> wrote:

> I decided to install Python2.5 on the server machine to save me the time
> for low-level debugging >;) but it doesn't find the MySQLdb module...
>
> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
> ... What's happening here?
>
> I have to say that the client PC (on which my script runs fine with 2.5)
> has Ubuntu installed - can it be that the MySQLdb module is behind in
> Debian?
>
> Sorry for going off topic - if you guys don't want that here can move
> the problem to the Debian list - but maybe someone here knows about the
> status of the packages...?
>
> - Paul
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080123/c480a6f2/attachment.htm 

From brunson at brunson.com  Wed Jan 23 17:51:42 2008
From: brunson at brunson.com (Eric Brunson)
Date: Wed, 23 Jan 2008 09:51:42 -0700
Subject: [Tutor] ssh script
In-Reply-To: <15038129.post@talk.nabble.com>
References: <15038129.post@talk.nabble.com>
Message-ID: <4797709E.30903@brunson.com>

washakie wrote:
> Hello, I'm trying to write a script which will allow me to create a reverse
> tunnel from a remote machine using SSH -R
>
> I know the reverse tunnel script works on it's own run from the shell, but I
> don't want to leave it open always... does anyone have any ideas on how to
> make this work? There seems to be something wrong with the subprocess call
> such that it just hangs on the remote side...
>
> #!/usr/bin/python
>
> import os, time, subprocess
> REMOTE_HOME='../'  #mounted drive to REMOTE_HOME from LOCAL_MACHINE
>
> cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ; sleep
>   

You probably need to add "-t" to the ssh invocation since you won't have 
a controlling terminal.

If that doesn't fix it, then try inserting some debugging output to know 
what's going on.

> 60; done'
> while 1:
> 	while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'):
> 		proc=subprocess.call(cmd,shell='True')
>
> 	if proc: os.kill(proc.pid)
>
> 	if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'):
> 		break
>
>   


From michael.langford at rowdylabs.com  Wed Jan 23 17:50:11 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Wed, 23 Jan 2008 11:50:11 -0500
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related) (was:
	csv.reader: bad argument type)
In-Reply-To: <479764D8.5080307@web.de>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>
	<479764D8.5080307@web.de>
Message-ID: <82b4f5810801230850k12ee055fn9224977c4f37eefc@mail.gmail.com>

It's a distribution issue. As far as what I've found as having cutting
edge (or even reasonably fresh) python packages in your package
manager is dictated by the distro, who vary wildly in this.

Debian SID at times> All the Ubuntus > Debian SID at times> Fedora
Core > Debian testing > Debian stable

This is the #1 reason I use ubuntu on servers right now. And if the
above is wrong now, these are generally feelings about a small sample
set over a period of time. I really have just gone all Kubuntu/Xubuntu
where I can these days.

I will suggest you look into learning eggs, cheese shop and
easy_install as an alternative to OS based package management for
python. I was an awesome presentation by Brandon Rhodes Mill about
Buildout  at PyAtl a couple weeks ago. It automagically downloads all
the eggs you need. You just create a setup.py and a quick config file,
and check those in with your source. When you run a command when you
start developing on a checkout, it pulls down all the eggs you need to
work with that checkout from the cheeshop, putting them in a project
local directory, which is then prepended to the python search path for
that project.

This means site-packages and you don't have fights when you install on
multiple system who may need other past versions of modules. Buildout
also gets the right version of python on the machine ( in a local
directory again ) and is compatible with system where you don't have
root access.

Buildout was originally written by the Zope people I believe, but has
been made independent of zope so all of us non-zope people can use it.

          --Michael

Cheese Shop: www.python.org/pypi
Monty Python Cheese Shop Skit: www.youtube.com/watch?v=B3KBuQHHKx0
Buildout: www.python.org/pypi/zc.buildout
More about Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
PyAtl (where presumably his talk will be posted): http://pyatl.org/

On Jan 23, 2008 11:01 AM,  <tetsuo2k6 at web.de> wrote:
> I decided to install Python2.5 on the server machine to save me the time
> for low-level debugging >;) but it doesn't find the MySQLdb module...
>
> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
> ... What's happening here?
>
> I have to say that the client PC (on which my script runs fine with 2.5)
> has Ubuntu installed - can it be that the MySQLdb module is behind in
> Debian?
>
> Sorry for going off topic - if you guys don't want that here can move
> the problem to the Debian list - but maybe someone here knows about the
> status of the packages...?
>
> - Paul
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From mlangford.cs03 at gtalumni.org  Wed Jan 23 19:36:47 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 23 Jan 2008 13:36:47 -0500
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related) (was:
	csv.reader: bad argument type)
In-Reply-To: <7c25bb490801230809t663dbec5qe2bbb4fb20b3dbce@mail.gmail.com>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>
	<479764D8.5080307@web.de>
	<7c25bb490801230809t663dbec5qe2bbb4fb20b3dbce@mail.gmail.com>
Message-ID: <82b4f5810801231036jf8f30e8gb2c8f1683f86ca43@mail.gmail.com>

It's a distribution issue. As far as what I've found as having cutting
edge (or even reasonably fresh) python packages in your package
manager is dictated by the distro, who vary wildly in this.

Debian SID at times> All the Ubuntus > Debian SID at times> Fedora
Core > Debian testing > Debian stable

This is the #1 reason I use ubuntu on servers right now. And if the
above is wrong now, these are generally feelings about a small sample
set over a period of time. I really have just gone all Kubuntu/Xubuntu
where I can these days.

I will suggest you look into learning eggs, cheese shop and
easy_install as an alternative to OS based package management for
python. I was an awesome presentation by Brandon Rhodes Mill about
Buildout  at PyAtl a couple weeks ago. It automagically downloads all
the eggs you need. You just create a setup.py and a quick config file,
and check those in with your source. When you run a command when you
start developing on a checkout, it pulls down all the eggs you need to
work with that checkout from the cheeshop, putting them in a project
local directory, which is then prepended to the python search path for
that project.

This means site-packages and you don't have fights when you install on
multiple system who may need other past versions of modules. Buildout
also gets the right version of python on the machine ( in a local
directory again ) and is compatible with system where you don't have
root access.

Buildout was originally written by the Zope people I believe, but has
been made independent of zope so all of us non-zope people can use it.

         --Michael

Cheese Shop: www.python.org/pypi
Monty Python Cheese Shop Skit: www.youtube.com/watch?v=B3KBuQHHKx0
Buildout: www.python.org/pypi/zc.buildout
More about Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
PyAtl (where presumably his talk will be posted): http://pyatl.org/
- Show quoted text -

On Jan 23, 2008 11:01 AM,  <tetsuo2k6 at web.de> wrote:
> I decided to install Python2.5 on the server machine to save me the time
> for low-level debugging >;) but it doesn't find the MySQLdb module...
>
> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
> ... What's happening here?
>
> I have to say that the client PC (on which my script runs fine with 2.5)
> has Ubuntu installed - can it be that the MySQLdb module is behind in
> Debian?
>
> Sorry for going off topic - if you guys don't want that here can move
> the problem to the Debian list - but maybe someone here knows about the
> status of the packages...?
>
> - Paul
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From eric at ericwalstad.com  Wed Jan 23 19:52:22 2008
From: eric at ericwalstad.com (Eric Walstad)
Date: Wed, 23 Jan 2008 10:52:22 -0800
Subject: [Tutor] ssh script
In-Reply-To: <15038129.post@talk.nabble.com>
References: <15038129.post@talk.nabble.com>
Message-ID: <47978CE6.9010506@ericwalstad.com>

I've done similar with pexpect:
http://pexpect.sourceforge.net/


washakie wrote:
> Hello, I'm trying to write a script which will allow me to create a reverse
> tunnel from a remote machine using SSH -R
> 
> I know the reverse tunnel script works on it's own run from the shell, but I
> don't want to leave it open always... does anyone have any ideas on how to
> make this work? There seems to be something wrong with the subprocess call
> such that it just hangs on the remote side...
> 
> #!/usr/bin/python
> 
> import os, time, subprocess
> REMOTE_HOME='../'  #mounted drive to REMOTE_HOME from LOCAL_MACHINE
> 
> cmd = 'while true; do ssh -R 8022:localhost:22 MyUserName at RemoteHost ; sleep
> 60; done'
> while 1:
> 	while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'):
> 		proc=subprocess.call(cmd,shell='True')
> 
> 	if proc: os.kill(proc.pid)
> 
> 	if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'):
> 		break


From carroll at tjc.com  Wed Jan 23 20:33:50 2008
From: carroll at tjc.com (Terry Carroll)
Date: Wed, 23 Jan 2008 11:33:50 -0800 (PST)
Subject: [Tutor] Projects
In-Reply-To: <7e3eab2c0801230620m4292033dsb35164f4ccf0a5f1@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0801231132020.12788-100000@violet.rahul.net>

On Wed, 23 Jan 2008, Jason Massey wrote:

> An example routine to translate a number into [its] english equivalent 
> was given (again, this is Java):
>   static String convertDigitToEnglish(int d)  {
>       switch ( d )
>       {
> 
>          case 1: return "one";
>          case 2: return "two";
>          case 3: return "three";
>          case 4: return "four";
>          case 5: return "five";
>          case 6: return "six";
>          case 7: return "seven";
>          case 8: return "eight";
>          case 9: return "nine";
>          default: return "\nFatal Error!\n"; // should I abort pgm?
>       } // end of switch
>   } // end of convertDigitToEnglish
> 
> In Python I'd just use a dictionary.

I'm no Java expert, but isn't Java's Map more or less equivalent to 
Python's dictionary?

http://java.sun.com/javase/6/docs/api/java/util/Map.html


From kent37 at tds.net  Wed Jan 23 20:44:10 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 23 Jan 2008 14:44:10 -0500
Subject: [Tutor] Projects
In-Reply-To: <Pine.LNX.4.44.0801231132020.12788-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0801231132020.12788-100000@violet.rahul.net>
Message-ID: <4797990A.8050208@tds.net>

Terry Carroll wrote:
> I'm no Java expert, but isn't Java's Map more or less equivalent to 
> Python's dictionary?

More or less, except Python dicts are about 10x easier to use.

Some (overly complicated) examples here:
http://personalpages.tds.net/~kent37/stories/00017.html

Kent

From tetsuo2k6 at web.de  Wed Jan 23 20:55:17 2008
From: tetsuo2k6 at web.de (tetsuo2k6 at web.de)
Date: Wed, 23 Jan 2008 20:55:17 +0100
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related)
In-Reply-To: <82b4f5810801230850k12ee055fn9224977c4f37eefc@mail.gmail.com>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>	
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>	
	<479764D8.5080307@web.de>
	<82b4f5810801230850k12ee055fn9224977c4f37eefc@mail.gmail.com>
Message-ID: <47979BA5.9000507@web.de>

Sounds very good! I think I read something about Python eggs some time 
ago, but didn't look deeper into it then. I'll do so tomorrow (if I find 
some spare time - there's so much to do...)

However, Debian is known for stability and security, right? I don't know 
if I should install things without apt in a production environment, so I 
first have to ask my guru if it's alright.

Maybe that sounds paranoid, but I'm new to Linux and all these server 
programs that make my head fuzzy o.O

Thanks for pointing to cheese shop etc.!



Michael Langford schrieb:
> It's a distribution issue. As far as what I've found as having cutting
> edge (or even reasonably fresh) python packages in your package
> manager is dictated by the distro, who vary wildly in this.
> 
> Debian SID at times> All the Ubuntus > Debian SID at times> Fedora
> Core > Debian testing > Debian stable
> 
> This is the #1 reason I use ubuntu on servers right now. And if the
> above is wrong now, these are generally feelings about a small sample
> set over a period of time. I really have just gone all Kubuntu/Xubuntu
> where I can these days.
> 
> I will suggest you look into learning eggs, cheese shop and
> easy_install as an alternative to OS based package management for
> python. I was an awesome presentation by Brandon Rhodes Mill about
> Buildout  at PyAtl a couple weeks ago. It automagically downloads all
> the eggs you need. You just create a setup.py and a quick config file,
> and check those in with your source. When you run a command when you
> start developing on a checkout, it pulls down all the eggs you need to
> work with that checkout from the cheeshop, putting them in a project
> local directory, which is then prepended to the python search path for
> that project.
> 
> This means site-packages and you don't have fights when you install on
> multiple system who may need other past versions of modules. Buildout
> also gets the right version of python on the machine ( in a local
> directory again ) and is compatible with system where you don't have
> root access.
> 
> Buildout was originally written by the Zope people I believe, but has
> been made independent of zope so all of us non-zope people can use it.
> 
>           --Michael
> 
> Cheese Shop: www.python.org/pypi
> Monty Python Cheese Shop Skit: www.youtube.com/watch?v=B3KBuQHHKx0
> Buildout: www.python.org/pypi/zc.buildout
> More about Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
> PyAtl (where presumably his talk will be posted): http://pyatl.org/
> 
> On Jan 23, 2008 11:01 AM,  <tetsuo2k6 at web.de> wrote:
>> I decided to install Python2.5 on the server machine to save me the time
>> for low-level debugging >;) but it doesn't find the MySQLdb module...
>>
>> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
>> ... What's happening here?
>>
>> I have to say that the client PC (on which my script runs fine with 2.5)
>> has Ubuntu installed - can it be that the MySQLdb module is behind in
>> Debian?
>>
>> Sorry for going off topic - if you guys don't want that here can move
>> the problem to the Debian list - but maybe someone here knows about the
>> status of the packages...?
>>
>> - Paul
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 


From mlangford.cs03 at gtalumni.org  Wed Jan 23 21:24:24 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Wed, 23 Jan 2008 15:24:24 -0500
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related)
In-Reply-To: <47979BA5.9000507@web.de>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>
	<479764D8.5080307@web.de>
	<82b4f5810801230850k12ee055fn9224977c4f37eefc@mail.gmail.com>
	<47979BA5.9000507@web.de>
Message-ID: <82b4f5810801231224i19ec2f39q1db72dffa93b5a36@mail.gmail.com>

> However, Debian is known for stability and security, right? I don't know
> if I should install things without apt in a production environment, so I
> first have to ask my guru if it's alright.

The *point* of buildout is that the entire installation is *local* to
the application. There is no change system wide, just for the
application that is running. This is *much* safer than using the
system package manager. Its like running a standalone exe like putty
on windows, versus installing a microsoft product.

       --Michael





> Michael Langford schrieb:
> > It's a distribution issue. As far as what I've found as having cutting
> > edge (or even reasonably fresh) python packages in your package
> > manager is dictated by the distro, who vary wildly in this.
> >
> > Debian SID at times> All the Ubuntus > Debian SID at times> Fedora
> > Core > Debian testing > Debian stable
> >
> > This is the #1 reason I use ubuntu on servers right now. And if the
> > above is wrong now, these are generally feelings about a small sample
> > set over a period of time. I really have just gone all Kubuntu/Xubuntu
> > where I can these days.
> >
> > I will suggest you look into learning eggs, cheese shop and
> > easy_install as an alternative to OS based package management for
> > python. I was an awesome presentation by Brandon Rhodes Mill about
> > Buildout  at PyAtl a couple weeks ago. It automagically downloads all
> > the eggs you need. You just create a setup.py and a quick config file,
> > and check those in with your source. When you run a command when you
> > start developing on a checkout, it pulls down all the eggs you need to
> > work with that checkout from the cheeshop, putting them in a project
> > local directory, which is then prepended to the python search path for
> > that project.
> >
> > This means site-packages and you don't have fights when you install on
> > multiple system who may need other past versions of modules. Buildout
> > also gets the right version of python on the machine ( in a local
> > directory again ) and is compatible with system where you don't have
> > root access.
> >
> > Buildout was originally written by the Zope people I believe, but has
> > been made independent of zope so all of us non-zope people can use it.
> >
> >           --Michael
> >
> > Cheese Shop: www.python.org/pypi
> > Monty Python Cheese Shop Skit: www.youtube.com/watch?v=B3KBuQHHKx0
> > Buildout: www.python.org/pypi/zc.buildout
> > More about Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
> > PyAtl (where presumably his talk will be posted): http://pyatl.org/
> >
> > On Jan 23, 2008 11:01 AM,  <tetsuo2k6 at web.de> wrote:
> >> I decided to install Python2.5 on the server machine to save me the time
> >> for low-level debugging >;) but it doesn't find the MySQLdb module...
> >>
> >> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
> >> ... What's happening here?
> >>
> >> I have to say that the client PC (on which my script runs fine with 2.5)
> >> has Ubuntu installed - can it be that the MySQLdb module is behind in
> >> Debian?
> >>
> >> Sorry for going off topic - if you guys don't want that here can move
> >> the problem to the Debian list - but maybe someone here knows about the
> >> status of the packages...?
> >>
> >> - Paul
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From dyoo at cs.wpi.edu  Thu Jan 24 00:50:55 2008
From: dyoo at cs.wpi.edu (Danny Yoo)
Date: Wed, 23 Jan 2008 18:50:55 -0500 (EST)
Subject: [Tutor] Projects (fwd)
Message-ID: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>

Hi Jason,


Looking back at that Java code:

////////////////////////////////////////////////
    static String convertDigitToEnglish(int d)  {
        switch ( d )
        {
           case 1: return "one";
           case 2: return "two";
           case 3: return "three";
           case 4: return "four";
           case 5: return "five";
           case 6: return "six";
           case 7: return "seven";
           case 8: return "eight";
           case 9: return "nine";
           default: return "\nFatal Error!\n"; // should I abort pgm?
        } // end of switch
   } // end of convertDigitToEnglis
////////////////////////////////////////////////


Frankly, this seems silly to me.  First, it ignores zero, which is a cardinal 
sin.  I'm being somewhat serious about this: functions should do what they say, 
and that function isn't.


But the code could also be written much more tightly as:

////////////////////////////////////////////////
      static String digitToString(int n) {
 	 String[] words = {"zero", "one", "two", "three", "four",
 	 		  "five", "six", "seven", "eight", "nine"};
 	 if (0 <= n && n < 10) {
 	     return words[n];
 	 }
 	 throw new IllegalArgumentException("input not a single digit");
     }
////////////////////////////////////////////////

I don't mean to make this post so Java-centric; it just seems a little unfair 
to compare a bad Java routine to a good Python routine.  :) Writing an 
equivalent in Python is also pretty straightforward:

#################################
## Pseudocode: just a sketch
def digitToString(n):
      words = ["zero", "one", ...]
      if 0 <= n < 10:
          return words[n]
     ...
#################################

Like dictionaries, the list data structure works pretty well for key/value 
lookup if the input key is a small number.


Good luck!


From ricaraoz at gmail.com  Thu Jan 24 02:21:53 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 23 Jan 2008 22:21:53 -0300
Subject: [Tutor] Projects (fwd)
In-Reply-To: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
Message-ID: <4797E831.5080203@bigfoot.com>

Danny Yoo wrote:
> Hi Jason,
> 
> 
> Looking back at that Java code:
> 
> ////////////////////////////////////////////////
>     static String convertDigitToEnglish(int d)  {
>         switch ( d )
>         {
>            case 1: return "one";
>            case 2: return "two";
>            case 3: return "three";
>            case 4: return "four";
>            case 5: return "five";
>            case 6: return "six";
>            case 7: return "seven";
>            case 8: return "eight";
>            case 9: return "nine";
>            default: return "\nFatal Error!\n"; // should I abort pgm?
>         } // end of switch
>    } // end of convertDigitToEnglis
> ////////////////////////////////////////////////
> 
> 
> Frankly, this seems silly to me.  First, it ignores zero, which is a cardinal 
> sin.  I'm being somewhat serious about this: functions should do what they say, 
> and that function isn't.
> 
> 
> But the code could also be written much more tightly as:
> 
> ////////////////////////////////////////////////
>       static String digitToString(int n) {
>  	 String[] words = {"zero", "one", "two", "three", "four",
>  	 		  "five", "six", "seven", "eight", "nine"};
>  	 if (0 <= n && n < 10) {
>  	     return words[n];
>  	 }
>  	 throw new IllegalArgumentException("input not a single digit");
>      }
> ////////////////////////////////////////////////
> 
> I don't mean to make this post so Java-centric; it just seems a little unfair 
> to compare a bad Java routine to a good Python routine.  :) Writing an 
> equivalent in Python is also pretty straightforward:
> 
> #################################
> ## Pseudocode: just a sketch
> def digitToString(n):
>       words = ["zero", "one", ...]
>       if 0 <= n < 10:
>           return words[n]
>      ...
> #################################
> 
> Like dictionaries, the list data structure works pretty well for key/value 
> lookup if the input key is a small number.
> 
> 
> Good luck!
> 

up to a thousand (not tested)

words = {0:'zero', 1:'one', 2:'two', 3:'three', ... , 10:'ten',
	 11:'eleven', 12:'twelve', ..., 19:'nineteen',
         20:'twenty', ...., 90:'ninety', 100:'one hundred' }
def digitToString(n) :
    try :
        retStr = words[n]
    except KeyError :
        if n > 100 :
            retStr = (digitToString(n // 100)
                     + ' hundred and '
                     + digitToString(n % 100))
        else :
            retStr = (digitToString(n - (n % 10))
                     + ' '
                     + digitToString(n % 10))

    return retStr

HTH

From keridee at jayco.net  Thu Jan 24 01:37:22 2008
From: keridee at jayco.net (Tiger12506)
Date: Wed, 23 Jan 2008 19:37:22 -0500
Subject: [Tutor] Projects (fwd)
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
	<4797E831.5080203@bigfoot.com>
Message-ID: <000c01c85e21$4c8c3d50$97fce004@jslaptop>

> up to a thousand (not tested)
>
> words = {0:'zero', 1:'one', 2:'two', 3:'three', ... , 10:'ten',
> 11:'eleven', 12:'twelve', ..., 19:'nineteen',
>         20:'twenty', ...., 90:'ninety', 100:'one hundred' }
> def digitToString(n) :
>    try :
>        retStr = words[n]
>    except KeyError :
>        if n > 100 :
>            retStr = (digitToString(n // 100)
>                     + ' hundred and '
>                     + digitToString(n % 100))
>        else :
>            retStr = (digitToString(n - (n % 10))
>                     + ' '
>                     + digitToString(n % 10))
>
>    return retStr

This could be written much more efficiently. It can be done with only these 
lists~
ones = 
['zero','one','two','three','four','five','six','seven','eight','nine']
teens = 
['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens = 
['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
hundstr = 'hundred'
thousand = 'thousand'

Exercise for reader to make it work ;-) Unless of course you genuinely want 
to see my code...
Current range 0 - 999,999    Easily extendable to millions, trillions, 
billions, etc. 


From ricaraoz at gmail.com  Thu Jan 24 03:20:08 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 23 Jan 2008 23:20:08 -0300
Subject: [Tutor] Projects (fwd)
In-Reply-To: <000c01c85e21$4c8c3d50$97fce004@jslaptop>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>	<4797E831.5080203@bigfoot.com>
	<000c01c85e21$4c8c3d50$97fce004@jslaptop>
Message-ID: <4797F5D8.4020707@bigfoot.com>

Tiger12506 wrote:
>> up to a thousand (not tested)
>>
>> words = {0:'zero', 1:'one', 2:'two', 3:'three', ... , 10:'ten',
>> 11:'eleven', 12:'twelve', ..., 19:'nineteen',
>>         20:'twenty', ...., 90:'ninety', 100:'one hundred' }
>> def digitToString(n) :
>>    try :
>>        retStr = words[n]
>>    except KeyError :
>>        if n > 100 :
>>            retStr = (digitToString(n // 100)
>>                     + ' hundred and '
>>                     + digitToString(n % 100))
>>        else :
>>            retStr = (digitToString(n - (n % 10))
>>                     + ' '
>>                     + digitToString(n % 10))
>>
>>    return retStr
> 
> This could be written much more efficiently. It can be done with only these 
> lists~
> ones = 
> ['zero','one','two','three','four','five','six','seven','eight','nine']
> teens = 
> ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
> tens = 
> ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
> hundstr = 'hundred'
> thousand = 'thousand'
> 

Isn't dictionary access faster than list access? Why are three lists
'much more efficient'?


From keridee at jayco.net  Thu Jan 24 02:45:09 2008
From: keridee at jayco.net (Tiger12506)
Date: Wed, 23 Jan 2008 20:45:09 -0500
Subject: [Tutor] Projects (fwd)
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu><4797E831.5080203@bigfoot.com>
	<000c01c85e21$4c8c3d50$97fce004@jslaptop>
Message-ID: <000801c85e2a$c439d160$e4fce004@jslaptop>

> This could be written much more efficiently. It can be done with only 
> these
> lists~
> ones =
> ['zero','one','two','three','four','five','six','seven','eight','nine']
> teens =
> ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']

What is it with me and mistakes lately? These two lists above should be 
combined into one. Saves a couple of range checks in the program.

:-{ 


From john at fouhy.net  Thu Jan 24 03:12:32 2008
From: john at fouhy.net (John Fouhy)
Date: Thu, 24 Jan 2008 15:12:32 +1300
Subject: [Tutor] Projects (fwd)
In-Reply-To: <4797F5D8.4020707@bigfoot.com>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
	<4797E831.5080203@bigfoot.com>
	<000c01c85e21$4c8c3d50$97fce004@jslaptop>
	<4797F5D8.4020707@bigfoot.com>
Message-ID: <5e58f2e40801231812x3970aacfp5d36e9000518aec8@mail.gmail.com>

On 24/01/2008, Ricardo Ar?oz <ricaraoz at gmail.com> wrote:
> Isn't dictionary access faster than list access? Why are three lists
> 'much more efficient'?

Well, not necessarily.

If you want a dictionary, you could use a list of tuples:

myDict = [('a', 'one'), ('b', 'two), ('c', 'three')]

Then you could do lookup as:

def lookup(key, listDict):
    for k, v in listDict:
        if k == key:
            return v

But, as you say, this would be a lot slower than using a dict (lookup
time is proportional to the length of the list for this naive
dictionary, whereas lookup time is essentially constant with a dict).

However, in this case, the keys are integers starting from 0 with no
holes.  Instead of having to search, our lookup is just:

    return digits[i]

which is also constant time.

If you really want to know which is faster, the timeit module is your
friend.  Here's what my computer says:

Morpork:~ repton$ python -m timeit -s 'd = {0:"zero", 1:"one",
2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight",
9:"nine"}' 'd[5]'
10000000 loops, best of 3: 0.127 usec per loop
Morpork:~ repton$ python -m timeit -s 'd = ["zero", "one", "two",
"three", "four", "five", "six", "seven", "eight", "nine"]' 'd[5]'
10000000 loops, best of 3: 0.102 usec per loop

So, if that extra 25 nanoseconds is important to you, definitely go
with the list!

-- 
John.

From keridee at jayco.net  Thu Jan 24 03:12:56 2008
From: keridee at jayco.net (Tiger12506)
Date: Wed, 23 Jan 2008 21:12:56 -0500
Subject: [Tutor] Projects (fwd)
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>	<4797E831.5080203@bigfoot.com>
	<000c01c85e21$4c8c3d50$97fce004@jslaptop>
	<4797F5D8.4020707@bigfoot.com>
Message-ID: <000e01c85e2e$a64c8b80$e36cfea9@jslaptop>

> Isn't dictionary access faster than list access? Why are three lists
> 'much more efficient'?

Oh no, no, no.  Dictionaries are faster when you are *searching through* for 
a particular value. If you already know the index of the item in the list, 
lists are much faster.

Dictionaries are hash based. Somewhere it has to calculate the hash of the 
key you give it...
These three lists are more efficient in terms of size/output ratio. It 
appeared as if the dictionary that was presented as an example was just 
going to map one to one all of the values from zero to 999,999 (to match my 
list version capabilities). Not only is that bad programming style, it's 
just plain unecessary. 


From bgailer at alum.rpi.edu  Thu Jan 24 04:13:11 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Wed, 23 Jan 2008 22:13:11 -0500
Subject: [Tutor] Projects (fwd)
In-Reply-To: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>
Message-ID: <47980247.9010506@alum.rpi.edu>

Danny Yoo wrote:
> [snip]

> First, it ignores zero, which is a cardinal sin.
Or is it an ordinal sin?

[snip]

From tknierim at mail.ieway.com  Thu Jan 24 04:48:27 2008
From: tknierim at mail.ieway.com (Daniel Knierim)
Date: Thu, 24 Jan 2008 03:48:27 GMT
Subject: [Tutor] TypeError in base class __init__ after reload
Message-ID: <200801231948109.SM06676@66.193.33.4>

Hello Pythonistas,

Running the script 'instantiate_and_reload.py' gives me the error 
    TypeError: unbound method __init__() must be called with ParentClass instance as first argument (got ChildClass instance instead)

on the last call to ChildClass(), at line 23. The earlier calls don't trigger the error.

-- Begin file instantiate_and_reload.py:
from parentclass import ParentClass
from childclass import ChildClass
import parentclass, childclass


p = parentclass.ParentClass()
c = childclass.ChildClass()
p = ParentClass()
c = ChildClass()

reload(parentclass)

p = parentclass.ParentClass()
c = childclass.ChildClass()
p = ParentClass()
c = ChildClass()

reload(childclass)

p = parentclass.ParentClass()
c = childclass.ChildClass()
p = ParentClass()
c = ChildClass()

-- End of file instantiate_and_reload.py

-- Begin file parentclass.py:
class ParentClass(): #same result with new-style classes (subclassing object)
    def __init__(self):
        pass


if __name__ == '__main__':
    p = ParentClass()

-- End of file parentclass.py

-- Begin file childclass.py:
from parentclass import ParentClass
import parentclass


class ChildClass(ParentClass):
    def __init__(self):
        ParentClass.__init__(self)


if __name__ == '__main__':
    p = ParentClass()
    c = ChildClass()

    reload(parentclass)
    
    p = ParentClass()
    c = ChildClass()

-- End of file childclass.py

-- Beginning of captured command-line session:
D:\Programs\Python\Sandbox\SubclassInitChain>python childclass.py

D:\Programs\Python\Sandbox\SubclassInitChain>python parentclass.py

D:\Programs\Python\Sandbox\SubclassInitChain>python instantiate_and_reload.py
Traceback (most recent call last):
  File "instantiate_and_reload.py", line 23, in <module>
    c = ChildClass()
  File "D:\Programs\Python\Sandbox\SubclassInitChain\childclass.py", line 7, in __init__
    ParentClass.__init__(self)
TypeError: unbound method __init__() must be called with ParentClass instance as first argument (got ChildClass instance instead)

D:\Programs\Python\Sandbox\SubclassInitChain>python -V
Python 2.5.1

-- end of captured command-line session

I can't understand why the last call to ChildClass() triggers the error, when the earlier calls don't.

Can somebody explain to me what's going on?  or what I'm doing wrong?

Thanks
- Dan Knierim

From washakie at gmail.com  Thu Jan 24 09:11:22 2008
From: washakie at gmail.com (washakie)
Date: Thu, 24 Jan 2008 00:11:22 -0800 (PST)
Subject: [Tutor] ssh script
In-Reply-To: <47978CE6.9010506@ericwalstad.com>
References: <15038129.post@talk.nabble.com> <47978CE6.9010506@ericwalstad.com>
Message-ID: <15060411.post@talk.nabble.com>


Thanks everyone these seem like promising directions to go... Eric, any
chance you could share your 'similar' code? The problem it seems with
paramiko is that it has little 'newbie' documentation, and I'm not clear how
to set up the reverse port forwarding on it. Thus I may need to use the
pexpect solution. 

-- 
View this message in context: http://www.nabble.com/ssh-script-tp15038129p15060411.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From fiyawerx at gmail.com  Thu Jan 24 09:15:01 2008
From: fiyawerx at gmail.com (Fiyawerx)
Date: Thu, 24 Jan 2008 03:15:01 -0500
Subject: [Tutor] Comparing more than 2 lists
Message-ID: <1b31ae500801240015s11c6f77bt6a209c97572a6abe@mail.gmail.com>

I have been able to find a few articles on comparing 2 lists, but I have 4
lists that I need to compare. I need to find any repeated elements and the
list that they came from. For example,

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'four', 'five']
list3 = ['two', 'three', 'six', 'seven']
list4 = ['three', 'five', 'six']


I need to be able to get along the lines of output:
Element 'one' contained in list1 and list2
Element 'two' contained in list1 and list2 and list3
...
Element 'five' contained in list2 and list4

etc.. and I can't quite figure out how to go about it
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/6f19f973/attachment.htm 

From mlangford.cs03 at gtalumni.org  Thu Jan 24 09:36:05 2008
From: mlangford.cs03 at gtalumni.org (Michael Langford)
Date: Thu, 24 Jan 2008 03:36:05 -0500
Subject: [Tutor] Comparing more than 2 lists
In-Reply-To: <1b31ae500801240015s11c6f77bt6a209c97572a6abe@mail.gmail.com>
References: <1b31ae500801240015s11c6f77bt6a209c97572a6abe@mail.gmail.com>
Message-ID: <82b4f5810801240036l5700396awe25879febcae05b2@mail.gmail.com>

You use a variation on bucket sort do to this:
http://en.wikipedia.org/wiki/Bucket_sort

You make a dict where the keys are the values in the lists, and a name
for each list is in the problem.

So you get something that looks like:

one: list1, list2
two: list1, list2, list3
etc

Doing this with collections.defaultdict is a breeze:
import collections

dd = collections.defaultdict(list)
for eachlist in lists:
   for each in eachlist:
       dd[each].append(getListName(eachlist))

Then to find the repeated elements you filter  where the list is of length > 1.

for each in dd:
     print "%s: %s" % (each, dd[each])

I'd provide code, but I'm not sure what an appropriate naming function
is for you, nor am I sure what you're doing with this when you're
done.

            --Michael



On Jan 24, 2008 3:15 AM, Fiyawerx <fiyawerx at gmail.com> wrote:
> I have been able to find a few articles on comparing 2 lists, but I have 4
> lists that I need to compare. I need to find any repeated elements and the
> list that they came from. For example,
>
> list1 = ['one', 'two', 'three']
> list2 = ['one', 'two', 'four', 'five']
> list3 = ['two', 'three', 'six', 'seven']
> list4 = ['three', 'five', 'six']
> https://mail.google.com/mail/#label/Pythontutor/117aadf8364dbf3b
Gmail - [Tutor] Comparing more than 2 lists - michael.langford at gmail.com
>
>  I need to be able to get along the lines of output:
> Element 'one' contained in list1 and list2
> Element 'two' contained in list1 and list2 and list3
> ...
> Element 'five' contained in list2 and list4
>
> etc.. and I can't quite figure out how to go about it
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From garry.willgoose at newcastle.edu.au  Thu Jan 24 08:20:19 2008
From: garry.willgoose at newcastle.edu.au (Garry Willgoose)
Date: Thu, 24 Jan 2008 18:20:19 +1100
Subject: [Tutor] creating a nested dictionary
Message-ID: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>

Is there any easy way to create a nested dictionary. I want to be  
able to allocate like

pdb[dataset][modulename][parametername]['value']=value

where dataset, modulename, parametername are variables that are  
determined within loops nested 3 deep, and value comes from a  
database call. Prior to the nested loops I do not know what the  
values of dataset, modulename, parametername will range over, but I  
do know pdb needs to be nested 3 deep. What I'd like to do is  
something like this

pdb={}
for dataset in dataset_list:
	modulename_list=getmodules(dataset)
	for modulename in modulename_list:
		parametername_list=getparameters(dataset,modulename)
		for parametername in parametername_list:
			value=getvalue(dataset, modulename, parametername)
			pdb[dataset][modulename][parametername]['value']=value
			
What I'm currently doing is

pdb={}
for dataset in dataset_list:
	modulename_list=getmodules(dataset)
	moduledict={}
	for modulename in modulename_list:
		parametername_list=getparameters(dataset,modulename)
		valuedict={}
		for parametername in parametername_list:
			value=getvalue(dataset, modulename, parametername)
			valuedict['value']=value
#  valuedict needs to be a dictionary because there is other stuff
			valuedict['otherstuff]=otherstuff
...
			parameterdict[parametername]=valuedict.copy()
		moduledict[modeulename]=copy.deepcopy(parameterdict)
	pdb[dataset]=copy.deepcopy(moduledict)


Now I know the 2nd is not that much more complex but this is a pretty  
common construct in what I'm doing so I'm just wondering if there is   
a clear and simple shortcut ;-)


====================================================================
Prof Garry Willgoose,
Australian Professorial Fellow in Environmental Engineering,
Director, Centre for Climate Impact Management (C2IM),
School of Engineering, The University of Newcastle,
Callaghan, 2308
Australia.

Centre webpage: www.c2im.org.au

Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574  
(Fri PM-Mon)
FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal  
and Telluric)
Env. Engg. Secretary: (International) +61 2 4921 6042

email:  garry.willgoose at newcastle.edu.au;  
g.willgoose at telluricresearch.com
email-for-life: garry.willgoose at alum.mit.edu
personal webpage: www.telluricresearch.com/garry
====================================================================
"Do not go where the path may lead, go instead where there is no path  
and leave a trail"
                           Ralph Waldo Emerson
====================================================================






From remco at gerlich.nl  Thu Jan 24 10:46:11 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 24 Jan 2008 10:46:11 +0100
Subject: [Tutor] creating a nested dictionary
In-Reply-To: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>
References: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>
Message-ID: <7ae3ca10801240146g2eeac1e9i36cade3e1b926c6e@mail.gmail.com>

Hi,

Stream of consciousness answer:

So, you want to set things in a dictionary with a statement like
d[a][b][c][d] = x,
 even though d[a] wasn't used before so it's not initialized yet (let alone
d[a][b]).

Of course, if d is a dict, the d[a] = x works. That's one level deep, and
non existing keys are just created for you. More levels is harder.

In the collections module, there is a defaultdict object. You can tell it
what to use as a default for some value if it doesn't exist yet. Other than
that, it works as a normal dict.
Say, if we do:

from collections import defaultdict
d = defaultdict(dict)

Then, if you use d[a] when it doesn't exist yet, it will call dict() to
create a new dictionary.

So now d[a][b] = x works.

But d[a][b][c] = x still doesn't, since the newly created dictionary isn't
_itself_ a default dictionary - it's a normal dict.

Instead of 'dict', we need to give defaultdict a function that takes no
arguments and returns a defaultdictionary object. Like

d = defaultdict(lambda: defaultdict(dict))

Now d[a][b][c] = x works. But, again, the last one is a dict, so we still
can't go deeper...

Now of course d = defaultdict(lambda: defaultdict(lambda:
defaultdict(dict))) is there. It solves your problem; you can now set
d[a][b][c][d] = x.

(importantly, you shouldn't mix depths; don't first set d[a][b][c] = 3 and
then try to set d[a][b][c][d]; since d[a][b][c] won't be a dictionary
anymore).

I can't think of a really good generalization, one that will work for all
depths. That's the sort of thing you use Lisp, combinators and lots of
coffee for. Perhaps later today.

For now though:

def deep_default_dict(level):
   if level < 1:
      raise ValueError()
   result = dict
   while level > 1:
      result = lambda: defaultdict(result)
      level -= 1
   return result

d = deep_default_dict(4)()

Should give a dictionary for level=1 and the appropriate defaultdict for the
number of levels you need.

But I can't test right now...

Remco


On Jan 24, 2008 8:20 AM, Garry Willgoose <garry.willgoose at newcastle.edu.au>
wrote:

> Is there any easy way to create a nested dictionary. I want to be
> able to allocate like
>
> pdb[dataset][modulename][parametername]['value']=value
>
> where dataset, modulename, parametername are variables that are
> determined within loops nested 3 deep, and value comes from a
> database call. Prior to the nested loops I do not know what the
> values of dataset, modulename, parametername will range over, but I
> do know pdb needs to be nested 3 deep. What I'd like to do is
> something like this
>
> pdb={}
> for dataset in dataset_list:
>        modulename_list=getmodules(dataset)
>        for modulename in modulename_list:
>                parametername_list=getparameters(dataset,modulename)
>                for parametername in parametername_list:
>                        value=getvalue(dataset, modulename, parametername)
>
>  pdb[dataset][modulename][parametername]['value']=value
>
> What I'm currently doing is
>
> pdb={}
> for dataset in dataset_list:
>        modulename_list=getmodules(dataset)
>        moduledict={}
>        for modulename in modulename_list:
>                parametername_list=getparameters(dataset,modulename)
>                valuedict={}
>                for parametername in parametername_list:
>                        value=getvalue(dataset, modulename, parametername)
>                        valuedict['value']=value
> #  valuedict needs to be a dictionary because there is other stuff
>                        valuedict['otherstuff]=otherstuff
> ...
>                        parameterdict[parametername]=valuedict.copy()
>                moduledict[modeulename]=copy.deepcopy(parameterdict)
>        pdb[dataset]=copy.deepcopy(moduledict)
>
>
> Now I know the 2nd is not that much more complex but this is a pretty
> common construct in what I'm doing so I'm just wondering if there is
> a clear and simple shortcut ;-)
>
>
> ====================================================================
> Prof Garry Willgoose,
> Australian Professorial Fellow in Environmental Engineering,
> Director, Centre for Climate Impact Management (C2IM),
> School of Engineering, The University of Newcastle,
> Callaghan, 2308
> Australia.
>
> Centre webpage: www.c2im.org.au
>
> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574
> (Fri PM-Mon)
> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal
> and Telluric)
> Env. Engg. Secretary: (International) +61 2 4921 6042
>
> email:  garry.willgoose at newcastle.edu.au;
> g.willgoose at telluricresearch.com
> email-for-life: garry.willgoose at alum.mit.edu
> personal webpage: www.telluricresearch.com/garry
> ====================================================================
> "Do not go where the path may lead, go instead where there is no path
> and leave a trail"
>                           Ralph Waldo Emerson
> ====================================================================
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/43dc5d4c/attachment-0001.htm 

From remco at gerlich.nl  Thu Jan 24 10:51:39 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 24 Jan 2008 10:51:39 +0100
Subject: [Tutor] creating a nested dictionary
In-Reply-To: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>
References: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>
Message-ID: <7ae3ca10801240151q65731b8bhb36e8a8cebed7f7c@mail.gmail.com>

Of course, I forgot to mention that you can use tuples as dictionary keys.

A common idiom is:

pdb[(dataset, modulename, parametername, 'value')] = value.

And if that works for you, it's much simpler. But you lose the ability to
use, say, pdb[dataset][modulename] as a dictionary on its own.

Remco


On Jan 24, 2008 8:20 AM, Garry Willgoose <garry.willgoose at newcastle.edu.au>
wrote:

> Is there any easy way to create a nested dictionary. I want to be
> able to allocate like
>
> pdb[dataset][modulename][parametername]['value']=value
>
> where dataset, modulename, parametername are variables that are
> determined within loops nested 3 deep, and value comes from a
> database call. Prior to the nested loops I do not know what the
> values of dataset, modulename, parametername will range over, but I
> do know pdb needs to be nested 3 deep. What I'd like to do is
> something like this
>
> pdb={}
> for dataset in dataset_list:
>        modulename_list=getmodules(dataset)
>        for modulename in modulename_list:
>                parametername_list=getparameters(dataset,modulename)
>                for parametername in parametername_list:
>                        value=getvalue(dataset, modulename, parametername)
>
>  pdb[dataset][modulename][parametername]['value']=value
>
> What I'm currently doing is
>
> pdb={}
> for dataset in dataset_list:
>        modulename_list=getmodules(dataset)
>        moduledict={}
>        for modulename in modulename_list:
>                parametername_list=getparameters(dataset,modulename)
>                valuedict={}
>                for parametername in parametername_list:
>                        value=getvalue(dataset, modulename, parametername)
>                        valuedict['value']=value
> #  valuedict needs to be a dictionary because there is other stuff
>                        valuedict['otherstuff]=otherstuff
> ...
>                        parameterdict[parametername]=valuedict.copy()
>                moduledict[modeulename]=copy.deepcopy(parameterdict)
>        pdb[dataset]=copy.deepcopy(moduledict)
>
>
> Now I know the 2nd is not that much more complex but this is a pretty
> common construct in what I'm doing so I'm just wondering if there is
> a clear and simple shortcut ;-)
>
>
> ====================================================================
> Prof Garry Willgoose,
> Australian Professorial Fellow in Environmental Engineering,
> Director, Centre for Climate Impact Management (C2IM),
> School of Engineering, The University of Newcastle,
> Callaghan, 2308
> Australia.
>
> Centre webpage: www.c2im.org.au
>
> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574
> (Fri PM-Mon)
> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal
> and Telluric)
> Env. Engg. Secretary: (International) +61 2 4921 6042
>
> email:  garry.willgoose at newcastle.edu.au;
> g.willgoose at telluricresearch.com
> email-for-life: garry.willgoose at alum.mit.edu
> personal webpage: www.telluricresearch.com/garry
> ====================================================================
> "Do not go where the path may lead, go instead where there is no path
> and leave a trail"
>                           Ralph Waldo Emerson
> ====================================================================
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/483b019b/attachment.htm 

From fiyawerx at gmail.com  Thu Jan 24 11:37:46 2008
From: fiyawerx at gmail.com (Fiyawerx)
Date: Thu, 24 Jan 2008 05:37:46 -0500
Subject: [Tutor] Comparing more than 2 lists
In-Reply-To: <82b4f5810801240036l5700396awe25879febcae05b2@mail.gmail.com>
References: <1b31ae500801240015s11c6f77bt6a209c97572a6abe@mail.gmail.com>
	<82b4f5810801240036l5700396awe25879febcae05b2@mail.gmail.com>
Message-ID: <1b31ae500801240237p1da76059wfe8931542352a549@mail.gmail.com>

Thanks Michael, this worked great, time to read up on collections!

On Jan 24, 2008 3:36 AM, Michael Langford <mlangford.cs03 at gtalumni.org>
wrote:

> You use a variation on bucket sort do to this:
> http://en.wikipedia.org/wiki/Bucket_sort
>
> You make a dict where the keys are the values in the lists, and a name
> for each list is in the problem.
>
> So you get something that looks like:
>
> one: list1, list2
> two: list1, list2, list3
> etc
>
> Doing this with collections.defaultdict is a breeze:
> import collections
>
> dd = collections.defaultdict(list)
> for eachlist in lists:
>   for each in eachlist:
>       dd[each].append(getListName(eachlist))
>
> Then to find the repeated elements you filter  where the list is of length
> > 1.
>
> for each in dd:
>     print "%s: %s" % (each, dd[each])
>
> I'd provide code, but I'm not sure what an appropriate naming function
> is for you, nor am I sure what you're doing with this when you're
> done.
>
>            --Michael
>
>
>
> On Jan 24, 2008 3:15 AM, Fiyawerx <fiyawerx at gmail.com> wrote:
> > I have been able to find a few articles on comparing 2 lists, but I have
> 4
> > lists that I need to compare. I need to find any repeated elements and
> the
> > list that they came from. For example,
> >
> > list1 = ['one', 'two', 'three']
> > list2 = ['one', 'two', 'four', 'five']
> > list3 = ['two', 'three', 'six', 'seven']
> > list4 = ['three', 'five', 'six']
> > https://mail.google.com/mail/#label/Pythontutor/117aadf8364dbf3b
> Gmail - [Tutor] Comparing more than 2 lists - michael.langford at gmail.com
> >
> >  I need to be able to get along the lines of output:
> > Element 'one' contained in list1 and list2
> > Element 'two' contained in list1 and list2 and list3
> > ...
> > Element 'five' contained in list2 and list4
> >
> > etc.. and I can't quite figure out how to go about it
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/feca40e7/attachment.htm 

From swartmumba at yahoo.com  Thu Jan 24 11:42:59 2008
From: swartmumba at yahoo.com (SwartMumba snake)
Date: Thu, 24 Jan 2008 02:42:59 -0800 (PST)
Subject: [Tutor] lst file
Message-ID: <136412.59532.qm@web44806.mail.sp1.yahoo.com>

Hi

I am trying to read from  a specific .lst file. When I read from it, it just prints out blank lines and I am sure that this file contains content.

This is what I am using to read from the file:

f = open("C:\\Users\\UserName\\Directory\\words.lst")

for line in f:
    print line

f.close()

Do you guys know what is wrong?

Thanks in advance.

       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/017ddbdc/attachment.htm 

From remco at gerlich.nl  Thu Jan 24 11:54:04 2008
From: remco at gerlich.nl (Remco Gerlich)
Date: Thu, 24 Jan 2008 11:54:04 +0100
Subject: [Tutor] lst file
In-Reply-To: <136412.59532.qm@web44806.mail.sp1.yahoo.com>
References: <136412.59532.qm@web44806.mail.sp1.yahoo.com>
Message-ID: <7ae3ca10801240254rea22f00pb22303d89618e6f8@mail.gmail.com>

Many things could be wrong; perhaps with reading the file, or the lines, or
with printing them... Debugging usually consists of what the problem is
exactly, where it occurs.

First thing I'd look at is seeing whether the lines do get read. I would
change "print line" into "print len(line)" and see if the lines are empty,
or filled with unprintable things.

Also, what sort of file is it?

Remco


On Jan 24, 2008 11:42 AM, SwartMumba snake <swartmumba at yahoo.com> wrote:

> Hi
>
> I am trying to read from  a specific .lst file. When I read from it, it
> just prints out blank lines and I am sure that this file contains content.
>
> This is what I am using to read from the file:
>
> f = open("C:\\Users\\UserName\\Directory\\words.lst")
>
> for line in f:
>     print line
>
> f.close()
>
> Do you guys know what is wrong?
>
> Thanks in advance.
>
> ------------------------------
> Never miss a thing. Make Yahoo your homepage.<http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/7d98c7ec/attachment.htm 

From tetsuo2k6 at web.de  Thu Jan 24 12:48:37 2008
From: tetsuo2k6 at web.de (tetsuo2k6 at web.de)
Date: Thu, 24 Jan 2008 12:48:37 +0100
Subject: [Tutor] MySQLdb for Python 2.5? (Debian related)
In-Reply-To: <82b4f5810801231224i19ec2f39q1db72dffa93b5a36@mail.gmail.com>
References: <479733F9.6090508@web.de> <47973B6E.60308@tds.net>	
	<47974470.5070005@web.de> <479748E0.3050506@tds.net>	
	<479764D8.5080307@web.de>	
	<82b4f5810801230850k12ee055fn9224977c4f37eefc@mail.gmail.com>	
	<47979BA5.9000507@web.de>
	<82b4f5810801231224i19ec2f39q1db72dffa93b5a36@mail.gmail.com>
Message-ID: <47987B15.3070203@web.de>

Michael Langford schrieb:
>> However, Debian is known for stability and security, right? I don't know
>> if I should install things without apt in a production environment, so I
>> first have to ask my guru if it's alright.
> 
> The *point* of buildout is that the entire installation is *local* to
> the application. There is no change system wide, just for the
> application that is running. This is *much* safer than using the
> system package manager. Its like running a standalone exe like putty
> on windows, versus installing a microsoft product.
> 
>        --Michael
> 

We're already considering to use the cheese shop for for all our Python 
stuff!

Again, thanks a lot for the hint!

- Paul

> 
> 
>> Michael Langford schrieb:
>>> It's a distribution issue. As far as what I've found as having cutting
>>> edge (or even reasonably fresh) python packages in your package
>>> manager is dictated by the distro, who vary wildly in this.
>>>
>>> Debian SID at times> All the Ubuntus > Debian SID at times> Fedora
>>> Core > Debian testing > Debian stable
>>>
>>> This is the #1 reason I use ubuntu on servers right now. And if the
>>> above is wrong now, these are generally feelings about a small sample
>>> set over a period of time. I really have just gone all Kubuntu/Xubuntu
>>> where I can these days.
>>>
>>> I will suggest you look into learning eggs, cheese shop and
>>> easy_install as an alternative to OS based package management for
>>> python. I was an awesome presentation by Brandon Rhodes Mill about
>>> Buildout  at PyAtl a couple weeks ago. It automagically downloads all
>>> the eggs you need. You just create a setup.py and a quick config file,
>>> and check those in with your source. When you run a command when you
>>> start developing on a checkout, it pulls down all the eggs you need to
>>> work with that checkout from the cheeshop, putting them in a project
>>> local directory, which is then prepended to the python search path for
>>> that project.
>>>
>>> This means site-packages and you don't have fights when you install on
>>> multiple system who may need other past versions of modules. Buildout
>>> also gets the right version of python on the machine ( in a local
>>> directory again ) and is compatible with system where you don't have
>>> root access.
>>>
>>> Buildout was originally written by the Zope people I believe, but has
>>> been made independent of zope so all of us non-zope people can use it.
>>>
>>>           --Michael
>>>
>>> Cheese Shop: www.python.org/pypi
>>> Monty Python Cheese Shop Skit: www.youtube.com/watch?v=B3KBuQHHKx0
>>> Buildout: www.python.org/pypi/zc.buildout
>>> More about Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
>>> PyAtl (where presumably his talk will be posted): http://pyatl.org/
>>>
>>> On Jan 23, 2008 11:01 AM,  <tetsuo2k6 at web.de> wrote:
>>>> I decided to install Python2.5 on the server machine to save me the time
>>>> for low-level debugging >;) but it doesn't find the MySQLdb module...
>>>>
>>>> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
>>>> ... What's happening here?
>>>>
>>>> I have to say that the client PC (on which my script runs fine with 2.5)
>>>> has Ubuntu installed - can it be that the MySQLdb module is behind in
>>>> Debian?
>>>>
>>>> Sorry for going off topic - if you guys don't want that here can move
>>>> the problem to the Debian list - but maybe someone here knows about the
>>>> status of the packages...?
>>>>
>>>> - Paul
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>>>
>>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 


From keridee at jayco.net  Thu Jan 24 13:45:47 2008
From: keridee at jayco.net (Tiger12506)
Date: Thu, 24 Jan 2008 07:45:47 -0500
Subject: [Tutor] [ctypes-users] calls to windll.user32
References: <20080122123047.M16491@cropwell.net> <fn7vdk$nh$1@ger.gmane.org>
	<47982C9C.6060508@telus.net>
Message-ID: <003f01c85e87$0ea63a70$18fce004@jslaptop>

> Something like this happens with Pygame and IDLE.  In Windows if you 
> right click on a Python file and choose the "Edit with IDLE" option IDLE 
> is started with a single process.  If the program is run and it does its 
> own windowing then it conflicts with Tkinter, used by IDLE.  Start IDLE 
> first, then open the file to edit.

Change the registry setting makes it easier to code in the future.

HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command
"C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1"

Take out the -n to remove the "no subprocess" option.
You should be able to use "Edit with IDLE" as expected.

From kent37 at tds.net  Thu Jan 24 14:34:06 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 24 Jan 2008 08:34:06 -0500
Subject: [Tutor] creating a nested dictionary
In-Reply-To: <7ae3ca10801240146g2eeac1e9i36cade3e1b926c6e@mail.gmail.com>
References: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>
	<7ae3ca10801240146g2eeac1e9i36cade3e1b926c6e@mail.gmail.com>
Message-ID: <479893CE.1000901@tds.net>

Remco Gerlich wrote:
> I can't think of a really good generalization, one that will work for 
> all depths. That's the sort of thing you use Lisp, combinators and lots 
> of coffee for. Perhaps later today.

Some nice solutions here:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9519c885a24a65ea/c9697fa73bb59709

Kent

From kent37 at tds.net  Thu Jan 24 14:51:38 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 24 Jan 2008 08:51:38 -0500
Subject: [Tutor] TypeError in base class __init__ after reload
In-Reply-To: <200801231948109.SM06676@66.193.33.4>
References: <200801231948109.SM06676@66.193.33.4>
Message-ID: <479897EA.1020704@tds.net>

Oops, sending to the list with this PS:
Google 'python reload' for discussion and workarounds.

Daniel Knierim wrote:
> Hello Pythonistas,
> 
> Running the script 'instantiate_and_reload.py' gives me the error 
>     TypeError: unbound method __init__() must be called with ParentClass instance as first argument (got ChildClass instance instead)

I haven't looked at your script closely enough to know exactly where the
  error is but there are some real problems with reloading modules when
you have references to objects in the module object. The module is
reloaded but the references are not automatically rebound to the new
module. In particular, names that are imported from the module will
still refer to the original module, and instances of classes from the
module will refer (via their __class__ attribute) to the original class.

The docs for reload() talk about this a little:
http://docs.python.org/lib/built-in-funcs.html#l2h-61

For example (using the cmd module just because it contains a class):
In [1]: from cmd import Cmd

Cmd is bound to the class object in the cmd module
In [2]: c=Cmd()

c is an instance of the original class

In [3]: import cmd
In [4]: cmd.Cmd is Cmd
Out[4]: True
In [5]: isinstance(c, cmd.Cmd)
Out[5]: True

cmd.Cmd, Cmd and c.__class__ all refer to the same class

In [6]: reload(cmd)
Out[6]: <module 'cmd' from
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/cmd.pyc'>
In [7]: isinstance(c, cmd.Cmd)
Out[7]: False

We now have a new class object bound to cmd.Cmd, it is not the same object!

In [8]: from cmd import Cmd
In [9]: c.__class__
Out[9]: <class cmd.Cmd at 0x10ac870>
In [10]: c.__class__ is Cmd
Out[10]: False

c.__class__ is still the old Cmd class

In [11]: Cmd is cmd.Cmd
Out[11]: True
In [12]: reload(cmd)
Out[12]: <module 'cmd' from
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/cmd.pyc'>
In [13]: Cmd is cmd.Cmd
Out[13]: False

Cmd itself has the same trouble.

Kent


From Andy.cheesman at bristol.ac.uk  Thu Jan 24 15:35:10 2008
From: Andy.cheesman at bristol.ac.uk (Andy Cheesman)
Date: Thu, 24 Jan 2008 14:35:10 +0000
Subject: [Tutor] printing format with list
Message-ID: <4798A21E.4030903@bristol.ac.uk>

Hi people

Is there a way to use a list with printf formating without having to 
explicitly expanding the list after the %

e.g

a = [1, 2, 3]

print """ Testing
                %i, %i, %i """ %(a[0], a[1], a[2])


Cheers

Andy


From mail at timgolden.me.uk  Thu Jan 24 15:42:45 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 24 Jan 2008 14:42:45 +0000
Subject: [Tutor] printing format with list
In-Reply-To: <4798A21E.4030903@bristol.ac.uk>
References: <4798A21E.4030903@bristol.ac.uk>
Message-ID: <4798A3E5.60700@timgolden.me.uk>

Andy Cheesman wrote:
> Hi people
> 
> Is there a way to use a list with printf formating without having to 
> explicitly expanding the list after the %
> 
> e.g
> 
> a = [1, 2, 3]
> 
> print """ Testing
>                 %i, %i, %i """ %(a[0], a[1], a[2])
> 

It looks as though string formatting only understands tuples,
not sequences in general:

a = [1, 2, 3]
print "Testing: %i, %i, %i" % tuple (a)

or just:

a = 1, 2, 3
print "Testing: %i, %i, %i" % a

TJG

From kent37 at tds.net  Thu Jan 24 15:47:52 2008
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 24 Jan 2008 09:47:52 -0500
Subject: [Tutor] printing format with list
In-Reply-To: <4798A21E.4030903@bristol.ac.uk>
References: <4798A21E.4030903@bristol.ac.uk>
Message-ID: <4798A518.2060006@tds.net>

Andy Cheesman wrote:
> Hi people
> 
> Is there a way to use a list with printf formating without having to 
> explicitly expanding the list after the %
> 
> e.g
> 
> a = [1, 2, 3]
> 
> print """ Testing
>                 %i, %i, %i """ %(a[0], a[1], a[2])

The argument after % must be a tuple (or a single item) so just convert 
the list to a tuple:
   print """ Testing %i, %i, %i """ % tuple(a)

or create it as a tuple to begin with if that is practical...

Kent

From prdo22002 at globemw.net  Thu Jan 24 17:23:09 2008
From: prdo22002 at globemw.net (prdo22002 at globemw.net)
Date: Thu, 24 Jan 2008 18:23:09 +0200 (CAT)
Subject: [Tutor] Tutor Digest, Vol 47, Issue 64
In-Reply-To: <mailman.69.1201172420.6388.tutor@python.org>
References: <mailman.69.1201172420.6388.tutor@python.org>
Message-ID: <1210.66.36.203.242.1201191789.squirrel@www.globemw.net>

Stop sending your mails

 Send Tutor mailing list submissions to
> 	tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request at python.org
>
> You can reach the person managing the list at
> 	tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>    1. Re: creating a nested dictionary (Remco Gerlich)
>    2. Re: Comparing more than 2 lists (Fiyawerx)
>    3. lst file (SwartMumba snake)
>    4. Re: lst file (Remco Gerlich)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Thu, 24 Jan 2008 10:51:39 +0100
> From: "Remco Gerlich" <remco at gerlich.nl>
> Subject: Re: [Tutor] creating a nested dictionary
> To: "Garry Willgoose" <garry.willgoose at newcastle.edu.au>
> Cc: tutor at python.org
> Message-ID:
> 	<7ae3ca10801240151q65731b8bhb36e8a8cebed7f7c at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> Of course, I forgot to mention that you can use tuples as dictionary keys.
>
> A common idiom is:
>
> pdb[(dataset, modulename, parametername, 'value')] = value.
>
> And if that works for you, it's much simpler. But you lose the ability to
> use, say, pdb[dataset][modulename] as a dictionary on its own.
>
> Remco
>
>
> On Jan 24, 2008 8:20 AM, Garry Willgoose
> <garry.willgoose at newcastle.edu.au>
> wrote:
>
>> Is there any easy way to create a nested dictionary. I want to be
>> able to allocate like
>>
>> pdb[dataset][modulename][parametername]['value']=value
>>
>> where dataset, modulename, parametername are variables that are
>> determined within loops nested 3 deep, and value comes from a
>> database call. Prior to the nested loops I do not know what the
>> values of dataset, modulename, parametername will range over, but I
>> do know pdb needs to be nested 3 deep. What I'd like to do is
>> something like this
>>
>> pdb={}
>> for dataset in dataset_list:
>>        modulename_list=getmodules(dataset)
>>        for modulename in modulename_list:
>>                parametername_list=getparameters(dataset,modulename)
>>                for parametername in parametername_list:
>>                        value=getvalue(dataset, modulename,
>> parametername)
>>
>>  pdb[dataset][modulename][parametername]['value']=value
>>
>> What I'm currently doing is
>>
>> pdb={}
>> for dataset in dataset_list:
>>        modulename_list=getmodules(dataset)
>>        moduledict={}
>>        for modulename in modulename_list:
>>                parametername_list=getparameters(dataset,modulename)
>>                valuedict={}
>>                for parametername in parametername_list:
>>                        value=getvalue(dataset, modulename,
>> parametername)
>>                        valuedict['value']=value
>> #  valuedict needs to be a dictionary because there is other stuff
>>                        valuedict['otherstuff]=otherstuff
>> ...
>>                        parameterdict[parametername]=valuedict.copy()
>>                moduledict[modeulename]=copy.deepcopy(parameterdict)
>>        pdb[dataset]=copy.deepcopy(moduledict)
>>
>>
>> Now I know the 2nd is not that much more complex but this is a pretty
>> common construct in what I'm doing so I'm just wondering if there is
>> a clear and simple shortcut ;-)
>>
>>
>> ====================================================================
>> Prof Garry Willgoose,
>> Australian Professorial Fellow in Environmental Engineering,
>> Director, Centre for Climate Impact Management (C2IM),
>> School of Engineering, The University of Newcastle,
>> Callaghan, 2308
>> Australia.
>>
>> Centre webpage: www.c2im.org.au
>>
>> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574
>> (Fri PM-Mon)
>> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal
>> and Telluric)
>> Env. Engg. Secretary: (International) +61 2 4921 6042
>>
>> email:  garry.willgoose at newcastle.edu.au;
>> g.willgoose at telluricresearch.com
>> email-for-life: garry.willgoose at alum.mit.edu
>> personal webpage: www.telluricresearch.com/garry
>> ====================================================================
>> "Do not go where the path may lead, go instead where there is no path
>> and leave a trail"
>>                           Ralph Waldo Emerson
>> ====================================================================
>>
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20080124/483b019b/attachment-0001.htm
>
> ------------------------------
>
> Message: 2
> Date: Thu, 24 Jan 2008 05:37:46 -0500
> From: Fiyawerx <fiyawerx at gmail.com>
> Subject: Re: [Tutor] Comparing more than 2 lists
> To: "Michael Langford" <mlangford.cs03 at gtalumni.org>, tutor at python.org
> Message-ID:
> 	<1b31ae500801240237p1da76059wfe8931542352a549 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Thanks Michael, this worked great, time to read up on collections!
>
> On Jan 24, 2008 3:36 AM, Michael Langford <mlangford.cs03 at gtalumni.org>
> wrote:
>
>> You use a variation on bucket sort do to this:
>> http://en.wikipedia.org/wiki/Bucket_sort
>>
>> You make a dict where the keys are the values in the lists, and a name
>> for each list is in the problem.
>>
>> So you get something that looks like:
>>
>> one: list1, list2
>> two: list1, list2, list3
>> etc
>>
>> Doing this with collections.defaultdict is a breeze:
>> import collections
>>
>> dd = collections.defaultdict(list)
>> for eachlist in lists:
>>   for each in eachlist:
>>       dd[each].append(getListName(eachlist))
>>
>> Then to find the repeated elements you filter  where the list is of
>> length
>> > 1.
>>
>> for each in dd:
>>     print "%s: %s" % (each, dd[each])
>>
>> I'd provide code, but I'm not sure what an appropriate naming function
>> is for you, nor am I sure what you're doing with this when you're
>> done.
>>
>>            --Michael
>>
>>
>>
>> On Jan 24, 2008 3:15 AM, Fiyawerx <fiyawerx at gmail.com> wrote:
>> > I have been able to find a few articles on comparing 2 lists, but I
>> have
>> 4
>> > lists that I need to compare. I need to find any repeated elements and
>> the
>> > list that they came from. For example,
>> >
>> > list1 = ['one', 'two', 'three']
>> > list2 = ['one', 'two', 'four', 'five']
>> > list3 = ['two', 'three', 'six', 'seven']
>> > list4 = ['three', 'five', 'six']
>> > https://mail.google.com/mail/#label/Pythontutor/117aadf8364dbf3b
>> Gmail - [Tutor] Comparing more than 2 lists - michael.langford at gmail.com
>> >
>> >  I need to be able to get along the lines of output:
>> > Element 'one' contained in list1 and list2
>> > Element 'two' contained in list1 and list2 and list3
>> > ...
>> > Element 'five' contained in list2 and list4
>> >
>> > etc.. and I can't quite figure out how to go about it
>> >
>> >
>> > _______________________________________________
>> > Tutor maillist  -  Tutor at python.org
>> > http://mail.python.org/mailman/listinfo/tutor
>> >
>> >
>>
>>
>>
>> --
>> Michael Langford
>> Phone: 404-386-0495
>> Consulting: http://www.RowdyLabs.com
>>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20080124/feca40e7/attachment-0001.htm
>
> ------------------------------
>
> Message: 3
> Date: Thu, 24 Jan 2008 02:42:59 -0800 (PST)
> From: SwartMumba snake <swartmumba at yahoo.com>
> Subject: [Tutor] lst file
> To: tutor at python.org
> Message-ID: <136412.59532.qm at web44806.mail.sp1.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi
>
> I am trying to read from  a specific .lst file. When I read from it, it
> just prints out blank lines and I am sure that this file contains content.
>
> This is what I am using to read from the file:
>
> f = open("C:\\Users\\UserName\\Directory\\words.lst")
>
> for line in f:
>     print line
>
> f.close()
>
> Do you guys know what is wrong?
>
> Thanks in advance.
>
>
> ---------------------------------
> Never miss a thing.   Make Yahoo your homepage.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20080124/017ddbdc/attachment-0001.htm
>
> ------------------------------
>
> Message: 4
> Date: Thu, 24 Jan 2008 11:54:04 +0100
> From: "Remco Gerlich" <remco at gerlich.nl>
> Subject: Re: [Tutor] lst file
> To: "SwartMumba snake" <swartmumba at yahoo.com>
> Cc: tutor at python.org
> Message-ID:
> 	<7ae3ca10801240254rea22f00pb22303d89618e6f8 at mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> Many things could be wrong; perhaps with reading the file, or the lines,
> or
> with printing them... Debugging usually consists of what the problem is
> exactly, where it occurs.
>
> First thing I'd look at is seeing whether the lines do get read. I would
> change "print line" into "print len(line)" and see if the lines are empty,
> or filled with unprintable things.
>
> Also, what sort of file is it?
>
> Remco
>
>
> On Jan 24, 2008 11:42 AM, SwartMumba snake <swartmumba at yahoo.com> wrote:
>
>> Hi
>>
>> I am trying to read from  a specific .lst file. When I read from it, it
>> just prints out blank lines and I am sure that this file contains
>> content.
>>
>> This is what I am using to read from the file:
>>
>> f = open("C:\\Users\\UserName\\Directory\\words.lst")
>>
>> for line in f:
>>     print line
>>
>> f.close()
>>
>> Do you guys know what is wrong?
>>
>> Thanks in advance.
>>
>> ------------------------------
>> Never miss a thing. Make Yahoo your
>> homepage.<http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> http://mail.python.org/pipermail/tutor/attachments/20080124/7d98c7ec/attachment-0001.htm
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 47, Issue 64
> *************************************
>



From bgailer at alum.rpi.edu  Thu Jan 24 18:52:52 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 24 Jan 2008 12:52:52 -0500
Subject: [Tutor] Tutor Digest, Vol 47, Issue 64
In-Reply-To: <1210.66.36.203.242.1201191789.squirrel@www.globemw.net>
References: <mailman.69.1201172420.6388.tutor@python.org>
	<1210.66.36.203.242.1201191789.squirrel@www.globemw.net>
Message-ID: <4798D074.1060007@alum.rpi.edu>

prdo22002 at globemw.net wrote:
> Stop sending your mails
>
>  Send Tutor mailing list submissions to
>   
>> 	tutor at python.org
>>     
Did you notice the instructions that appeared at the top of what you 
just sent?

Only you can manage your subscription.
>> To subscribe or unsubscribe via the World Wide Web, visit
>> 	http://mail.python.org/mailman/listinfo/tutor
>> or, via email, send a message with subject or body 'help' to
>> 	tutor-request at python.org
>>     


From jeg_r_dejlig at hotmail.com  Thu Jan 24 20:11:18 2008
From: jeg_r_dejlig at hotmail.com (sigurt dinesen)
Date: Thu, 24 Jan 2008 19:11:18 +0000
Subject: [Tutor] (no subject)
Message-ID: <BLU102-W27F4A4E12B7C0AB47C3B59DC380@phx.gbl>

Hi
i have been fooling around in python a bit and looked at a couple of tutorials, but something i wonder about: is it posible to make python make an output in a windows "tekstbox" for instance to make several adjustments to my network settings at once, by running a python program
and if it is, how?
_________________________________________________________________
F? styr p? dine billeder gratis med Windows Live Billedgalleri
www.windowslive.dk/billedgalleri
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/c16adf53/attachment.htm 

From ricaraoz at gmail.com  Thu Jan 24 14:20:35 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Thu, 24 Jan 2008 10:20:35 -0300
Subject: [Tutor] Projects (fwd)
In-Reply-To: <000e01c85e2e$a64c8b80$e36cfea9@jslaptop>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>	<4797E831.5080203@bigfoot.com>	<000c01c85e21$4c8c3d50$97fce004@jslaptop>	<4797F5D8.4020707@bigfoot.com>
	<000e01c85e2e$a64c8b80$e36cfea9@jslaptop>
Message-ID: <479890A3.1040305@bigfoot.com>

Tiger12506 wrote:
>> Isn't dictionary access faster than list access? Why are three lists
>> 'much more efficient'?
> 
> Oh no, no, no.  Dictionaries are faster when you are *searching through* for 
> a particular value. If you already know the index of the item in the list, 
> lists are much faster.
> 
> Dictionaries are hash based. Somewhere it has to calculate the hash of the 
> key you give it...
> These three lists are more efficient in terms of size/output ratio. It 
> appeared as if the dictionary that was presented as an example was just 
> going to map one to one all of the values from zero to 999,999 (to match my 
> list version capabilities). Not only is that bad programming style, it's 
> just plain unecessary. 

Nope, if you read the code you'll see the only mapping done is up to 20
and then by tens up to 100, that's all.
The same code could be used with a list, you'd only have to change the
exception name.


From alan.gauld at btinternet.com  Thu Jan 24 23:58:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Jan 2008 22:58:59 -0000
Subject: [Tutor] lst file
References: <136412.59532.qm@web44806.mail.sp1.yahoo.com>
Message-ID: <fnb53r$cbv$1@ger.gmane.org>


"SwartMumba snake" <swartmumba at yahoo.com> wrote

> I am trying to read from  a specific .lst file. When I read from it,
> it just prints out blank lines and I am sure that this file contains
> content.

Wjat kind of content? Have you opened it in a text editor and
looked at it? You are reading the file as text but if its binary
data it may not be printable. Or the file may reach an EOF
character before encountering any printavble characters.

> This is what I am using to read from the file:
>
> f = open("C:\\Users\\UserName\\Directory\\words.lst")
>
> for line in f:
>    print line
>
> f.close()

It should work if its a text file with printable content.

Alan G 



From eric at ericwalstad.com  Fri Jan 25 00:09:44 2008
From: eric at ericwalstad.com (Eric Walstad)
Date: Thu, 24 Jan 2008 15:09:44 -0800
Subject: [Tutor] ssh script
In-Reply-To: <15060411.post@talk.nabble.com>
References: <15038129.post@talk.nabble.com> <47978CE6.9010506@ericwalstad.com>
	<15060411.post@talk.nabble.com>
Message-ID: <47991AB8.6080803@ericwalstad.com>

Hi Washake,

Here's a sample I just whipped up from the example I found here:
<http://pexpect.svn.sourceforge.net/viewvc/pexpect/trunk/pexpect/examples/ssh_tunnel.py?revision=498&view=markup>
Note that I had to tweak the 'tunnel_command' line a bit as it was 
missing the conversion type.  This sets up a tunnel from a PostgreSQL 
server I have to my workstation.  I then use the tunnel on my 
workstation to connect to the database.

##### On the PostgreSQL server machine ('a_server') #####
# Setup a reverse forward
username at a_server:~$ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import pexpect
 >>> import getpass
 >>> import time
 >>> tunnel_command = """ssh -R5432:localhost:5432 %(user)s@%(host)s"""
 >>> host = raw_input('Hostname: ')
Hostname: 192.168.1.1
 >>> user = raw_input('Username: ')
Username: username
 >>> X = getpass.getpass('Password: ')
Password:
 >>> ssh_tunnel = pexpect.spawn(tunnel_command % globals())
 >>> ssh_tunnel.expect('password:')
 >>> time.sleep(0.1)
 >>> ssh_tunnel.sendline(X)
 >>> ssh_tunnel.expect (pexpect.EOF)
 >>>

# Now the reverse forward is set up and I can connect to the PostgreSQL
# instance running on 'a_server'
##### On the client machine: 192.168.1.1 #####
username at 192.168.1.1:~$ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import psycopg2 as Database
 >>> conn_parts = {
...     'user':'dbuser',
...     'dbname': 'mydatabase',
...     'password':'',
...     'host':'127.0.0.1',
...     'port':'5432',
...     }
 >>> cs = ' '.join(["%s=%s" % (k, v) for k, v in conn_parts.items() if v])
 >>> print cs
port=5432 host=127.0.0.1 user=dbuser dbname=mydatabase
 >>> conn = Database.connect(cs)
 >>> cur = conn.cursor()
 >>> sql = 'select count(*) from mytable'
 >>> cur.execute(sql)
 >>> records = cur.fetchall()
 >>> conn.close()
 >>>
 >>> print records
[(557L,)]
 >>>


washakie wrote:
> Thanks everyone these seem like promising directions to go... Eric, any
> chance you could share your 'similar' code? The problem it seems with
> paramiko is that it has little 'newbie' documentation, and I'm not clear how
> to set up the reverse port forwarding on it. Thus I may need to use the
> pexpect solution. 
> 


From alan.gauld at btinternet.com  Fri Jan 25 00:14:28 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Jan 2008 23:14:28 -0000
Subject: [Tutor] Comparing more than 2 lists
References: <1b31ae500801240015s11c6f77bt6a209c97572a6abe@mail.gmail.com>
Message-ID: <fnb60s$fsl$1@ger.gmane.org>


"Fiyawerx" <fiyawerx at gmail.com> wrote 

> list1 = ['one', 'two', 'three']
> list2 = ['one', 'two', 'four', 'five']
> list3 = ['two', 'three', 'six', 'seven']
> list4 = ['three', 'five', 'six']
> 
> I need to be able to get along the lines of output:
> Element 'one' contained in list1 and list2
> Element 'two' contained in list1 and list2 and list3
> ...
> Element 'five' contained in list2 and list4
> 
> etc.. and I can't quite figure out how to go about it

There are lots of approaches, one of the easest is to 
use a dictionary keyed by the elements of the lists 
and the values the identity of the list in which it 
appears:

d = {}
for n, lst in enumerate([list1,list2,list3,list4[):
   for item in lst:
       d.setdefault(item,[]).append(n)

Gets close

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 
    




From trs164 at hotmail.com  Fri Jan 25 01:38:13 2008
From: trs164 at hotmail.com (Timothy Sikes)
Date: Thu, 24 Jan 2008 18:38:13 -0600
Subject: [Tutor] Dos and os.walk with Python
Message-ID: <BAY140-W3111D7EBC2968FA56EF3A89390@phx.gbl>

Hi.    I wrote a python script that goes through a specified directory and returns a list of all the files that haven't been modified since a certain date.  I was hoping to be able to then continue with the program to bring up dos, and zip, then move the files (to my external hard drive). I have Windows XP. I don't know if it's okay to ask about Dos in python mailing list, so I hope it's alright.  Here is my program, I don't know if there are any formatting rules for posting programs, so I hope this will sufice.import os, sys, timedef earlierThan (path, year, exclude=[]):    all = []    walk = os.walk(path)    for root, dirs, files in walk:        for i in files:            try:                if (time.localtime(os.path.getmtime(root + "\\" + i))[0] < year                and doesNotHave(exclude, root)) :                    all.append(root + "\\" + i)            except OSError:  #I think that I might need a more specific error message, as this one would handle something
                                   #That's not necessarily a broken file name. (I got one of them when I ran it).                print root + "\\" + i + " was not included in the list"    return all
def doesNotHave(exclude, root):    for x in exclude:        if root.startswith(x) > -1:            return False    return TrueI've had little experience with dos.  I believe I should use the COMPACT, and then the MOVE dos command... Would it go something like this?g = earlierThan("G:\My Documents", 2007, ["Music"])for x in g:
     os.system("COMPACT /F " + x)
     os.sytem("MOVE " + x + " " + "H:\Backup")Thanks
_________________________________________________________________
Need to know the score, the latest news, or you need your Hotmail?-get your "fix".
http://www.msnmobilefix.com/Default.aspx
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/3a253b10/attachment.htm 

From trs164 at hotmail.com  Fri Jan 25 01:55:41 2008
From: trs164 at hotmail.com (Timothy Sikes)
Date: Thu, 24 Jan 2008 18:55:41 -0600
Subject: [Tutor] Forgot something...
In-Reply-To: <82b4f5810801091444l1b93c84dla85a4fa57ca9325a@mail.gmail.com>
References: <BAY140-W3070F8E0B4AFEBCA8BCB4F89490@phx.gbl>
	<82b4f5810801091444l1b93c84dla85a4fa57ca9325a@mail.gmail.com>
Message-ID: <BAY140-W181CAF8377E80235934C8889390@phx.gbl>

Sorry, but in my previous message, I realized that I hadn't changed the code from doesNotHave...  It's supposed to be x.find(), not x.startswith......Oh, and I also am not worried about messing up any files too much, because I have them all backed up on another computer already....
_________________________________________________________________
Helping your favorite cause is as easy as instant messaging.?You IM, we give.
http://im.live.com/Messenger/IM/Home/?source=text_hotmail_join
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/51b0f68b/attachment.htm 

From alan.gauld at btinternet.com  Fri Jan 25 02:11:00 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jan 2008 01:11:00 -0000
Subject: [Tutor] Dos and os.walk with Python
References: <BAY140-W3111D7EBC2968FA56EF3A89390@phx.gbl>
Message-ID: <fnbcrb$4ae$1@ger.gmane.org>


"Timothy Sikes" <trs164 at hotmail.com> wrote

>  I don't know if it's okay to ask about Dos in python mailing list,

If its related to programming in python as well its fine :-)

> I don't know if there are any formatting rules for posting programs

It helps if we can see the formatting, especially since Python
relies on  layout. This was just a mess on my screen!

I've tried to sort it out...

---------------------------------------
import os, sys, time

def earlierThan (path, year, exclude=[]):
    all = []
    walk = os.walk(path)
    for root, dirs, files in walk:
        for i in files:
            try:
                if (time.localtime(os.path.getmtime(root + "\\" + 
i))[0] < year
                    and doesNotHave(exclude, root)) :
                    all.append(root + "\\" + i)
            except OSError:
                 #I think that I might need a more specific error 
message,
                 #as this one would handle something
                 #That's not necessarily a broken file name. (I got 
one of them when I ran it).
                 print root + "\\" + i + " was not included in the 
list"
    return all

def doesNotHave(exclude, root):
    for x in exclude:
        if root.startswith(x) > -1:
            return False
    return True
----------------------------------------------

That last function is a little odd. startswith already returns
a boolean so comparing to -1 is weird. I'm not sure what
you think it will do.

Consider:

>>> 'fred'.startswith('x')
False
>>> 'fred'.startswith('x') > -1
True
>>> 'fred'.startswith('f') > -1
True
>>>

I'm not sure when it would ever fail the test so I think your
function will nearly always return False.

> I've had little experience with dos.  I believe I should use the
> COMPACT, and then the MOVE dos command... Would
> it go something like this?

You could use these but you'd be better just using Python
to do it via the shutil and os modules and avoid the DOS
commands completely IMHO.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From trs164 at hotmail.com  Fri Jan 25 02:28:18 2008
From: trs164 at hotmail.com (Timothy Sikes)
Date: Thu, 24 Jan 2008 19:28:18 -0600
Subject: [Tutor] Dos and os.walk with Python
In-Reply-To: <mailman.4550.1201223353.894.tutor@python.org>
References: <mailman.4550.1201223353.894.tutor@python.org>
Message-ID: <BAY140-W3904937C94006976EE02489390@phx.gbl>

I'm getting the "Digest" version of the mailing list, if there's any better way to respond to a specific message, I would like to know. thanks :>



> From: tutor-request at python.org> Subject: Tutor Digest, Vol 47, Issue 66> To: tutor at python.org> Date: Fri, 25 Jan 2008 02:09:13 +0100> > ------------------------------> > Message: 9> Date: Fri, 25 Jan 2008 01:11:00 -0000> From: "Alan Gauld" <alan.gauld at btinternet.com>> Subject: Re: [Tutor] Dos and os.walk with Python> To: tutor at python.org> Message-ID: <fnbcrb$4ae$1 at ger.gmane.org>> Content-Type: text/plain; format=flowed; charset="iso-8859-1";> reply-type=original> > > "Timothy Sikes" <trs164 at hotmail.com> wrote> > > I don't know if it's okay to ask about Dos in python mailing list,> > If its related to programming in python as well its fine :-)> > > I don't know if there are any formatting rules for posting programs> > It helps if we can see the formatting, especially since Python> relies on layout. This was just a mess on my screen!> > I've tried to sort it out...
 
I can't seem to figure out how to make hotmail keep those spaces and new lines.....   ah oh well
> > ---------------------------------------> import os, sys, time> > def earlierThan (path, year, exclude=[]):> all = []> walk = os.walk(path)> for root, dirs, files in walk:> for i in files:> try:> if (time.localtime(os.path.getmtime(root + "\\" + > i))[0] < year> and doesNotHave(exclude, root)) :> all.append(root + "\\" + i)> except OSError:> #I think that I might need a more specific error > message,> #as this one would handle something> #That's not necessarily a broken file name. (I got > one of them when I ran it).> print root + "\\" + i + " was not included in the > list"> return all> > def doesNotHave(exclude, root):> for x in exclude:> if root.startswith(x) > -1:> return False> return True> ----------------------------------------------> > That last function is a little odd. startswith already returns> a boolean so comparing to -1 is weird. I'm not sure what> you think it will do.
 
yeah, I meant to have it as .find()
> > Consider:> > >>> 'fred'.startswith('x')> False> >>> 'fred'.startswith('x') > -1> True> >>> 'fred'.startswith('f') > -1> True> >>>> > I'm not sure when it would ever fail the test so I think your> function will nearly always return False.> > > I've had little experience with dos. I believe I should use the> > COMPACT, and then the MOVE dos command... Would> > it go something like this?> > You could use these but you'd be better just using Python> to do it via the shutil and os modules and avoid the DOS> commands completely IMHO.> 
 
Okay, I've found the move command from the shutil module,  but I don't see one that compressess files...  Are there some? or am I just not seeing them...thanks.> HTH,> > > -- > Alan Gauld> Author of the Learn to Program web site> http://www.freenetpages.co.uk/hp/alan.gauld > > > > > ------------------------------> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor> > > End of Tutor Digest, Vol 47, Issue 66> *************************************
_________________________________________________________________
Helping your favorite cause is as easy as instant messaging.?You IM, we give.
http://im.live.com/Messenger/IM/Home/?source=text_hotmail_join
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/9ad2b6a9/attachment.htm 

From kpsingh at gmail.com  Fri Jan 25 02:38:54 2008
From: kpsingh at gmail.com (Kamal)
Date: Thu, 24 Jan 2008 17:38:54 -0800
Subject: [Tutor] Error connecting to MySQL from Python script
Message-ID: <333eea650801241738p1079174v6c16fee55b2ecb7d@mail.gmail.com>

I have the MySQL Server (5.0.51) running on Windows XP machine, when I try
to connect to this server with a Python script, it gives the below error.
Wondering why is it happening?

_mysql_exceptions.Operational
Error: (1251, 'Client does not support authentication protocol requested by
server; consider upgrading MySQL client')

-- 
Thanks,
Kamal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/8e3b70b2/attachment.htm 

From marc.tompkins at gmail.com  Fri Jan 25 03:16:11 2008
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 24 Jan 2008 18:16:11 -0800
Subject: [Tutor] Dos and os.walk with Python
In-Reply-To: <BAY140-W3904937C94006976EE02489390@phx.gbl>
References: <mailman.4550.1201223353.894.tutor@python.org>
	<BAY140-W3904937C94006976EE02489390@phx.gbl>
Message-ID: <40af687b0801241816n5f47efb4w90fea6f25cc07bbe@mail.gmail.com>

On Jan 24, 2008 5:28 PM, Timothy Sikes <trs164 at hotmail.com> wrote:

> I'm getting the "Digest" version of the mailing list, if there's any
> better way to respond to a specific message, I would like to know. thanks :>
>

I also originally signed up for the digest - it drove me up the wall, so I
subscribed to the regular feed instead.  Lots more individual messages, but
I have them filtered into a separate folder.  Much, much easier to write
replies this way.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/28c40a69/attachment.htm 

From keridee at jayco.net  Fri Jan 25 04:01:03 2008
From: keridee at jayco.net (Tiger12506)
Date: Thu, 24 Jan 2008 22:01:03 -0500
Subject: [Tutor] Projects (fwd)
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>	<4797E831.5080203@bigfoot.com>	<000c01c85e21$4c8c3d50$97fce004@jslaptop>	<4797F5D8.4020707@bigfoot.com>
	<000e01c85e2e$a64c8b80$e36cfea9@jslaptop>
	<479890A3.1040305@bigfoot.com>
Message-ID: <002001c85efe$8c5628a0$e36cfea9@jslaptop>

> Nope, if you read the code you'll see the only mapping done is up to 20
> and then by tens up to 100, that's all.
> The same code could be used with a list, you'd only have to change the
> exception name.

I see. There were "..." in between each of the tens entries which I took to 
mean that "big huge dictionary but left out some values in email for 
simplicity". I feel ashamed for not recognizing that the ellipses where 
there for some other purpose. ;-)

Anyway, beyond speed-up you might be able to get some better memory usage 
stats by switching my lists to tuples, since the contents never change. 


From keridee at jayco.net  Fri Jan 25 04:10:25 2008
From: keridee at jayco.net (Tiger12506)
Date: Thu, 24 Jan 2008 22:10:25 -0500
Subject: [Tutor] (no subject)
References: <BLU102-W27F4A4E12B7C0AB47C3B59DC380@phx.gbl>
Message-ID: <008d01c85eff$d8264fc0$e36cfea9@jslaptop>

>Hi
>i have been fooling around in python a bit and looked at a couple of 
>tutorials, but something i >wonder about: is it posible to make python make 
>an output in a windows "tekstbox" for >instance to make several adjustments 
>to my network settings at once, by running a python >program
>and if it is, how?

Python is powerful. Mostly likely python can do anything you dream up.

"tekstbox" must mean "textbox" which in Windows is called an Edit control.
Since I assume you mean to put text in a control that is already open before 
you run your program, the answer is yes it is possible. Easier is the next 
option.

Several adjustments to your network settings... The best way to do this to 
find the registry entries that those network settings actually change and 
change them directly in python. How do you find those registry settings? 
Google. How do you change them? Look at _winreg module. 


From keridee at jayco.net  Fri Jan 25 04:17:47 2008
From: keridee at jayco.net (Tiger12506)
Date: Thu, 24 Jan 2008 22:17:47 -0500
Subject: [Tutor] Dos and os.walk with Python
References: <BAY140-W3111D7EBC2968FA56EF3A89390@phx.gbl>
	<fnbcrb$4ae$1@ger.gmane.org>
Message-ID: <00d701c85f00$dfcc0e30$e36cfea9@jslaptop>

>> I've had little experience with dos.  I believe I should use the
>> COMPACT, and then the MOVE dos command... Would
>> it go something like this?
>
> You could use these but you'd be better just using Python
> to do it via the shutil and os modules and avoid the DOS
> commands completely IMHO.

Python has the zipfile module which is very handy to use, which wasn't 
mentioned but provides the zip functionality that the OP was looking for. 


From jeffpeery at yahoo.com  Fri Jan 25 07:41:00 2008
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Thu, 24 Jan 2008 22:41:00 -0800 (PST)
Subject: [Tutor] setstate trouble when unpickling
Message-ID: <576766.42314.qm@web43135.mail.sp1.yahoo.com>

Hello,
   
  I've got a fairly simple class instance that I'm pickling. I'm using setstate to update the instance when I unpickle. Although the setstate doesn't seem to be called upon unpickling... here's an example, if anyone see's what I'm doing wrong, please let me know. Thanks!
   
  so I say start out with this class:
   
  class dog:
      def __init__(self):
          self.num_legs = 4
   
  then I pickle the instance of:
  sparky = dog()
   
  then I update my dog class to:
  class dog:
      def __init__(self):
          self.hair_color = 'brown'
          self.num_legs = 4
   
      def __setstate__(self, d):
          if 'hair_color' not in d:
              d['hair_color'] = 'brown'
          self.__dict__.update(d)
          print 'did this work?'
   
  Now when I unpickle the original pickled object sparky I would hope to see 'did this work' and I would also hope that sparky would have updated to have the attribute 'hair_color' but nothing of the sort happens. if just unpickles sparky without updating the attributes as I was hoping.
   
  Thanks!
   
  Jeff



       
---------------------------------
Never miss a thing.   Make Yahoo your homepage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080124/dc7580bd/attachment.htm 

From alan.gauld at btinternet.com  Fri Jan 25 08:36:21 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Jan 2008 07:36:21 -0000
Subject: [Tutor] Dos and os.walk with Python
References: <mailman.4550.1201223353.894.tutor@python.org>
	<BAY140-W3904937C94006976EE02489390@phx.gbl>
Message-ID: <fnc3ds$qbb$1@ger.gmane.org>


"Timothy Sikes" <trs164 at hotmail.com> wrote 

> I'm getting the "Digest" version of the mailing list, 
> if there's any better way to respond to a specific message, 
> I would like to know. thanks :>

I used to use the digest before switching to the gmane news feed.

I seem to recall there are two digest settings.
One sends all the messages in one long message 
the other sends all the messages as attachments.
The second method makes replying easier. 
I think its called Mime style?

But its been a while...

Alan G.


From khan.s.firoze at gmail.com  Fri Jan 25 09:37:22 2008
From: khan.s.firoze at gmail.com (Firoze Khan)
Date: Fri, 25 Jan 2008 14:07:22 +0530
Subject: [Tutor] Hi
Message-ID: <9404a3db0801250037u6172aad6x81081e51168f00b3@mail.gmail.com>

Hi,
  I want Tutors mailing List
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080125/4672b96f/attachment.htm 

From ricaraoz at gmail.com  Fri Jan 25 10:51:55 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 25 Jan 2008 06:51:55 -0300
Subject: [Tutor] Projects (fwd)
In-Reply-To: <002001c85efe$8c5628a0$e36cfea9@jslaptop>
References: <Pine.LNX.4.63.0801231850410.29719@cs.wpi.edu>	<4797E831.5080203@bigfoot.com>	<000c01c85e21$4c8c3d50$97fce004@jslaptop>	<4797F5D8.4020707@bigfoot.com>	<000e01c85e2e$a64c8b80$e36cfea9@jslaptop>	<479890A3.1040305@bigfoot.com>
	<002001c85efe$8c5628a0$e36cfea9@jslaptop>
Message-ID: <4799B13B.7010904@bigfoot.com>

Tiger12506 wrote:
>> Nope, if you read the code you'll see the only mapping done is up to 20
>> and then by tens up to 100, that's all.
>> The same code could be used with a list, you'd only have to change the
>> exception name.
> 
> I see. There were "..." in between each of the tens entries which I took to 
> mean that "big huge dictionary but left out some values in email for 
> simplicity". I feel ashamed for not recognizing that the ellipses where 
> there for some other purpose. ;-)
> 

Checked my mail and yes, it was not outright clear what I meant in the
dictionary, sorry. Anyway if you check the rest of the code you'll see
it works as I said and you don't use the intermediate values between the
tens. As usual I learned something from the exercise, I thought that
indexed access would be faster than list access, didn't think lists
where implemented as C arrays (because they have no fixed size), now I
can see tuples will be faster and will save memory because memory will
not have to be reserved in chunks.


From kent37 at tds.net  Fri Jan 25 12:36:37 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 06:36:37 -0500
Subject: [Tutor] Dos and os.walk with Python
In-Reply-To: <BAY140-W3904937C94006976EE02489390@phx.gbl>
References: <mailman.4550.1201223353.894.tutor@python.org>
	<BAY140-W3904937C94006976EE02489390@phx.gbl>
Message-ID: <4799C9C5.1070109@tds.net>

Timothy Sikes wrote:
> I can't seem to figure out how to make hotmail keep those spaces and new 
> lines.....   ah oh well

You are sending HTML mail. If you can configure hotmail to send plain 
text that is preferable.

Kent


From kent37 at tds.net  Fri Jan 25 12:49:31 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 06:49:31 -0500
Subject: [Tutor] Forgot something...
In-Reply-To: <BAY140-W181CAF8377E80235934C8889390@phx.gbl>
References: <BAY140-W3070F8E0B4AFEBCA8BCB4F89490@phx.gbl>	<82b4f5810801091444l1b93c84dla85a4fa57ca9325a@mail.gmail.com>
	<BAY140-W181CAF8377E80235934C8889390@phx.gbl>
Message-ID: <4799CCCB.2030107@tds.net>

Timothy Sikes wrote:
> Sorry, but in my previous message, I realized that I hadn't changed the 
> code from doesNotHave...  It's supposed to be x.find(), not 
> x.startswith......

You meant to write:

def doesNotHave(exclude, root):
     for x in exclude:
         if root.find(x) > -1:
             return False
     return True

This can be written as
def doesNotHave(exclude, root):
     for x in exclude:
         if x in root:
             return False
     return True

or

def doesNotHave(exclude, root):
     return not any(x in root for x in exclude)

Kent

From kent37 at tds.net  Fri Jan 25 12:50:43 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 06:50:43 -0500
Subject: [Tutor] Error connecting to MySQL from Python script
In-Reply-To: <333eea650801241738p1079174v6c16fee55b2ecb7d@mail.gmail.com>
References: <333eea650801241738p1079174v6c16fee55b2ecb7d@mail.gmail.com>
Message-ID: <4799CD13.7050109@tds.net>

Kamal wrote:
> I have the MySQL Server (5.0.51) running on Windows XP machine, when I 
> try to connect to this server with a Python script, it gives the below 
> error. Wondering why is it happening?
> 
> _mysql_exceptions.Operational
> Error: (1251, 'Client does not support authentication protocol requested 
> by server; consider upgrading MySQL client')

What version of what client are you using? Have you considered upgrading it?

Kent

From kent37 at tds.net  Fri Jan 25 12:56:44 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 06:56:44 -0500
Subject: [Tutor] setstate trouble when unpickling
In-Reply-To: <576766.42314.qm@web43135.mail.sp1.yahoo.com>
References: <576766.42314.qm@web43135.mail.sp1.yahoo.com>
Message-ID: <4799CE7C.2070609@tds.net>

Jeff Peery wrote:
> Hello,
>  
> I've got a fairly simple class instance that I'm pickling. I'm using 
> setstate to update the instance when I unpickle. Although the setstate 
> doesn't seem to be called upon unpickling... here's an example, if 
> anyone see's what I'm doing wrong, please let me know. Thanks!
>  
> so I say start out with this class:
>  
> class dog:
>     def __init__(self):
>         self.num_legs = 4
>  
> then I pickle the instance of:
> sparky = dog()
>  
> then I update my dog class to:
> class dog:
>     def __init__(self):
>         self.hair_color = 'brown'
>         self.num_legs = 4
>  
>     def __setstate__(self, d):
>         if 'hair_color' not in d:
>             d['hair_color'] = 'brown'
>         self.__dict__.update(d)
>         print 'did this work?'
>  
> Now when I unpickle the original pickled object sparky I would hope to 
> see 'did this work' and I would also hope that sparky would have updated 
> to have the attribute 'hair_color' but nothing of the sort happens. if 
> just unpickles sparky without updating the attributes as I was hoping.

Are you sure the unpickle program is getting the new definition of dog? 
Can you show more code and tell us how you are running it?

This does what you expect, when run in a single program:

import pickle

class dog:
     def __init__(self):
         self.num_legs = 4

sparky = dog()
p = pickle.dumps(sparky)

class dog:
     def __init__(self):
         self.hair_color = 'brown'
         self.num_legs = 4

     def __setstate__(self, d):
         if 'hair_color' not in d:
             d['hair_color'] = 'brown'
         self.__dict__.update(d)
         print 'did this work?'

sparky2 = pickle.loads(p)
print sparky2.hair_color


prints:
did this work?
brown

Kent

From kent37 at tds.net  Fri Jan 25 12:57:11 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 06:57:11 -0500
Subject: [Tutor] Hi
In-Reply-To: <9404a3db0801250037u6172aad6x81081e51168f00b3@mail.gmail.com>
References: <9404a3db0801250037u6172aad6x81081e51168f00b3@mail.gmail.com>
Message-ID: <4799CE97.60903@tds.net>

Firoze Khan wrote:
> Hi,
>   I want Tutors mailing List

You seem to have found it.

Kent

From meanburrito920 at yahoo.com  Fri Jan 25 18:49:43 2008
From: meanburrito920 at yahoo.com (John Gunderman)
Date: Fri, 25 Jan 2008 09:49:43 -0800 (PST)
Subject: [Tutor] namespaces and the __dict__ function?
Message-ID: <776841.80732.qm@web56309.mail.re3.yahoo.com>

I am new to python and have found both the concept of namespaces and the __dict__ function to be rather confusing, and I cant find any good explanations on the web. Could any of you give me a good explanation of these? And for __dict__, is is the same thing as __str__ except in string form, or does it store all current objects of that class in a __dict__?

John




      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080125/74b6c12c/attachment.htm 

From kent37 at tds.net  Fri Jan 25 20:15:22 2008
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 25 Jan 2008 14:15:22 -0500
Subject: [Tutor] namespaces and the __dict__ function?
In-Reply-To: <776841.80732.qm@web56309.mail.re3.yahoo.com>
References: <776841.80732.qm@web56309.mail.re3.yahoo.com>
Message-ID: <479A354A.8040706@tds.net>

John Gunderman wrote:
> I am new to python and have found both the concept of namespaces and the 
> __dict__ function to be rather confusing, and I cant find any good 
> explanations on the web. Could any of you give me a good explanation of 
> these? And for __dict__, is is the same thing as __str__ except in 
> string form, or does it store all current objects of that class in a 
> __dict__?

First, __dict__ is an attribute of an object whose value is a dict, not 
a function.

A namespace is a place where names can be defined. The official tutorial 
says,
A namespace is a mapping from names to objects. Most namespaces are 
currently implemented as Python dictionaries... Examples of namespaces 
are: the set of built-in names (functions such as abs(), and built-in 
exception names); the global names in a module; and the local names in a 
function invocation. In a sense the set of attributes of an object also 
form a namespace.

http://docs.python.org/tut/node11.html#SECTION0011200000000000000000

Another way to think of it is, a namespace is a place where names are 
looked up. When you use a bare name (not an attribute), it is looked up 
in the local namespace, then the global namespace, then the built-in 
namespace. For example:

y = 2	# Defines y in the global (module) namespace

def f():
   x = 1 # Defines x in the local (function) namespace

   # This looks up x, finds it in the local namespace
   # looks up abs, finds it in the built-in namespace
   print abs(x)

   # This looks up y, finds it in the global namespace
   print y

Note that none of the above namespaces have a related __dict__ 
attribute, the namespace mappings are not stored that way.

Objects also define a sort of namespace, where attributes are defined 
and looked up. The dict containing the namespace of an object is itself 
stored as an attribute of the object, called __dict__. So __dict__ is an 
implementation detail of the way object attributes are stored.

As a beginner, it is important to understand the way bare names are 
looked up (local, global, built-in namespace) and a bit about the way 
attributes work. You don't have to be concerned with the implementation 
details such as __dict__.

(For completeness, I will say that the full attribute lookup model is 
much more complicated than I have indicated above. I have simplified to 
focus on __dict__.)

Kent

From bgailer at alum.rpi.edu  Fri Jan 25 20:26:01 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Fri, 25 Jan 2008 14:26:01 -0500
Subject: [Tutor] Hi
In-Reply-To: <9404a3db0801250037u6172aad6x81081e51168f00b3@mail.gmail.com>
References: <9404a3db0801250037u6172aad6x81081e51168f00b3@mail.gmail.com>
Message-ID: <479A37C9.5070808@alum.rpi.edu>

Firoze Khan wrote:
> Hi,
>   I want Tutors mailing List
If you want to subscribe visit:

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



From bsnipes at snipes.org  Fri Jan 25 22:39:38 2008
From: bsnipes at snipes.org (bsnipes)
Date: Fri, 25 Jan 2008 13:39:38 -0800 (PST)
Subject: [Tutor] Dos and os.walk with Python
In-Reply-To: <BAY140-W3904937C94006976EE02489390@phx.gbl>
References: <BAY140-W3111D7EBC2968FA56EF3A89390@phx.gbl>
	<BAY140-W3904937C94006976EE02489390@phx.gbl>
Message-ID: <15097304.post@talk.nabble.com>




Timothy Sikes wrote:
> 
> I'm getting the "Digest" version of the mailing list, if there's any
> better way to respond to a specific message, I would like to know. thanks
> :>
> 
> 

I use Nabble ( http://www.nabble.com ).  Great interface, multiple lists,
tag messages, you can control list options, etc.  all from one interface.  I
just set it to never send emails and read and reply from the Nabble page
itself.

Brian
-- 
View this message in context: http://www.nabble.com/Dos-and-os.walk-with-Python-tp15078734p15097304.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From trs164 at hotmail.com  Sat Jan 26 22:57:49 2008
From: trs164 at hotmail.com (Timothy Sikes)
Date: Sat, 26 Jan 2008 15:57:49 -0600
Subject: [Tutor] IronPython, the wii remote, and blender
Message-ID: <BAY140-W32070429A44977AE1761D3893A0@phx.gbl>



Well, I was playing my Wii the other day and then sat down to mess around on blender. Then I had an idea! What if the Wii remote could be used as an input device for blender? It would be great for 3d modeling, and you could always switch back to a mouse and keyboard for more precise control.

So my next thought was.... Is it possible? Obviously it would be somehow, but whether it would be feasible or not for me I had to research.  I remebered that they have a wii remote library for vb.net and C#(http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx), and IronPython is a .net framework.   Would it be fairly easy to convert their code to work with IronPython?  After that is working, I would might need some help from someone who already knows the blender source, or who can write externals for it fairly well. 

Basically, is it feasible to do the above?  If I decide to carry this project out, it would take a lot of planning.  Is there anyone out there willing to help?

Oh, and if this is just a crazy idea, please tell me so. => (I got this message in plain text this time!)
_________________________________________________________________
Shed those extra pounds with MSN and The Biggest Loser!
http://biggestloser.msn.com/

From rabidpoobear at gmail.com  Sat Jan 26 23:12:11 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 26 Jan 2008 16:12:11 -0600
Subject: [Tutor] IronPython, the wii remote, and blender
In-Reply-To: <BAY140-W32070429A44977AE1761D3893A0@phx.gbl>
References: <BAY140-W32070429A44977AE1761D3893A0@phx.gbl>
Message-ID: <479BB03B.9070303@gmail.com>

Timothy Sikes wrote:
> Well, I was playing my Wii the other day and then sat down to mess around on blender. Then I had an idea! What if the Wii remote could be used as an input device for blender? It would be great for 3d modeling, and you could always switch back to a mouse and keyboard for more precise control.
>
> So my next thought was.... Is it possible? Obviously it would be somehow, but whether it would be feasible or not for me I had to research.  I remebered that they have a wii remote library for vb.net and C#(http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx), and IronPython is a .net framework.   Would it be fairly easy to convert their code to work with IronPython?  After that is working, I would might need some help from someone who already knows the blender source, or who can write externals for it fairly well. 
>   
Gary Bishop is working on a ctypes wrapper for wiiuse, a lightweight 
single-threaded non-blocking wii remote input application.  Thus you can 
use it in normal cpython.
If you really wanted to use .NET, you might need to do something else, 
but if you use cpython you're set.  This also makes your application 
cross-platform, since wiiuse, blender and cpython are all cross-platform 
(and .NET is not.)


> Basically, is it feasible to do the above?  If I decide to carry this project out, it would take a lot of planning.  Is there anyone out there willing to help?
>   
The wii remote side of it is simple.  The blender part would be the 
difficult thing.
What you need to realize is that the wii remote only contains 
accelerometers, not gyroscopes.  As such, the way you tell how the wii 
remote is tilted is by the acceleration of gravity on the axes.  So if 
it's perfectly upright, you'll have -1g in Z, 0 in X, and 0 in Y.  If 
it's upside down, you'll have 0g,0g,1g.  if it's on its right side, 
you'll have 0g,1g,0g.

Because of this aspect of the remote's operation, you can get pitch 
(tilt forward/back) and roll (tilt left/right), but you can't get yaw.
Yaw is the action of rotating the remote horizontally around  the origin 
(the location of the accelerometers.)  In this case, the only 
accelerations that are added are X and Y, but gravity stays consistent 
at -1g on Z.  since gravity is not moving around on the axes, there's no 
way for you to detect this change.

So if you think you can do 3D modeling with just pitch and roll, and 
maybe a sensor bar for distance estimates, you could.
Or you can try what a grad student researcher did: use a custom-shaped 
sensor bar (4 LEDs) so you can determine exact 3D positioning.  You have 
to use kalman filters to estimate your position based on accelerometer 
data while the LEDs aren't visible.
> Oh, and if this is just a crazy idea, please tell me so. 
It's not crazy, it just requires some advanced knowledge about physics 
and 3d positioning.
-Luke


From michael.langford at rowdylabs.com  Sat Jan 26 23:15:14 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Sat, 26 Jan 2008 17:15:14 -0500
Subject: [Tutor] IronPython, the wii remote, and blender
In-Reply-To: <BAY140-W32070429A44977AE1761D3893A0@phx.gbl>
References: <BAY140-W32070429A44977AE1761D3893A0@phx.gbl>
Message-ID: <82b4f5810801261415o3a478cf6ga8a5061c45abf9c0@mail.gmail.com>

Yes it is possible. Checkout pybluez, its a pretty easy to use
bluetooth toolkit. Looks like these guys have a lower level driver
needed to get the wiimote going

http://www.wiindows.org/index.php/WMD#Introduction

On Jan 26, 2008 4:57 PM, Timothy Sikes <trs164 at hotmail.com> wrote:
>
>
> Well, I was playing my Wii the other day and then sat down to mess around on blender. Then I had an idea! What if the Wii remote could be used as an input device for blender? It would be great for 3d modeling, and you could always switch back to a mouse and keyboard for more precise control.
>
> So my next thought was.... Is it possible? Obviously it would be somehow, but whether it would be feasible or not for me I had to research.  I remebered that they have a wii remote library for vb.net and C#(http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx), and IronPython is a .net framework.   Would it be fairly easy to convert their code to work with IronPython?  After that is working, I would might need some help from someone who already knows the blender source, or who can write externals for it fairly well.
>
> Basically, is it feasible to do the above?  If I decide to carry this project out, it would take a lot of planning.  Is there anyone out there willing to help?
>
> Oh, and if this is just a crazy idea, please tell me so. => (I got this message in plain text this time!)
> _________________________________________________________________
> Shed those extra pounds with MSN and The Biggest Loser!
> http://biggestloser.msn.com/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From dineshbvadhia at hotmail.com  Sun Jan 27 07:40:45 2008
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Sat, 26 Jan 2008 22:40:45 -0800
Subject: [Tutor] An -1.#IND error
Message-ID: <BAY109-DAV13F6273D2E8152FBF51684A33B0@phx.gbl>

After a matrix*vector multiplication (ie. b = Ax, with A, x and b all floats), the b vector elements are all "-1.#IND".  What does this mean?  Btw, they are no divisions in the program eg. no divide by zeros.

Dinesh

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080126/a0183233/attachment.htm 

From rabidpoobear at gmail.com  Sun Jan 27 08:12:35 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 27 Jan 2008 01:12:35 -0600
Subject: [Tutor] An -1.#IND error
In-Reply-To: <BAY109-DAV13F6273D2E8152FBF51684A33B0@phx.gbl>
References: <BAY109-DAV13F6273D2E8152FBF51684A33B0@phx.gbl>
Message-ID: <479C2EE3.1000701@gmail.com>

Dinesh B Vadhia wrote:
> After a matrix*vector multiplication (ie. b = Ax, with A, x and b all 
> floats), the b vector elements are all "-1.#IND".  What does this 
> mean?  Btw, they are no divisions in the program eg. no divide by zeros.
A code sample would be _much_ more helpful here.
Please include one that exhibits the problem.
>  
> Dinesh
>  
>  
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From robert.spilleboudt at skynet.be  Sun Jan 27 18:00:26 2008
From: robert.spilleboudt at skynet.be (rspil)
Date: Sun, 27 Jan 2008 09:00:26 -0800 (PST)
Subject: [Tutor] setstate trouble when unpickling
In-Reply-To: <576766.42314.qm@web43135.mail.sp1.yahoo.com>
References: <576766.42314.qm@web43135.mail.sp1.yahoo.com>
Message-ID: <15121172.post@talk.nabble.com>


I load a "cellule" with 
self.cellule=pickle.load(prjfile)

Within the class "cellule" I use this method  to add an attribute "note"
,with success:
def __setstate__(self, state):
        #20080127 ajoute note
        if 'note' not in state:
            self.note="***"
        self.__dict__.update(state)

self.note="***" is the new attribute in __init__

I checked with a debug: after the pickle.load the class instance is created
without the attribute "note". The method __setstate__ is called and the new
attribute is added.

With python 2.5.1

Robert



Jeff Peery-2 wrote:
> 
> Hello,
>    
>   I've got a fairly simple class instance that I'm pickling. I'm using
> setstate to update the instance when I unpickle. Although the setstate
> doesn't seem to be called upon unpickling... here's an example, if anyone
> see's what I'm doing wrong, please let me know. Thanks!
>    
>   so I say start out with this class:
>    
>   class dog:
>       def __init__(self):
>           self.num_legs = 4
>    
>   then I pickle the instance of:
>   sparky = dog()
>    
>   then I update my dog class to:
>   class dog:
>       def __init__(self):
>           self.hair_color = 'brown'
>           self.num_legs = 4
>    
>       def __setstate__(self, d):
>           if 'hair_color' not in d:
>               d['hair_color'] = 'brown'
>           self.__dict__.update(d)
>           print 'did this work?'
>    
>   Now when I unpickle the original pickled object sparky I would hope to
> see 'did this work' and I would also hope that sparky would have updated
> to have the attribute 'hair_color' but nothing of the sort happens. if
> just unpickles sparky without updating the attributes as I was hoping.
>    
>   Thanks!
>    
>   Jeff
> 
> 
> 
>        
> ---------------------------------
> Never miss a thing.   Make Yahoo your homepage.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://www.nabble.com/setstate-trouble-when-unpickling-tp15082091p15121172.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From rob.rstevenson at gmail.com  Mon Jan 28 00:01:20 2008
From: rob.rstevenson at gmail.com (Rob Stevenson)
Date: Sun, 27 Jan 2008 23:01:20 +0000
Subject: [Tutor] conditionals with slicing not seeming to work
Message-ID: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>

Hello,

I'm working at a certain website's puzzles using pythonin order to learn the
language, but am stuck understanding what is going on in my code (ie why it
doesn't do as expected)

the intention of this snippet is to only print slices where character 1 is
lower case, 2-4 and 6-8 are upper.  The logic here looks right to a VB eye.

Here's the code...

s="""kKjyaqbooOlNkAddgAazFlgKLjlXDGtlvRBYCYQiRfRIfWIYaLZxLrQzrYzBghYOKAaKgXmUpPkCaMmN
GlAXokgPsdyUjsiaKSSoeCqMrMbQXeRZqkNeAQpujYJFGfbeceunpFNYjuUPiQVOZPXTKhiwPMLKZEKP
NoEPPwXtRoVfGYIRyRgZWyJrMjuBQNchjZBNQUwSgIyXniXCMeXRfAcDKxskxYvMyRGyXeSlOFKFItyI
wgDEIuvHFxRfQhtqLKnJfONtkcnDORkZqbtPplsjjTEIsquhSsQTwNZuPVxaTqDvwMONBfCsNJuJpJHZ
dCdFLtBQPtFQuCdKOrpndJNUFQIDSbetUKylhSUjcDVtbiQrWMRQhAwGUZyPneCGUjGBBTkLqxLAXXtB
KfErkDaWMFZZeuqDmXKJEGHyToPUhPphfVhgUZgbIuRAtWnroImpJKqqmEZqeNQCKzhjIkKQHURWLXFw
PBuijeoTSpsVLaOGuLVjMZXkBvVXwUuHfBihziiavGSYofPNeKsTXruMUumRRPQJzvSzJkKbtSipiqBd"""
h = range(len(s)-9)
for i in h:
    j=s[i:i+8]
    if j[0].islower():
        if j[1:3].isupper():
          if j[5:7].isupper():
              print j

Any help much appreciated!

Rob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080127/32abbd31/attachment.htm 

From jeff at drinktomi.com  Mon Jan 28 01:51:06 2008
From: jeff at drinktomi.com (Jeff Younker)
Date: Sun, 27 Jan 2008 16:51:06 -0800
Subject: [Tutor] conditionals with slicing not seeming to work
In-Reply-To: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
References: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
Message-ID: <52D7982B-3380-4A2D-9295-0C489FFECA33@drinktomi.com>


- Jeff Younker - jeff at drinktomi.com -



On Jan 27, 2008, at 3:01 PM, Rob Stevenson wrote:
> I'm working at a certain website's puzzles using pythonin order to  
> learn the language, but am stuck understanding what is going on in  
> my code (ie why it doesn't do as expected)
>
> the intention of this snippet is to only print slices where  
> character 1 is lower case, 2-4 and 6-8 are upper.  The logic here  
> looks right to a VB eye.
>
> Here's the code...
>
> s 
> = 
> """kKjyaqbooOlNkAddgAazFlgKLjlXDGtlvRBYCYQiRfRIfWIYaLZxLrQzrYzBghYOKAaKgXmUpPkCaMmN
> GlAXokgPsdyUjsiaKSSoeCqMrMbQXeRZqkNeAQpujYJFGfbeceunpFNYjuUPiQVOZPXTKhiwPMLKZEKP
> NoEPPwXtRoVfGYIRyRgZWyJrMjuBQNchjZBNQUwSgIyXniXCMeXRfAcDKxskxYvMyRGyXeSlOFKFItyI
> wgDEIuvHFxRfQhtqLKnJfONtkcnDORkZqbtPplsjjTEIsquhSsQTwNZuPVxaTqDvwMONBfCsNJuJpJHZ
> dCdFLtBQPtFQuCdKOrpndJNUFQIDSbetUKylhSUjcDVtbiQrWMRQhAwGUZyPneCGUjGBBTkLqxLAXXtB
> KfErkDaWMFZZeuqDmXKJEGHyToPUhPphfVhgUZgbIuRAtWnroImpJKqqmEZqeNQCKzhjIkKQHURWLXFw
> PBuijeoTSpsVLaOGuLVjMZXkBvVXwUuHfBihziiavGSYofPNeKsTXruMUumRRPQJzvSzJkKbtSipiqBd 
> """
> h = range(len(s)-9)
> for i in h:
>     j=s[i:i+8]
>     if j[0].islower():
>         if j[1:3].isupper():
>           if j[5:7].isupper():
>               print j
>
> Any help much appreciated!

Your slice indexes are off:

 >>> m = "01234567"
 >>> m[0]
'0'
 >>> m[1:3]
'12'
 >>> m[5:7]
'56'
 >>>

What you want is:

 >>> m[2:4]
'23'
 >>> m[6:8]
'67'

-jeff

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080127/1c83bdd3/attachment.htm 

From kent37 at tds.net  Mon Jan 28 04:19:55 2008
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 27 Jan 2008 22:19:55 -0500
Subject: [Tutor] conditionals with slicing not seeming to work
In-Reply-To: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
References: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
Message-ID: <479D49DB.5020605@tds.net>

Rob Stevenson wrote:

> the intention of this snippet is to only print slices where character 1 
> is lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
> VB eye.

> for i in h:
>     j=s[i:i+8]
>     if j[0].islower():
>         if j[1:3].isupper():
>           if j[5:7].isupper():
>               print j
> 
> Any help much appreciated!

If you want the second character through the fourth (three characters), 
use j[1:4]. Slices include the first index, not the second - they are 
'up to but not including' the end index.

Likewise j[5:8] would be the sixth through eigth characters.

Kent

From dineshbvadhia at hotmail.com  Mon Jan 28 04:29:55 2008
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Sun, 27 Jan 2008 19:29:55 -0800
Subject: [Tutor] An -1.#IND error
References: <BAY109-DAV13F6273D2E8152FBF51684A33B0@phx.gbl>
	<479C2EE3.1000701@gmail.com>
Message-ID: <BAY109-DAV48379B0612709F1ABAF51A3340@phx.gbl>

Luke:

This is literally the core of the code:

A = scipy.asmatrix(scipy.zeros((M, N), float))
q = scipy.asmatrix(scipy.zeros((N, 1)), float)
b = scipy.asmatrix(scipy.zeros((1, N)), float)

# populate A
# x is a vector of valid floats (I've checked)
# calculate b as:

b = A * x

After the matrix multiplication, the b vector elements are all "-1.#IND" 's.  Note that there are no divisions by zero in the program.


Cheers

Dinesh



----- Original Message ----- 
From: Luke Paireepinart 
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Sent: Saturday, January 26, 2008 11:12 PM
Subject: Re: [Tutor] An -1.#IND error


Dinesh B Vadhia wrote:
> After a matrix*vector multiplication (ie. b = Ax, with A, x and b all 
> floats), the b vector elements are all "-1.#IND".  What does this 
> mean?  Btw, they are no divisions in the program eg. no divide by zeros.
A code sample would be _much_ more helpful here.
Please include one that exhibits the problem.
>  
> Dinesh
>  
>  
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080127/72b4c7c7/attachment.htm 

From alan.gauld at btinternet.com  Mon Jan 28 09:32:46 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Jan 2008 08:32:46 -0000
Subject: [Tutor] conditionals with slicing not seeming to work
References: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
Message-ID: <fnk3ro$mq$1@ger.gmane.org>

"Rob Stevenson" <rob.rstevenson at gmail.com> wrote

> I'm working at a certain website's puzzles using
> python in order to learn the language,

OK, Then I'll add some other comments

> the intention of this snippet is to only print slices where 
> character 1 is
> lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
> VB eye.

s="""kKjyaqbooOlNkAddgAazFlgKLjlXDGtlv....
> etc...

> h = range(len(s)-9)
> for i in h:

more conventionally in python to just say

for i in range(len(s)-9)

>    j=s[i:i+8]
>    if j[0].islower():
>        if j[1:3].isupper():
>          if j[5:7].isupper():

And this would reflect the problem statement better if
you used boolean logic

if j[0].islower() and j[1:4].isupper() and j[5:8].isupper():
    print j

You could also do this using regular expressions if
you want an alternative approach.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From Andy.cheesman at bristol.ac.uk  Mon Jan 28 13:59:12 2008
From: Andy.cheesman at bristol.ac.uk (Andy Cheesman)
Date: Mon, 28 Jan 2008 12:59:12 +0000
Subject: [Tutor] replacing range with xrange
Message-ID: <479DD1A0.70303@bristol.ac.uk>

Hi people,

After watching a nice Google video on Python 3K, and seeing the 
forthcoming removal of range, I've looked at substitution range with 
xrange within my code. Direct substitution works for 90% percent of the 
case (i.e.   for thing in xrange(number):  ), however i can't change the 
example below where I need a non-continuous range. Any suggestions?

Andy

x = range(10)  + range(20, 30)

for thing in x:
    ...


From mail at timgolden.me.uk  Mon Jan 28 14:09:27 2008
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 28 Jan 2008 13:09:27 +0000
Subject: [Tutor] replacing range with xrange
In-Reply-To: <479DD1A0.70303@bristol.ac.uk>
References: <479DD1A0.70303@bristol.ac.uk>
Message-ID: <479DD407.2080900@timgolden.me.uk>

Andy Cheesman wrote:
> Hi people,
> 
> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, I've looked at substitution range with 
> xrange within my code. Direct substitution works for 90% percent of the 
> case (i.e.   for thing in xrange(number):  ), however i can't change the 
> example below where I need a non-continuous range. Any suggestions?
> 
> Andy
> 
> x = range(10)  + range(20, 30)
> 
> for thing in x:
>     ...

Define your own top-level range as:

def range (x):
   return list (xrange (x))

maybe?


TJG

From ricaraoz at gmail.com  Mon Jan 28 15:39:07 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Mon, 28 Jan 2008 11:39:07 -0300
Subject: [Tutor] conditionals with slicing not seeming to work
In-Reply-To: <fnk3ro$mq$1@ger.gmane.org>
References: <3e12fcbf0801271501w51dd51e2g7ebccdf4bcd8ac0b@mail.gmail.com>
	<fnk3ro$mq$1@ger.gmane.org>
Message-ID: <479DE90B.8010405@bigfoot.com>

Alan Gauld wrote:
> "Rob Stevenson" <rob.rstevenson at gmail.com> wrote
> 
>> I'm working at a certain website's puzzles using
>> python in order to learn the language,
> 
> OK, Then I'll add some other comments
> 
>> the intention of this snippet is to only print slices where 
>> character 1 is
>> lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
>> VB eye.
> 
> s="""kKjyaqbooOlNkAddgAazFlgKLjlXDGtlv....
>> etc...
> 
>> h = range(len(s)-9)
>> for i in h:
> 
> more conventionally in python to just say
> 
> for i in range(len(s)-9)
> 
>>    j=s[i:i+8]
>>    if j[0].islower():
>>        if j[1:3].isupper():
>>          if j[5:7].isupper():
> 
> And this would reflect the problem statement better if
> you used boolean logic
> 
> if j[0].islower() and j[1:4].isupper() and j[5:8].isupper():
>     print j
> 
> You could also do this using regular expressions if
> you want an alternative approach.
> 
> HTH,
> 

Maybe you are trying to pass python challenge #3? Better use re module
as Alan suggested, and remember, it's EXACTLY three on each side.


From kent37 at tds.net  Mon Jan 28 15:13:27 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Jan 2008 09:13:27 -0500
Subject: [Tutor] replacing range with xrange
In-Reply-To: <479DD1A0.70303@bristol.ac.uk>
References: <479DD1A0.70303@bristol.ac.uk>
Message-ID: <479DE307.6050805@tds.net>

Andy Cheesman wrote:

> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, I've looked at substitution range with 
> xrange within my code. Direct substitution works for 90% percent of the 
> case (i.e.   for thing in xrange(number):  ), however i can't change the 
> example below where I need a non-continuous range. Any suggestions?
> 
> Andy
> 
> x = range(10)  + range(20, 30)

x = list(range(10)) + list(range(20, 30))

or

from itertools import chain
for thing in chain(range(10), range(20, 30)):

which avoids creating the intermediate lists.

Kent

From bgailer at alum.rpi.edu  Mon Jan 28 15:43:56 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 28 Jan 2008 09:43:56 -0500
Subject: [Tutor] replacing range with xrange
In-Reply-To: <479DD1A0.70303@bristol.ac.uk>
References: <479DD1A0.70303@bristol.ac.uk>
Message-ID: <479DEA2C.5060706@alum.rpi.edu>

Andy Cheesman wrote:
> Hi people,
>
> After watching a nice Google video on Python 3K, and seeing the 
> forthcoming removal of range, 
I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)

Built-in Namespace:
- Make built-ins return an iterator where appropriate (e.g. range(), 
zip(), map(), filter(), etc.)

To be removed:
- xrange(): use range() instead

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From kent37 at tds.net  Mon Jan 28 16:03:17 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Jan 2008 10:03:17 -0500
Subject: [Tutor] replacing range with xrange
In-Reply-To: <479DEA2C.5060706@alum.rpi.edu>
References: <479DD1A0.70303@bristol.ac.uk> <479DEA2C.5060706@alum.rpi.edu>
Message-ID: <479DEEB5.2060606@tds.net>

bob gailer wrote:

> I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)
> 
> Built-in Namespace:
> - Make built-ins return an iterator where appropriate (e.g. range(), 
> zip(), map(), filter(), etc.)
> 
> To be removed:
> - xrange(): use range() instead

Right, that's a good clarification.

xrange() is being renamed to range(), so there will be no xrange() and 
range() will return an iterator rather than a list.

Hmm, does that mean that the arguments to range() will be restricted to 
long integers?

Kent

From bgailer at alum.rpi.edu  Mon Jan 28 17:11:33 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 28 Jan 2008 11:11:33 -0500
Subject: [Tutor] replacing range with xrange
In-Reply-To: <479DEEB5.2060606@tds.net>
References: <479DD1A0.70303@bristol.ac.uk> <479DEA2C.5060706@alum.rpi.edu>
	<479DEEB5.2060606@tds.net>
Message-ID: <479DFEB5.9000702@alum.rpi.edu>

Kent Johnson wrote:
> bob gailer wrote:
>
>   
>> I disagree based on PEP 3100 (http://www.python.org/dev/peps/pep-3100/)
>>
>> Built-in Namespace:
>> - Make built-ins return an iterator where appropriate (e.g. range(), 
>> zip(), map(), filter(), etc.)
>>
>> To be removed:
>> - xrange(): use range() instead
>>     
>
> Right, that's a good clarification.
>
> xrange() is being renamed to range(), so there will be no xrange() and 
> range() will return an iterator rather than a list.
>
> Hmm, does that mean that the arguments to range() will be restricted to 
> long integers?
>   
Well the same PEP says:

Atomic Types:
- Remove distinction between int and long types

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From alan.gauld at btinternet.com  Mon Jan 28 20:32:18 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Jan 2008 19:32:18 -0000
Subject: [Tutor] replacing range with xrange
References: <479DD1A0.70303@bristol.ac.uk> <479DEA2C.5060706@alum.rpi.edu>
	<479DEEB5.2060606@tds.net>
Message-ID: <fnlagc$ekd$1@ger.gmane.org>

> xrange() is being renamed to range(), so there will be no xrange() 
> and
> range() will return an iterator rather than a list.

That's sad to see, I use range to generate lists of integers
almost as much as I use it for iteration. But maybe I'm
unusual in that respect, I do use Python mainly for
simulations and its ease of creating large test data
sets is one of its nicer features. Having to convert
an iterator into a list is a bit ugly IMHO! I'd have
preferred to see xrange kept as an iterator and range
returning a list. That seems to me more in keeping
with the names too.

Alan G. 



From bgailer at alum.rpi.edu  Mon Jan 28 23:11:24 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Mon, 28 Jan 2008 17:11:24 -0500
Subject: [Tutor] replacing range with xrange
In-Reply-To: <fnlagc$ekd$1@ger.gmane.org>
References: <479DD1A0.70303@bristol.ac.uk>
	<479DEA2C.5060706@alum.rpi.edu>	<479DEEB5.2060606@tds.net>
	<fnlagc$ekd$1@ger.gmane.org>
Message-ID: <479E530C.3030609@alum.rpi.edu>

Alan Gauld wrote:
>> xrange() is being renamed to range(), so there will be no xrange() 
>> and
>> range() will return an iterator rather than a list.
>>     
>
> That's sad to see, I use range to generate lists of integers
> almost as much as I use it for iteration. But maybe I'm
> unusual in that respect, I do use Python mainly for
> simulations and its ease of creating large test data
> sets is one of its nicer features. Having to convert
> an iterator into a list is a bit ugly IMHO! I'd have
> preferred to see xrange kept as an iterator and range
> returning a list. That seems to me more in keeping
> with the names too.
>   
FWIW on my computer
l = range(30000000) takes under 0.19 seconds
l = list(xrange(3000000)) under 0.27.
So I don't think performance is an issue.


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From alejck at gmail.com  Tue Jan 29 00:31:14 2008
From: alejck at gmail.com (Alexander)
Date: Mon, 28 Jan 2008 18:31:14 -0500
Subject: [Tutor] data structure question
In-Reply-To: <fmrig8$ujo$1@ger.gmane.org>
References: <2e177a690801181106i43c7a9a8la873bb033e9ce1fa@mail.gmail.com>
	<001001c85a1b$b0d19080$81fde004@jslaptop>
	<000601c85a1e$0dbedcb0$81fde004@jslaptop> <fmrig8$ujo$1@ger.gmane.org>
Message-ID: <2e177a690801281531y53f03ea1tae9f79148005248@mail.gmail.com>

Thanks for all the responses. I'm using this both as an opportunity to
learn and to create something that does exactly what I want it to so
that's why I want to write my own program.

I decided to go with a flat list in the end. Now I have a working
implementation but it's not as nice as I think it could be. This is
what I need:

Each task has a set of attributes. Some of these attribute values have
an internal and an external value or representation (for example the
attribute deadline, which is a datetime internally and a formatted
string externally).

The list of tasks should be sortable, filterable, and searchable on
any of the attributes. This needs to be done on the internal
attributes. The list of tasks should also be easily displayed with the
attributes as formatted strings.

My attempt is pasted below. My question now is whether this is a
tenable implementation, what's wrong with it if not, and at which
point something like this is better done using a relational backend
with SQL. To me it seems like the operations that I want to be able to
do are more easily implemented in SQL (perhaps because I don't know
enough python...) but what are the drawbacks of such an approach?

The code:

#! /usr/bin/python
# vim: tabstop=4 expandtab shiftwidth=4
"""Flat implementation of tasklist."""

import cPickle as pickle
import datetime
import parsedatetime.parsedatetime

import pdb

class TaskList(object):
	defaults = ['rgtd','backend','testing 1','tomorrow',1,'open']
	def __init__(self):
		"""Create an empty instance"""
		self.tasks = []
		self.modified = False

	def addTask(self,args):
		"""Add a task."""
		args = args + self.defaults[len(args):]
		task = Task(args)
		self.tasks.append(task)
		self.modified = True
	
	def clear(self):
		"""Delete all tasks."""
		self.tasks = []
		self.modified = True
	
	def removeTask(self,index):
		try:
			task = self.tasks.pop(index)
			self.modified = True
			result = 'Removed task %i\t%s'  (index,task.__str__())
		except:
			result = 'Removing task %i failed.' % index
		return result

	def setStatus(self,index,status):
		self.tasks[int(index)].status = str(status)
		self.modified=True

	def save(self, filename='.rgtddb'):
		"""Save tasklist to file using pickle."""
		file = open(filename,'wb')
		pickle.dump(self,file)
		file.close()
		self.modified = False

	def sorted(self,field='int_deadline',ascending=False):
		"""Return tasks sorted on int_deadline.
		Adapted from Python Cookbook 2ed Recipe 5.3.
		"""
		intermed = [ (getattr(x, field), i, x) for i, x in enumerate(self.tasks) ]
		intermed.sort(reverse=ascending)
		return [x[-1] for x in intermed]
	
	def sort(self,field='int_deadline',ascending=False):
		self.tasks[:] = self.sorted(field,ascending)

	def output(self,displaymask=False):
		row = ''
		
		# Set displaymask to all fields in sortorder if no mask is supplied.
		if not displaymask:
			displaymask = ['status','deadline','cost','project','area','task']
		
		# Sort tasks
		self.sort()

		# Produce output string
		for index, task in enumerate(self.tasks):
			row = row + '%i\t%s\n' % (index, '\t'.join([getattr(task,field)for
field in displaymask]))
		return row

class Task(object):
	def __init__(self,args):
		"""Set all task attributes from an argument list in correct order."""
		self.project = args[0]
		self.area = args[1]
		self.task = args[2]
		self.deadline = args[3]
		self.cost = args[4]
		self.status = args[5]
	
	def setDeadline(self, value):
		"""Use parsedatetime.parsedatetime to parse human-readable
		deadline entry to a datetime object.
		"""
		parsedatetime.parsedatetime._debug=False
		calendar = parsedatetime.parsedatetime.Calendar()
		self.__deadline = datetime.datetime(*calendar.parse(value)[0][0:7])
		# datetime object is also stored in for internal use (sorting)
		self.int_deadline = datetime.datetime(*calendar.parse(value)[0][0:7])

	def getDeadline(self):
		"""Return deadline as a string in the format day-month."""
		return self.__deadline.strftime('%d-%m %H')

	def setCost(self,value):
		"""Set cost to a timedelta object."""
		self.__cost = datetime.timedelta(hours=int(value))
		# datetime object is also stored for internal use (sorting)
		self.int_cost = datetime.timedelta(hours=int(value))	
	
	def getCost(self):
		"""Return a cost as a formatted string.
		Adapted from http://www.nabble.com/Formatting-timedelta-objects-td14259934.html
		"""
		hours = self.__cost.seconds // 3600
		#minutes = (self.__cost.seconds % 3600) // 60
		return '%sh' % (hours)

	
 	# Task properties that use overloading for setting and getting.
	deadline = property(getDeadline,setDeadline)
	cost = property(getCost,setCost)

#############################
# Methods that have not been
# encapsulated in TaskList.
#############################

def load(filename=False):
	"""Load tasklist from disk using pickle."""
	if not filename:
		filename = '.rgtddb'
	ts = False
	try:
		ts = pickle.load(open(filename,'rb'))
		ts.modified = False
	except IOError:
		print 'The file %s does not exist.' % filename
	return ts

Best,

Alexander


On 1/18/08, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Tiger12506" <keridee at jayco.net> wrote in message
> news:000601c85a1e$0dbedcb0$81fde004 at jslaptop...
> >>    def recursive_print(self, level=0):
> >>        print "\t"*level + self.cargo
> >>        for x in self.children:
> >>          recursive_print(x,level+1)
> >
> > Whoops. should be
> >
> > for x in self.children:
> >    x.recursive_print(level+1)
>
> Ah, you already caught it, my gmane feed ruinning a bit slow...
>
> Alan G
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From carroll at tjc.com  Tue Jan 29 01:35:37 2008
From: carroll at tjc.com (Terry Carroll)
Date: Mon, 28 Jan 2008 16:35:37 -0800 (PST)
Subject: [Tutor] What web framework?
Message-ID: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>

I'm writing a pretty small database program.  It tracks CDROMs with
archives of, say, MP3 files; although I'm writing it with an eye to to
generalize to, for example, support a collection of image files, or actual 
audio CDs, as well; or just about any types of files that might lend 
themselves to being stored on CDROM in a consistently organized manner.

I've decided to split out the program(s) to add and delete data from the
querying.  Data will be added by reading a CDROM and processing all the
files; all the data going into the database is derived from the files
themselves, so there's no data entry.  Similarly, data will only be
deleted by deleting all rows that relate back to a particular volume; I'll 
probably do that with a separate program that does just that function.  
Neither of these is really worthy of a flashy GUI interface.

But querying's different.  I'd initially planed on making this a wxPython 
application, but I think it might be simpler to have it as a web app, even 
though I'll be the only user, and the db will be resident on the same 
program I'm querying from.

This calls for using a web framework, and I'm casting about for advice on 
which one to use.  This probably isn't the best-formed question, because I 
don't know what factors should influence a choice of framework.  Some 
factors that come to mind are:

- this application will be query-only; no updating, adding or deleting.
- the database is SQLite.
- security and authentication are not important; there's no private data 
  here, I'm the only user, and I'm firewalled. If a particular framework
  has security features, I'll use them, but I don't see them as important.
  (Famous last words.)

I'd like something that doesn't take forever to get up to speed on, but
that isn't short on features.  Although this is the only framework project
I see in the immediate future, I can imagine I might want to do another
project sometime in the future.  I really want to be framework-monogamous
here: I don't program for a living, and getting up to speed on a framework
seems like work to me.

It looks like the leading candidates here are Turbogears and Django.  
Turbogears looks kind of nice to me, but it looks like it's going through
some big changes right now.  Apparently, on the database side, SQLObject
is being replaced with SQLAlchemy, and on the templating side, Kid is
being replaced with Genshi.  I worry that a lot of the time put into 
learning TG in its present form will ultimately be time wasted.

Any thoughts on these two frameworks, or another that I might be 
overlooking?  Oh, since I don't know enough about frameworks to even know 
what factors are worth considering: what factors would I be considering?


From alan.gauld at btinternet.com  Tue Jan 29 01:54:10 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jan 2008 00:54:10 -0000
Subject: [Tutor] replacing range with xrange
References: <479DD1A0.70303@bristol.ac.uk><479DEA2C.5060706@alum.rpi.edu>	<479DEEB5.2060606@tds.net><fnlagc$ekd$1@ger.gmane.org>
	<479E530C.3030609@alum.rpi.edu>
Message-ID: <fnltbt$hlb$1@ger.gmane.org>


"bob gailer" <bgailer at alum.rpi.edu> wrote

>> That's sad to see, I use range to generate lists of integers
>> almost as much as I use it for iteration. 

> FWIW on my computer
> l = range(30000000) takes under 0.19 seconds
> l = list(xrange(3000000)) under 0.27.
> So I don't think performance is an issue.

Performance was never an issue for me, its just that I think 
the explicit conversion to list looks ugly. After all a range is 
a range of numbers to my mind and a list (actually a tuple) 
seems like the sensible representation. Making it an iterator 
seems to be based on an assumption that range will 
primarily be used in a for loop.

Alan G


From alan.gauld at btinternet.com  Tue Jan 29 02:00:22 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jan 2008 01:00:22 -0000
Subject: [Tutor] What web framework?
References: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
Message-ID: <fnltng$icn$1@ger.gmane.org>

"Terry Carroll" <carroll at tjc.com> wrote

> But querying's different.  I'd initially planed on making this a 
> wxPython
> application, but I think it might be simpler to have it as a web 
> app, even
> though I'll be the only user, and the db will be resident on the 
> same
> program I'm querying from.
>
> This calls for using a web framework,

Not really, a simple CGI app would be suffficient.
A framework is really only needed where you have lots of pages
all with the same look n feel and lots of interaction between them.
If all you need is a query screen and a results screen then basic
CGI should be more than adequate.

If you really want more then look at basic CherryPy rather than
TurboGears/Django. It takes the CGI pains away while keeping
the code simple and direct.

TurboGears and Django are both excellent but the learning curve
for a simple app is more than the gain IMHO. OTOH If you want
to build knowledge for the future then pick one and go with it.
It doesn't much matter which they all use the same principles
its only syntax differences really.

IMHO at least,

Alan G. 



From kent37 at tds.net  Tue Jan 29 02:15:17 2008
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 28 Jan 2008 20:15:17 -0500
Subject: [Tutor] What web framework?
In-Reply-To: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
Message-ID: <479E7E25.2020507@tds.net>

Terry Carroll wrote:
> Any thoughts on these two frameworks, or another that I might be 
> overlooking?  Oh, since I don't know enough about frameworks to even know 
> what factors are worth considering: what factors would I be considering?

TG and Django both work well, and both have many satisfied users. 
Personally I prefer Django, I am using it at work and like it a lot. My 
first impressions of both are here:
http://personalpages.tds.net/~kent37/blog/arch_m1_2007_02.html#e73

There are some lighter-weight frameworks you might consider as well, 
web.py anyway.

Kent

From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=  Tue Jan 29 12:48:48 2008
From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=)
Date: Tue, 29 Jan 2008 14:48:48 +0300
Subject: [Tutor] What web framework?
In-Reply-To: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
Message-ID: <1201607328.5388.3.camel@gobuntu>

On Mon, 2008-01-28 at 16:35 -0800, Terry Carroll wrote:
  <snip>
> - this application will be query-only; no updating, adding or deleting.
> - the database is SQLite.
> - security and authentication are not important; there's no private data 
>   here, I'm the only user, and I'm firewalled. If a particular framework
>   has security features, I'll use them, but I don't see them as important.
>   (Famous last words.)
> 
> I'd like something that doesn't take forever to get up to speed on, but
> that isn't short on features.  Although this is the only framework project
> I see in the immediate future, I can imagine I might want to do another
> project sometime in the future.  I really want to be framework-monogamous
> here: I don't program for a living, and getting up to speed on a framework
> seems like work to me.
  <snip>

Try:
  http://webpy.org/

About WebPy:
  web.py is a web framework for python that is as simple as it is
  powerful. web.py is in the public domain; you can use it for whatever
  purpose with absolutely no restrictions.

Tutorial:
  http://webpy.org/tutorial2

Hope this will help you.
Ziyad.


From imonthejazz at googlemail.com  Tue Jan 29 14:02:18 2008
From: imonthejazz at googlemail.com (Damian Archer)
Date: Tue, 29 Jan 2008 13:02:18 +0000
Subject: [Tutor] Serious N00b question.
Message-ID: <c7cfa05e0801290502n284f41dem5117e0e3b961aaf2@mail.gmail.com>

Guys,

Thanks for your help on my last question, got a few projects in mind now.

I usually work on Linux(Fedora) enviroment, i have no trouble with running
scripts/programs i write. But i have now got IDLE on my Windows build.

Now when i write something in Notepad, how do i then open that so it runs in
IDLE??

Sorry for the terrible question!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080129/895a3e6b/attachment.htm 

From alan.gauld at btinternet.com  Tue Jan 29 14:33:45 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Jan 2008 13:33:45 -0000
Subject: [Tutor] Serious N00b question.
References: <c7cfa05e0801290502n284f41dem5117e0e3b961aaf2@mail.gmail.com>
Message-ID: <fnn9s4$dbp$1@ger.gmane.org>


"Damian Archer" <imonthejazz at googlemail.com> wrote

> Now when i write something in Notepad, how do i then open that so it 
> runs in
> IDLE??

Just use File->Open and then Run->Run Module

But better still don't use Notepad. The editor in IDLE is
far better than Notepad for editing Python code!

Alan G. 



From bba at inbox.com  Tue Jan 29 16:39:08 2008
From: bba at inbox.com (Ben Bartrum)
Date: Tue, 29 Jan 2008 07:39:08 -0800
Subject: [Tutor] What web framework?
In-Reply-To: <fnltng$icn$1@ger.gmane.org>
References: <pine.lnx.4.44.0801281613450.29226-100000@violet.rahul.net>
Message-ID: <0612A9FF324.000001D4bba@inbox.com>

Yes, CherryPy is an excellent, and uniquely straightforward tool for writing a database-driven web application.  I'd start looking into things like Django for larger sites where you also want templating, and client-side interactivity through JavaScript etc.
In my simple CherryPy apps, I use Python's own (%) string substitution instead of a templating language, so a simple CherryPy app can consist of pure Python code, SQL queries and nothing else needed.  

    

> -----Original Message-----
> From: alan.gauld at btinternet.com
> Sent: Tue, 29 Jan 2008 01:00:22 -0000
> To: tutor at python.org
> Subject: Re: [Tutor] What web framework?
> 
> "Terry Carroll" <carroll at tjc.com> wrote
> 
>> But querying's different.  I'd initially planed on making this a
>> wxPython
>> application, but I think it might be simpler to have it as a web
>> app, even
>> though I'll be the only user, and the db will be resident on the
>> same
>> program I'm querying from.
>> 
>> This calls for using a web framework,
> 
> Not really, a simple CGI app would be suffficient.
> A framework is really only needed where you have lots of pages
> all with the same look n feel and lots of interaction between them.
> If all you need is a query screen and a results screen then basic
> CGI should be more than adequate.
> 
> If you really want more then look at basic CherryPy rather than
> TurboGears/Django. It takes the CGI pains away while keeping
> the code simple and direct.
> 
> TurboGears and Django are both excellent but the learning curve
> for a simple app is more than the gain IMHO. OTOH If you want
> to build knowledge for the future then pick one and go with it.
> It doesn't much matter which they all use the same principles
> its only syntax differences really.
> 
> IMHO at least,
> 
> Alan G.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

____________________________________________________________
FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth

From michael.langford at rowdylabs.com  Tue Jan 29 17:46:55 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Tue, 29 Jan 2008 11:46:55 -0500
Subject: [Tutor] What web framework?
In-Reply-To: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
Message-ID: <82b4f5810801290846k1cd7cad4la92def6884f99fa4@mail.gmail.com>

On Jan 28, 2008 7:35 PM, Terry Carroll <carroll at tjc.com> wrote:
> It looks like the leading candidates here are Turbogears and Django.

This s a results of trying and sometimes using these frameworks over 3
years now. I sometimes thoughtfully evaluate all my options before
choosing, other times, I just pick what I can ape off of quickly as
possible then get to work. Please don't firebomb my house because I
misspoke or put down your favorite web framework. I know this is a
tender subject for some of you. I guarantee the below is factually
inaccurate in some ways. Then again, it wouldn't be written if I had
to do more research to write it.

I talk about Magic and Configuration below. Configuration is what you
do in Java frameworks, where you make 2^23 xml files to make hello
world work. Magic is what happens in Ruby on Rails, where things work
and sometimes don't work, but they do it with very little
specification required by the user. This makes it hard to tell how
something isn't working, or why it is working but slowly. Then again,
it makes all initial work fast fast fast. Which frankly, will get you
to actually finish your application a lot faster.

The new standard for python web applications is WSGI. If you write
your apps to be WSGI compliant, you can integrate them with each other
and with different webservers within minutes. Yes. Minutes. It's
really quite cool. And it's really not that hard. (Look into Paste to
get that "minutes" thing down).

This question is sort of like asking what is the best text editor.
Here is a good screencast to see one guy doing this comparison:
http://plone.org/about/movies/better-web-app-development.png

Here are your choices of full frameworks, what they bring, and why you
might want them:
Pylons: Infinite customizablity. Plays well with other frameworks.It's
the python analog to Ruby on Rails. If you like lots of magic (i.e.
Little configuration), you'll like this. Pylons is WSGI compliant.
http://pylonshq.com/

Zope/Plone. The framework really is Zope, but cutting down and turning
off parts of Plone if it already does most of what you want is often
faster than writing it all yourself.  They have awesome screencasts to
get you going, and you can quickly get a GUI for free with this
system.  I think these guys are the ones who dreamt up WSGI IIRC.
These guys have lots of cross platform apps you can use for Zope and
Plone Sites: http://plone.org/about/movies
http://www.zope.org/WhatIsZope You can build anything on Zope. It is
becoming less of a ghetto (i.e. all the code is walled off in zope)
every day, especially with tools such as Repoze
http://radio.weblogs.com/0116506/2007/10/26.html#a441 Plone (and
therefore Zope) comes with an easy installer for all platforms.

Django: You can run a newspaper off this. A number of people do, as a
matter of fact, the framework came out of newspapers. If you need to
do something other than running a newspaper, this probably isn't for
you. Its a little configuration file heavy for my tastes, and the
installable apps aren't as cross platform as the Zope ones in my
experience http://www.djangoproject.com/ I feel the documentation is
light years behind zope and pylons (then again, that's because pylons
needs so little documentation). Is compliant with WSGI according to
them.

Turbogears: Ahh Turbogears. Your tutorial screencast turned everyone
on to you, then they tried it, and it didn't work for them because
they had the wrong version of something installed or they were on a
different flavor of linux, or etc etc etc. Frankly, this has worked
sometimes for me, sometimes not. I don't like that. I like being able
to make it work no matter where I am. When it does work though, you
pop out a site pretty quickly. You also have a good mix of magic and
configuration, that way you can just get a site out there, then you
can redo it to be higher performance the night after your server melts
from being posted on a busy site like slashdot or the python tutor
archives. Appears to be on WSGI now.

Paste. This is Ian Bicking showing us how we're all inferior human
beings. http://pythonpaste.org/ It's the lightest possible weight
framework. It's so light weight, half of the above frameworks use it
internally. You should probably use this one from what you've said.

Then you can go for something I'd call a microframework:
Web.py and mod_python and cherrypy all fit that bill. These are often
tied to a given webserver, which may be just fine for you. Or you can
write a WSGI compliant app on top of one of those, then upgrade
when/if you need it. I don't see a single one that beats Paste for
what you need.

In short:
Do WSGI if you can: http://wsgi.org/wsgi/Frameworks
Pick according to your comfort level/motivation level when choosing
between Configuration and Magic
Probably use Paste(http://pythonpaste.org/), but maybe use a more
involved framework too.

           --Michael
-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From kent37 at tds.net  Tue Jan 29 18:11:24 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Jan 2008 12:11:24 -0500
Subject: [Tutor] What web framework?
In-Reply-To: <82b4f5810801290846k1cd7cad4la92def6884f99fa4@mail.gmail.com>
References: <Pine.LNX.4.44.0801281613450.29226-100000@violet.rahul.net>
	<82b4f5810801290846k1cd7cad4la92def6884f99fa4@mail.gmail.com>
Message-ID: <479F5E3C.4070204@tds.net>

Michael Langford wrote:
> Django: You can run a newspaper off this. A number of people do, as a
> matter of fact, the framework came out of newspapers. If you need to
> do something other than running a newspaper, this probably isn't for
> you.

Not for you, perhaps, but certainly many people find Django suitable for 
web sites that are not newspapers. For example:
http://www.djangosites.org/

> I feel the documentation is
> light years behind zope and pylons (then again, that's because pylons
> needs so little documentation).

I guess the Zope and Pylons docs must be truly magnificent then, because 
the Django docs are IMO very good:
http://www.djangoproject.com/documentation/

Kent

From nephish at gmail.com  Tue Jan 29 21:37:04 2008
From: nephish at gmail.com (shawn bright)
Date: Tue, 29 Jan 2008 14:37:04 -0600
Subject: [Tutor] question about a number and bytes.
Message-ID: <384c93600801291237q4c577adt8e8a67de512582a4@mail.gmail.com>

Hello there all.

I have a need to make a hi byte and lo byte out of a number.

so, lets say i have a number 300, and need this number to be
represented in two bytes, how do i go about that?

thanks for any tips,

sk

From keridee at jayco.net  Tue Jan 29 21:55:11 2008
From: keridee at jayco.net (Tiger12506)
Date: Tue, 29 Jan 2008 15:55:11 -0500
Subject: [Tutor] question about a number and bytes.
References: <384c93600801291237q4c577adt8e8a67de512582a4@mail.gmail.com>
Message-ID: <001a01c862b9$4446edb0$79fde004@jslaptop>

> Hello there all.
>
> I have a need to make a hi byte and lo byte out of a number.
>
> so, lets say i have a number 300, and need this number to be
> represented in two bytes, how do i go about that?

First question. Why would you need to do this in python? Second question. If 
you could do that, how would you use it in any other python context? 


From nephish at gmail.com  Tue Jan 29 22:13:16 2008
From: nephish at gmail.com (shawn bright)
Date: Tue, 29 Jan 2008 15:13:16 -0600
Subject: [Tutor] question about a number and bytes.
In-Reply-To: <001a01c862b9$4446edb0$79fde004@jslaptop>
References: <384c93600801291237q4c577adt8e8a67de512582a4@mail.gmail.com>
	<001a01c862b9$4446edb0$79fde004@jslaptop>
Message-ID: <384c93600801291313n3ca28b84t3426e5ee4fc9f81b@mail.gmail.com>

Thanks for your reply.
i need to do this in python because python is what scripting language
our data I/O system is written in.
i am writing a command out over a serial port that tells an RTU to
change part of it's program. I am not sure what you mean by using it
in any other python context, this is about the only thing we will need
to be able to do this for, at least, that is the case for right now.
thanks
sk

On Jan 29, 2008 2:55 PM, Tiger12506 <keridee at jayco.net> wrote:
> > Hello there all.
> >
> > I have a need to make a hi byte and lo byte out of a number.
> >
> > so, lets say i have a number 300, and need this number to be
> > represented in two bytes, how do i go about that?
>
> First question. Why would you need to do this in python? Second question. If
> you could do that, how would you use it in any other python context?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From michael.langford at rowdylabs.com  Tue Jan 29 22:16:12 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Tue, 29 Jan 2008 16:16:12 -0500
Subject: [Tutor] question about a number and bytes.
In-Reply-To: <384c93600801291313n3ca28b84t3426e5ee4fc9f81b@mail.gmail.com>
References: <384c93600801291237q4c577adt8e8a67de512582a4@mail.gmail.com>
	<001a01c862b9$4446edb0$79fde004@jslaptop>
	<384c93600801291313n3ca28b84t3426e5ee4fc9f81b@mail.gmail.com>
Message-ID: <82b4f5810801291316i1205d992jdfce38193492c9e4@mail.gmail.com>

Use pyserial:

http://pyserial.sourceforge.net/

Use struct.pack:

http://docs.python.org/lib/module-struct.html

The format string will depend whether you need little or big endian.

       --Michael


On Jan 29, 2008 4:13 PM, shawn bright <nephish at gmail.com> wrote:
> Thanks for your reply.
> i need to do this in python because python is what scripting language
> our data I/O system is written in.
> i am writing a command out over a serial port that tells an RTU to
> change part of it's program. I am not sure what you mean by using it
> in any other python context, this is about the only thing we will need
> to be able to do this for, at least, that is the case for right now.
> thanks
> sk
>
>
> On Jan 29, 2008 2:55 PM, Tiger12506 <keridee at jayco.net> wrote:
> > > Hello there all.
> > >
> > > I have a need to make a hi byte and lo byte out of a number.
> > >
> > > so, lets say i have a number 300, and need this number to be
> > > represented in two bytes, how do i go about that?
> >
> > First question. Why would you need to do this in python? Second question. If
> > you could do that, how would you use it in any other python context?
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From nephish at gmail.com  Tue Jan 29 22:29:02 2008
From: nephish at gmail.com (shawn bright)
Date: Tue, 29 Jan 2008 15:29:02 -0600
Subject: [Tutor] question about a number and bytes.
In-Reply-To: <82b4f5810801291316i1205d992jdfce38193492c9e4@mail.gmail.com>
References: <384c93600801291237q4c577adt8e8a67de512582a4@mail.gmail.com>
	<001a01c862b9$4446edb0$79fde004@jslaptop>
	<384c93600801291313n3ca28b84t3426e5ee4fc9f81b@mail.gmail.com>
	<82b4f5810801291316i1205d992jdfce38193492c9e4@mail.gmail.com>
Message-ID: <384c93600801291329t6034c55did679dd9aeebe24d@mail.gmail.com>

ok, was using pyserial, but was not using struct.pack.
thanks
sk

On Jan 29, 2008 3:16 PM, Michael Langford
<michael.langford at rowdylabs.com> wrote:
> Use pyserial:
>
> http://pyserial.sourceforge.net/
>
> Use struct.pack:
>
> http://docs.python.org/lib/module-struct.html
>
> The format string will depend whether you need little or big endian.
>
>        --Michael
>
>
>
> On Jan 29, 2008 4:13 PM, shawn bright <nephish at gmail.com> wrote:
> > Thanks for your reply.
> > i need to do this in python because python is what scripting language
> > our data I/O system is written in.
> > i am writing a command out over a serial port that tells an RTU to
> > change part of it's program. I am not sure what you mean by using it
> > in any other python context, this is about the only thing we will need
> > to be able to do this for, at least, that is the case for right now.
> > thanks
> > sk
> >
> >
> > On Jan 29, 2008 2:55 PM, Tiger12506 <keridee at jayco.net> wrote:
> > > > Hello there all.
> > > >
> > > > I have a need to make a hi byte and lo byte out of a number.
> > > >
> > > > so, lets say i have a number 300, and need this number to be
> > > > represented in two bytes, how do i go about that?
> > >
> > > First question. Why would you need to do this in python? Second question. If
> > > you could do that, how would you use it in any other python context?
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.RowdyLabs.com
>

From bhaaluu at gmail.com  Wed Jan 30 02:17:13 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Tue, 29 Jan 2008 20:17:13 -0500
Subject: [Tutor] results not quite 100 percent yet
Message-ID: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>

Greetings,

I'm having a problem with the following test.
I make a dictionary with 19 keys (1 to 19).
Each key has a list of 7 numbers  (A to G)

# Set up the table
#    key#   A  B  C  D  E  F  G
tablE= {1:[ 0, 2, 0, 0, 0, 0, 0],    # 1
        2:[ 1, 3, 3, 0, 0, 0, 0],    # 2
        3:[ 2, 0, 5, 2, 0, 0, 0],    # 3
        4:[ 0, 5, 0, 0, 0, 0, 0],    # 4
        5:[ 4, 0, 0, 3,15,13, 0],    # 5
        6:[ 0, 0, 1, 0, 0, 0, 0],    # 6
        7:[ 0, 8, 0, 0, 0, 0, 0],    # 7
        8:[ 7,10, 0, 0, 0, 0, 0],    # 8
        9:[ 0,19, 0, 0, 0, 8, 0],    # 9
       10:[ 8, 0,11, 0, 0, 0, 0],   # 10
       11:[ 0, 0,10, 0, 0, 0, 0],   # 11
       12:[ 0, 0, 0,13, 0, 0, 0],   # 12
       13:[ 0, 0,12, 0, 5, 0, 0],   # 13
       14:[ 0,15,17, 0, 0, 0, 0],   # 14
       15:[14, 0, 0, 0, 0, 5, 0],   # 15
       16:[17, 0,19, 0, 0, 0, 0],   # 16
       17:[18,16, 0,14, 0, 0, 0],   # 17
       18:[ 0,17, 0, 0, 0, 0, 0],   # 18
       19:[ 9, 0, 0,16, 0, 0, 0]}   # 19
#    key#   A  B  C  D  E  F  G


The first loop is supposed to populate G with
a random range of 4 integers 10 to 109
in random keys 1-19 that have a zero (except keY 6 and  keY 11)
So keY 6 and keY 11 should both have a zero in G after the
four integers have been sown.

# populate G column with range of 4 integers 10 to 109
# in random keys that have a zero [except keYs 6 and 11]
print "%"*69
cnt=0
while cnt <= 3:
    print "CNT111=",cnt  #debug-remove when done
    a = range(1,20) # 1 to 19
    keY = random.choice(a)
    if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
        tablE.values()[5][6] = 0
        tablE.values()[10][6] = 0
        cnt -= 1
        keY = random.choice(a)
    if keY != 6 or keY != 11 or table.values()[keY-1][6] == 0:
        b = range(10,110) # 10 to 109
        integer = random.choice(b)
        tablE.values()[keY-1][6] = integer
        cnt += 1


The second loop is supposed to populate G with
numbers -4 to -1 in random keys 1-19 that have a zero
(except keY 6 and keY11). So once again, 6 and 11 should have
a zero in G after the loop is finished.

# populate G with range of integers -1 to -4
# in random keYs that have a zero [except keYs 6 and 11]
cnt=4
while cnt > 0:
    print "CNT222=",cnt
    a = range(1,20)
    if keY != 6 or keY != 11 and tablE.values()[keY-1][6] == 0:
        keY = random.choice(a)
        tablE.values()[keY-1][6] = -cnt
        cnt -= 1
    if keY == 6 or keY == 11:
        tablE.values()[5][6] = 0
        tablE.values()[10][6] = 0
        cnt += 1


The last thing is that two integers are placed in specific keys
4 and 16, overwriting anything that may be in G whether a
negative number or a number > 9.

# Put an integer in G at two specific keys: 4 & 16
# These will overwrite anything placed there previously
#a = range(1,99)
#tablE.values()[3][6]= 100 + random.choice(a)
#tablE.values()[15][6]= 100 + random.choice(a)

The above has been commented out so I see if the two loops are
each distributing four numbers each, without putting anything
in G of keys 6 and 11.

I've approached the problem by trying to get the loop to repeat
if a number ends up in G at key 6 or key 11. I've done this changing
the loop count. This seems to work about 97% of the time, or so.
I'm looking for 100%.

I know I can always just set those keys to zero before the table is
written, but I'd rather have the table as fully populated by the two
loops and just not have anything get in G in keys 6 & 11.

Anyway, this is just a short test, part of a larger program.
Here's the test code:

#!/usr/bin/python

import random

print "\n"*30

# Set up the table
#    key#   A  B  C  D  E  F  G
tablE= {1:[ 0, 2, 0, 0, 0, 0, 0],    # 1
        2:[ 1, 3, 3, 0, 0, 0, 0],    # 2
        3:[ 2, 0, 5, 2, 0, 0, 0],    # 3
        4:[ 0, 5, 0, 0, 0, 0, 0],    # 4
        5:[ 4, 0, 0, 3,15,13, 0],    # 5
        6:[ 0, 0, 1, 0, 0, 0, 0],    # 6
        7:[ 0, 8, 0, 0, 0, 0, 0],    # 7
        8:[ 7,10, 0, 0, 0, 0, 0],    # 8
        9:[ 0,19, 0, 0, 0, 8, 0],    # 9
       10:[ 8, 0,11, 0, 0, 0, 0],   # 10
       11:[ 0, 0,10, 0, 0, 0, 0],   # 11
       12:[ 0, 0, 0,13, 0, 0, 0],   # 12
       13:[ 0, 0,12, 0, 5, 0, 0],   # 13
       14:[ 0,15,17, 0, 0, 0, 0],   # 14
       15:[14, 0, 0, 0, 0, 5, 0],   # 15
       16:[17, 0,19, 0, 0, 0, 0],   # 16
       17:[18,16, 0,14, 0, 0, 0],   # 17
       18:[ 0,17, 0, 0, 0, 0, 0],   # 18
       19:[ 9, 0, 0,16, 0, 0, 0]}   # 19
#    key#   A  B  C  D  E  F  G

# populate G column with range of 4 integers 10 to 109
# in random keys that have a zero [except keYs 6 and 11]
print "%"*69
cnt=0
while cnt <= 3:
    print "CNT111=",cnt
    a = range(1,20) # 1 to 19
    keY = random.choice(a)
    if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
        tablE.values()[5][6] = 0
        tablE.values()[10][6] = 0
        cnt -= 1
        keY = random.choice(a)
    if keY != 6 or keY != 11 or table.values()[keY-1][6] == 0:
        b = range(10,110) # 10 to 109
        integer = random.choice(b)
        tablE.values()[keY-1][6] = integer
        cnt += 1

# populate G with range of integers -1 to -4
# in random keYs that have a zero [except keYs 6 and 11]
cnt=4
while cnt > 0:
    print "CNT222=",cnt
    a = range(1,20)
    if keY != 6 or keY != 11 and tablE.values()[keY-1][6] == 0:
        keY = random.choice(a)
        tablE.values()[keY-1][6] = -cnt
        cnt -= 1
    if keY == 6 or keY == 11:
        tablE.values()[5][6] = 0
        tablE.values()[10][6] = 0
        cnt += 1

# Put an integer in G at two specific keys: 4 & 16
# These will overwrite anything placed there previously
#a = range(1,99)
#tablE.values()[3][6]= 100 + random.choice(a)
#tablE.values()[15][6]= 100 + random.choice(a)

# print-out tablE
print "    data table"
print "---------------------"
print "       values"
print "key A B C D E F G"
for roomNum in range(0,19):
    print " ",roomNum+1,
    for compass in range(0,7):
        xVal = tablE.values()[roomNum][compass]
        print xVal,
        if compass == 6:
            print

I'm looking for suggestions on how to improve the two
loops so that I get 100% distribution each time (eight
numbers total).

I'm running a GNU/Linux OS,
Python 2.4.3
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From kent37 at tds.net  Wed Jan 30 03:26:05 2008
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 29 Jan 2008 21:26:05 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
Message-ID: <479FE03D.5050406@tds.net>

bhaaluu wrote:
>     if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
>         tablE.values()[5][6] = 0
>         tablE.values()[10][6] = 0

This is not the right way to access the values of a dict. tablE.values() 
is a list of the values in tablE, but it is not in the order you expect; 
it is easiest to think that it is in a random or indeterminate order.

Try
     if keY == 6 or keY == 11 or tablE[keY-1][6] != 0:
         tablE[5][6] = 0
         tablE[10][6] = 0

etc.

Kent

PS what's with the strange capitalization of variable names?

From varsha.purohit at gmail.com  Wed Jan 30 04:30:23 2008
From: varsha.purohit at gmail.com (Varsha Purohit)
Date: Tue, 29 Jan 2008 19:30:23 -0800
Subject: [Tutor] [tutor] Question on multithreading
Message-ID: <c2157c790801291930u796a8251i4f1de8cb5c1c1b08@mail.gmail.com>

Hello friends,
        I hve a GUI where i have start button and stop button. When i press
start button one thread is created and it is executing some background task
and when i press stop button that thread is stopped/killed. These two things
are working properly. But i have to implement pause button in my GUI. When i
press pause the thread execution should come to a halt and after that it
should be resumed when i press pause again or may be i can implement some
other button.

Does anybody have an example where they have implemented this kind of
threading concept ??

any help is apreciated,

-- 
Varsha Purohit,
Graduate Student
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080129/34c1077f/attachment.htm 

From john at fouhy.net  Wed Jan 30 04:43:35 2008
From: john at fouhy.net (John Fouhy)
Date: Wed, 30 Jan 2008 16:43:35 +1300
Subject: [Tutor] [tutor] Question on multithreading
In-Reply-To: <c2157c790801291930u796a8251i4f1de8cb5c1c1b08@mail.gmail.com>
References: <c2157c790801291930u796a8251i4f1de8cb5c1c1b08@mail.gmail.com>
Message-ID: <5e58f2e40801291943p7bc756c3o850dbe495ff707c0@mail.gmail.com>

On 30/01/2008, Varsha Purohit <varsha.purohit at gmail.com> wrote:
> Hello friends,
>         I hve a GUI where i have start button and stop button. When i press
> start button one thread is created and it is executing some background task
> and when i press stop button that thread is stopped/killed. These two things
> are working properly. But i have to implement pause button in my GUI. When i
> press pause the thread execution should come to a halt and after that it
> should be resumed when i press pause again or may be i can implement some
> other button.
>
> Does anybody have an example where they have implemented this kind of
> threading concept ??

How did you implement your stop button?  Can you adapt that solution?

-- 
John.

From bgailer at alum.rpi.edu  Wed Jan 30 05:41:22 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Tue, 29 Jan 2008 23:41:22 -0500
Subject: [Tutor] [tutor] Question on multithreading
In-Reply-To: <c2157c790801291930u796a8251i4f1de8cb5c1c1b08@mail.gmail.com>
References: <c2157c790801291930u796a8251i4f1de8cb5c1c1b08@mail.gmail.com>
Message-ID: <479FFFF2.3090304@alum.rpi.edu>

Varsha Purohit wrote:
> Hello friends,
>         I hve a GUI where i have start button and stop button. When i 
> press start button one thread is created and it is executing some 
> background task and when i press stop button that thread is 
> stopped/killed. These two things are working properly. But i have to 
> implement pause button in my GUI. When i press pause the thread 
> execution should come to a halt and after that it should be resumed 
> when i press pause again or may be i can implement some other button.
>
> Does anybody have an example where they have implemented this kind of 
> threading concept ??
Take a look at the threading module. The thread should acquire() a 
condition then wait(). The following is quickly thrown together and not 
tested.

main program:
import threading
cond = threading.Condition() # create a condition variable with a new RLock

thread:
while True: # I assume the thread runs in some kind of loop
  if pause: # pressing Pause should set this variable True
    cond .acquire()
    cond .wait() # pauses until notified
    cond .release()
    # rest of thread - assumes loop repeats fast enough to give the 
desired response time

code behind the pause/resume button:
pause = not pause # toggle
if not pause:
  cond.notify()

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From brindly at gmail.com  Wed Jan 30 08:25:10 2008
From: brindly at gmail.com (brindly sujith)
Date: Wed, 30 Jan 2008 12:55:10 +0530
Subject: [Tutor] how to make python program as executable
Message-ID: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>

hi

i am developing a  GUI application in python(tkinter)

i want to know how to make the python program as a application ie i want to
make it executable

please guide me
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080130/59d6b2bc/attachment-0001.htm 

From alan.gauld at btinternet.com  Wed Jan 30 09:35:29 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Jan 2008 08:35:29 -0000
Subject: [Tutor] results not quite 100 percent yet
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
Message-ID: <fnpcoo$up6$1@ger.gmane.org>


"bhaaluu" <bhaaluu at gmail.com> wrote 

In addition to Kents comments about dictionaruy 
access I think there may be another problem in 
your logic.

> The first loop is supposed to populate G with
> a random range of 4 integers 10 to 109
> in random keys 1-19 that have a zero (except keY 6 and  keY 11)
> So keY 6 and keY 11 should both have a zero in G after the
> four integers have been sown.
> 
>    if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
>        tablE.values()[5][6] = 0
>        tablE.values()[10][6] = 0
>        cnt -= 1
>        keY = random.choice(a)

This detects any of the exception cases so a simple else 
clause should be sufficient for the others. However if you 
really want an explicit check...

>    if keY != 6 or keY != 11 or table.values()[keY-1][6] == 0:

This test should use 'and' rather than 'or' since you want 
all of the conditions to be true, not just one of them.
But since the failing condituions should all have been 
caught above simply using else here would do what 
I think you want.

>        b = range(10,110) # 10 to 109
>        integer = random.choice(b)
>        tablE.values()[keY-1][6] = integer
>        cnt += 1


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at btinternet.com  Wed Jan 30 09:39:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Jan 2008 08:39:59 -0000
Subject: [Tutor] how to make python program as executable
References: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
Message-ID: <fnpd15$vgh$1@ger.gmane.org>

"brindly sujith" <brindly at gmail.com> wrote

> i am developing a  GUI application in python(tkinter)
>
> i want to know how to make the python program as a application ie i 
> want to
> make it executable

If you are on Windows it should be executable already,
just double click on the main file in Windows Explorer
and it should run. If not the file associations need setting.

If you are on a Unix based system you will need to use
chmod +x to  make the file executable. You will also
need the shebang line set:

#! /bin/env python

or whatever is appropriate on your system.

HTH,

Alan G. 



From brindly at gmail.com  Wed Jan 30 10:33:33 2008
From: brindly at gmail.com (brindly sujith)
Date: Wed, 30 Jan 2008 15:03:33 +0530
Subject: [Tutor] how to enable overrideredirect
Message-ID: <bfb67a4d0801300133jd90ed6dm62decf019ff72bcf@mail.gmail.com>

from Tkinter import *
import tkMessageBox
import tkFileDialog,os
def quit():
	if tkMessageBox.askokcancel("Quit","DO u really want to quit"):
		root.destroy()

def fiopen():
	file1 = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
	os.system("openoffice %s"%file1.name)
	
root=Tk()
label=Label(root,text="Welcome to PC-FREE PROJECTOR")
label.pack()
button=Button(root,text="select",command=fiopen)
button.pack()
button1=Button(root,text="Exit",command=quit)
button1.pack()
root.overrideredirect(True)
root.geometry('%dx%d+%d+%d' % (root.winfo_screenwidth(),
                               root.winfo_screenheight(),
                               0, 0))
root.lift()
root.mainloop()


the above program is my application

please execute this program...

while executing this program

initially a window will open....after that the buttons 'select'
and 'exit' is not working...

i checked out by disabling root.overrideredirect(True) line in
the program...then its working

what is the problem here...i want this program to work perfectly

plz do reply me

thanx
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080130/fea54117/attachment.htm 

From rabidpoobear at gmail.com  Wed Jan 30 10:59:59 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 30 Jan 2008 03:59:59 -0600
Subject: [Tutor] how to make python program as executable
In-Reply-To: <fnpd15$vgh$1@ger.gmane.org>
References: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
	<fnpd15$vgh$1@ger.gmane.org>
Message-ID: <47A04A9F.2030509@gmail.com>

Alan Gauld wrote:
> "brindly sujith" <brindly at gmail.com> wrote
>
>   
>> i am developing a  GUI application in python(tkinter)
>>
>> i want to know how to make the python program as a application ie i 
>> want to
>> make it executable
>>     
>
> If you are on Windows it should be executable already,
> just double click on the main file in Windows Explorer
> and it should run. If not the file associations need setting.
>
> If you are on a Unix based system you will need to use
> chmod +x to  make the file executable. You will also
> need the shebang line set:
>
> #! /bin/env python
>
> or whatever is appropriate on your system.
>   
I think he meant " i want to make the application [into an] executable" 
I.E. he wants an .exe file on Windows.
In this case, you can use py2exe, and there's another alternative I 
can't remember.

From thorsten at thorstenkampe.de  Wed Jan 30 11:40:10 2008
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Wed, 30 Jan 2008 10:40:10 -0000
Subject: [Tutor] how to make python program as executable
References: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
	<fnpd15$vgh$1@ger.gmane.org> <47A04A9F.2030509@gmail.com>
Message-ID: <fnpk6a$mol$1@ger.gmane.org>

* Luke Paireepinart (Wed, 30 Jan 2008 03:59:59 -0600)
> I think he meant " i want to make the application [into an]
> executable" I.E. he wants an .exe file on Windows.
> In this case, you can use py2exe, and there's another alternative I
> can't remember.

The better alternative is "Pyinstaller"...

Thorsten


From rdm at rcblue.com  Wed Jan 30 11:54:25 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 02:54:25 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
Message-ID: <20080130105429.7C7BE1E4006@bag.python.org>

This is probably a totally na?ve and silly idea, 
but I thought I'd run it by the Tutors anyway.

Years ago I learned a bit of Visual Basic (VB6, 
IIRC) at a community college. Months ago I 
downloaded the free Visual Basic 2005 Express 
(<http://www.microsoft.com/express/vb/Default.aspx>), 
but didn't do much with it.

But I was wondering if it was possible to write 
Python code in Iron Python and use it somehow in 
Visual Basic 2005 Express. VB seemed a very easy 
way to create a GUI, but of course I prefer Python for the code.

So, possible/impossible/impractical/foolish/Pythonically_traitorous?

Thanks,

Dick Moores


From kent37 at tds.net  Wed Jan 30 12:54:54 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 06:54:54 -0500
Subject: [Tutor] how to enable overrideredirect
In-Reply-To: <bfb67a4d0801300133jd90ed6dm62decf019ff72bcf@mail.gmail.com>
References: <bfb67a4d0801300133jd90ed6dm62decf019ff72bcf@mail.gmail.com>
Message-ID: <47A0658E.2060307@tds.net>

brindly sujith wrote:

> while executing this program 
> 
> initially a window will open....after that the buttons 'select'
> and 'exit' is not working...

It works for me as written on Mac OSX with Python 2.5.1. What platform 
are you running on? How are you running the program? If you are running 
it from IDLE, try running from a command line.

Kent

From kent37 at tds.net  Wed Jan 30 13:02:36 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 07:02:36 -0500
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <20080130105429.7C7BE1E4006@bag.python.org>
References: <20080130105429.7C7BE1E4006@bag.python.org>
Message-ID: <47A0675C.9090803@tds.net>

Dick Moores wrote:

> But I was wondering if it was possible to write 
> Python code in Iron Python and use it somehow in 
> Visual Basic 2005 Express. VB seemed a very easy 
> way to create a GUI, but of course I prefer Python for the code.
> 
> So, possible/impossible/impractical/foolish/Pythonically_traitorous?

This shows how to use IronPython code from C#, does that help?
http://www.ironpython.info/index.php/Contents#Embedding

Kent

From bhaaluu at gmail.com  Wed Jan 30 13:06:21 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 07:06:21 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <479FE03D.5050406@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<479FE03D.5050406@tds.net>
Message-ID: <ea979d70801300406hec7c789s133aa661165d8cb6@mail.gmail.com>

On Jan 29, 2008 9:26 PM, Kent Johnson <kent37 at tds.net> wrote:
> Try
>      if keY == 6 or keY == 11 or tablE[keY-1][6] != 0:
>          tablE[5][6] = 0
>          tablE[10][6] = 0
>
> etc.
>
> Kent
>
> PS what's with the strange capitalization of variable names?

It's a test snippet. I use unusual names in my tests.

-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From bhaaluu at gmail.com  Wed Jan 30 13:29:22 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 07:29:22 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <479FE03D.5050406@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<479FE03D.5050406@tds.net>
Message-ID: <ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>

On Jan 29, 2008 9:26 PM, Kent Johnson <kent37 at tds.net> wrote:
> bhaaluu wrote:
> >     if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
> >         tablE.values()[5][6] = 0
> >         tablE.values()[10][6] = 0
>
> This is not the right way to access the values of a dict. tablE.values()
> is a list of the values in tablE, but it is not in the order you expect;
> it is easiest to think that it is in a random or indeterminate order.
>
> Try
>      if keY == 6 or keY == 11 or tablE[keY-1][6] != 0:
>          tablE[5][6] = 0
>          tablE[10][6] = 0
>
> etc.
>
> Kent
>

Now that you mention it, I do seem to remember that the order of
a list is indeterminate.

What kind of Python array structure would you use if you need to
access each element in the exact order it appears in the table?
The only element that gets changed is the last one, all the others
stay exactly the same. So far, this structure seems to be working
okay in the big program. Maybe 2-3% of the time is an integer put
in keys 6 or 11.

-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From rdm at rcblue.com  Wed Jan 30 14:11:17 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 05:11:17 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <47A0675C.9090803@tds.net>
References: <20080130105429.7C7BE1E4006@bag.python.org>
	<47A0675C.9090803@tds.net>
Message-ID: <20080130131325.66D191E4006@bag.python.org>

At 04:02 AM 1/30/2008, Kent Johnson wrote:
>Dick Moores wrote:
>
>>But I was wondering if it was possible to write Python code in Iron 
>>Python and use it somehow in Visual Basic 2005 Express. VB seemed a 
>>very easy way to create a GUI, but of course I prefer Python for the code.
>>So, possible/impossible/impractical/foolish/Pythonically_traitorous?
>
>This shows how to use IronPython code from C#, does that help?
>http://www.ironpython.info/index.php/Contents#Embedding

Thanks, Kent, but I can't tell if it does or not..

Dick


From kent37 at tds.net  Wed Jan 30 14:24:52 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 08:24:52 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>	
	<479FE03D.5050406@tds.net>
	<ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>
Message-ID: <47A07AA4.1020408@tds.net>

bhaaluu wrote:
> Now that you mention it, I do seem to remember that the order of
> a list is indeterminate.

No; the order of a dict is indeterminate, and consequently the order of 
lists derived from dicts with keys(), values(), etc. is indeterminate.

The order of a list is determined by how you create it.
> 
> What kind of Python array structure would you use if you need to
> access each element in the exact order it appears in the table?

A list of lists may be the correct structure for your program. You could 
define tablE as

tablE= [[ 0, 2, 0, 0, 0, 0, 0],    # 1
         [ 1, 3, 3, 0, 0, 0, 0],    # 2
         [ 2, 0, 5, 2, 0, 0, 0],    # 3
...
        [ 9, 0, 0,16, 0, 0, 0]]   # 19

Kent

From kent37 at tds.net  Wed Jan 30 14:26:05 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 08:26:05 -0500
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <20080130131325.66D191E4006@bag.python.org>
References: <20080130105429.7C7BE1E4006@bag.python.org>	<47A0675C.9090803@tds.net>
	<20080130131325.66D191E4006@bag.python.org>
Message-ID: <47A07AED.9020008@tds.net>

Dick Moores wrote:

>>> But I was wondering if it was possible to write Python code in Iron 
>>> Python and use it somehow in Visual Basic 2005 Express.

You might have better luck asking on an IronPython list. I don't know if 
we have any IronPython gurus here.

Kent

From michael.langford at rowdylabs.com  Wed Jan 30 14:26:40 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Wed, 30 Jan 2008 08:26:40 -0500
Subject: [Tutor] how to make python program as executable
In-Reply-To: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
References: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
Message-ID: <82b4f5810801300526y4836af4areae908685922d3a6@mail.gmail.com>

What platform? The mechanism is different for each major OS.



On Jan 30, 2008 2:25 AM, brindly sujith <brindly at gmail.com> wrote:
> hi
>
> i am developing a  GUI application in python(tkinter)
>
> i want to know how to make the python program as a application ie i want to
> make it executable
>
> please guide me
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From rdm at rcblue.com  Wed Jan 30 14:47:56 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 05:47:56 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <47A07AED.9020008@tds.net>
References: <20080130105429.7C7BE1E4006@bag.python.org>
	<47A0675C.9090803@tds.net>
	<20080130131325.66D191E4006@bag.python.org>
	<47A07AED.9020008@tds.net>
Message-ID: <20080130135005.44A131E4006@bag.python.org>

At 05:26 AM 1/30/2008, Kent Johnson wrote:
>Dick Moores wrote:
>
>>>>But I was wondering if it was possible to write Python code in 
>>>>Iron Python and use it somehow in Visual Basic 2005 Express.
>
>You might have better luck asking on an IronPython list. I don't 
>know if we have any IronPython gurus here.

Thanks, Kent. I will.

Dick



From bhaaluu at gmail.com  Wed Jan 30 15:07:30 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 09:07:30 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A07AA4.1020408@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<479FE03D.5050406@tds.net>
	<ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>
	<47A07AA4.1020408@tds.net>
Message-ID: <ea979d70801300607n4da04543u798803cdb6ce76be@mail.gmail.com>

On Jan 30, 2008 8:24 AM, Kent Johnson <kent37 at tds.net> wrote:
> bhaaluu wrote:
> > Now that you mention it, I do seem to remember that the order of
> > a list is indeterminate.
>
> No; the order of a dict is indeterminate, and consequently the order of
> lists derived from dicts with keys(), values(), etc. is indeterminate.

The order of the dictionary is indeterminate. But the key is always
attached to the value, and in my case, the value is a list, so

print tablE.keys() #prints all the keys [in an ordered list, 1-19]

print tablE.keys()[5] #prints the key, 6

print tablE.values() #prints a list of [all [the lists]]

print tablE.values()[5] #prints only the [list for key 6]

print tablE.values()[5][2] #prints the third element: 1

So what you're saying here is that while it might work okay on
my system, that this may not work the same way on another
system?

>
> The order of a list is determined by how you create it.

Yes, this is how it works in my list test, and this is what my Python
books say. (Although I may have forgotten that on a conscious level,
I am now reminded of it.) 8^D

> >
> > What kind of Python array structure would you use if you need to
> > access each element in the exact order it appears in the table?
>
> A list of lists may be the correct structure for your program. You could
> define tablE as
>
> tablE= [[ 0, 2, 0, 0, 0, 0, 0],    # 1
>          [ 1, 3, 3, 0, 0, 0, 0],    # 2
>          [ 2, 0, 5, 2, 0, 0, 0],    # 3
> ...
>
>         [ 9, 0, 0,16, 0, 0, 0]]   # 19
>
> Kent
>

I'll give it a go, and see if I can make that work.
However, except for not getting 100% in my number
distribution routine, the dictionary seems to be working okay
(on my system).

Here's a simple example of the dictionary in action.
"for" loops have replaced all the "if" selections... this was the first example.
I've left the "if"'s in so the table.values() can be easily seen.

#!/usr/bin/python
# 2007-01-19
# 2007-01-20
"""
Map
+------+------+
|      |      |
|         5   |
|  1   |      |
|      +--  --+    N
|      |      |    |
+--  --+  4   | W--+--E
|      |      |    |
|      +--  --+    S
|  2   |      |
|         3   |
|      |      |
+------+------+
"""
#            rm#  N S E W
travelTable = {1:[0,2,5,0],
               2:[1,0,3,0],
               3:[4,0,0,2],
               4:[5,3,0,0],
               5:[0,4,0,1]}

def main():
    roomNum = 1
    print \
    """
    Instructions:
    Move through the rooms by pressing [N] for North, [S]
    for South, [E] for East, [W] for West, and [Q] to Quit.
    These movement keys are not case sensitive (ie. [n] is
    the same as [N]).
    """
    name = raw_input("What is your name? ")
    exploring=True
    while exploring:
        print name + ", your strength is",
        print str(strength) +"."
        #########################################################
        print name,"you are in room",roomNum
        #########################################################
        if travelTable.values()[roomNum-1][0] != 0:
            print "A door leads North."
        if travelTable.values()[roomNum-1][1] != 0:
            print "A door leads South."
        if travelTable.values()[roomNum-1][2] != 0:
            print "A door leads East."
        if travelTable.values()[roomNum-1][3] != 0:
            print "A door leads West."
        #########################################################
        move = raw_input("Which way do you want to go? ")
        if move.upper() == "Q":
            exploring=False
        #########################################################
        if move.upper()=="N" and travelTable.values()[roomNum-1][0] == 0:
            print
            print "You cannot move that way."
        if move.upper()=="S" and travelTable.values()[roomNum-1][1] == 0:
            print
            print "You can't walk through walls."
        if move.upper()=="E" and travelTable.values()[roomNum-1][2] == 0:
            print
            print "Try another direction."
        if move.upper()=="W" and travelTable.values()[roomNum-1][3] == 0:
            print
            print "There is no door to the West."
        #########################################################
        if move.upper() =="N" and travelTable.values()[roomNum-1][0] != 0:
            roomNum = travelTable.values()[roomNum-1][0]
        if move.upper() =="S" and travelTable.values()[roomNum-1][1] != 0:
            roomNum = travelTable.values()[roomNum-1][1]
        if move.upper() =="E" and travelTable.values()[roomNum-1][2] != 0:
            roomNum = travelTable.values()[roomNum-1][2]
        if move.upper() =="W" and travelTable.values()[roomNum-1][3] != 0:
            roomNum = travelTable.values()[roomNum-1][3]
        #########################################################
        print
main()

-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From kent37 at tds.net  Wed Jan 30 15:22:43 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 09:22:43 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801300607n4da04543u798803cdb6ce76be@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>	
	<479FE03D.5050406@tds.net>	
	<ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>	
	<47A07AA4.1020408@tds.net>
	<ea979d70801300607n4da04543u798803cdb6ce76be@mail.gmail.com>
Message-ID: <47A08833.8000206@tds.net>

bhaaluu wrote:
> On Jan 30, 2008 8:24 AM, Kent Johnson <kent37 at tds.net> wrote:
>> bhaaluu wrote:
>>> Now that you mention it, I do seem to remember that the order of
>>> a list is indeterminate.
>> No; the order of a dict is indeterminate, and consequently the order of
>> lists derived from dicts with keys(), values(), etc. is indeterminate.
> 
> The order of the dictionary is indeterminate. But the key is always
> attached to the value, and in my case, the value is a list, so
> 
> print tablE.keys() #prints all the keys [in an ordered list, 1-19]

This is implementation dependent. You should not depend on the order of 
elements in tablE.keys()

> print tablE.keys()[5] #prints the key, 6

This is implementation dependent.

> print tablE.values() #prints a list of [all [the lists]]

Yes. The order of the list (of lists) is implementation dependent.

> print tablE.values()[5] #prints only the [list for key 6]

This is implementation dependent and pointless. You are not using the 
dict at all except as a way to store a list of lists. Either use 
tablE[6], which will always return the list associated with the key 6, 
or just keep your lists in a list directly.

> So what you're saying here is that while it might work okay on
> my system, that this may not work the same way on another
> system?

Yes. The order of keys() and values() is implementation dependent. It 
may change with different versions of Python and different 
implementations. It can also change as you add more elements to the dict.

(For example, one problem the Jython folks have had getting Django to 
run on Jython is that the Django unit tests make assumptions about the 
order of dict values. These assumptions are not true in Jython and the 
unit tests fail.)

>         if travelTable.values()[roomNum-1][0] != 0:

Again, the use of travelTable.values() is pointless, inefficient (it 
creates a new list every time you call it) and indeterminate. Really, 
you shouldn't be doing this. I can't think of any reason to code this way.

Kent

From bhaaluu at gmail.com  Wed Jan 30 15:29:21 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 09:29:21 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A08833.8000206@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<479FE03D.5050406@tds.net>
	<ea979d70801300429m115a4511qdb440c93e295bb5c@mail.gmail.com>
	<47A07AA4.1020408@tds.net>
	<ea979d70801300607n4da04543u798803cdb6ce76be@mail.gmail.com>
	<47A08833.8000206@tds.net>
Message-ID: <ea979d70801300629j27681ad2mf613da66cc91fda9@mail.gmail.com>

On Jan 30, 2008 9:22 AM, Kent Johnson <kent37 at tds.net> wrote:
> This is implementation dependent.
>[snip]
>
> >         if travelTable.values()[roomNum-1][0] != 0:
>
> Again, the use of travelTable.values() is pointless, inefficient (it
> creates a new list every time you call it) and indeterminate. Really,
> you shouldn't be doing this. I can't think of any reason to code this way.
>
> Kent

This is good to know!
The reason I coded it that way is because I'm learning.
I seem to always be learning... that's why I'm subscribed
to THIS list. 8^D

Back to the drawing board!
Thank you very much for your help!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From michael.langford at rowdylabs.com  Wed Jan 30 15:32:57 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Wed, 30 Jan 2008 09:32:57 -0500
Subject: [Tutor] how to make python program as executable
In-Reply-To: <bfb67a4d0801300611w404c3d63j98e0db46acbc5d4d@mail.gmail.com>
References: <bfb67a4d0801292325r763a9abcm1d633bd985acfd0f@mail.gmail.com>
	<82b4f5810801300526y4836af4areae908685922d3a6@mail.gmail.com>
	<bfb67a4d0801300611w404c3d63j98e0db46acbc5d4d@mail.gmail.com>
Message-ID: <82b4f5810801300632x53c3d14ayabb962b3da06c052@mail.gmail.com>

On the command line type "which python"

Then at the top of your script put:

#!/usr/bin/python

or whatever path the which command outputted.

Then run chmod on the program:

chmod ugo+x script.py

then the following will work:
./script.py

If you actually want to build an executable that doesn't depend on the
presence of python, then this tutorial will help you:
http://wiki.python.org/moin/Freeze


          --Michael

On Jan 30, 2008 9:11 AM, brindly sujith <brindly at gmail.com> wrote:
> i am using linux...
>
> plz tell me how to do it
>
>
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From bhaaluu at gmail.com  Wed Jan 30 18:19:05 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 12:19:05 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <fnpcoo$up6$1@ger.gmane.org>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
Message-ID: <ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>

On Jan 30, 2008 3:35 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> In addition to Kents comments about dictionaruy
> access I think there may be another problem in
> your logic.
>
>
> "bhaaluu" <bhaaluu at gmail.com> wrote
>
> > The first loop is supposed to populate G with
> > a random range of 4 integers 10 to 109
> > in random keys 1-19 that have a zero (except keY 6 and  keY 11)
> > So keY 6 and keY 11 should both have a zero in G after the
> > four integers have been sown.
> >
> >    if keY == 6 or keY == 11 or tablE.values()[keY-1][6] != 0:
> >        tablE.values()[5][6] = 0
> >        tablE.values()[10][6] = 0
> >        cnt -= 1
> >        keY = random.choice(a)
>
> This detects any of the exception cases so a simple else
> clause should be sufficient for the others. However if you
> really want an explicit check...
>
> >    if keY != 6 or keY != 11 or table.values()[keY-1][6] == 0:
>
> This test should use 'and' rather than 'or' since you want
> all of the conditions to be true, not just one of them.
> But since the failing condituions should all have been
> caught above simply using else here would do what
> I think you want.
>
>
> >        b = range(10,110) # 10 to 109
> >        integer = random.choice(b)
> >        tablE.values()[keY-1][6] = integer
> >        cnt += 1
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld

Thank you Alan and Kent.
Your suggestions caused me to completely start
from scratch. It also looks like the "nested sequence"
will be easier to use in the long run (and I'm into this
for the long run!). 8^D

This is working properly now on my
GNU/Linux system running Python 2.4.3:

#!/usr/bin/python
# 2008-01-30

import random

# setup environment
#             N S E W U D T
travelTable=[[0,2,0,0,0,0,0],    # ROOM 1
             [1,3,3,0,0,0,0],    # ROOM 2
             [2,0,5,2,0,0,0],    # ROOM 3
             [0,5,0,0,0,0,0],    # ROOM 4
             [4,0,0,3,5,13,0],   # ROOM 5
             [0,0,1,0,0,0,0],    # ROOM 6
             [0,8,0,0,0,0,0],    # ROOM 7
             [7,0,0,0,0,0,0],    # ROOM 8
             [0,9,0,0,0,8,0],    # ROOM 9
             [8,0,11,0,0,0,0],   # ROOM 10
             [0,0,10,0,0,0,0],   # ROOM 11
             [0,0,0,13,0,0,0],   # ROOM 12
             [0,0,12,0,5,0,0],   # ROOM 13
             [0,15,17,0,0,0,0],  # ROOM 14
             [14,0,0,0,0,5,0],   # ROOM 15
             [17,0,19,0,0,0,0],  # ROOM 16
             [18,16,0,14,0,0,0], # ROOM 17
             [0,17,0,0,0,0,0],   # ROOM 18
             [9,0,0,16,0,0,0]]   # ROOM 19

# distribute positive numbers 10 to 109
# place in last element of 4 random lists
# nothing is placed in list 6 or 11
cnt=0
while cnt <= 3:
    a = range(1,20)
    room = random.choice(a)
    if room != 6 and room != 11 and travelTable[room-1][6] == 0:
        b = range(10,110)
        treasure = random.choice(b)
        travelTable[room-1][6] = treasure
    else:
        cnt -= 1
    cnt += 1

# distribute negtive numbers -4 to -1
# place in last element of 4 random lists
# nothing is placed in list 6 or 11
cnt=4
while cnt > 0:
    a = range(1,20)
    room = random.choice(a)
    if room != 6 and room != 11 and travelTable[room-1][6] == 0:
        travelTable[room-1][6] = -cnt
    else:
        cnt += 1
    cnt -= 1

# put positive numbers in the last element
# of two specific lists overwriting any
# number that exists
a = range(1,99)
travelTable[3][6]= 100 + random.choice(a)
travelTable[15][6]= 100 + random.choice(a)

print " 1:", travelTable[0][6]
print " 2:", travelTable[1][6]
print " 3:", travelTable[2][6]
print " 4:", travelTable[3][6]
print " 5:", travelTable[4][6]
print " 6:", travelTable[5][6]
print " 7:", travelTable[6][6]
print " 8:", travelTable[7][6]
print " 9:", travelTable[8][6]
print "10:", travelTable[9][6]
print "11:", travelTable[10][6]
print "12:", travelTable[11][6]
print "13:", travelTable[12][6]
print "14:", travelTable[13][6]
print "15:", travelTable[14][6]
print "16:", travelTable[15][6]
print "17:", travelTable[16][6]
print "18:", travelTable[17][6]
print "19:", travelTable[18][6]
# end of program

-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From kent37 at tds.net  Wed Jan 30 18:46:48 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 12:46:48 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
Message-ID: <47A0B808.7080702@tds.net>

bhaaluu wrote:

> # distribute positive numbers 10 to 109
> # place in last element of 4 random lists
> # nothing is placed in list 6 or 11
> cnt=0
> while cnt <= 3:
>     a = range(1,20)
>     room = random.choice(a)

room = random.randint(1, 19) is simpler.

>     if room != 6 and room != 11 and travelTable[room-1][6] == 0:
>         b = range(10,110)
>         treasure = random.choice(b)

Use randint() here too.

>         travelTable[room-1][6] = treasure
>     else:
>         cnt -= 1
>     cnt += 1

This use of cnt is a bit strange. Why not increment only in the 
successful 'if' and get rid of the 'else' entirely?

Rather than repeating the loop until you get three distinct, valid 
random numbers, you could do something like this:

# Change 7 rooms, not room 6 or 11
changeableRooms = range(1, 20)
changeableRooms.remove(6)
changeableRooms.remove(11)

roomsToChange = random.sample(changeableRooms, 7)

# First three get something good
for room in roomsToChange[:3]:
   travelTable[room-1][6] = random.randint(10, 119)

# Last four get something bad
for i, room in enumerate(roomsToChange[3:]):
   travelTable[room-1][6] = -i-1

> print " 1:", travelTable[0][6]
etc - use a loop and string formatting:

for i, room in enumerate(travelTable):
   print ' %s: %s' % (i+1, room[6])

Finally, you might consider putting a dummy entry at travelTable[0], or 
number the rooms from 0, so you don't have to adjust the indices all the 
time.

Kent

From bgailer at alum.rpi.edu  Wed Jan 30 20:24:35 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Wed, 30 Jan 2008 14:24:35 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
Message-ID: <47A0CEF3.1080902@alum.rpi.edu>

bhaaluu wrote:
> #             N S E W U D T
> travelTable=[[0,2,0,0,0,0,0],    # ROOM 1
>              [1,3,3,0,0,0,0],    # ROOM 2
It is good to finally see that you are building an adventure game.

Consider creating a instance of a Room class for each room and saving 
them in a collection such as a list.

This will give you much more flexibility as your game grows.

Inevitably I wound up doing a bunch of things more "Pythonically" so 
there may be stuff here you don't relate to yet. But is is all worth 
studying and will save you hours of headache later.

----------------------------- code -----------------------------
import random
class Room:
  roomNo = 0
  def __init__(self, destinations, updatable=True):
    Room.roomNo += 1
    self.roomNo = Room.roomNo
    self.destinations = destinations
    # store treasure apaart from destinations
    self.treasure = 0 # add intial treasure
    self.updatable = updatable # may have the treasure updated
  def updateTreasure(self, treasure):
    self.treasure = treasure
  def __repr__(self):
    return " %s:%s" % (self.roomNo, self.treasure)

rooms = [
  Room([0,2,0,0,0,0]),  # ROOM 1
  Room([1,3,3,0,0,0]),  # ROOM 2
  Room([2,0,5,2,0,0]),  # ROOM 3
  Room([0,5,0,0,0,0]),  # ROOM 4
  Room([4,0,0,3,5,13]), # ROOM 5
  Room([0,0,1,0,0,0], False), # ROOM 6 flagged as not updatable
  Room([0,8,0,0,0,0]), # ROOM 7
  Room([7,0,0,0,0,0]), # ROOM 8
  Room([0,9,0,0,0,8]), # ROOM 9
  # etc for the rest of the rooms -
        ]
  # note I omitted the initial treasure value since it is always 0
  # I modified the last for statement to account for only 9 rooms

# use random.sample to create random subsets of values and rooms
# - eliminates all the loops and tests
# note this ensures no duplicate treasures (do you want that?)

# create list of 8 random treasure values
values = random.sample(range(10,110),4) + random.sample(range(-4, 0),4)

# create list of 8 randomly selected updatable rooms
roomsToUpdate= random.sample([room for room in rooms if room.updatable], 8)

# update the rooms' Treasures
for room, value in zip(roomsToUpdate, values):
  room.updateTreasure(value)

a = range(1,99)
for room in (3,5):
  rooms[room].updateTreasure(100 + random.choice(a))

for room in rooms: print room 
----------------------------- end code -----------------------------

Things I did not do, but suggest:
- store the room destinations in a text file rather than hard-coding 
them in the program. It is almost always a good idea to separate logic 
from data.

 -create a Treasure class, storing instances directly in roo,s rather 
than indexes, and storing treasure definitions in the text file.

-store room instances in the destinations rather than indexes.

At this point you no longer need indexes!

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From alan.gauld at btinternet.com  Wed Jan 30 20:46:27 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Jan 2008 19:46:27 -0000
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
References: <20080130105429.7C7BE1E4006@bag.python.org>
Message-ID: <fnqk2q$k75$1@ger.gmane.org>


"Dick Moores" <rdm at rcblue.com> wrote

> But I was wondering if it was possible to write 
> Python code in Iron Python and use it somehow in 
> Visual Basic 2005 Express. VB seemed a very easy 
> way to create a GUI, but of course I prefer Python for the code.


It should be possible but I've no idea how. I suspect you 
might need to write the Python code in a class but I'm not 
even sure about that. My experiece of .NET is both very
limited and entirely in C#

But the whole idea of the intermediate code thing is 
that you can intermix languages.

Alan G


From bhaaluu at gmail.com  Wed Jan 30 20:45:32 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 14:45:32 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A0B808.7080702@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0B808.7080702@tds.net>
Message-ID: <ea979d70801301145i6fc3fa9doc6ea1191103be890@mail.gmail.com>

On Jan 30, 2008 12:46 PM, Kent Johnson <kent37 at tds.net> wrote:
> bhaaluu wrote:
>
> > # distribute positive numbers 10 to 109
> > # place in last element of 4 random lists
> > # nothing is placed in list 6 or 11
> > cnt=0
> > while cnt <= 3:
> >     a = range(1,20)
> >     room = random.choice(a)
>
> room = random.randint(1, 19) is simpler.
>
> >     if room != 6 and room != 11 and travelTable[room-1][6] == 0:
> >         b = range(10,110)
> >         treasure = random.choice(b)
>
> Use randint() here too.
>
> >         travelTable[room-1][6] = treasure
> >     else:
> >         cnt -= 1
> >     cnt += 1
>
> This use of cnt is a bit strange. Why not increment only in the
> successful 'if' and get rid of the 'else' entirely?
>
> Rather than repeating the loop until you get three distinct, valid
> random numbers, you could do something like this:
>
> # Change 7 rooms, not room 6 or 11
> changeableRooms = range(1, 20)
> changeableRooms.remove(6)
> changeableRooms.remove(11)
>
> roomsToChange = random.sample(changeableRooms, 7)
>
> # First three get something good
> for room in roomsToChange[:3]:
>    travelTable[room-1][6] = random.randint(10, 119)
>
> # Last four get something bad
> for i, room in enumerate(roomsToChange[3:]):
>    travelTable[room-1][6] = -i-1
>
> > print " 1:", travelTable[0][6]
> etc - use a loop and string formatting:
>
> for i, room in enumerate(travelTable):
>    print ' %s: %s' % (i+1, room[6])
>
> Finally, you might consider putting a dummy entry at travelTable[0], or
> number the rooms from 0, so you don't have to adjust the indices all the
> time.
>
> Kent
>

Thank you Kent! All of these look like very useful suggestions.

What I'm trying to do is implement an old Text Adventure Game
that was written c.1983. I'm trying to keep the flavor of the game
as close as possible to the original.

I'm not old enough, in computer years, to remember the "Glory Days"
of Text Adventure Games on computers like the Apple ][, Atari,
Commodore 64, IBM PC, VIC 20, and so forth. As a result, I don't
know anything about Text Adventure Games. So this is a real
learning experience for me in more ways than just learning Python.

The book I'm using as a reference is at:
http://www.atariarchives.org/adventure/
Creating Adventure Games On Your Computer.
The author was Tim Hartnell.
http://en.wikipedia.org/wiki/Tim_Hartnell

Most of the problems so far stem from the old line-numbered BASIC's
GOTO [line-number] statements. There are other problems as well,
but _that one crops up regularly.

Nevertheless, it has been fun, so far. I'm a Hobbyist programmer, so
even if I don't succeed at making a Retro-game, I'm having fun trying.

At least I'm getting a good idea of what an old-timey Text Adventure
Game is all about. The only thing I can think of of, is that it must have
been quite a challenge to get one of those old computers to do anything
at all.... so if someone could get a TAG working, it must have been
quite a thrill! 8^D

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From bhaaluu at gmail.com  Wed Jan 30 21:14:17 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 15:14:17 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A0CEF3.1080902@alum.rpi.edu>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0CEF3.1080902@alum.rpi.edu>
Message-ID: <ea979d70801301214y32144357je6dde97a14cc9276@mail.gmail.com>

On Jan 30, 2008 2:24 PM, bob gailer <bgailer at alum.rpi.edu> wrote:
> bhaaluu wrote:
> > #             N S E W U D T
> > travelTable=[[0,2,0,0,0,0,0],    # ROOM 1
> >              [1,3,3,0,0,0,0],    # ROOM 2
> It is good to finally see that you are building an adventure game.
>
> Consider creating a instance of a Room class for each room and saving
> them in a collection such as a list.
>
> This will give you much more flexibility as your game grows.

WooHoo! YES! This is what I started out wanting to do, as an exercise
in learning Python Object Oriented Programming (POOP). I thought
a Text Adventure Game would be a perfect learning tool because
it seems to have objects that model the real world (or a fantasy world).
There is the Explorer, a world (The Castle), Rooms to explore, objects
in the rooms, like Treasure to be picked-up, and Monsters to fight.

However, not having any experience with Text Adventure Games has
been a real bummer for me as far as designing POOP classes. So I
fell back on procedural programming in order to learn more about
TAGs, so I'd have a better idea about how to design the class in POOP.

>
> Inevitably I wound up doing a bunch of things more "Pythonically" so
> there may be stuff here you don't relate to yet. But is is all worth
> studying and will save you hours of headache later.
>

I really appreciate source code. I probably learn faster by modifying
and running source code than anything else, unless it is a step-by-step
tutorial that also has source code that can be modified and run! 8^D

> ----------------------------- code -----------------------------
> import random
> class Room:
>   roomNo = 0
>   def __init__(self, destinations, updatable=True):
>     Room.roomNo += 1
>     self.roomNo = Room.roomNo
>     self.destinations = destinations
>     # store treasure apaart from destinations
>     self.treasure = 0 # add intial treasure
>     self.updatable = updatable # may have the treasure updated
>   def updateTreasure(self, treasure):
>     self.treasure = treasure
>   def __repr__(self):
>     return " %s:%s" % (self.roomNo, self.treasure)
>
> rooms = [
>   Room([0,2,0,0,0,0]),  # ROOM 1
>   Room([1,3,3,0,0,0]),  # ROOM 2
>   Room([2,0,5,2,0,0]),  # ROOM 3
>   Room([0,5,0,0,0,0]),  # ROOM 4
>   Room([4,0,0,3,5,13]), # ROOM 5
>   Room([0,0,1,0,0,0], False), # ROOM 6 flagged as not updatable
>   Room([0,8,0,0,0,0]), # ROOM 7
>   Room([7,0,0,0,0,0]), # ROOM 8
>   Room([0,9,0,0,0,8]), # ROOM 9
>   # etc for the rest of the rooms -
>         ]
>   # note I omitted the initial treasure value since it is always 0
>   # I modified the last for statement to account for only 9 rooms
>
> # use random.sample to create random subsets of values and rooms
> # - eliminates all the loops and tests
> # note this ensures no duplicate treasures (do you want that?)
>
> # create list of 8 random treasure values
> values = random.sample(range(10,110),4) + random.sample(range(-4, 0),4)
>
> # create list of 8 randomly selected updatable rooms
> roomsToUpdate= random.sample([room for room in rooms if room.updatable], 8)
>
> # update the rooms' Treasures
> for room, value in zip(roomsToUpdate, values):
>   room.updateTreasure(value)
>
> a = range(1,99)
> for room in (3,5):
>   rooms[room].updateTreasure(100 + random.choice(a))
>
> for room in rooms: print room
> ----------------------------- end code -----------------------------

I'll copy/paste this into an editor, and see if I can make it do anything.
Thank you!

>
> Things I did not do, but suggest:
> - store the room destinations in a text file rather than hard-coding
> them in the program. It is almost always a good idea to separate logic
> from data.

Right now, my procedural Python program has a main.py, data.py and
action.py. After Kent told me about using a nested sequence structure
instead of a dictionary, all I had to do was edit data.py and change
the table from a dictionary to a list of lists, then edit the other two
files and do a simple search and destroy to get rid of the " .values() ".
It really didn't take as long as I thought it would to change over.

>
>  -create a Treasure class, storing instances directly in roo,s rather
> than indexes, and storing treasure definitions in the text file.
>
> -store room instances in the destinations rather than indexes.
>
> At this point you no longer need indexes!
>
> --
> Bob Gailer
> 919-636-4239 Chapel Hill, NC

Thanks again for the POOP!
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From rdm at rcblue.com  Wed Jan 30 21:29:43 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 12:29:43 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <fnqk2q$k75$1@ger.gmane.org>
References: <20080130105429.7C7BE1E4006@bag.python.org>
	<fnqk2q$k75$1@ger.gmane.org>
Message-ID: <20080130202948.393301E4008@bag.python.org>

At 11:46 AM 1/30/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
> > But I was wondering if it was possible to write
> > Python code in Iron Python and use it somehow in
> > Visual Basic 2005 Express. VB seemed a very easy
> > way to create a GUI, but of course I prefer Python for the code.
>
>
>It should be possible but I've no idea how. I suspect you
>might need to write the Python code in a class but I'm not
>even sure about that. My experiece of .NET is both very
>limited and entirely in C#
>
>But the whole idea of the intermediate code thing is
>that you can intermix languages.

Alan, could you explain what you mean by "the intermediate code thing"?

Thanks,

Dick


From bhaaluu at gmail.com  Wed Jan 30 21:52:08 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 15:52:08 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A0CEF3.1080902@alum.rpi.edu>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0CEF3.1080902@alum.rpi.edu>
Message-ID: <ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com>

I got Bob's code running!
Here it is for all nineteen rooms:

#!/usr/bin/python
# 2008-01-30
# bob gailer [Tutor]
import random
class Room:
 roomNo = 0
 def __init__(self, destinations, updatable=True):
   Room.roomNo += 1
   self.roomNo = Room.roomNo
   self.destinations = destinations
   # store treasure apaart from destinations
   self.treasure = 0 # add intial treasure
   self.updatable = updatable # may have the treasure updated
 def updateTreasure(self, treasure):
   self.treasure = treasure
 def __repr__(self):
   return " %s:%s" % (self.roomNo, self.treasure)

# Table of Rooms
rooms = [
      Room([0,2,0,0,0,0,0]),    # 1 Hallway
      Room([1,3,3,0,0,0,0]),    # 2 Audience Chamber
      Room([2,0,5,2,0,0,0]),    # 3 Great Hall
      Room([0,5,0,0,0,0,0]),    # 4 Private Meeting Room
      Room([4,0,0,3,15,13,0]),  # 5 Inner Hallway
      Room([0,0,1,0,0,0,0],False),  # 6 Entrance (Not Updatable)
      Room([0,8,0,0,0,0,0]),    # 7 Kitchen
      Room([7,10,0,0,0,0,0]),   # 8 Store Room
      Room([8,8,8,8,8,8,0]),    # 9 Lift
      Room([8,0,11,0,0,0,0]),   #10 Rear Vestibule
      Room([0,0,10,0,0,0,0],False), #11 Exit (Not Updatable)
      Room([0,0,0,13,0,0,0]),   #12 Dungeon
      Room([0,0,12,0,5,0,0]),   #13 Guardroom
      Room([0,15,17,0,0,0,0]),  #14 Master Bedroom
      Room([14,0,0,0,0,5,0]),   #15 Upper Hall
      Room([17,0,19,0,0,0,0]),  #16 Treasury
      Room([18,16,0,14,0,0,0]), #17 Chambermaid's Bedroom
      Room([0,17,0,0,0,0,0]),   #18 Dressing Chamber
      Room([9,0,0,16,0,0,0])]   #19 Small Room

# note I omitted the initial treasure value since it is always 0
# use random.sample to create random subsets of values and rooms
# - eliminates all the loops and tests
# note this ensures no duplicate treasures (do you want that?)

# create list of 8 random treasure values
values = random.sample(range(10,110),4) + random.sample(range(-4, 0),4)
print " values:",values

# create list of 8 randomly selected updatable rooms
roomsToUpdate = random.sample([room for room in rooms if room.updatable], 8)
print "8 rooms:",roomsToUpdate

# update the rooms' Treasures
for room, value in zip(roomsToUpdate, values):
 room.updateTreasure(value)

a = range(1,99)
for room in (3,15):
 rooms[room].updateTreasure(100 + random.choice(a))

for room in rooms:
    print room
# end code ################################


On Jan 30, 2008 2:24 PM, bob gailer <bgailer at alum.rpi.edu> wrote:
> bhaaluu wrote:
> > #             N S E W U D T
> > travelTable=[[0,2,0,0,0,0,0],    # ROOM 1
> >              [1,3,3,0,0,0,0],    # ROOM 2
> It is good to finally see that you are building an adventure game.
>
> Consider creating a instance of a Room class for each room and saving
> them in a collection such as a list.
>
> This will give you much more flexibility as your game grows.
>
> Inevitably I wound up doing a bunch of things more "Pythonically" so
> there may be stuff here you don't relate to yet. But is is all worth
> studying and will save you hours of headache later.
>
>[code snipped - see at top]
>
> Things I did not do, but suggest:
> - store the room destinations in a text file rather than hard-coding
> them in the program. It is almost always a good idea to separate logic
> from data.
>
>  -create a Treasure class, storing instances directly in roo,s rather
> than indexes, and storing treasure definitions in the text file.
>
> -store room instances in the destinations rather than indexes.
>
> At this point you no longer need indexes!
>
> --
> Bob Gailer
> 919-636-4239 Chapel Hill, NC
>
>

Thanks!
Happy Programing!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From rabidpoobear at gmail.com  Wed Jan 30 23:32:37 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 30 Jan 2008 16:32:37 -0600
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <20080130202948.393301E4008@bag.python.org>
References: <20080130105429.7C7BE1E4006@bag.python.org>	<fnqk2q$k75$1@ger.gmane.org>
	<20080130202948.393301E4008@bag.python.org>
Message-ID: <47A0FB05.5090309@gmail.com>


>
> Alan, could you explain what you mean by "the intermediate code thing"?
He's referring to CLR.  The .NET framework compiles all of its programs 
into a Common Language Runtime, so at the lower level,
there's no(t much?) difference between the different languages, and thus 
they can interface with each other.
I'm sure the Wikipedia article on CLR would be a lot more informative 
than I can be.
HTH,
-Luke

From bhaaluu at gmail.com  Wed Jan 30 23:40:39 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Wed, 30 Jan 2008 22:40:39 +0000
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <007401c8638d$6a8fb2c0$3cfce004@jslaptop>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0CEF3.1080902@alum.rpi.edu>
	<ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com>
	<007401c8638d$6a8fb2c0$3cfce004@jslaptop>
Message-ID: <ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>

On Jan 30, 2008 10:13 PM, Tiger12506 <keridee at jayco.net> wrote:
> If you're looking for examples - I like the zork games...
>
> http://www.csd.uwo.ca/Infocom/download.html
>

I've already looked at the Infocom site and didn't find
anything that helped me understand Text Adventure
Games like  Hartnell's book does. BASIC is easy to
read, and with the book's explanations, I'm learning
how to program a TAG in Python. My goal is to code
the game in POOP when I understand enough game
elements to design classes for the various objects in
the game, like rooms, treasure, monsters, and so
forth. Bob Gailer recently sent a POOP example
that does a setup of the environment. His Room class
gave me an idea of how it is done. POOP has been
somewhat difficult for me to grasp. At first, it was all
the new vocabulary. Then connecting the vocabulary
to concepts. Most tutorials revolve around the mechanics
of POOP, but don't really get into how to think about
POOP from a design point of view. I'm pretty sure that
once I "get it", I'll wonder why it took me so long... at
least that's how it's been in the past when I've tried to
learn a new concept. So I study it until I hit a block, then
go do something else for awhile. Then I study it some
more. Hartnell's book doesn't get into POOP because
it was written in c.1983 line-numbered BASIC. However,
he has a much better grasp of c.1983 TAGs than I do.
I fixed enough typos in two of the games in the book
to get them running in a GWBASIC interpreter on an
old 286 DOS computer. I can play the game on the 286,
read the code, and read the book. Then I try to do
something similar in Python.

The Infocom games are cool, but they don't give me
the feedback like Hartnell's book and code does.

BTW, there's also "RenPy" which is an Open Source
Interactive Fiction / Visual Novel engine written in Python.
That's pretty cool, but they aren't at all like the TAGs
in Hartnell's book.

There's also a really nice Adventure game tutorial
over at Brian Wisti's site:
http://coolnamehere.com/geekery/python/ifiction/index.html

References:
http://www.csd.uwo.ca/Infocom/
http://www.atariarchives.org/adventure/
http://en.wikipedia.org/wiki/Tim_Hartnell
http://www.renpy.org/wiki/renpy/Home_Page

Believe me, I've looked at a LOT of stuff trying to get a
handle on Adventure Games. 8^D

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From alan.gauld at btinternet.com  Thu Jan 31 00:03:06 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Jan 2008 23:03:06 -0000
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
References: <20080130105429.7C7BE1E4006@bag.python.org><fnqk2q$k75$1@ger.gmane.org>
	<20080130202948.393301E4008@bag.python.org>
Message-ID: <fnqvjg$u9u$1@ger.gmane.org>


"Dick Moores" <rdm at rcblue.com> wrote

>>But the whole idea of the intermediate code thing is
>>that you can intermix languages.
>
> Alan, could you explain what you mean by "the intermediate code 
> thing"?

.NET works like Java in that it doesn't compile into machine
language object code directly but uses a framework called
the Common Language Runtime(CLR)  and an underlying
foundation known as the Common Language Infrastructure (CLI)
which in turn includes the Common Type System (CTS) and the
Common Intermediate Language (CIL)  which all of the .NET family
of languages must support.

The CLR includes things like a common exception handling
framework, comon object model and of course the common
types (so an int looks the same in VB or C#) and intermediate
language that is interpreted by the .NET environment. Exactly like a
Java JIT compiler converts Java bytecode into machine code
prior to execution.compiled Java bytecode. This is all hidden
inside an exe file by providing a standard exe style header
which Windows can use to determine the type of exe and
for CLR files launch the .NET environment.

For more detail see the MS .NET web pages and other .NET sites.

I also recommend the O'Reilly ".NET Framework Essentials"
book for an overview of how it all fits together.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld








From rdm at rcblue.com  Thu Jan 31 00:07:11 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 15:07:11 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <47A0FB05.5090309@gmail.com>
References: <20080130105429.7C7BE1E4006@bag.python.org>
	<fnqk2q$k75$1@ger.gmane.org>
	<20080130202948.393301E4008@bag.python.org>
	<47A0FB05.5090309@gmail.com>
Message-ID: <20080130230750.6CF361E4014@bag.python.org>

At 02:32 PM 1/30/2008, Luke Paireepinart wrote:


>>Alan, could you explain what you mean by "the intermediate code thing"?
>He's referring to CLR.  The .NET framework compiles all of its 
>programs into a Common Language Runtime, so at the lower level,
>there's no(t much?) difference between the different languages, and 
>thus they can interface with each other.
>I'm sure the Wikipedia article on CLR would be a lot more 
>informative than I can be.

Looks like a good article, Luke. 
<http://en.wikipedia.org/wiki/Common_Language_Runtime>

I just remembered that a friend dropping by this evening is a 
Microsoft programmer/manager. I think he's mentioned IPython to me 
before. Maybe he can help with what I'm trying to do. No answer from 
the IPython Users List yet..

Dick



From rdm at rcblue.com  Thu Jan 31 00:17:26 2008
From: rdm at rcblue.com (Dick Moores)
Date: Wed, 30 Jan 2008 15:17:26 -0800
Subject: [Tutor] Iron Python and Visual Basic 2005 Express
In-Reply-To: <fnqvjg$u9u$1@ger.gmane.org>
References: <20080130105429.7C7BE1E4006@bag.python.org>
	<fnqk2q$k75$1@ger.gmane.org>
	<20080130202948.393301E4008@bag.python.org>
	<fnqvjg$u9u$1@ger.gmane.org>
Message-ID: <20080130231732.091101E400E@bag.python.org>

At 03:03 PM 1/30/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
> >>But the whole idea of the intermediate code thing is
> >>that you can intermix languages.
> >
> > Alan, could you explain what you mean by "the intermediate code
> > thing"?
>
>.NET works like Java in that it doesn't compile into machine
>language object code directly but uses a framework called
>the Common Language Runtime(CLR)  and an underlying
>foundation known as the Common Language Infrastructure (CLI)
>which in turn includes the Common Type System (CTS) and the
>Common Intermediate Language (CIL)  which all of the .NET family
>of languages must support.
>
>The CLR includes things like a common exception handling
>framework, comon object model and of course the common
>types (so an int looks the same in VB or C#) and intermediate
>language that is interpreted by the .NET environment. Exactly like a
>Java JIT compiler converts Java bytecode into machine code
>prior to execution.compiled Java bytecode. This is all hidden
>inside an exe file by providing a standard exe style header
>which Windows can use to determine the type of exe and
>for CLR files launch the .NET environment.
>
>For more detail see the MS .NET web pages and other .NET sites.
>
>I also recommend the O'Reilly ".NET Framework Essentials"
>book for an overview of how it all fits together.

Thanks very much, Alan. I think I'm in over my head here.

I'm somewhat surprised that what I asked about doing in my initial 
post doesn't seem to have been done yet..

Dick



From kent37 at tds.net  Thu Jan 31 00:25:58 2008
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 30 Jan 2008 18:25:58 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>	<fnpcoo$up6$1@ger.gmane.org>	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>	<47A0CEF3.1080902@alum.rpi.edu>	<ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com>	<007401c8638d$6a8fb2c0$3cfce004@jslaptop>
	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
Message-ID: <47A10786.4090606@tds.net>

bhaaluu wrote:
> References:
> http://www.csd.uwo.ca/Infocom/
> http://www.atariarchives.org/adventure/
> http://en.wikipedia.org/wiki/Tim_Hartnell
> http://www.renpy.org/wiki/renpy/Home_Page
> 
> Believe me, I've looked at a LOT of stuff trying to get a
> handle on Adventure Games. 8^D

I'm surprised you don't have any references to Colossal Cave:
http://en.wikipedia.org/wiki/Colossal_Cave_Adventure

This article talks about the data files used to define the cave - a good 
example of data-driven programming:
http://www.digitalhumanities.org/dhq/vol/001/2/000009.html

Kent

From bhaaluu at gmail.com  Thu Jan 31 01:06:18 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 31 Jan 2008 00:06:18 +0000
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <47A10786.4090606@tds.net>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0CEF3.1080902@alum.rpi.edu>
	<ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com>
	<007401c8638d$6a8fb2c0$3cfce004@jslaptop>
	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
	<47A10786.4090606@tds.net>
Message-ID: <ea979d70801301606h2ab0e2falabc030b5e57afbe8@mail.gmail.com>

On Jan 30, 2008 11:25 PM, Kent Johnson <kent37 at tds.net> wrote:
> bhaaluu wrote:
> > References:
> > http://www.csd.uwo.ca/Infocom/
> > http://www.atariarchives.org/adventure/
> > http://en.wikipedia.org/wiki/Tim_Hartnell
> > http://www.renpy.org/wiki/renpy/Home_Page
> >
> > Believe me, I've looked at a LOT of stuff trying to get a
> > handle on Adventure Games. 8^D
>
> I'm surprised you don't have any references to Colossal Cave:
> http://en.wikipedia.org/wiki/Colossal_Cave_Adventure

I've heard of Colossal Cave, but no, I haven't looked at
it (yet?). Most of my searches have tried to be related
to programming an Adventure Game, with less of an
interest in just playing an adventure game. However,
I have tried a couple of the older Infocom games (with
limited success, I might add).

>
> This article talks about the data files used to define the cave - a good
> example of data-driven programming:
> http://www.digitalhumanities.org/dhq/vol/001/2/000009.html

THIS IS SWEET!  This article is really well written.
Actually, Hartnell's book also has a brief history of
adventure games, and Crowther and Woods, among
others are mentioned. Hartnell talks about the
pre-computer gamers who recreated historical battles,
who later went on  and developed Dungeon & Dragons
type games and RPGs (another genre of gaming that
I know nothing about). Later, those games were
computerized.  I'm not sure how many people still
play these games? The local used-book store has
several shelves packed with RPG books.

>
> Kent
>

Thanks for these links, Kent!
I never may have found them otherwise.
Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From david.bear at asu.edu  Thu Jan 31 05:17:50 2008
From: david.bear at asu.edu (David Bear)
Date: Wed, 30 Jan 2008 21:17:50 -0700
Subject: [Tutor] appending to a list
Message-ID: <3759044.QGIov8qMN4@teancum>

I want to return a tuple from a function. I want to append the second
element of that tupple to a list. For example

mylist = []
def somefunc():
   return(3.14, 'some string')

somenum, mylist.append(??) somefunc()

obviously, the syntax doesn't work. This should be easy, but I've never seen
example code. any pointers?


-- 
--
David Bear
College of Public Programs at Arizona State University


From bill at celestial.net  Thu Jan 31 06:35:07 2008
From: bill at celestial.net (Bill Campbell)
Date: Wed, 30 Jan 2008 21:35:07 -0800
Subject: [Tutor] appending to a list
In-Reply-To: <3759044.QGIov8qMN4@teancum>
References: <3759044.QGIov8qMN4@teancum>
Message-ID: <20080131053507.GB28484@ayn.mi.celestial.com>

On Wed, Jan 30, 2008, David Bear wrote:
>I want to return a tuple from a function. I want to append the second
>element of that tupple to a list. For example
>
>mylist = []
>def somefunc():
>   return(3.14, 'some string')
>
>somenum, mylist.append(??) somefunc()
>
>obviously, the syntax doesn't work. This should be easy, but I've never seen
>example code. any pointers?

mylist.append(somefunc()[1])

Bill
--
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

If ye love wealth greater than liberty, the tranquillity of servitude
greater than the animating contest for freedom, go home from us in peace.
We seek not your consul, nor your arms.  Crouch down and lick the hand that
feeds you.  May your chains set lightly upon you;  and may posterity forget
ye were our countrymen. -- Samuel Adams (American Patriot)

From brindly at gmail.com  Thu Jan 31 08:23:31 2008
From: brindly at gmail.com (brindly sujith)
Date: Thu, 31 Jan 2008 12:53:31 +0530
Subject: [Tutor] how to use freeze for making executable python file in linux
Message-ID: <bfb67a4d0801302323n13dbaec9ld712e79e0b47257e@mail.gmail.com>

can i use freeze to make my python program in to executable in linux

if yes...plz tell me how to use freeze

whether i need to install something or its default in python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080131/58c354e2/attachment.htm 

From alan.gauld at btinternet.com  Thu Jan 31 09:19:43 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 08:19:43 -0000
Subject: [Tutor] results not quite 100 percent yet
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com><fnpcoo$up6$1@ger.gmane.org><ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com><47A0CEF3.1080902@alum.rpi.edu><ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com><007401c8638d$6a8fb2c0$3cfce004@jslaptop>
	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
Message-ID: <fns076$g9k$1@ger.gmane.org>

"bhaaluu" <bhaaluu at gmail.com> wrote

> how to program a TAG in Python. My goal is to code
> the game in POOP 

POOP????

> I fixed enough typos in two of the games in the book
> to get them running in a GWBASIC interpreter on an
> old 286 DOS computer. 

Why not run it on a modern computer under QBASIC 
which, last time I looked, was still being shipped with 
Win98 and NT4 - dunno about XP/Vista. But there are 
several unofficial download sites on the web too. And 
the QBASIC IDE is much nicer than GWBASIC

Thats why the original version of my tutorial useed 
QBASIC as one of its languages. It came for free 
with Windows.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


From rabidpoobear at gmail.com  Thu Jan 31 09:20:48 2008
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 31 Jan 2008 02:20:48 -0600
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <fns076$g9k$1@ger.gmane.org>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com><fnpcoo$up6$1@ger.gmane.org><ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com><47A0CEF3.1080902@alum.rpi.edu><ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com><007401c8638d$6a8fb2c0$3cfce004@jslaptop>	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
	<fns076$g9k$1@ger.gmane.org>
Message-ID: <47A184E0.5000401@gmail.com>

Alan Gauld wrote:
> "bhaaluu" <bhaaluu at gmail.com> wrote
>
>   
>> how to program a TAG in Python. My goal is to code
>> the game in POOP 
>>     
>
> POOP????
>   
Python Object-Oriented Programming.
You really should try to be less funny.  I totally didn't read your 
e-mail seriously cause I was laughing at all the poop jokes.

From alan.gauld at btinternet.com  Thu Jan 31 09:25:38 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 08:25:38 -0000
Subject: [Tutor] results not quite 100 percent yet
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com><fnpcoo$up6$1@ger.gmane.org><ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com><47A0CEF3.1080902@alum.rpi.edu><ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com><007401c8638d$6a8fb2c0$3cfce004@jslaptop><ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com><47A10786.4090606@tds.net>
	<ea979d70801301606h2ab0e2falabc030b5e57afbe8@mail.gmail.com>
Message-ID: <fns0i9$ha5$1@ger.gmane.org>


"bhaaluu" <bhaaluu at gmail.com> wrote

> others are mentioned. Hartnell talks about the
> pre-computer gamers who recreated historical battles,
> who later went on  and developed Dungeon & Dragons
> type games and RPGs (another genre of gaming that
> I know nothing about). Later, those games were
> computerized.  I'm not sure how many people still
> play these games? 

Huge numbers and they take it very seriously.
A colleague (a Physics PHd and ex NASA scientist!)
takes holidays each year to spend a week at a gaming 
convention in Florida (and he is UK based!) where several 
hundred folks turn up to do nothing but play games for 
a week. A lot (most?) of those games are RPGs.
And they are not all computerised, in fact many of the 
most complex ones are traditional board games.

There are all sorts of online forums etc supporting these 
gamers "out of season" too. As someone who occasionally 
plays Freecell or Spider on my PC I can't see the 
fascinatioon, but lots of folks do!

Alan G


From alan.gauld at btinternet.com  Thu Jan 31 09:39:32 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 08:39:32 -0000
Subject: [Tutor] appending to a list
References: <3759044.QGIov8qMN4@teancum>
Message-ID: <fns1cb$jql$1@ger.gmane.org>

"David Bear" <david.bear at asu.edu> wrote

>I want to return a tuple from a function. I want to append the second
> element of that tupple to a list. For example
>
> mylist = []
> def somefunc():
>   return(3.14, 'some string')
>
> somenum, mylist.append(??) somefunc()
>
> obviously, the syntax doesn't work.

The problem here is that you are trying to combine
too many advanmced features in one step. You can
pass back a tuple into a tuple. Or you can pass
back an N-tuple and unpack it into N variables.
Or you can pass back an N-tuple and select
one of the elements. But you can't combine any
two of these in one step.

So if you only want to append the second element
and throw away the first, you can do it. Otherwise
you have to either store the results in a tuple and
access them seperatly later, or unpack into two
vars and append the second var.

t = somefunc()
mylist.append(t[1])
somenum = t[0]

OR

somenum, someval = somefunc()
mylist.append(someval)

OR

mylist.append(somefunc()[1])  # losing the first value

> This should be easy,

Why should it be easy? :-)
The syntax for unpacking tuples hides what is a complex
operation in most languages which a) don't allow the
passing of tuples and b) dont support auto unpacking
of tuples. Its only the fact that Python allows this in one
move that makes it appear that is should be easy to access
the tuple elements anonymously.

FWIW To do this in C you would have to explicitly
create a struct or array inside the function and pass
back a pointer to the struct. Then in the calling code
you would have to explicitly dereference the struct elements
and then, finally, dispose of it. - Python makes it all
much easier, but still has its limits.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



From alan.gauld at btinternet.com  Thu Jan 31 09:46:34 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 08:46:34 -0000
Subject: [Tutor] how to use freeze for making executable python file in
	linux
References: <bfb67a4d0801302323n13dbaec9ld712e79e0b47257e@mail.gmail.com>
Message-ID: <fns1ph$kt7$1@ger.gmane.org>

"brindly sujith" <brindly at gmail.com> wrote

> can i use freeze to make my python program 
> into executable in linux

Since you have picked up on Freeze I'll assume Luke was 
right and that you don't really want to make your program 
executable but that you want to create a self contained file
that can be distributed without the need for the Python 
interpreter to already exist. Is that the case?

If so its quite unusual on Linux since most Linux distros 
include Python as standard. Can you clarify why you think 
this will be needed? It will bring several disadvantages 
including a) wasted disk space since you will be packaging 
Python with your program even for users who already have it,
b) limiting the use to one platform since the freeze version 
will only work on the platform you create it on, whereas python 
files wuill runon any machine with Python installed (assuming 
no non-portable code), c) maintenance becomes harder since 
you have to remember to refreeze the code after every bug fix etc.
And then you have to ship/install a whole new package instead of 
a single fixed python file.

There are valid reasons for doing this but these's a whole 
bunch of reasons not to as well...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld at btinternet.com  Thu Jan 31 09:51:29 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 08:51:29 -0000
Subject: [Tutor] results not quite 100 percent yet
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com><fnpcoo$up6$1@ger.gmane.org><ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com><47A0CEF3.1080902@alum.rpi.edu><ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com><007401c8638d$6a8fb2c0$3cfce004@jslaptop>	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com><fns076$g9k$1@ger.gmane.org>
	<47A184E0.5000401@gmail.com>
Message-ID: <fns22o$lob$1@ger.gmane.org>


"Luke Paireepinart" <rabidpoobear at gmail.com> wrote

>> POOP????
>>
> Python Object-Oriented Programming.

Aah! Obvious really.
Except - in what way is POOP different to any other
kind of OOP? Nobody talks abot JOOP or COOP
or SOOP or LOOP or BOOP or... you could go on for hours!
Although JOOP used to be a magazine and LOOPS was a
Lisp environment for a while...

> You really should try to be less funny.  I totally didn't read your
> e-mail seriously cause I was laughing at all the poop jokes.

Yes, that was kind of my reaction too.

Alan G. 



From bhaaluu at gmail.com  Thu Jan 31 11:02:04 2008
From: bhaaluu at gmail.com (bhaaluu)
Date: Thu, 31 Jan 2008 05:02:04 -0500
Subject: [Tutor] results not quite 100 percent yet
In-Reply-To: <fns076$g9k$1@ger.gmane.org>
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com>
	<fnpcoo$up6$1@ger.gmane.org>
	<ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com>
	<47A0CEF3.1080902@alum.rpi.edu>
	<ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com>
	<007401c8638d$6a8fb2c0$3cfce004@jslaptop>
	<ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com>
	<fns076$g9k$1@ger.gmane.org>
Message-ID: <ea979d70801310202g7c60cb4o6a74b33c6603950f@mail.gmail.com>

On Jan 31, 2008 3:19 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "bhaaluu" <bhaaluu at gmail.com> wrote
>
> > how to program a TAG in Python. My goal is to code
> > the game in POOP
>
> POOP????

Python Object Oriented Programming
8^D

>
> > I fixed enough typos in two of the games in the book
> > to get them running in a GWBASIC interpreter on an
> > old 286 DOS computer.
>
> Why not run it on a modern computer under QBASIC
> which, last time I looked, was still being shipped with
> Win98 and NT4 - dunno about XP/Vista. But there are
> several unofficial download sites on the web too. And
> the QBASIC IDE is much nicer than GWBASIC

Try it. I'll even send  the code that is working in GWBASIC
to you if you think you can get it working in QBasic. The
286 has all the old interpreters/compilers on it. I used
QBasic to fix most of the typos in the code, but never
could get the code to work in QBasic. (QBasic was the
first interpreter I learned to program with -- I never did
learn the old line-numbered BASIC). Once I fixed everything
I could in QBasic, I fired up the program in GWBASIC and
it runs fine. I don't have MS-XP/Vista/NT. I have MS-DOS 6.2,
MS-Windows 3.1, MS-Windows95. I've been using GNU/Linux
as my primary OS since 1996. My computer "museum"
includes a 286,386,486, an old Pentium, a 586, and a 686.

>
> Thats why the original version of my tutorial useed
> QBASIC as one of its languages. It came for free
> with Windows.
>

I've seen your QBasic/Python tutorial!

> HTH,
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
"You assist an evil system most effectively by obeying its
orders and decrees. An evil system never deserves such
allegiance.  Allegiance to it means partaking of the evil.
A good person will resist an evil system with his or her
whole soul." [Mahatma Gandhi]

From alan.gauld at btinternet.com  Thu Jan 31 11:32:59 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 10:32:59 -0000
Subject: [Tutor] results not quite 100 percent yet
References: <ea979d70801291717v25a5bfb7l20ac4056bc3c38e6@mail.gmail.com><fnpcoo$up6$1@ger.gmane.org><ea979d70801300919g1dbb65e4h150985a56d017f72@mail.gmail.com><47A0CEF3.1080902@alum.rpi.edu><ea979d70801301252r3f383d28k163d37a125e4c437@mail.gmail.com><007401c8638d$6a8fb2c0$3cfce004@jslaptop><ea979d70801301440n12e9b1b8uc42d2040418b3128@mail.gmail.com><fns076$g9k$1@ger.gmane.org>
	<ea979d70801310202g7c60cb4o6a74b33c6603950f@mail.gmail.com>
Message-ID: <fns812$98o$1@ger.gmane.org>

"bhaaluu" <bhaaluu at gmail.com> wrote

> Try it. I'll even send  the code that is working in GWBASIC
> to you if you think you can get it working in QBasic. 

Please do, I've not found anything from GWBASIC that 
didn't work in QBASIC - in fact I use a GWBASIC reference 
book when writing QBASIC.

> could get the code to work in QBasic. (QBasic was the
> first interpreter I learned to program with -- I never did
> learn the old line-numbered BASIC). 

QBASIC works with the line numbering style just fine, 
although there's no good reason to use it.

Alan G.


From alan.gauld at btinternet.com  Thu Jan 31 11:44:06 2008
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Jan 2008 10:44:06 -0000
Subject: [Tutor] how to use freeze for making executable python file in
	linux
References: <bfb67a4d0801302323n13dbaec9ld712e79e0b47257e@mail.gmail.com>
Message-ID: <fns8lt$bhd$1@ger.gmane.org>


"brindly sujith" <brindly at gmail.com> wrote 

> if yes...plz tell me how to use freeze
> 
> whether i need to install something or its default in python

Googling 'python freeze' for tutorials etc

Its not a library module but a utility that usually comes 
with Python on supported platforms. Try searching with find.

Alan G




From p1p1p1p1p1p1p1p1p1p1p1 at gmail.com  Thu Jan 31 14:15:10 2008
From: p1p1p1p1p1p1p1p1p1p1p1 at gmail.com (pee one)
Date: Thu, 31 Jan 2008 07:15:10 -0600
Subject: [Tutor] Please comment on
Message-ID: <82321bc0801310515k1234b8e9g6048319ee52548a9@mail.gmail.com>

Please comment on
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/543267

Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080131/8180b515/attachment.htm 

From brunson at brunson.com  Thu Jan 31 17:25:01 2008
From: brunson at brunson.com (Eric Brunson)
Date: Thu, 31 Jan 2008 09:25:01 -0700
Subject: [Tutor] Please comment on
In-Reply-To: <82321bc0801310515k1234b8e9g6048319ee52548a9@mail.gmail.com>
References: <82321bc0801310515k1234b8e9g6048319ee52548a9@mail.gmail.com>
Message-ID: <47A1F65D.2030008@brunson.com>


I think the page is a little busy, but relatively clean overall.  I 
don't like the popup that makes me interact with the page when I load it.

Is that what you were looking for or would you like to be a little more 
specific?

pee one wrote:
> Please comment on 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/543267
>
> Thank you.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From sorcrow at gmail.com  Thu Jan 31 20:19:55 2008
From: sorcrow at gmail.com (Sorghum Crow)
Date: Thu, 31 Jan 2008 14:19:55 -0500
Subject: [Tutor] How to compare the first line from multiple files
Message-ID: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>

How to compare the first line from multiple files

Greetings,

 I'm new on the forum and relatively new to Python. I have been tasked
at work with checking some files for consistency.

 What I need to do is verify that the first lines of a group of text
files are identical.
 The files are all in the same directory.
 I know what the first line should be (or I can take the first line
from the first file as the reference.)

How would I go about doing this.

Thanks in advance.

Regards,
Sorghum Crow

From michael.langford at rowdylabs.com  Thu Jan 31 20:25:19 2008
From: michael.langford at rowdylabs.com (Michael Langford)
Date: Thu, 31 Jan 2008 14:25:19 -0500
Subject: [Tutor] How to compare the first line from multiple files
In-Reply-To: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>
References: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>
Message-ID: <82b4f5810801311125m9f5b9cfv5fa2224dde6f139c@mail.gmail.com>

You should checkout os.listdir()

http://docs.python.org/lib/os-file-dir.html

On Jan 31, 2008 2:19 PM, Sorghum Crow <sorcrow at gmail.com> wrote:
> How to compare the first line from multiple files
>
> Greetings,
>
>  I'm new on the forum and relatively new to Python. I have been tasked
> at work with checking some files for consistency.
>
>  What I need to do is verify that the first lines of a group of text
> files are identical.
>  The files are all in the same directory.
>  I know what the first line should be (or I can take the first line
> from the first file as the reference.)
>
> How would I go about doing this.
>
> Thanks in advance.
>
> Regards,
> Sorghum Crow
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

From Shawn at Milochik.com  Thu Jan 31 20:33:41 2008
From: Shawn at Milochik.com (Shawn Milochik)
Date: Thu, 31 Jan 2008 14:33:41 -0500
Subject: [Tutor] How to compare the first line from multiple files
In-Reply-To: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>
References: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>
Message-ID: <1201808021.674.2.camel@smilochik-lin>


-----Original Message-----
From: Sorghum Crow <sorcrow at gmail.com>
To: tutor at python.org
Subject: [Tutor] How to compare the first line from multiple files
Date: Thu, 31 Jan 2008 14:19:55 -0500

How to compare the first line from multiple files

Greetings,

 I'm new on the forum and relatively new to Python. I have been tasked
at work with checking some files for consistency.

 What I need to do is verify that the first lines of a group of text
files are identical.
 The files are all in the same directory.
 I know what the first line should be (or I can take the first line
from the first file as the reference.)

How would I go about doing this.

Thanks in advance.

Regards,
Sorghum Crow
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor





Try this:

Find code which will loop through each file in a directory. Easy to do.

Open each file and read the first line into a variable.

Then do something fun with this info, such as adding it to a dictionary 
and incrementing the value for that dictionary value each time you find that line.

When you're done, you can check the length of the dictionary to see if there is more than
one value, and then view the contents of the dictionary to find out what the unique values are.


Shawn




From bgailer at alum.rpi.edu  Thu Jan 31 21:09:35 2008
From: bgailer at alum.rpi.edu (bob gailer)
Date: Thu, 31 Jan 2008 15:09:35 -0500
Subject: [Tutor] How to compare the first line from multiple files
In-Reply-To: <82b4f5810801311125m9f5b9cfv5fa2224dde6f139c@mail.gmail.com>
References: <e2ed96de0801311119t628631a1k4a0269b2e9037f97@mail.gmail.com>
	<82b4f5810801311125m9f5b9cfv5fa2224dde6f139c@mail.gmail.com>
Message-ID: <47A22AFF.2030705@alum.rpi.edu>

Michael Langford wrote:
> You should checkout os.listdir()
>
> http://docs.python.org/lib/os-file-dir.html
>   
Which will give you a list of the filenames.

Then (pseudo-code):
  open the first file, read its first line and save that in a variable
  loop thru the rest of the filenames
    open each, read the first line and compare it to the variable
     if comparison fails
       report that

For that you need:
   the open() built-in function
   the file readline() method
   the assignment, for, if and print statements
   comparison

Rather than one of us writing it for you, give it a try.
Show us what you wrote, what responses you get when you run it, what 
questions you have.
We'll take it from there.

> On Jan 31, 2008 2:19 PM, Sorghum Crow <sorcrow at gmail.com> wrote:
>   
>> How to compare the first line from multiple files
>>
>> Greetings,
>>
>>  I'm new on the forum and relatively new to Python. I have been tasked
>> at work with checking some files for consistency.
>>
>>  What I need to do is verify that the first lines of a group of text
>> files are identical.
>>  The files are all in the same directory.
>>  I know what the first line should be (or I can take the first line
>> from the first file as the reference.)


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC


From ricaraoz at gmail.com  Fri Jan 25 14:26:04 2008
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 25 Jan 2008 10:26:04 -0300
Subject: [Tutor] creating a nested dictionary
In-Reply-To: <479893CE.1000901@tds.net>
References: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au>	<7ae3ca10801240146g2eeac1e9i36cade3e1b926c6e@mail.gmail.com>
	<479893CE.1000901@tds.net>
Message-ID: <4799E36C.4090404@bigfoot.com>

Kent Johnson wrote:
> Remco Gerlich wrote:
>> I can't think of a really good generalization, one that will work for 
>> all depths. That's the sort of thing you use Lisp, combinators and lots 
>> of coffee for. Perhaps later today.
> 
> Some nice solutions here:
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/9519c885a24a65ea/c9697fa73bb59709
> 
> Kent

These solutions sometimes may have unexpected behavior.

class recursivedefaultdict(object):
    def __init__(self):
        self.__dd = defaultdict(recursivedefaultdict)
    def __getattr__(self,attr):
        return self.__dd.__getattribute__(attr)
    def __getitem__(self,*args):
        return self.__dd.__getitem__(*args)
    def __setitem__(self,*args):
        return self.__dd.__setitem__(*args)

d = recursivedefaultdict()
d['pepe']['jose']['juan'] = 25
d['pepe']['jose'] = 25
d['pepe']['martin'] = 33
[i for i in d['pepe']]

And it went into an infinite loop.

class recursivedefaultdict(defaultdict):
    def __init__(self):
        self.default_factory = type(self)
d = recursivedefaultdict()
d['pepe']['jose']['juan'] = 25
d['pepe']['jose'] = 25
d['pepe']['martin'] = 33
d
it prints : defaultdict(<class '__main__.hash'>, {'pepe':
defaultdict(<class '__main__.hash'>, {'jose': defaultdict(<class
'__main__.hash'>, {'juan': 25}), 'pedro': 25, 'martin': 33})})

[i for i in d['pepe']]
it prints : ['jose', 'pedro', 'martin']
expected  : [defaultdict(<class '__main__.hash'>, {'jose':
defaultdict(<class '__main__.hash'>, {'juan': 25}), 'pedro': 25,
'martin': 33})]

[i for i in d]
it prints : ['pepe']
expected  : [defaultdict(<class '__main__.hash'>, {'pepe':
defaultdict(<class '__main__.hash'>, {'jose': defaultdict(<class
'__main__.hash'>, {'juan': 25})})})]

Anyway it otherwise seems to behave properly :
a = d['pepe']
a
it prints : defaultdict(<class '__main__.hash'>, {'jose':
defaultdict(<class '__main__.hash'>, {'juan': 25}), 'pedro': 25,
'martin': 33})

as would be expected.


And class hash behaves like this last one.
class hash(defaultdict):
    def __init__(self):
        defaultdict.__init__(self, hash)